Make insecure perform as expected
[asterisk/asterisk.git] / channels / chan_sip.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Implementation of Session Initiation Protocol
5  * 
6  * Copyright (C) 1999, Mark Spencer
7  *
8  * Mark Spencer <markster@linux-support.net>
9  *
10  * This program is free software, distributed under the terms of
11  * the GNU General Public License
12  */
13
14 #include <stdio.h>
15 #include <ctype.h>
16 #include <pthread.h>
17 #include <string.h>
18 #include <asterisk/lock.h>
19 #include <asterisk/channel.h>
20 #include <asterisk/channel_pvt.h>
21 #include <asterisk/config.h>
22 #include <asterisk/logger.h>
23 #include <asterisk/module.h>
24 #include <asterisk/pbx.h>
25 #include <asterisk/options.h>
26 #include <asterisk/lock.h>
27 #include <asterisk/sched.h>
28 #include <asterisk/io.h>
29 #include <asterisk/rtp.h>
30 #include <asterisk/acl.h>
31 #include <asterisk/callerid.h>
32 #include <asterisk/cli.h>
33 #include <asterisk/md5.h>
34 #include <asterisk/app.h>
35 #include <asterisk/musiconhold.h>
36 #include <asterisk/dsp.h>
37 #include <asterisk/parking.h>
38 #include <asterisk/acl.h>
39 #include <sys/socket.h>
40 #include <sys/ioctl.h>
41 #include <net/if.h>
42 #include <errno.h>
43 #include <unistd.h>
44 #include <stdlib.h>
45 #include <fcntl.h>
46 #include <netdb.h>
47 #include <arpa/inet.h>
48 #include <sys/signal.h>
49 #include <netinet/in_systm.h>
50 #include <netinet/ip.h>
51
52 #ifndef IPTOS_MINCOST
53 #define IPTOS_MINCOST 0x02
54 #endif
55
56 /* #define VOCAL_DATA_HACK */
57
58 #define SIPDUMPER
59 #define DEFAULT_DEFAULT_EXPIRY  120
60 #define DEFAULT_MAX_EXPIRY      3600
61 #define EXPIRY_GUARD_SECS       15
62
63 #define SIP_DTMF_RFC2833        (1 << 0)
64 #define SIP_DTMF_INBAND         (1 << 1)
65 #define SIP_DTMF_INFO           (1 << 2)
66
67 static int max_expiry = DEFAULT_MAX_EXPIRY;
68 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
69
70 #define DEFAULT_MAXMS           2000            /* Must be faster than 2 seconds by default */
71
72 #define DEFAULT_MAXMS           2000            /* Must be faster than 2 seconds by default */
73 #define DEFAULT_FREQ_OK         60 * 1000               /* How often to check for the host to be up */
74 #define DEFAULT_FREQ_NOTOK      10 * 1000               /* How often to check, if the host is down... */
75
76 #define DEFAULT_RETRANS         1000                    /* How frequently to retransmit */
77 #define MAX_RETRANS                     5                               /* Try only 5 times for retransmissions */
78
79 static char *desc = "Session Initiation Protocol (SIP)";
80 static char *type = "sip";
81 static char *tdesc = "Session Initiation Protocol (SIP)";
82 static char *config = "sip.conf";
83
84 #define DEFAULT_SIP_PORT        5060    /* From RFC 2543 */
85 #define SIP_MAX_PACKET  1500            /* Also from RFC 2543, should sub headers tho */
86
87 static char context[AST_MAX_EXTENSION] = "default";
88
89 static char language[MAX_LANGUAGE] = "";
90
91 static char callerid[AST_MAX_EXTENSION] = "asterisk";
92
93 static char fromdomain[AST_MAX_EXTENSION] = "";
94
95 static char notifymime[AST_MAX_EXTENSION] = "application/simple-message-summary";
96
97 static int usecnt =0;
98 static pthread_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
99
100 /* Protect the interface list (of sip_pvt's) */
101 static pthread_mutex_t iflock = AST_MUTEX_INITIALIZER;
102
103 /* Protect the monitoring thread, so only one process can kill or start it, and not
104    when it's doing something critical. */
105 static pthread_mutex_t netlock = AST_MUTEX_INITIALIZER;
106
107 static pthread_mutex_t monlock = AST_MUTEX_INITIALIZER;
108
109 /* This is the thread for the monitor which checks for input on the channels
110    which are not currently in use.  */
111 static pthread_t monitor_thread = 0;
112
113 static int restart_monitor(void);
114
115 /* Codecs that we support by default: */
116 static int capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM;
117 static int noncodeccapability = AST_RTP_DTMF;
118
119 static char ourhost[256];
120 static struct in_addr __ourip;
121 static int ourport;
122
123 static int sipdebug = 0;
124
125 static int tos = 0;
126
127 static int globaldtmfmode = SIP_DTMF_RFC2833;
128
129 /* Expire slowly */
130 static int expiry = 900;
131
132 static struct sched_context *sched;
133 static struct io_context *io;
134 /* The private structures of the  sip channels are linked for
135    selecting outgoing channels */
136    
137 #define SIP_MAX_HEADERS         64
138 #define SIP_MAX_LINES           64
139
140 static struct sip_codec_pref {
141         int codec;
142         struct sip_codec_pref *next;
143 } *prefs;
144
145 struct sip_request {
146   char *rlPart1; /* SIP Method Name or "SIP/2.0" protocol version */
147   char *rlPart2; /* The Request URI or Response Status */
148         int len;
149         int headers;                                    /* SIP Headers */
150         char *header[SIP_MAX_HEADERS];
151         int lines;                                              /* SDP Content */
152         char *line[SIP_MAX_LINES];
153         char data[SIP_MAX_PACKET];
154 };
155
156 struct sip_pkt;
157
158 struct sip_route {
159         struct sip_route *next;
160         char hop[0];
161 };
162
163 static struct sip_pvt {
164         pthread_mutex_t lock;                           /* Channel private lock */
165         char callid[80];                                        /* Global CallID */
166         char randdata[80];      /* Random data */
167         unsigned int ocseq;                                     /* Current outgoing seqno */
168         unsigned int icseq;                                     /* Current incoming seqno */
169         unsigned int callgroup;
170         unsigned int pickupgroup;
171         int lastinvite;                                         /* Last Cseq of invite */
172         int alreadygone;                                        /* Whether or not we've already been destroyed by or peer */
173         int needdestroy;                                        /* if we need to be destroyed */
174         int capability;                                         /* Special capability */
175         int noncodeccapability;
176         int outgoing;                                           /* Outgoing or incoming call? */
177         int authtries;                                          /* Times we've tried to authenticate */
178         int insecure;                                           /* Don't check source port/ip */
179         int expiry;                                             /* How long we take to expire */
180         int branch;                                                     /* One random number */
181         int canreinvite;                                        /* Do we support reinvite */
182         int progress;                                           /* Have sent 183 message progress */
183         int tag;                                                        /* Another random number */
184         int nat;                                                        /* Whether to try to support NAT */
185         struct sockaddr_in sa;                          /* Our peer */
186         struct sockaddr_in redirip;                     /* Where our RTP should be going if not to us */
187         struct sockaddr_in recv;                        /* Received as */
188         struct in_addr ourip;                           /* Our IP */
189         struct ast_channel *owner;                      /* Who owns us */
190         char exten[AST_MAX_EXTENSION];          /* Extention where to start */
191         char refer_to[AST_MAX_EXTENSION];       /* Place to store REFER-TO extension */
192         char referred_by[AST_MAX_EXTENSION];/* Place to store REFERRED-BY extension */
193         char refer_contact[AST_MAX_EXTENSION];/* Place to store Contact info from a REFER extension */
194         struct sip_pvt *refer_call;                     /* Call we are referring */
195         struct sip_route *route;                        /* Head of linked list of routing steps (fm Record-Route) */
196         char remote_party_id[256];
197         char context[AST_MAX_EXTENSION];
198         char fromdomain[AST_MAX_EXTENSION];     /* Domain to show in the from field */
199         char fromuser[AST_MAX_EXTENSION];       /* Domain to show in the user field */
200         char tohost[AST_MAX_EXTENSION];         /* Host we should put in the "to" field */
201         char language[MAX_LANGUAGE];
202         char theirtag[256];                             /* Their tag */
203         char username[81];
204         char peername[81];
205         char uri[81];                                   /* Original requested URI */
206         char peersecret[81];
207         char callerid[256];                                     /* Caller*ID */
208         char via[256];
209         char accountcode[20];                           /* Account code */
210         char our_contact[256];                          /* Our contact header */
211         char realm[256];                                /* Authorization realm */
212         char nonce[256];                                /* Authorization nonce */
213         int amaflags;                                           /* AMA Flags */
214         int pendinginvite;                                      /* Any pending invite */
215         int pendingbye;                                         /* Need to send bye after we ack? */
216         struct sip_request initreq;                     /* Initial request */
217         
218         int maxtime;                                            /* Max time for first response */
219         int initid;                                                     /* Auto-congest ID if appropriate */
220         int autokillid;                                         /* Auto-kill ID */
221
222         int subscribed;
223         int stateid;
224         int dialogver;
225         
226         int dtmfmode;
227         struct ast_dsp *vad;
228         
229         struct sip_peer *peerpoke;                      /* If this calls is to poke a peer, which one */
230         struct sip_registry *registry;                  /* If this is a REGISTER call, to which registry */
231         struct ast_rtp *rtp;                            /* RTP Session */
232         struct sip_pkt *packets;                        /* Packets scheduled for re-transmission */
233         struct sip_pvt *next;
234 } *iflist = NULL;
235
236 struct sip_pkt {
237         struct sip_pkt *next;                           /* Next packet */
238         int retrans;                                            /* Retransmission number */
239         int seqno;                                                      /* Sequence number */
240         int resp;                                                       /* non-zero if this is a response packet (e.g. 200 OK) */
241         struct sip_pvt *owner;                          /* Owner call */
242         int retransid;                                          /* Retransmission ID */
243         int packetlen;                                          /* Length of packet */
244         char data[0];
245 };      
246
247 struct sip_user {
248         /* Users who can access various contexts */
249         char name[80];
250         char secret[80];
251         char context[80];
252         char callerid[80];
253         char methods[80];
254         char accountcode[20];
255         unsigned int callgroup;
256         unsigned int pickupgroup;
257         int nat;
258         int hascallerid;
259         int amaflags;
260         int insecure;
261         int canreinvite;
262         int dtmfmode;
263         struct ast_ha *ha;
264         struct sip_user *next;
265 };
266
267 struct sip_peer {
268         char name[80];
269         char secret[80];
270         char context[80];               /* JK02: peers need context too to allow parking etc */
271         char methods[80];
272         char username[80];
273         char tohost[80];
274         char fromuser[80];
275         char fromdomain[80];
276         char mailbox[AST_MAX_EXTENSION];
277         int lastmsgssent;
278         time_t  lastmsgcheck;
279         int dynamic;
280         int expire;
281         int expiry;
282         int capability;
283         int insecure;
284         int nat;
285         int canreinvite;
286         unsigned int callgroup;
287         unsigned int pickupgroup;
288         int dtmfmode;
289         struct sockaddr_in addr;
290         struct in_addr mask;
291
292         /* Qualification */
293         struct sip_pvt *call;           /* Call pointer */
294         int pokeexpire;                         /* When to expire poke */
295         int lastms;                                     /* How long last response took (in ms), or -1 for no response */
296         int maxms;                                      /* Max ms we will accept for the host to be up, 0 to not monitor */
297         struct timeval ps;                      /* Ping send time */
298         
299         struct sockaddr_in defaddr;
300         struct ast_ha *ha;
301         int delme;
302         int lastmsg;
303         struct sip_peer *next;
304 };
305
306 static struct ast_user_list {
307         struct sip_user *users;
308         pthread_mutex_t lock;
309 } userl = { NULL, AST_MUTEX_INITIALIZER };
310
311 static struct ast_peer_list {
312         struct sip_peer *peers;
313         pthread_mutex_t lock;
314 } peerl = { NULL, AST_MUTEX_INITIALIZER };
315
316
317 #define REG_STATE_UNREGISTERED 0
318 #define REG_STATE_REGSENT          1
319 #define REG_STATE_AUTHSENT         2
320 #define REG_STATE_REGISTERED   3
321 #define REG_STATE_REJECTED         4
322 #define REG_STATE_TIMEOUT          5
323 #define REG_STATE_NOAUTH           6
324
325 struct sip_registry {
326         pthread_mutex_t lock;                           /* Channel private lock */
327         struct sockaddr_in addr;                /* Who we connect to for registration purposes */
328         char username[80];                              /* Who we are registering as */
329         char authuser[80];                              /* Who we *authenticate* as */
330         char hostname[80];
331         char secret[80];                        /* Password or key name in []'s */
332         char contact[80];                       /* Contact extension */
333         char random[80];
334         int expire;                                     /* Sched ID of expiration */
335         int timeout;                                    /* sched id of sip_reg_timeout */
336         int refresh;                                    /* How often to refresh */
337         struct sip_pvt *call;                           /* create a sip_pvt structure for each outbound "registration call" in progress */
338         int regstate;
339         int callid_valid;               /* 0 means we haven't chosen callid for this registry yet. */
340         char callid[80];                /* Global CallID for this registry */
341         unsigned int ocseq;             /* Sequence number we got to for REGISTERs for this registry */
342         struct sockaddr_in us;                  /* Who the server thinks we are */
343         struct sip_registry *next;
344 };
345
346 #define REINVITE_INVITE         1
347 #define REINVITE_UPDATE         2
348
349 static int sip_do_register(struct sip_registry *r);
350 static struct sip_registry *registrations;
351
352 static int sipsock  = -1;
353 static int globalnat = 0;
354
355 static struct sockaddr_in bindaddr;
356
357 static struct ast_frame  *sip_read(struct ast_channel *ast);
358 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
359 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
360 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *rand, int reliable);
361 static int transmit_request(struct sip_pvt *p, char *msg, int inc, int reliable);
362 static int transmit_request_with_auth(struct sip_pvt *p, char *msg, int inc, int reliable);
363 static int transmit_invite(struct sip_pvt *p, char *msg, int sendsdp, char *auth, char *vxml_url);
364 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp);
365 static int transmit_info_with_digit(struct sip_pvt *p, char digit);
366 static int transmit_message_with_text(struct sip_pvt *p, char *text);
367 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req);
368 static char *getsipuri(char *header);
369 static void free_old_route(struct sip_route *route);
370 static int build_reply_digest(struct sip_pvt *p, char *orig_header, char *digest, int digest_len);
371
372 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
373 {
374         int res;
375         if (p->nat)
376             res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->recv, sizeof(struct sockaddr_in));
377         else
378             res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
379         if (res != len) {
380                 ast_log(LOG_WARNING, "sip_xmit of %p (len %d) to %s returned %d: %s\n", data, len, inet_ntoa(p->sa.sin_addr), res, strerror(errno));
381         }
382         return res;
383 }
384
385 static void sip_destroy(struct sip_pvt *p);
386
387 static int retrans_pkt(void *data)
388 {
389         struct sip_pkt *pkt=data;
390         int res = 0;
391         ast_pthread_mutex_lock(&pkt->owner->lock);
392         if (1 /* !p->owner->needdestroy */) {
393                 if (pkt->retrans < MAX_RETRANS) {
394                         pkt->retrans++;
395                         if (sipdebug) {
396                                 if (pkt->owner->nat)
397                                         ast_verbose("Retransmitting #%d (NAT):\n%s\n to %s:%d\n", pkt->retrans, pkt->data, inet_ntoa(pkt->owner->recv.sin_addr), ntohs(pkt->owner->recv.sin_port));
398                                 else
399                                         ast_verbose("Retransmitting #%d (no NAT):\n%s\n to %s:%d\n", pkt->retrans, pkt->data, inet_ntoa(pkt->owner->sa.sin_addr), ntohs(pkt->owner->sa.sin_port));
400                         }
401                         __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
402                         res = 1;
403                 } else {
404                         ast_log(LOG_WARNING, "Maximum retries exceeded on call %s for seqno %d (%s)\n", pkt->owner->callid, pkt->seqno, pkt->resp ? "Response" : "Request");
405                         pkt->retransid = -1;
406                         if (pkt->owner->owner) {
407                                 /* XXX Potential deadlocK?? XXX */
408                                 ast_queue_hangup(pkt->owner->owner, 1);
409                         } else {
410                                 /* If no owner, destroy now */
411                                 ast_pthread_mutex_unlock(&pkt->owner->lock);
412                                 sip_destroy(pkt->owner);
413                                 pkt = NULL;
414                         }
415                 }
416         } else {
417                 /* Don't bother retransmitting.  It's about to be killed anyway */
418                 pkt->retransid = -1;
419                 if (pkt->owner->owner) {
420                         /* XXX Potential deadlocK?? XXX */
421                         ast_queue_hangup(pkt->owner->owner, 1);
422                 } else {
423                         /* If no owner, destroy now */
424                         ast_pthread_mutex_unlock(&pkt->owner->lock);
425                         sip_destroy(pkt->owner);
426                         pkt=NULL;
427                 }
428         }
429         if (pkt)
430                 ast_pthread_mutex_unlock(&pkt->owner->lock);
431         return res;
432 }
433
434 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len)
435 {
436         struct sip_pkt *pkt;
437         pkt = malloc(sizeof(struct sip_pkt) + len);
438         if (!pkt)
439                 return -1;
440         memset(pkt, 0, sizeof(struct sip_pkt));
441         memcpy(pkt->data, data, len);
442         pkt->packetlen = len;
443         pkt->next = p->packets;
444         pkt->owner = p;
445         pkt->seqno = seqno;
446         pkt->resp = resp;
447         /* Schedule retransmission */
448         pkt->retransid = ast_sched_add(sched, 1000, retrans_pkt, pkt);
449         pkt->next = p->packets;
450         p->packets = pkt;
451         __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
452         if (!strncasecmp(pkt->data, "INVITE", 6)) {
453                 /* Note this is a pending invite */
454                 p->pendinginvite = seqno;
455         }
456         return 0;
457 }
458
459 static int __sip_autodestruct(void *data)
460 {
461         struct sip_pvt *p = data;
462         p->autokillid = -1;
463         ast_log(LOG_DEBUG, "Auto destroying call '%s'\n", p->callid);
464         if (p->owner) {
465                 ast_log(LOG_WARNING, "Autodestruct on call '%s' with owner in place\n", p->callid);
466                 ast_queue_hangup(p->owner, 0);
467         } else {
468                 sip_destroy(p);
469         }
470         return 0;
471 }
472
473 static int sip_scheddestroy(struct sip_pvt *p, int ms)
474 {
475         if (p->autokillid > -1)
476                 ast_sched_del(sched, p->autokillid);
477         p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
478         return 0;
479 }
480
481 static int sip_cancel_destroy(struct sip_pvt *p)
482 {
483         if (p->autokillid > -1)
484                 ast_sched_del(sched, p->autokillid);
485         p->autokillid = -1;
486         return 0;
487 }
488
489 static int __sip_ack(struct sip_pvt *p, int seqno, int resp)
490 {
491         struct sip_pkt *cur, *prev = NULL;
492         int res = -1;
493         int resetinvite = 0;
494         cur = p->packets;
495         while(cur) {
496                 if ((cur->seqno == seqno) && (cur->resp == resp)) {
497                         if (!resp && (seqno == p->pendinginvite)) {
498                                 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
499                                 p->pendinginvite = 0;
500                                 resetinvite = 1;
501                         }
502                         /* this is our baby */
503                         if (prev)
504                                 prev->next = cur->next;
505                         else
506                                 p->packets = cur->next;
507                         if (cur->retransid > -1)
508                                 ast_sched_del(sched, cur->retransid);
509                         free(cur);
510                         res = 0;
511                         break;
512                 }
513                 prev = cur;
514                 cur = cur->next;
515         }
516         ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
517         return res;
518 }
519
520 static int send_response(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
521 {
522         int res;
523         if (sipdebug) {
524                 if (p->nat)
525                         ast_verbose("%sTransmitting (NAT):\n%s\n to %s:%d\n", reliable ? "Reliably " : "", req->data, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
526                 else
527                         ast_verbose("%sTransmitting (no NAT):\n%s\n to %s:%d\n", reliable ? "Reliably " : "", req->data, inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
528         }
529         if (reliable)
530                 res = __sip_reliable_xmit(p, seqno, 1, req->data, req->len);
531         else
532                 res = __sip_xmit(p, req->data, req->len);
533         if (res > 0)
534                 res = 0;
535         return res;
536 }
537
538 static int send_request(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
539 {
540         int res;
541         if (sipdebug) {
542                 if (p->nat)
543                         ast_verbose("%sTransmitting:\n%s (NAT) to %s:%d\n", reliable ? "Reliably " : "", req->data, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
544                 else
545                         ast_verbose("%sTransmitting:\n%s (no NAT) to %s:%d\n", reliable ? "Reliably " : "", req->data, inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
546         }
547         if (reliable)
548                 res = __sip_reliable_xmit(p, seqno, 0, req->data, req->len);
549         else
550                 res = __sip_xmit(p, req->data, req->len);
551         return res;
552 }
553
554 static char *ditch_braces(char *tmp)
555 {
556         char *c = tmp;
557         char *n;
558         c = tmp;
559         if ((n = strchr(tmp, '<')) ) {
560                 c = n + 1;
561                 while(*c && *c != '>') c++;
562                 if (*c != '>') {
563                         ast_log(LOG_WARNING, "No closing brace in '%s'\n", tmp);
564                 } else {
565                         *c = '\0';
566                 }
567                 return n+1;
568         }
569         return c;
570 }
571
572 static int sip_sendtext(struct ast_channel *ast, char *text)
573 {
574         struct sip_pvt *p = ast->pvt->pvt;
575         if (sipdebug) 
576                 ast_verbose("Sending text %s on %s\n", text, ast->name);
577         if (!p)
578                 return -1;
579         if (!text || !strlen(text))
580                 return 0;
581         if (sipdebug)
582                 ast_verbose("Really sending text %s on %s\n", text, ast->name);
583         transmit_message_with_text(p, text);
584         return 0;       
585 }
586
587 static int create_addr(struct sip_pvt *r, char *peer)
588 {
589         struct hostent *hp;
590         struct sip_peer *p;
591         int found=0;
592         char *port;
593
594         r->sa.sin_family = AF_INET;
595         ast_pthread_mutex_lock(&peerl.lock);
596         p = peerl.peers;
597         while(p) {
598                 if (!strcasecmp(p->name, peer)) {
599                         found++;
600                         r->capability = p->capability;
601                         r->nat = p->nat;
602                         if (r->rtp) {
603                                 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", r->nat);
604                                 ast_rtp_setnat(r->rtp, r->nat);
605                         }
606                         strncpy(r->peername, p->username, sizeof(r->peername)-1);
607                         strncpy(r->peersecret, p->secret, sizeof(r->peersecret)-1);
608                         strncpy(r->username, p->username, sizeof(r->username)-1);
609                         strncpy(r->tohost, p->tohost, sizeof(r->tohost)-1);
610                         if (!strlen(r->tohost)) {
611                                 if (p->addr.sin_addr.s_addr)
612                                         snprintf(r->tohost, sizeof(r->tohost), inet_ntoa(p->addr.sin_addr));
613                                 else
614                                         snprintf(r->tohost, sizeof(r->tohost), inet_ntoa(p->defaddr.sin_addr));
615                         }
616                         if (strlen(p->fromdomain))
617                                 strncpy(r->fromdomain, p->fromdomain, sizeof(r->fromdomain)-1);
618                         if (strlen(p->fromuser))
619                                 strncpy(r->fromuser, p->fromuser, sizeof(r->fromuser)-1);
620                         r->insecure = p->insecure;
621                         r->canreinvite = p->canreinvite;
622                         r->maxtime = p->maxms;
623                         r->callgroup = p->callgroup;
624                         r->pickupgroup = p->pickupgroup;
625                         if (p->dtmfmode) {
626                                 r->dtmfmode = p->dtmfmode;
627                                 if (r->dtmfmode & SIP_DTMF_RFC2833)
628                                         r->noncodeccapability |= AST_RTP_DTMF;
629                                 else
630                                         r->noncodeccapability &= ~AST_RTP_DTMF;
631                         }
632                         strncpy(r->context, p->context,sizeof(r->context)-1);
633                         if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
634                                 (!p->maxms || ((p->lastms > 0)  && (p->lastms <= p->maxms)))) {
635                                 if (p->addr.sin_addr.s_addr) {
636                                         r->sa.sin_addr = p->addr.sin_addr;
637                                         r->sa.sin_port = p->addr.sin_port;
638                                 } else {
639                                         r->sa.sin_addr = p->defaddr.sin_addr;
640                                         r->sa.sin_port = p->defaddr.sin_port;
641                                 }
642                                 memcpy(&r->recv, &r->sa, sizeof(r->recv));
643                                 break;
644                         }
645                 }
646                 p = p->next;
647         }
648         ast_pthread_mutex_unlock(&peerl.lock);
649         if (!p && !found) {
650                 if ((port=strchr(peer, ':'))) {
651                         *port='\0';
652                         port++;
653                 }
654                 hp = gethostbyname(peer);
655                 if (hp) {
656                         strncpy(r->tohost, peer, sizeof(r->tohost) - 1);
657                         memcpy(&r->sa.sin_addr, hp->h_addr, sizeof(r->sa.sin_addr));
658                         if (port) {
659                                 r->sa.sin_port = htons(atoi(port));
660                         } else {
661                                 r->sa.sin_port = htons(DEFAULT_SIP_PORT);
662                         }
663                         memcpy(&r->recv, &r->sa, sizeof(r->recv));
664                         return 0;
665                 } else {
666                         ast_log(LOG_WARNING, "No such host: %s\n", peer);
667                         return -1;
668                 }
669         } else if (!p)
670                 return -1;
671         else
672                 return 0;
673 }
674
675 static int auto_congest(void *nothing)
676 {
677         struct sip_pvt *p = nothing;
678         ast_pthread_mutex_lock(&p->lock);
679         p->initid = -1;
680         if (p->owner) {
681                 if (!pthread_mutex_trylock(&p->owner->lock)) {
682                         ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
683                         ast_queue_control(p->owner, AST_CONTROL_CONGESTION, 0);
684                         ast_pthread_mutex_unlock(&p->owner->lock);
685                 }
686         }
687         ast_pthread_mutex_unlock(&p->lock);
688         return 0;
689 }
690
691 static void sip_prefs_free(void)
692 {
693         struct sip_codec_pref *cur, *next;
694         cur = prefs;
695         while(cur) {
696                 next = cur->next;
697                 free(cur);
698                 cur = next;
699         }
700         prefs = NULL;
701 }
702
703 static void sip_pref_remove(int format)
704 {
705         struct sip_codec_pref *cur, *prev=NULL;
706         cur = prefs;
707         while(cur) {
708                 if (cur->codec == format) {
709                         if (prev)
710                                 prev->next = cur->next;
711                         else
712                                 prefs = cur->next;
713                         free(cur);
714                         return;
715                 }
716                 prev = cur;
717                 cur = cur->next;
718         }
719 }
720
721 static int sip_pref_append(int format)
722 {
723         struct sip_codec_pref *cur, *tmp;
724         sip_pref_remove(format);
725         tmp = (struct sip_codec_pref *)malloc(sizeof(struct sip_codec_pref));
726         if (!tmp)
727                 return -1;
728         memset(tmp, 0, sizeof(struct sip_codec_pref));
729         tmp->codec = format;
730         if (prefs) {
731                 cur = prefs;
732                 while(cur->next)
733                         cur = cur->next;
734                 cur->next = tmp;
735         } else
736                 prefs = tmp;
737         return 0;
738 }
739
740 static int sip_codec_choose(int formats)
741 {
742         struct sip_codec_pref *cur;
743         cur = prefs;
744         while(cur) {
745                 if (formats & cur->codec)
746                         return cur->codec;
747                 cur = cur->next;
748         }
749         return ast_best_codec(formats);
750 }
751
752 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
753 {
754         int res;
755         struct sip_pvt *p;
756         char *vxml_url = NULL;
757         struct varshead *headp;
758         struct ast_var_t *current;
759         
760         p = ast->pvt->pvt;
761         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
762                 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
763                 return -1;
764         }
765
766         /* Check whether there is a VXML_URL variable */
767         headp=&ast->varshead;
768         AST_LIST_TRAVERSE(headp,current,entries) {
769                 if (strcasecmp(ast_var_name(current),"VXML_URL")==0)
770                 {
771                         vxml_url = ast_var_value(current);
772                         break;
773                 }
774         }
775         
776         res = 0;
777         p->outgoing = 1;
778         transmit_invite(p, "INVITE", 1, NULL, vxml_url);
779         if (p->maxtime) {
780                 /* Initialize auto-congest time */
781                 p->initid = ast_sched_add(sched, p->maxtime * 2, auto_congest, p);
782         }
783         return res;
784 }
785
786 static void __sip_destroy(struct sip_pvt *p, int lockowner)
787 {
788         struct sip_pvt *cur, *prev = NULL;
789         struct sip_pkt *cp;
790         if (sipdebug)
791                 ast_log(LOG_DEBUG, "Destorying call '%s'\n", p->callid);
792         if (p->stateid > -1)
793                 ast_extension_state_del(p->stateid, NULL);
794         if (p->initid > -1)
795                 ast_sched_del(sched, p->initid);
796         if (p->autokillid > -1)
797                 ast_sched_del(sched, p->autokillid);
798
799         if (p->rtp) {
800                 ast_rtp_destroy(p->rtp);
801         }
802         if (p->route) {
803                 free_old_route(p->route);
804                 p->route = NULL;
805         }
806         /* Unlink us from the owner if we have one */
807         if (p->owner) {
808                 if (lockowner)
809                         ast_pthread_mutex_lock(&p->owner->lock);
810                 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
811                 p->owner->pvt->pvt = NULL;
812                 if (lockowner)
813                         ast_pthread_mutex_unlock(&p->owner->lock);
814         }
815         cur = iflist;
816         while(cur) {
817                 if (cur == p) {
818                         if (prev)
819                                 prev->next = cur->next;
820                         else
821                                 iflist = cur->next;
822                         break;
823                 }
824                 prev = cur;
825                 cur = cur->next;
826         }
827         if (!cur) {
828                 ast_log(LOG_WARNING, "%p is not in list?!?! \n", cur);
829         } else {
830                 if (p->initid > -1)
831                         ast_sched_del(sched, p->initid);
832                 while((cp = p->packets)) {
833                         p->packets = p->packets->next;
834                         if (cp->retransid > -1)
835                                 ast_sched_del(sched, cp->retransid);
836                         free(cp);
837                 }
838                 free(p);
839         }
840 }
841 static void sip_destroy(struct sip_pvt *p)
842 {
843         ast_pthread_mutex_lock(&iflock);
844         __sip_destroy(p, 1);
845         ast_pthread_mutex_unlock(&iflock);
846 }
847
848 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req);
849
850
851 static int sip_hangup(struct ast_channel *ast)
852 {
853         struct sip_pvt *p = ast->pvt->pvt;
854         int needcancel = 0;
855         int needdestroy = 0;
856         if (option_debug)
857                 ast_log(LOG_DEBUG, "sip_hangup(%s)\n", ast->name);
858         if (!ast->pvt->pvt) {
859                 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
860                 return 0;
861         }
862         ast_pthread_mutex_lock(&p->lock);
863         /* Determine how to disconnect */
864         if (p->owner != ast) {
865                 ast_log(LOG_WARNING, "Huh?  We aren't the owner?\n");
866                 ast_pthread_mutex_unlock(&p->lock);
867                 return 0;
868         }
869         if (!ast || (ast->_state != AST_STATE_UP))
870                 needcancel = 1;
871         /* Disconnect */
872         p = ast->pvt->pvt;
873         if (p->vad) {
874             ast_dsp_free(p->vad);
875         }
876         p->owner = NULL;
877         ast->pvt->pvt = NULL;
878
879         needdestroy = 1;
880         /* Start the process if it's not already started */
881         if (!p->alreadygone && strlen(p->initreq.data)) {
882                 if (needcancel) {
883                         if (p->outgoing) {
884                                 transmit_request_with_auth(p, "CANCEL", p->ocseq, 1);
885                                 /* Actually don't destroy us yet, wait for the 487 on our original 
886                                    INVITE, but do set an autodestruct just in case. */
887                                 needdestroy = 0;
888                                 sip_scheddestroy(p, 15000);
889                         } else
890                                 transmit_response_reliable(p, "403 Forbidden", &p->initreq);
891                 } else {
892                         if (!p->pendinginvite) {
893                                 /* Send a hangup */
894                                 transmit_request_with_auth(p, "BYE", 0, 1);
895                         } else {
896                                 /* Note we will need a BYE when this all settles out
897                                    but we can't send one while we have "INVITE" outstanding. */
898                                 p->pendingbye = 1;
899                         }
900                 }
901         }
902         p->needdestroy = needdestroy;
903         ast_pthread_mutex_unlock(&p->lock);
904         return 0;
905 }
906
907 static int sip_answer(struct ast_channel *ast)
908 {
909         int res = 0,fmt;
910         char *codec;
911         struct sip_pvt *p = ast->pvt->pvt;
912
913         
914         if (ast->_state != AST_STATE_UP) {
915         
916         
917         
918                 codec=pbx_builtin_getvar_helper(p->owner,"SIP_CODEC");
919                 if (codec) {
920                         ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n",codec);
921                         fmt=ast_getformatbyname(codec);
922                         if (fmt) {
923                                 p->capability=fmt;
924                         } else ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized codec: %s\n",codec);
925                 }
926
927                 ast_setstate(ast, AST_STATE_UP);
928                 if (option_debug)
929                         ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name);
930                 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, 1);
931         }
932         return res;
933 }
934
935 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
936 {
937         struct sip_pvt *p = ast->pvt->pvt;
938         int res = 0;
939         if (frame->frametype != AST_FRAME_VOICE) {
940                 if (frame->frametype == AST_FRAME_IMAGE)
941                         return 0;
942                 else {
943                         ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
944                         return 0;
945                 }
946         } else {
947                 if (!(frame->subclass & ast->nativeformats)) {
948                         ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
949                                 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
950                         return -1;
951                 }
952         }
953         if (p) {
954                 ast_pthread_mutex_lock(&p->lock);
955                 if (p->rtp) {
956                         if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
957                                 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
958                                 p->progress = 1;
959                         }
960                         res =  ast_rtp_write(p->rtp, frame);
961                 }
962                 ast_pthread_mutex_unlock(&p->lock);
963         }
964         return res;
965 }
966
967 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
968 {
969         struct sip_pvt *p = newchan->pvt->pvt;
970         ast_pthread_mutex_lock(&p->lock);
971         if (p->owner != oldchan) {
972                 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
973                 ast_pthread_mutex_unlock(&p->lock);
974                 return -1;
975         }
976         p->owner = newchan;
977         ast_pthread_mutex_unlock(&p->lock);
978         return 0;
979 }
980
981 static int sip_senddigit(struct ast_channel *ast, char digit)
982 {
983         struct sip_pvt *p = ast->pvt->pvt;
984         if (p && (p->dtmfmode & SIP_DTMF_INFO)) {
985                 transmit_info_with_digit(p, digit);
986         }
987         if (p && p->rtp && (p->dtmfmode & SIP_DTMF_RFC2833)) {
988                 ast_rtp_senddigit(p->rtp, digit);
989         }
990         /* If in-band DTMF is desired, send that */
991         if (p->dtmfmode & SIP_DTMF_INBAND)
992                 return -1;
993         return 0;
994 }
995
996 static int sip_indicate(struct ast_channel *ast, int condition)
997 {
998         struct sip_pvt *p = ast->pvt->pvt;
999         switch(condition) {
1000         case AST_CONTROL_RINGING:
1001                 if (ast->_state == AST_STATE_RING) {
1002                         if (!p->progress) {
1003                                 transmit_response(p, "180 Ringing", &p->initreq);
1004                                 break;
1005                         } else {
1006                                 /* Oops, we've sent progress tones.  Let Asterisk do it instead */
1007                         }
1008                 }
1009                 return -1;
1010         case AST_CONTROL_BUSY:
1011                 if (ast->_state != AST_STATE_UP) {
1012                         transmit_response(p, "486 Busy Here", &p->initreq);
1013                         p->alreadygone = 1;
1014                         ast_softhangup(ast, AST_SOFTHANGUP_DEV);
1015                         break;
1016                 }
1017                 return -1;
1018         case AST_CONTROL_CONGESTION:
1019                 if (ast->_state != AST_STATE_UP) {
1020                         transmit_response(p, "503 Service Unavailable", &p->initreq);
1021                         p->alreadygone = 1;
1022                         ast_softhangup(ast, AST_SOFTHANGUP_DEV);
1023                         break;
1024                 }
1025                 return -1;
1026         case -1:
1027                 return -1;
1028         default:
1029                 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
1030                 return -1;
1031         }
1032         return 0;
1033 }
1034
1035
1036
1037 static struct ast_channel *sip_new(struct sip_pvt *i, int state, char *title)
1038 {
1039         struct ast_channel *tmp;
1040         int fmt;
1041         tmp = ast_channel_alloc(1);
1042         if (tmp) {
1043                 /* Select our native format based on codec preference until we receive
1044                    something from another device to the contrary. */
1045                 if (i->capability)
1046                         tmp->nativeformats = sip_codec_choose(i->capability);
1047                 else 
1048                         tmp->nativeformats = sip_codec_choose(capability);
1049                 fmt = ast_best_codec(tmp->nativeformats);
1050                 if (title)
1051                         snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%04x", title, rand() & 0xffff);
1052                 else
1053                         snprintf(tmp->name, sizeof(tmp->name), "SIP/%s:%d", inet_ntoa(i->sa.sin_addr), ntohs(i->sa.sin_port));
1054                 tmp->type = type;
1055                 if (i->dtmfmode & SIP_DTMF_INBAND) {
1056                     i->vad = ast_dsp_new();
1057                     ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
1058                 }
1059                 tmp->fds[0] = ast_rtp_fd(i->rtp);
1060                 ast_setstate(tmp, state);
1061                 if (state == AST_STATE_RING)
1062                         tmp->rings = 1;
1063                 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
1064                 tmp->writeformat = fmt;
1065                 tmp->pvt->rawwriteformat = fmt;
1066                 tmp->readformat = fmt;
1067                 tmp->pvt->rawreadformat = fmt;
1068                 tmp->pvt->pvt = i;
1069                 tmp->pvt->send_text = sip_sendtext;
1070                 tmp->pvt->call = sip_call;
1071                 tmp->pvt->hangup = sip_hangup;
1072                 tmp->pvt->answer = sip_answer;
1073                 tmp->pvt->read = sip_read;
1074                 tmp->pvt->write = sip_write;
1075                 tmp->pvt->indicate = sip_indicate;
1076                 tmp->pvt->fixup = sip_fixup;
1077                 tmp->pvt->send_digit = sip_senddigit;
1078                 tmp->pvt->bridge = ast_rtp_bridge;
1079                 tmp->callgroup = i->callgroup;
1080                 tmp->pickupgroup = i->pickupgroup;
1081                 if (strlen(i->accountcode))
1082                         strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
1083                 if (i->amaflags)
1084                         tmp->amaflags = i->amaflags;
1085                 if (strlen(i->language))
1086                         strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
1087                 i->owner = tmp;
1088                 ast_pthread_mutex_lock(&usecnt_lock);
1089                 usecnt++;
1090                 ast_pthread_mutex_unlock(&usecnt_lock);
1091                 ast_update_use_count();
1092                 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
1093                 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
1094                 if (strlen(i->callerid))
1095                         tmp->callerid = strdup(i->callerid);
1096                 tmp->priority = 1;
1097                 if (state != AST_STATE_DOWN) {
1098                         if (ast_pbx_start(tmp)) {
1099                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
1100                                 ast_hangup(tmp);
1101                                 tmp = NULL;
1102                         }
1103                 }
1104         } else
1105                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
1106         return tmp;
1107 }
1108
1109 static struct cfalias {
1110         char *fullname;
1111         char *shortname;
1112 } aliases[] = {
1113         { "Content-Type", "c" },
1114         { "Content-Encoding", "e" },
1115         { "From", "f" },
1116         { "Call-ID", "i" },
1117         { "Contact", "m" },
1118         { "Content-Length", "l" },
1119         { "Subject", "s" },
1120         { "To", "t" },
1121         { "Via", "v" },
1122 };
1123
1124 static char* get_sdp_by_line(char* line, char *name, int nameLen) {
1125   if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
1126     char* r = line + nameLen + 1;
1127     while (*r && (*r < 33)) ++r;
1128     return r;
1129   }
1130
1131   return "";
1132 }
1133
1134 static char *get_sdp(struct sip_request *req, char *name) {
1135   int x;
1136   int len = strlen(name);
1137   char *r;
1138
1139   for (x=0; x<req->lines; x++) {
1140     r = get_sdp_by_line(req->line[x], name, len);
1141     if (r[0] != '\0') return r;
1142   }
1143   return "";
1144 }
1145
1146 static void sdpLineNum_iterator_init(int* iterator) {
1147   *iterator = 0;
1148 }
1149
1150 static char* get_sdp_iterate(int* iterator,
1151                              struct sip_request *req, char *name) {
1152   int len = strlen(name);
1153   char *r;
1154   while (*iterator < req->lines) {
1155     r = get_sdp_by_line(req->line[(*iterator)++], name, len);
1156     if (r[0] != '\0') return r;
1157   }
1158   return "";
1159 }
1160
1161 static char *__get_header(struct sip_request *req, char *name, int *start)
1162 {
1163         int x;
1164         int len = strlen(name);
1165         char *r;
1166         for (x=*start;x<req->headers;x++) {
1167                 if (!strncasecmp(req->header[x], name, len) && 
1168                                 (req->header[x][len] == ':')) {
1169                                         r = req->header[x] + len + 1;
1170                                         while(*r && (*r < 33))
1171                                                         r++;
1172                                         *start = x+1;
1173                                         return r;
1174                 }
1175         }
1176         /* Try aliases */
1177         for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++) 
1178                 if (!strcasecmp(aliases[x].fullname, name))
1179                         return __get_header(req, aliases[x].shortname, start);
1180
1181         /* Don't return NULL, so get_header is always a valid pointer */
1182         return "";
1183 }
1184
1185 static char *get_header(struct sip_request *req, char *name)
1186 {
1187         int start = 0;
1188         return __get_header(req, name, &start);
1189 }
1190
1191 static struct ast_frame *sip_rtp_read(struct sip_pvt *p)
1192 {
1193         /* Retrieve audio/etc from channel.  Assumes p->lock is already held. */
1194         struct ast_frame *f;
1195         static struct ast_frame null_frame = { AST_FRAME_NULL, };
1196         f = ast_rtp_read(p->rtp);
1197         /* Don't send RFC2833 if we're not supposed to */
1198         if (f && (f->frametype == AST_FRAME_DTMF) && !(p->dtmfmode & SIP_DTMF_RFC2833))
1199                 return &null_frame;
1200         if (p->owner) {
1201                 /* We already hold the channel lock */
1202                 if (f->frametype == AST_FRAME_VOICE) {
1203                         if (f->subclass != p->owner->nativeformats) {
1204                                 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
1205                                 p->owner->nativeformats = f->subclass;
1206                                 ast_set_read_format(p->owner, p->owner->readformat);
1207                                 ast_set_write_format(p->owner, p->owner->writeformat);
1208                         }
1209             if (p->dtmfmode & SIP_DTMF_INBAND) {
1210                    f = ast_dsp_process(p->owner,p->vad,f,0);
1211             }
1212                 }
1213         }
1214         return f;
1215 }
1216
1217 static struct ast_frame *sip_read(struct ast_channel *ast)
1218 {
1219         struct ast_frame *fr;
1220         struct sip_pvt *p = ast->pvt->pvt;
1221         ast_pthread_mutex_lock(&p->lock);
1222         fr = sip_rtp_read(p);
1223         ast_pthread_mutex_unlock(&p->lock);
1224         return fr;
1225 }
1226
1227 static void build_callid(char *callid, int len, struct in_addr ourip)
1228 {
1229         int res;
1230         int val;
1231         int x;
1232         for (x=0;x<4;x++) {
1233                 val = rand();
1234                 res = snprintf(callid, len, "%08x", val);
1235                 len -= res;
1236                 callid += res;
1237         }
1238         /* It's not important that we really use our right IP here... */
1239         snprintf(callid, len, "@%s", inet_ntoa(ourip));
1240 }
1241
1242 static struct sip_pvt *sip_alloc(char *callid, struct sockaddr_in *sin, int useglobalnat)
1243 {
1244         struct sip_pvt *p;
1245
1246         p = malloc(sizeof(struct sip_pvt));
1247         if (!p)
1248                 return NULL;
1249         /* Keep track of stuff */
1250         memset(p, 0, sizeof(struct sip_pvt));
1251         p->initid = -1;
1252         p->autokillid = -1;
1253         p->stateid = -1;
1254         p->rtp = ast_rtp_new(NULL, NULL);
1255         p->branch = rand();     
1256         p->tag = rand();
1257         
1258         /* Start with 101 instead of 1 */
1259         p->ocseq = 101;
1260         if (!p->rtp) {
1261                 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
1262                 free(p);
1263                 return NULL;
1264         }
1265         ast_rtp_settos(p->rtp, tos);
1266         if (useglobalnat && sin) {
1267                 /* Setup NAT structure according to global settings if we have an address */
1268                 p->nat = globalnat;
1269                 memcpy(&p->recv, sin, sizeof(p->recv));
1270                 ast_rtp_setnat(p->rtp, p->nat);
1271         }
1272         ast_pthread_mutex_init(&p->lock);
1273 #if 0
1274         ast_rtp_set_data(p->rtp, p);
1275         ast_rtp_set_callback(p->rtp, rtpready);
1276 #endif  
1277         if (sin) {
1278                 memcpy(&p->sa, sin, sizeof(p->sa));
1279                 if (ast_ouraddrfor(&p->sa.sin_addr,&p->ourip))
1280                         memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
1281         } else {
1282                 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
1283         }
1284         /* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
1285         snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
1286         if (!callid)
1287                 build_callid(p->callid, sizeof(p->callid), p->ourip);
1288         else
1289                 strncpy(p->callid, callid, sizeof(p->callid) - 1);
1290         /* Assume reinvite OK and via INVITE */
1291         p->canreinvite = REINVITE_INVITE;
1292         p->dtmfmode = globaldtmfmode;
1293         if (p->dtmfmode & SIP_DTMF_RFC2833)
1294                 p->noncodeccapability |= AST_RTP_DTMF;
1295         strncpy(p->context, context, sizeof(p->context) - 1);
1296         strncpy(p->fromdomain, fromdomain, sizeof(p->fromdomain) - 1);
1297         /* Add to list */
1298         ast_pthread_mutex_lock(&iflock);
1299         p->next = iflist;
1300         iflist = p;
1301         ast_pthread_mutex_unlock(&iflock);
1302         if (option_debug)
1303                 ast_log(LOG_DEBUG, "Allocating new SIP call for %s\n", callid);
1304         return p;
1305 }
1306
1307 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin)
1308 {
1309         struct sip_pvt *p;
1310         char *callid;
1311         callid = get_header(req, "Call-ID");
1312         if (!strlen(callid)) {
1313                 ast_log(LOG_WARNING, "Call missing call ID from '%s'\n", inet_ntoa(sin->sin_addr));
1314                 return NULL;
1315         }
1316         ast_pthread_mutex_lock(&iflock);
1317         p = iflist;
1318         while(p) {
1319                 if (!strcmp(p->callid, callid)) {
1320                         /* Found the call */
1321 #if 0
1322                         if (!p->insecure && ((p->sa.sin_addr.s_addr != sin->sin_addr.s_addr) ||
1323                             (p->sa.sin_port != sin->sin_port))) {
1324                                         char orig[80];
1325                                         char new[80];
1326                                         snprintf(orig, sizeof(orig), "%s:%d", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
1327                                         snprintf(new, sizeof(new), "%s:%d", inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
1328                                         ast_log(LOG_WARNING, "Looks like %s is trying to steal call '%s' from %s?\n", new, p->callid, orig);
1329                                         ast_pthread_mutex_unlock(&iflock);
1330                                         return NULL;
1331                         }
1332 #endif
1333                         ast_pthread_mutex_lock(&p->lock);
1334                         ast_pthread_mutex_unlock(&iflock);
1335                         return p;
1336                 }
1337                 p = p->next;
1338         }
1339         ast_pthread_mutex_unlock(&iflock);
1340         return sip_alloc(callid, sin, 1);
1341 }
1342
1343 static int sip_register(char *value, int lineno)
1344 {
1345         struct sip_registry *reg;
1346         char copy[256] = "";
1347         char *username=NULL, *hostname=NULL, *secret=NULL, *authuser=NULL;
1348         char *porta=NULL;
1349         char *contact=NULL;
1350         char *stringp=NULL;
1351         
1352         struct hostent *hp;
1353         if (!value)
1354                 return -1;
1355         strncpy(copy, value, sizeof(copy)-1);
1356         stringp=copy;
1357         username = stringp;
1358         hostname = strrchr(stringp, '@');
1359         if (hostname) {
1360                 *hostname = '\0';
1361                 hostname++;
1362         }
1363         if (!username || !strlen(username) || !hostname || !strlen(hostname)) {
1364                 ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port] at line %d", lineno);
1365                 return -1;
1366         }
1367         stringp=username;
1368         username = strsep(&stringp, ":");
1369         if (username) {
1370                 secret = strsep(&stringp, ":");
1371                 if (secret) 
1372                         authuser = strsep(&stringp, ":");
1373         }
1374         stringp = hostname;
1375         hostname = strsep(&stringp, "/");
1376         if (hostname) 
1377                 contact = strsep(&stringp, "/");
1378         if (!contact || !strlen(contact))
1379                 contact = "s";
1380         stringp=hostname;
1381         hostname = strsep(&stringp, ":");
1382         porta = strsep(&stringp, ":");
1383         
1384         if (porta && !atoi(porta)) {
1385                 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
1386                 return -1;
1387         }
1388         hp = gethostbyname(hostname);
1389         if (!hp) {
1390                 ast_log(LOG_WARNING, "Host '%s' not found at line %d\n", hostname, lineno);
1391                 return -1;
1392         }
1393         reg = malloc(sizeof(struct sip_registry));
1394         if (reg) {
1395                 memset(reg, 0, sizeof(struct sip_registry));
1396                 strncpy(reg->contact, contact, sizeof(reg->contact) - 1);
1397                 if (username)
1398                         strncpy(reg->username, username, sizeof(reg->username)-1);
1399                 if (hostname)
1400                         strncpy(reg->hostname, hostname, sizeof(reg->hostname)-1);
1401                 if (authuser)
1402                         strncpy(reg->authuser, authuser, sizeof(reg->authuser)-1);
1403                 if (secret)
1404                         strncpy(reg->secret, secret, sizeof(reg->secret)-1);
1405                 reg->expire = -1;
1406                 reg->timeout =  -1;
1407                 reg->refresh = default_expiry;
1408                 reg->addr.sin_family = AF_INET;
1409                 memcpy(&reg->addr.sin_addr, hp->h_addr, sizeof(&reg->addr.sin_addr));
1410                 reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(DEFAULT_SIP_PORT);
1411                 reg->next = registrations;
1412                 reg->callid_valid = 0;
1413                 reg->ocseq = 101;
1414                 registrations = reg;
1415         } else {
1416                 ast_log(LOG_ERROR, "Out of memory\n");
1417                 return -1;
1418         }
1419         return 0;
1420 }
1421
1422 static void parse(struct sip_request *req)
1423 {
1424         /* Divide fields by NULL's */
1425         char *c;
1426         int f = 0;
1427         c = req->data;
1428
1429         /* First header starts immediately */
1430         req->header[f] = c;
1431         while(*c) {
1432                 if (*c == '\n') {
1433                         /* We've got a new header */
1434                         *c = 0;
1435
1436 #if 0
1437                         printf("Header: %s (%d)\n", req->header[f], strlen(req->header[f]));
1438 #endif                  
1439                         if (!strlen(req->header[f])) {
1440                                 /* Line by itself means we're now in content */
1441                                 c++;
1442                                 break;
1443                         }
1444                         if (f >= SIP_MAX_HEADERS - 1) {
1445                                 ast_log(LOG_WARNING, "Too many SIP headers...\n");
1446                         } else
1447                                 f++;
1448                         req->header[f] = c + 1;
1449                 } else if (*c == '\r') {
1450                         /* Ignore but eliminate \r's */
1451                         *c = 0;
1452                 }
1453                 c++;
1454         }
1455         /* Check for last header */
1456         if (strlen(req->header[f])) 
1457                 f++;
1458         req->headers = f;
1459         /* Now we process any mime content */
1460         f = 0;
1461         req->line[f] = c;
1462         while(*c) {
1463                 if (*c == '\n') {
1464                         /* We've got a new line */
1465                         *c = 0;
1466 #if 0
1467                         printf("Line: %s (%d)\n", req->line[f], strlen(req->line[f]));
1468 #endif                  
1469                         if (f >= SIP_MAX_LINES - 1) {
1470                                 ast_log(LOG_WARNING, "Too many SDP lines...\n");
1471                         } else
1472                                 f++;
1473                         req->line[f] = c + 1;
1474                 } else if (*c == '\r') {
1475                         /* Ignore and eliminate \r's */
1476                         *c = 0;
1477                 }
1478                 c++;
1479         }
1480         /* Check for last line */
1481         if (strlen(req->line[f])) 
1482                 f++;
1483         req->lines = f;
1484         if (sipdebug)
1485                 ast_verbose("%d headers, %d lines\n", req->headers, req->lines);
1486         if (*c) 
1487                 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
1488 }
1489
1490 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
1491 {
1492         char *m;
1493         char *c;
1494         char *a;
1495         char host[258];
1496         int len = -1;
1497         int portno;
1498         int peercapability, peernoncodeccapability;
1499         struct sockaddr_in sin;
1500         char *codecs;
1501         struct hostent *hp;
1502         int codec;
1503         int iterator;
1504
1505         /* Get codec and RTP info from SDP */
1506         if (strcasecmp(get_header(req, "Content-Type"), "application/sdp")) {
1507                 ast_log(LOG_NOTICE, "Content is '%s', not 'application/sdp'\n", get_header(req, "Content-Type"));
1508                 return -1;
1509         }
1510         m = get_sdp(req, "m");
1511         c = get_sdp(req, "c");
1512         if (!strlen(m) || !strlen(c)) {
1513                 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
1514                 return -1;
1515         }
1516         if (sscanf(c, "IN IP4 %256s", host) != 1) {
1517                 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
1518                 return -1;
1519         }
1520         /* XXX This could block for a long time, and block the main thread! XXX */
1521         hp = gethostbyname(host);
1522         if (!hp) {
1523                 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
1524                 return -1;
1525         }
1526         if ((sscanf(m, "audio %d RTP/AVP %n", &portno, &len) != 1) || (len < 0)) {
1527                 ast_log(LOG_WARNING, "Unable to determine port number for RTP in '%s'\n", m); 
1528                 return -1;
1529         }
1530         sin.sin_family = AF_INET;
1531         memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
1532         sin.sin_port = htons(portno);
1533         if (p->rtp)
1534                 ast_rtp_set_peer(p->rtp, &sin);
1535 #if 0
1536         printf("Peer RTP is at port %s:%d\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
1537 #endif  
1538         // Scan through the RTP payload types specified in a "m=" line:
1539         ast_rtp_pt_clear(p->rtp);
1540         codecs = m + len;
1541         while(strlen(codecs)) {
1542                 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
1543                         ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
1544                         return -1;
1545                 }
1546                 ast_rtp_set_m_type(p->rtp, codec);
1547                 codecs += len;
1548                 /* Skip over any whitespace */
1549                 while(*codecs && (*codecs < 33)) codecs++;
1550         }
1551
1552         // Next, scan through each "a=rtpmap:" line, noting each
1553         // specified RTP payload type (with corresponding MIME subtype):
1554         sdpLineNum_iterator_init(&iterator);
1555         while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
1556           char* mimeSubtype = strdup(a); // ensures we have enough space
1557           if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) != 2) continue;
1558           // Note: should really look at the 'freq' and '#chans' params too
1559           ast_rtp_set_rtpmap_type(p->rtp, codec, "audio", mimeSubtype);
1560           free(mimeSubtype);
1561         }
1562
1563         // Now gather all of the codecs that were asked for:
1564         ast_rtp_get_current_formats(p->rtp,
1565                                 &peercapability, &peernoncodeccapability);
1566         p->capability = capability & peercapability;
1567         p->noncodeccapability = noncodeccapability & peernoncodeccapability;
1568         if (sipdebug) {
1569                 ast_verbose("Capabilities: us - %d, them - %d, combined - %d\n",
1570                             capability, peercapability, p->capability);
1571                 ast_verbose("Non-codec capabilities: us - %d, them - %d, combined - %d\n",
1572                             noncodeccapability, peernoncodeccapability,
1573                             p->noncodeccapability);
1574         }
1575         if (!p->capability) {
1576                 ast_log(LOG_WARNING, "No compatible codecs!\n");
1577                 return -1;
1578         }
1579         if (p->owner) {
1580                 if (!(p->owner->nativeformats & p->capability)) {
1581                         ast_log(LOG_DEBUG, "Oooh, we need to change our formats since our peer supports only %d and not %d\n", p->capability, p->owner->nativeformats);
1582                         p->owner->nativeformats = sip_codec_choose(p->capability);
1583                         ast_set_read_format(p->owner, p->owner->readformat);
1584                         ast_set_write_format(p->owner, p->owner->writeformat);
1585                 }
1586                 if (p->owner->bridge) {
1587                         /* Turn on/off music on hold if we are holding/unholding */
1588                         if (sin.sin_addr.s_addr) {
1589                                 ast_moh_stop(p->owner->bridge);
1590                         } else {
1591                                 ast_moh_start(p->owner->bridge, NULL);
1592                         }
1593                 }
1594         }
1595         return 0;
1596         
1597 }
1598
1599 static int add_header(struct sip_request *req, char *var, char *value)
1600 {
1601         if (req->len >= sizeof(req->data) - 4) {
1602                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1603                 return -1;
1604         }
1605         if (req->lines) {
1606                 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1607                 return -1;
1608         }
1609         req->header[req->headers] = req->data + req->len;
1610         snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", var, value);
1611         req->len += strlen(req->header[req->headers]);
1612         if (req->headers < SIP_MAX_HEADERS)
1613                 req->headers++;
1614         else {
1615                 ast_log(LOG_WARNING, "Out of header space\n");
1616                 return -1;
1617         }
1618         return 0;       
1619 }
1620
1621 static int add_blank_header(struct sip_request *req)
1622 {
1623         if (req->len >= sizeof(req->data) - 4) {
1624                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1625                 return -1;
1626         }
1627         if (req->lines) {
1628                 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1629                 return -1;
1630         }
1631         req->header[req->headers] = req->data + req->len;
1632         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "\r\n");
1633         req->len += strlen(req->header[req->headers]);
1634         if (req->headers < SIP_MAX_HEADERS)
1635                 req->headers++;
1636         else {
1637                 ast_log(LOG_WARNING, "Out of header space\n");
1638                 return -1;
1639         }
1640         return 0;       
1641 }
1642
1643 static int add_line(struct sip_request *req, char *line)
1644 {
1645         if (req->len >= sizeof(req->data) - 4) {
1646                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1647                 return -1;
1648         }
1649         if (!req->lines) {
1650                 /* Add extra empty return */
1651                 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
1652                 req->len += strlen(req->data + req->len);
1653         }
1654         req->line[req->lines] = req->data + req->len;
1655         snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
1656         req->len += strlen(req->line[req->lines]);
1657         if (req->lines < SIP_MAX_LINES)
1658                 req->lines++;
1659         else {
1660                 ast_log(LOG_WARNING, "Out of line space\n");
1661                 return -1;
1662         }
1663         return 0;       
1664 }
1665
1666 static int copy_header(struct sip_request *req, struct sip_request *orig, char *field)
1667 {
1668         char *tmp;
1669         tmp = get_header(orig, field);
1670         if (strlen(tmp)) {
1671                 /* Add what we're responding to */
1672                 return add_header(req, field, tmp);
1673         }
1674         ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1675         return -1;
1676 }
1677
1678 static int copy_all_header(struct sip_request *req, struct sip_request *orig, char *field)
1679 {
1680         char *tmp;
1681         int start = 0;
1682         int copied = 0;
1683         for (;;) {
1684                 tmp = __get_header(orig, field, &start);
1685                 if (strlen(tmp)) {
1686                         /* Add what we're responding to */
1687                         add_header(req, field, tmp);
1688                         copied++;
1689                 } else
1690                         break;
1691         }
1692         return copied ? 0 : -1;
1693 }
1694
1695 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, struct sip_request *orig, char *field)
1696 {
1697         char *tmp;
1698         int start = 0;
1699         int copied = 0;
1700         char new[256];
1701         for (;;) {
1702                 tmp = __get_header(orig, field, &start);
1703                 if (strlen(tmp)) {
1704                         if (!copied && p->nat) {
1705                                 /* SLD: FIXME: Nice try, but the received= should not have a port */
1706                                 /* SLD: FIXME: See RFC2543 BNF in Section 6.40.5 */
1707                                 if (ntohs(p->recv.sin_port) != DEFAULT_SIP_PORT)
1708                                         snprintf(new, sizeof(new), "%s;received=%s:%d", tmp, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
1709                                 else
1710                                         snprintf(new, sizeof(new), "%s;received=%s", tmp, inet_ntoa(p->recv.sin_addr));
1711                                 add_header(req, field, new);
1712                         } else {
1713                                 /* Add what we're responding to */
1714                                 add_header(req, field, tmp);
1715                         }
1716                         copied++;
1717                 } else
1718                         break;
1719         }
1720         if (!copied) {
1721                 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1722                 return -1;
1723         }
1724         return 0;
1725 }
1726
1727 /* Add Route: header into request per learned route */
1728 static void add_route(struct sip_request *req, struct sip_route *route)
1729 {
1730         char r[256], *p;
1731         int n, rem = 255; /* sizeof(r)-1: Room for terminating 0 */
1732
1733         if (!route) return;
1734
1735         p = r;
1736         while (route) {
1737                 n = strlen(route->hop);
1738                 if ((n+3)>rem) break;
1739                 if (p != r) {
1740                         *p++ = ',';
1741                         --rem;
1742                 }
1743                 *p++ = '<';
1744                 strcpy(p, route->hop);  p += n;
1745                 *p++ = '>';
1746                 rem -= (n+2);
1747                 route = route->next;
1748         }
1749         *p = '\0';
1750         add_header(req, "Route", r);
1751 }
1752
1753 static void set_destination(struct sip_pvt *p, char *uri)
1754 {
1755         char *h, *maddr, hostname[256];
1756         int port, hn;
1757         struct hostent *hp;
1758
1759         /* Parse uri to h (host) and port - uri is already just the part inside the <> */
1760         /* general form we are expecting is sip[s]:username[:password]@host[:port][;...] */
1761
1762         if (sipdebug)
1763                 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
1764
1765         /* Find and parse hostname */
1766         h = strchr(uri, '@');
1767         if (h)
1768                 ++h;
1769         else {
1770                 h = uri;
1771                 if (strncmp(h, "sip:", 4) == 0)
1772                         h += 4;
1773                 else if (strncmp(h, "sips:", 5) == 0)
1774                         h += 5;
1775         }
1776         hn = strcspn(h, ":;>");
1777         if (hn>255) hn=255;
1778         strncpy(hostname, h, hn);  hostname[hn] = '\0';
1779         h+=hn;
1780
1781         /* Is "port" present? if not default to 5060 */
1782         if (*h == ':') {
1783                 /* Parse port */
1784                 ++h;
1785                 port = strtol(h, &h, 10);
1786         }
1787         else
1788                 port = 5060;
1789
1790         /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
1791         maddr = strstr(h, "maddr=");
1792         if (maddr) {
1793                 maddr += 6;
1794                 hn = strspn(maddr, "0123456789.");
1795                 if (hn>255) hn=255;
1796                 strncpy(hostname, maddr, hn);  hostname[hn] = '\0';
1797         }
1798         
1799         hp = gethostbyname(hostname);
1800         if (hp == NULL)  {
1801                 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
1802                 return;
1803         }
1804         p->sa.sin_family = AF_INET;
1805         memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
1806         p->sa.sin_port = htons(port);
1807         if (sipdebug)
1808                 ast_verbose("set_destination: set destination to %s, port %d\n", inet_ntoa(p->sa.sin_addr), port);
1809 }
1810
1811 static int init_resp(struct sip_request *req, char *resp, struct sip_request *orig)
1812 {
1813         /* Initialize a response */
1814         if (req->headers || req->len) {
1815                 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1816                 return -1;
1817         }
1818         req->header[req->headers] = req->data + req->len;
1819         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "SIP/2.0 %s\r\n", resp);
1820         req->len += strlen(req->header[req->headers]);
1821         if (req->headers < SIP_MAX_HEADERS)
1822                 req->headers++;
1823         else
1824                 ast_log(LOG_WARNING, "Out of header space\n");
1825         return 0;
1826 }
1827
1828 static int init_req(struct sip_request *req, char *resp, char *recip)
1829 {
1830         /* Initialize a response */
1831         if (req->headers || req->len) {
1832                 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1833                 return -1;
1834         }
1835         req->header[req->headers] = req->data + req->len;
1836         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s SIP/2.0\r\n", resp, recip);
1837         req->len += strlen(req->header[req->headers]);
1838         if (req->headers < SIP_MAX_HEADERS)
1839                 req->headers++;
1840         else
1841                 ast_log(LOG_WARNING, "Out of header space\n");
1842         return 0;
1843 }
1844
1845 static int respprep(struct sip_request *resp, struct sip_pvt *p, char *msg, struct sip_request *req)
1846 {
1847         char newto[256] = "", *ot;
1848         memset(resp, 0, sizeof(*resp));
1849         init_resp(resp, msg, req);
1850         copy_via_headers(p, resp, req, "Via");
1851         if (msg[0] == '2') copy_all_header(resp, req, "Record-Route");
1852         copy_header(resp, req, "From");
1853         ot = get_header(req, "To");
1854         if (!strstr(ot, "tag=")) {
1855                 /* Add the proper tag if we don't have it already.  If they have specified
1856                    their tag, use it.  Otherwise, use our own tag */
1857                 if (strlen(p->theirtag) && p->outgoing)
1858                         snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
1859                 else if (p->tag && !p->outgoing)
1860                         snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
1861                 else
1862                         strncpy(newto, ot, sizeof(newto) - 1);
1863                 ot = newto;
1864         }
1865         add_header(resp, "To", ot);
1866         copy_header(resp, req, "Call-ID");
1867         copy_header(resp, req, "CSeq");
1868         add_header(resp, "User-Agent", "Asterisk PBX");
1869         if (p->expiry) {
1870                 /* For registration responses, we also need expiry and
1871                    contact info */
1872                 char contact[256];
1873                 char tmp[256];
1874                 snprintf(contact, sizeof(contact), "%s;expires=%d", p->our_contact, p->expiry);
1875                 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
1876                 add_header(resp, "Expires", tmp);
1877                 add_header(resp, "Contact", contact);
1878         } else {
1879                 add_header(resp, "Contact", p->our_contact);
1880         }
1881         return 0;
1882 }
1883
1884 static int reqprep(struct sip_request *req, struct sip_pvt *p, char *msg, int seqno)
1885 {
1886         struct sip_request *orig = &p->initreq;
1887         char stripped[80] ="";
1888         char tmp[80];
1889         char newto[256];
1890         char *c, *n;
1891         char *ot, *of;
1892
1893         memset(req, 0, sizeof(struct sip_request));
1894         
1895         if (!seqno) {
1896                 p->ocseq++;
1897                 seqno = p->ocseq;
1898         }
1899
1900         if (p->outgoing)
1901                 strncpy(stripped, get_header(orig, "To"), sizeof(stripped) - 1);
1902         else
1903                 strncpy(stripped, get_header(orig, "From"), sizeof(stripped) - 1);
1904         
1905         c = strchr(stripped, '<');
1906         if (c) 
1907                 c++;
1908         else
1909                 c = stripped;
1910         n = strchr(c, '>');
1911         if (n)
1912                 *n = '\0';
1913         n = strchr(c, ';');
1914         if (n)
1915                 *n = '\0';
1916         
1917         init_req(req, msg, c);
1918
1919         snprintf(tmp, sizeof(tmp), "%d %s", seqno, msg);
1920
1921         add_header(req, "Via", p->via);
1922         if (p->route) {
1923                 set_destination(p, p->route->hop);
1924                 add_route(req, p->route->next);
1925         }
1926
1927         ot = get_header(orig, "To");
1928         of = get_header(orig, "From");
1929
1930         /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
1931            as our original request, including tag (or presumably lack thereof) */
1932         if (!strstr(ot, "tag=") && strcasecmp(msg, "CANCEL")) {
1933                 /* Add the proper tag if we don't have it already.  If they have specified
1934                    their tag, use it.  Otherwise, use our own tag */
1935                 if (p->outgoing && strlen(p->theirtag))
1936                         snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
1937                 else if (!p->outgoing)
1938                         snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
1939                 else
1940                         snprintf(newto, sizeof(newto), "%s", ot);
1941                 ot = newto;
1942         }
1943
1944         if (p->outgoing) {
1945                 add_header(req, "From", of);
1946                 add_header(req, "To", ot);
1947         } else {
1948                 add_header(req, "From", ot);
1949                 add_header(req, "To", of);
1950         }
1951         add_header(req, "Contact", p->our_contact);
1952         copy_header(req, orig, "Call-ID");
1953         add_header(req, "CSeq", tmp);
1954
1955         add_header(req, "User-Agent", "Asterisk PBX");
1956         return 0;
1957 }
1958
1959 static int __transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req, int reliable)
1960 {
1961         struct sip_request resp;
1962         int seqno = 0;
1963         if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
1964                 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
1965                 return -1;
1966         }
1967         respprep(&resp, p, msg, req);
1968         add_header(&resp, "Content-Length", "0");
1969         add_blank_header(&resp);
1970         return send_response(p, &resp, reliable, seqno);
1971 }
1972
1973 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req) 
1974 {
1975         return __transmit_response(p, msg, req, 0);
1976 }
1977 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req)
1978 {
1979         return __transmit_response(p, msg, req, 1);
1980 }
1981
1982 static void append_date(struct sip_request *req)
1983 {
1984         char tmpdat[256];
1985         struct tm tm;
1986         time_t t;
1987         time(&t);
1988         gmtime_r(&t, &tm);
1989         strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
1990         add_header(req, "Date", tmpdat);
1991 }
1992
1993 static int transmit_response_with_date(struct sip_pvt *p, char *msg, struct sip_request *req)
1994 {
1995         struct sip_request resp;
1996         respprep(&resp, p, msg, req);
1997         append_date(&resp);
1998         add_header(&resp, "Content-Length", "0");
1999         add_blank_header(&resp);
2000         return send_response(p, &resp, 0, 0);
2001 }
2002
2003 static int transmit_response_with_allow(struct sip_pvt *p, char *msg, struct sip_request *req)
2004 {
2005         struct sip_request resp;
2006         respprep(&resp, p, msg, req);
2007         add_header(&resp, "Allow", "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER");
2008         add_header(&resp, "Accept", "application/sdp");
2009         add_header(&resp, "Content-Length", "0");
2010         add_blank_header(&resp);
2011         return send_response(p, &resp, 0, 0);
2012 }
2013
2014 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *randdata, int reliable)
2015 {
2016         struct sip_request resp;
2017         char tmp[256];
2018         int seqno = 0;
2019         if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
2020                 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
2021                 return -1;
2022         }
2023         snprintf(tmp, sizeof(tmp), "Digest realm=\"asterisk\", nonce=\"%s\"", randdata);
2024         respprep(&resp, p, msg, req);
2025         add_header(&resp, "Proxy-Authenticate", tmp);
2026         add_header(&resp, "Content-Length", "0");
2027         add_blank_header(&resp);
2028         return send_response(p, &resp, reliable, seqno);
2029 }
2030
2031 static int add_text(struct sip_request *req, char *text)
2032 {
2033         /* XXX Convert \n's to \r\n's XXX */
2034         int len = strlen(text);
2035         char clen[256];
2036         snprintf(clen, sizeof(clen), "%d", len);
2037         add_header(req, "Content-Type", "text/plain");
2038         add_header(req, "Content-Length", clen);
2039         add_line(req, text);
2040         return 0;
2041 }
2042
2043 static int add_digit(struct sip_request *req, char digit)
2044 {
2045         char tmp[256];
2046         int len;
2047         char clen[256];
2048         snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=250\r\n", digit);
2049         len = strlen(tmp);
2050         snprintf(clen, sizeof(clen), "%d", len);
2051         add_header(req, "Content-Type", "application/dtmf-relay");
2052         add_header(req, "Content-Length", clen);
2053         add_line(req, tmp);
2054         return 0;
2055 }
2056
2057 static int add_sdp(struct sip_request *resp, struct sip_pvt *p, struct ast_rtp *rtp)
2058 {
2059         int len;
2060         int codec;
2061         int alreadysent = 0;
2062         char costr[80];
2063         struct sockaddr_in sin;
2064         struct sip_codec_pref *cur;
2065         char v[256];
2066         char s[256];
2067         char o[256];
2068         char c[256];
2069         char t[256];
2070         char m[256];
2071         char a[1024] = "";
2072         int x;
2073         struct sockaddr_in dest;
2074         /* XXX We break with the "recommendation" and send our IP, in order that our
2075                peer doesn't have to gethostbyname() us XXX */
2076         len = 0;
2077         if (!p->rtp) {
2078                 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
2079                 return -1;
2080         }
2081         ast_rtp_get_us(p->rtp, &sin);
2082         if (p->redirip.sin_addr.s_addr) {
2083                 dest.sin_port = p->redirip.sin_port;
2084                 dest.sin_addr = p->redirip.sin_addr;
2085         } else if (rtp) {
2086                 ast_rtp_get_peer(rtp, &dest);
2087         } else {
2088                 dest.sin_addr = p->ourip;
2089                 dest.sin_port = sin.sin_port;
2090         }
2091         if (sipdebug)
2092                 ast_verbose("We're at %s port %d\n", inet_ntoa(p->ourip), ntohs(sin.sin_port)); 
2093         snprintf(v, sizeof(v), "v=0\r\n");
2094         snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", getpid(), getpid(), inet_ntoa(dest.sin_addr));
2095         snprintf(s, sizeof(s), "s=session\r\n");
2096         snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", inet_ntoa(dest.sin_addr));
2097         snprintf(t, sizeof(t), "t=0 0\r\n");
2098         snprintf(m, sizeof(m), "m=audio %d RTP/AVP", ntohs(dest.sin_port));
2099         /* Start by sending our preferred codecs */
2100         cur = prefs;
2101         while(cur) {
2102                 if (p->capability & cur->codec) {
2103                         if (sipdebug)
2104                                 ast_verbose("Answering with preferred capability %d\n", cur->codec);
2105                         codec = ast_rtp_lookup_code(p->rtp, 1, cur->codec);
2106                         if (codec > -1) {
2107                                 snprintf(costr, sizeof(costr), " %d", codec);
2108                                 strcat(m, costr);
2109                                 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, cur->codec));
2110                                 strcat(a, costr);
2111                         }
2112                 }
2113                 alreadysent |= cur->codec;
2114                 cur = cur->next;
2115         }
2116         /* Now send any other common codecs, and non-codec formats: */
2117         for (x = 1; x <= AST_FORMAT_MAX_AUDIO; x <<= 1) {
2118                 if ((p->capability & x) && !(alreadysent & x)) {
2119                         if (sipdebug)
2120                                 ast_verbose("Answering with capability %d\n", x);       
2121                         codec = ast_rtp_lookup_code(p->rtp, 1, x);
2122                         if (codec > -1) {
2123                         snprintf(costr, sizeof(costr), " %d", codec);
2124                                 strcat(m, costr);
2125                                 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
2126                                 strcat(a, costr);
2127                         }
2128                 }
2129         }
2130         for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
2131                 if (p->noncodeccapability & x) {
2132                         if (sipdebug)
2133                                 ast_verbose("Answering with non-codec capability %d\n", x);
2134                         codec = ast_rtp_lookup_code(p->rtp, 0, x);
2135                         if (codec > -1) {
2136                                 snprintf(costr, sizeof(costr), " %d", codec);
2137                                 strcat(m, costr);
2138                                 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(0, x));
2139                                 strcat(a, costr);
2140                                 if (x == AST_RTP_DTMF) {
2141                                   /* Indicate we support DTMF...  Not sure about 16, but MSN supports it so dang it, we will too... */
2142                                   snprintf(costr, sizeof costr, "a=fmtp:%d 0-16\r\n",
2143                                            codec);
2144                                   strcat(a, costr);
2145                                 }
2146                         }
2147                 }
2148         }
2149         strcat(m, "\r\n");
2150         len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m) + strlen(a);
2151         snprintf(costr, sizeof(costr), "%d", len);
2152         add_header(resp, "Content-Type", "application/sdp");
2153         add_header(resp, "Content-Length", costr);
2154         add_line(resp, v);
2155         add_line(resp, o);
2156         add_line(resp, s);
2157         add_line(resp, c);
2158         add_line(resp, t);
2159         add_line(resp, m);
2160         add_line(resp, a);
2161         return 0;
2162 }
2163
2164 static void copy_request(struct sip_request *dst,struct sip_request *src)
2165 {
2166         long offset;
2167         int x;
2168         offset = ((void *)dst) - ((void *)src);
2169         /* First copy stuff */
2170         memcpy(dst, src, sizeof(*dst));
2171         /* Now fix pointer arithmetic */
2172         for (x=0;x<src->headers;x++)
2173                 dst->header[x] += offset;
2174         for (x=0;x<src->lines;x++)
2175                 dst->line[x] += offset;
2176 }
2177
2178 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
2179 {
2180         struct sip_request resp;
2181         int seqno;
2182         if (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1) {
2183                 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
2184                 return -1;
2185         }
2186         respprep(&resp, p, msg, req);
2187         add_sdp(&resp, p, NULL);
2188         return send_response(p, &resp, retrans, seqno);
2189 }
2190
2191 static int determine_firstline_parts( struct sip_request *req ) {
2192
2193   char *e, *cmd;
2194   int len;
2195   
2196   cmd= req->header[0];
2197   while(*cmd && (*cmd < 33)) {
2198     cmd++;
2199   }
2200   if (!*cmd) {
2201     return -1;
2202   }
2203   e= cmd;
2204   while(*e && (*e > 32)) {
2205     e++;
2206   }
2207   /* Get the command */
2208   if (*e) {
2209     *e = '\0';
2210     e++;
2211   }
2212   req->rlPart1= cmd;
2213   while( *e && ( *e < 33 ) ) {
2214     e++; 
2215   }
2216   if( !*e ) {
2217     return -1;
2218   }
2219     
2220   if ( !strcasecmp(cmd, "SIP/2.0") ) {
2221     /* We have a response */
2222     req->rlPart2= e;
2223     len= strlen( req->rlPart2 );
2224     if( len < 2 ) { return -1; }
2225     e+= len - 1;
2226     while( *e && *e<33 ) {
2227       e--; 
2228     }
2229     *(++e)= '\0';
2230   } else {
2231     /* We have a request */
2232     if( *e == '<' ) { 
2233       e++;
2234       if( !*e ) { return -1; }  
2235     }
2236     req->rlPart2= e;
2237     if( ( e= strrchr( req->rlPart2, 'S' ) ) == NULL ) {
2238       return -1;
2239     }
2240     while( isspace( *(--e) ) ) {}
2241     if( *e == '>' ) {
2242       *e= '\0';
2243     } else {
2244       *(++e)= '\0';
2245     }
2246   }
2247   return 1;
2248 }
2249
2250 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp)
2251 {
2252         struct sip_request req;
2253         if (p->canreinvite == REINVITE_UPDATE)
2254                 reqprep(&req, p, "UPDATE", 0);
2255         else
2256                 reqprep(&req, p, "INVITE", 0);
2257         add_sdp(&req, p, rtp);
2258         /* Use this as the basis */
2259         copy_request(&p->initreq, &req);
2260         parse(&p->initreq);
2261         determine_firstline_parts(&p->initreq);
2262         p->lastinvite = p->ocseq;
2263         p->outgoing = 1;
2264         return send_request(p, &req, 1, p->ocseq);
2265 }
2266
2267 static void build_contact(struct sip_pvt *p)
2268 {
2269         /* Construct Contact: header */
2270         if (ourport != 5060)
2271                 snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s@%s:%d>", p->exten, inet_ntoa(p->ourip), ourport);
2272         else
2273                 snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s@%s>", p->exten, inet_ntoa(p->ourip));
2274 }
2275
2276 static void initreqprep(struct sip_request *req, struct sip_pvt *p, char *cmd, char *vxml_url)
2277 {
2278         char invite[256];
2279         char from[256];
2280         char to[256];
2281         char tmp[80];
2282         char cid[256];
2283         char *l = callerid, *n=NULL;
2284         if (p->owner && p->owner->callerid) {
2285                 strcpy(cid, p->owner->callerid);
2286                 ast_callerid_parse(cid, &n, &l);
2287                 if (l) 
2288                         ast_shrink_phone_number(l);
2289                 if (!l || !ast_isphonenumber(l))
2290                                 l = callerid;
2291         }
2292         if (!n || !strlen(n))
2293                 n = l;
2294         /* Allow user to be overridden */
2295         if (strlen(p->fromuser))
2296                 l = p->fromuser;
2297
2298         if ((ourport != 5060) && !strlen(p->fromdomain))
2299                 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=as%08x", n, l, strlen(p->fromdomain) ? p->fromdomain : inet_ntoa(p->ourip), ourport, p->tag);
2300         else
2301                 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=as%08x", n, l, strlen(p->fromdomain) ? p->fromdomain : inet_ntoa(p->ourip), p->tag);
2302
2303         if (strlen(p->username)) {
2304                 if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
2305                         snprintf(invite, sizeof(invite), "sip:%s@%s:%d",p->username, p->tohost, ntohs(p->sa.sin_port));
2306                 } else {
2307                         snprintf(invite, sizeof(invite), "sip:%s@%s",p->username, p->tohost);
2308                 }
2309         } else if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
2310                 snprintf(invite, sizeof(invite), "sip:%s:%d", p->tohost, ntohs(p->sa.sin_port));
2311         } else {
2312                 snprintf(invite, sizeof(invite), "sip:%s", p->tohost);
2313         }
2314         strncpy(p->uri, invite, sizeof(p->uri) - 1);
2315         /* If there is a VXML URL append it to the SIP URL */
2316         if (vxml_url)
2317         {
2318                 snprintf(to, sizeof(to), "<%s>;%s", invite, vxml_url);
2319         }
2320         else
2321         {
2322                 snprintf(to, sizeof(to), "<%s>", invite );
2323         }
2324         memset(req, 0, sizeof(struct sip_request));
2325         init_req(req, cmd, invite);
2326         snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
2327
2328         add_header(req, "Via", p->via);
2329         /* SLD: FIXME?: do Route: here too?  I think not cos this is the first request.
2330          * OTOH, then we won't have anything in p->route anyway */
2331         add_header(req, "From", from);
2332         strncpy(p->exten, l, sizeof(p->exten) - 1);
2333         build_contact(p);
2334         add_header(req, "To", to);
2335         add_header(req, "Contact", p->our_contact);
2336         add_header(req, "Call-ID", p->callid);
2337         add_header(req, "CSeq", tmp);
2338         add_header(req, "User-Agent", "Asterisk PBX");
2339 }
2340
2341 static int transmit_invite(struct sip_pvt *p, char *cmd, int sdp, char *auth, char *vxml_url)
2342 {
2343         struct sip_request req;
2344         initreqprep(&req, p, cmd, vxml_url);
2345         if (auth)
2346                 add_header(&req, "Proxy-Authorization", auth);
2347         if (sdp) {
2348                 add_sdp(&req, p, NULL);
2349         } else {
2350                 add_header(&req, "Content-Length", "0");
2351                 add_blank_header(&req);
2352         }
2353         if (!p->initreq.headers) {
2354                 /* Use this as the basis */
2355                 copy_request(&p->initreq, &req);
2356                 parse(&p->initreq);
2357                 determine_firstline_parts(&p->initreq);
2358         }
2359         p->lastinvite = p->ocseq;
2360         return send_request(p, &req, 1, p->ocseq);
2361 }
2362
2363 static int transmit_state_notify(struct sip_pvt *p, int state, int full)
2364 {
2365         char tmp[2000];
2366         char from[256], to[256];
2367         char *t, *c, *a;
2368         char *mfrom, *mto;
2369         struct sip_request req;
2370         char clen[20];
2371         
2372         strncpy(from, get_header(&p->initreq, "From"), sizeof(from)-1);
2373
2374         c = ditch_braces(from);
2375         if (strncmp(c, "sip:", 4)) {
2376                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
2377                 return -1;
2378         }
2379         if ((a = strchr(c, ';'))) {
2380                 *a = '\0';
2381         }
2382         mfrom = c;
2383                 
2384         reqprep(&req, p, "NOTIFY", 0);
2385
2386         if (p->subscribed == 1) {
2387             strncpy(to, get_header(&p->initreq, "To"), sizeof(to)-1);
2388
2389             c = ditch_braces(to);
2390             if (strncmp(c, "sip:", 4)) {
2391                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
2392                 return -1;
2393             }
2394             if ((a = strchr(c, ';'))) {
2395                 *a = '\0';
2396             }
2397             mto = c;
2398
2399             add_header(&req, "Content-Type", "application/xpidf+xml");
2400
2401             if ((state==AST_EXTENSION_UNAVAILABLE) || (state==AST_EXTENSION_BUSY))
2402                 state = 2;
2403             else if (state==AST_EXTENSION_INUSE)
2404                 state = 1;
2405             else
2406                 state = 0;
2407             
2408             t = tmp;            
2409             sprintf(t, "<?xml version=\"1.0\"?>\n");
2410             t = tmp + strlen(tmp);
2411             sprintf(t, "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n");
2412             t = tmp + strlen(tmp);
2413             sprintf(t, "<presence>\n");
2414             t = tmp + strlen(tmp);
2415             sprintf(t, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
2416             t = tmp + strlen(tmp);
2417             sprintf(t, "<atom id=\"%s\">\n", p->exten);
2418             t = tmp + strlen(tmp);
2419             sprintf(t, "<address uri=\"%s;user=ip\" priority=\"0,800000\">\n", mto);
2420             t = tmp + strlen(tmp);
2421             sprintf(t, "<status status=\"%s\" />\n", !state ? "open" : (state==1) ? "inuse" : "closed");
2422             t = tmp + strlen(tmp);
2423             sprintf(t, "<msnsubstatus substatus=\"%s\" />\n", !state ? "online" : (state==1) ? "onthephone" : "offline");
2424             t = tmp + strlen(tmp);
2425             sprintf(t, "</address>\n</atom>\n</presence>\n");           
2426         } else {
2427             add_header(&req, "Event", "dialog");
2428             add_header(&req, "Content-Type", "application/dialog-info+xml");
2429         
2430             t = tmp;            
2431             sprintf(t, "<?xml version=\"1.0\"?>\n");
2432             t = tmp + strlen(tmp);
2433             sprintf(t, "<dialog-info xmlns=\"urn:ietf:params:xml:ns:dialog-info\" version=\"%d\" state=\"%s\" entity=\"%s\">\n", p->dialogver++, full ? "full":"partial", mfrom);
2434             t = tmp + strlen(tmp);
2435             sprintf(t, "<dialog id=\"%s\">\n", p->exten);
2436             t = tmp + strlen(tmp);
2437             sprintf(t, "<state>%s</state>\n", state ? "confirmed" : "terminated");
2438             t = tmp + strlen(tmp);
2439             sprintf(t, "</dialog>\n</dialog-info>\n");  
2440         }
2441
2442         snprintf(clen, sizeof(clen), "%d", strlen(tmp));
2443         add_header(&req, "Content-Length", clen);
2444         add_line(&req, tmp);
2445
2446         return send_request(p, &req, 1, p->ocseq);
2447 }
2448
2449 static int transmit_notify(struct sip_pvt *p, int newmsgs, int oldmsgs)
2450 {
2451         struct sip_request req;
2452         char tmp[256];
2453         char tmp2[256];
2454         char clen[20];
2455         initreqprep(&req, p, "NOTIFY", NULL);
2456         add_header(&req, "Event", "message-summary");
2457         add_header(&req, "Content-Type", notifymime);
2458
2459         snprintf(tmp, sizeof(tmp), "Messages-Waiting: %s\n", newmsgs ? "yes" : "no");
2460         snprintf(tmp2, sizeof(tmp2), "Voicemail: %d/%d\n", newmsgs, oldmsgs);
2461         snprintf(clen, sizeof(clen), "%d", strlen(tmp) + strlen(tmp2));
2462         add_header(&req, "Content-Length", clen);
2463         add_line(&req, tmp);
2464         add_line(&req, tmp2);
2465
2466         if (!p->initreq.headers) {
2467                 /* Use this as the basis */
2468                 copy_request(&p->initreq, &req);
2469                 parse(&p->initreq);
2470                 determine_firstline_parts(&p->initreq);
2471         }
2472
2473         return send_request(p, &req, 1, p->ocseq);
2474 }
2475
2476 static int transmit_register(struct sip_registry *r, char *cmd, char *auth);
2477
2478 static int sip_reregister(void *data) 
2479 {
2480         /* if we are here, we know that we need to reregister. */
2481         struct sip_registry *r=(struct sip_registry *)data;
2482         r->expire = -1;
2483         sip_do_register(r);
2484         return 0;
2485 }
2486
2487
2488 static int sip_do_register(struct sip_registry *r)
2489 {
2490         int res;
2491         ast_pthread_mutex_lock(&r->lock);
2492         res=transmit_register(r, "REGISTER", NULL);
2493         ast_pthread_mutex_unlock(&r->lock);
2494         return res;
2495 }
2496
2497 static int sip_reg_timeout(void *data)
2498 {
2499         /* if we are here, our registration timed out, so we'll just do it over */
2500         struct sip_registry *r=data;
2501         struct sip_pvt *p;
2502         int res;
2503         ast_pthread_mutex_lock(&r->lock);
2504         ast_log(LOG_NOTICE, "Registration for '%s@%s' timed out, trying again\n", r->username, inet_ntoa(r->addr.sin_addr)); 
2505         if (r->call) {
2506                 /* Unlink us, destroy old call.  Locking is not relevent here because all this happens
2507                    in the single SIP manager thread. */
2508                 p = r->call;
2509                 p->registry = NULL;
2510                 r->call = NULL;
2511                 p->needdestroy = 1;
2512         }
2513         r->regstate=REG_STATE_UNREGISTERED;
2514         r->timeout = -1;
2515         res=transmit_register(r, "REGISTER", NULL);
2516         ast_pthread_mutex_unlock(&r->lock);
2517         return 0;
2518 }
2519
2520 static int transmit_register(struct sip_registry *r, char *cmd, char *auth)
2521 {
2522         struct sip_request req;
2523         char from[256];
2524         char to[256];
2525         char tmp[80];
2526         char via[80];
2527         char addr[80];
2528         struct sip_pvt *p;
2529         /* exit if we are already in process with this registrar ?*/
2530         if ( r == NULL || ((auth==NULL) && (r->regstate==REG_STATE_REGSENT || r->regstate==REG_STATE_AUTHSENT))) {
2531                 ast_log(LOG_NOTICE, "Strange, trying to register when registration already pending\n");
2532                 return 0;
2533         }
2534
2535         if (r->call) {
2536                 if (!auth) {
2537                         ast_log(LOG_WARNING, "Already have a call??\n");
2538                         return 0;
2539                 } else
2540                         p = r->call;
2541         } else {
2542                 if (!r->callid_valid) {
2543                         build_callid(r->callid, sizeof(r->callid), __ourip);
2544                         r->callid_valid = 1;
2545                 }
2546                 p=sip_alloc( r->callid, &r->addr, 0);
2547                 if (!p) {
2548                         ast_log(LOG_WARNING, "Unable to allocate registration call\n");
2549                         return 0;
2550                 }
2551                 p->outgoing = 1;
2552                 r->call=p;
2553                 p->registry=r;
2554                 strncpy(p->peersecret, r->secret, sizeof(p->peersecret)-1);
2555                 if (strlen(r->authuser))
2556                         strncpy(p->peername, r->authuser, sizeof(p->peername)-1);
2557                 else
2558                         strncpy(p->peername, r->username, sizeof(p->peername)-1);
2559                 strncpy(p->username, r->username, sizeof(p->username)-1);
2560                 strncpy(p->exten, r->contact, sizeof(p->exten) - 1);
2561                 build_contact(p);
2562         }
2563
2564         /* set up a timeout */
2565         if (auth==NULL)  {
2566                 if (r->timeout > -1) {
2567                         ast_log(LOG_WARNING, "Still have a timeout, %d\n", r->timeout);
2568                         ast_sched_del(sched, r->timeout);
2569                 }
2570                 r->timeout = ast_sched_add(sched, 20*1000, sip_reg_timeout, r);
2571                 ast_log(LOG_DEBUG, "Scheduled a timeout # %d\n", r->timeout);
2572         }
2573
2574         snprintf(from, sizeof(from), "<sip:%s@%s>;tag=as%08x", r->username, r->hostname, p->tag);
2575         snprintf(to, sizeof(to),     "<sip:%s@%s>", r->username, r->hostname);
2576         
2577         snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
2578         strncpy(p->uri, addr, sizeof(p->uri) - 1);
2579
2580         memset(&req, 0, sizeof(req));
2581         init_req(&req, cmd, addr);
2582
2583         snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, cmd);
2584         p->ocseq = r->ocseq;
2585
2586         /* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
2587         snprintf(via, sizeof(via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
2588         add_header(&req, "Via", via);
2589         add_header(&req, "From", from);
2590         add_header(&req, "To", to);
2591         add_header(&req, "Call-ID", p->callid);
2592         add_header(&req, "CSeq", tmp);
2593         add_header(&req, "User-Agent", "Asterisk PBX");
2594         if (auth) 
2595                 add_header(&req, "Authorization", auth);
2596
2597         snprintf(tmp, sizeof(tmp), "%d", default_expiry);
2598         add_header(&req, "Expires", tmp);
2599         add_header(&req, "Contact", p->our_contact);
2600         add_header(&req, "Event", "registration");
2601         add_header(&req, "Content-length", "0");
2602         add_blank_header(&req);
2603         copy_request(&p->initreq, &req);
2604         parse(&p->initreq);
2605         determine_firstline_parts(&p->initreq);
2606         r->regstate=auth?REG_STATE_AUTHSENT:REG_STATE_REGSENT;
2607         return send_request(p, &req, 1, p->ocseq);
2608 }
2609
2610 static int transmit_message_with_text(struct sip_pvt *p, char *text)
2611 {
2612         struct sip_request req;
2613         reqprep(&req, p, "MESSAGE", 0);
2614         add_text(&req, text);
2615         return send_request(p, &req, 1, p->ocseq);
2616 }
2617
2618 static int transmit_info_with_digit(struct sip_pvt *p, char digit)
2619 {
2620         struct sip_request req;
2621         reqprep(&req, p, "INFO", 0);
2622         add_digit(&req, digit);
2623         return send_request(p, &req, 1, p->ocseq);
2624 }
2625
2626 static int transmit_request(struct sip_pvt *p, char *msg, int seqno, int reliable)
2627 {
2628         struct sip_request resp;
2629         reqprep(&resp, p, msg, seqno);
2630         add_header(&resp, "Content-Length", "0");
2631         add_blank_header(&resp);
2632         return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
2633 }
2634
2635 static int transmit_request_with_auth(struct sip_pvt *p, char *msg, int seqno, int reliable)
2636 {
2637         struct sip_request resp;
2638         reqprep(&resp, p, msg, seqno);
2639         if (*p->realm)
2640         {
2641                 char digest[256];
2642                 memset(digest,0,sizeof(digest));
2643                 build_reply_digest(p, msg, digest, sizeof(digest));
2644                 add_header(&resp, "Proxy-Authorization", digest);
2645         }
2646
2647         add_header(&resp, "Content-Length", "0");
2648         add_blank_header(&resp);
2649         return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);      
2650 }
2651
2652 static int expire_register(void *data)
2653 {
2654         struct sip_peer *p = data;
2655         memset(&p->addr, 0, sizeof(p->addr));
2656         p->expire = -1;
2657         ast_device_state_changed("SIP/%s", p->name);
2658         return 0;
2659 }
2660
2661 static int sip_poke_peer(struct sip_peer *peer);
2662
2663 static int parse_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req)
2664 {
2665         char contact[80]= ""; 
2666         char *expires = get_header(req, "Expires");
2667         int expiry = atoi(expires);
2668         char *c, *n, *pt;
2669         int port;
2670         struct hostent *hp;
2671         struct sockaddr_in oldsin;
2672         if (!strlen(expires)) {
2673                 expires = strstr(get_header(req, "Contact"), "expires=");
2674                 if (expires) {
2675                         if (sscanf(expires + 8, "%d;", &expiry) != 1)
2676                                 expiry = default_expiry;
2677                 } else {
2678                         /* Nothing has been specified */
2679                         expiry = default_expiry;
2680                 }
2681         }
2682         /* Look for brackets */
2683         strncpy(contact, get_header(req, "Contact"), sizeof(contact) - 1);
2684         c = contact;
2685         
2686         if ((n=strchr(c, '<'))) {
2687                 c = n + 1;
2688                 n = strchr(c, '>');
2689                 /* Lose the part after the > */
2690                 if (n) 
2691                         *n = '\0';
2692         }
2693         if (!strcasecmp(c, "*") || !expiry) {
2694                 /* This means remove all registrations and return OK */
2695                 memset(&p->addr, 0, sizeof(p->addr));
2696                 if (p->expire > -1)
2697                         ast_sched_del(sched, p->expire);
2698                 p->expire = -1;
2699                 if (option_verbose > 2)
2700                         ast_verbose(VERBOSE_PREFIX_3 "Unregistered SIP '%s'\n", p->username);
2701                 return 0;
2702         }
2703         /* Make sure it's a SIP URL */
2704         if (strncasecmp(c, "sip:", 4)) {
2705                 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", c);
2706         } else
2707                 c += 4;
2708         /* Ditch q */
2709         n = strchr(c, ';');
2710         if (n) 
2711                 *n = '\0';
2712         /* Grab host */
2713         n = strchr(c, '@');
2714         if (!n) {
2715                 n = c;
2716                 c = NULL;
2717         } else {
2718                 *n = '\0';
2719                 n++;
2720         }
2721         pt = strchr(n, ':');
2722         if (pt) {
2723                 *pt = '\0';
2724                 pt++;
2725                 port = atoi(pt);
2726         } else
2727                 port = DEFAULT_SIP_PORT;
2728         memcpy(&oldsin, &p->addr, sizeof(oldsin));
2729         if (!p->nat) {
2730                 /* XXX This could block for a long time XXX */
2731                 hp = gethostbyname(n);
2732                 if (!hp)  {
2733                         ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
2734                         return -1;
2735                 }
2736                 p->addr.sin_family = AF_INET;
2737                 memcpy(&p->addr.sin_addr, hp->h_addr, sizeof(p->addr.sin_addr));
2738                 p->addr.sin_port = htons(port);
2739         } else {
2740                 /* Don't trust the contact field.  Just use what they came to us
2741                    with */
2742                 memcpy(&p->addr, &pvt->recv, sizeof(p->addr));
2743         }
2744         if (c)
2745                 strncpy(p->username, c, sizeof(p->username) - 1);
2746         else
2747                 strcpy(p->username, "");
2748         if (p->expire > -1)
2749                 ast_sched_del(sched, p->expire);
2750         if ((expiry < 1) || (expiry > max_expiry))
2751                 expiry = max_expiry;
2752         p->expire = ast_sched_add(sched, (expiry + 10) * 1000, expire_register, p);
2753         pvt->expiry = expiry;
2754         if (inaddrcmp(&p->addr, &oldsin)) {
2755                 sip_poke_peer(p);
2756                 if (option_verbose > 2)
2757                         ast_verbose(VERBOSE_PREFIX_3 "Registered SIP '%s' at %s port %d expires %d\n", p->username, inet_ntoa(p->addr.sin_addr), ntohs(p->addr.sin_port), expiry);
2758         }
2759         return 0;
2760 }
2761
2762 static void free_old_route(struct sip_route *route)
2763 {
2764         struct sip_route *next;
2765         while (route) {
2766                 next = route->next;
2767                 free(route);
2768                 route = next;
2769         }
2770 }
2771
2772 static void list_route(struct sip_route *route)
2773 {
2774         if (!route) {
2775                 ast_verbose("list_route: no route\n");
2776                 return;
2777         }
2778         while (route) {
2779                 ast_verbose("list_route: hop: <%s>\n", route->hop);
2780                 route = route->next;
2781         }
2782 }
2783
2784 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
2785 {
2786         struct sip_route *thishop, *head, *tail;
2787         int start = 0;
2788         int len;
2789         char *rr, *contact, *c;
2790
2791         if (p->route) {
2792                 free_old_route(p->route);
2793                 p->route = NULL;
2794         }
2795         /* We build up head, then assign it to p->route when we're done */
2796         head = NULL;  tail = head;
2797         /* 1st we pass through all the hops in any Record-Route headers */
2798         for (;;) {
2799                 /* Each Record-Route header */
2800                 rr = __get_header(req, "Record-Route", &start);
2801                 if (*rr == '\0') break;
2802                 for (;;) {
2803                         /* Each route entry */
2804                         /* Find < */
2805                         rr = strchr(rr, '<');
2806                         if (!rr) break; /* No more hops */
2807                         ++rr;
2808                         len = strcspn(rr, ">");
2809                         /* Make a struct route */
2810                         thishop = (struct sip_route *)malloc(sizeof(struct sip_route)+len+1);
2811                         if (thishop) {
2812                                 strncpy(thishop->hop, rr, len);
2813                                 thishop->hop[len] = '\0';
2814                                 ast_log(LOG_DEBUG, "build_route: Record-Route hop: <%s>\n", thishop->hop);
2815                                 /* Link in */
2816                                 if (backwards) {
2817                                         /* Link in at head so they end up in reverse order */
2818                                         thishop->next = head;
2819                                         head = thishop;
2820                                         /* If this was the first then it'll be the tail */
2821                                         if (!tail) tail = thishop;
2822                                 } else {
2823                                         thishop->next = NULL;
2824                                         /* Link in at the end */
2825                                         if (tail)
2826                                                 tail->next = thishop;
2827                                         else
2828                                                 head = thishop;
2829                                         tail = thishop;
2830                                 }
2831                         }
2832                         rr += len+1;
2833                 }
2834         }
2835         /* 2nd append the Contact: if there is one */
2836         /* Can be multiple Contact headers, comma separated values - we just take the first */
2837         contact = get_header(req, "Contact");
2838         if (strlen(contact)) {
2839                 ast_log(LOG_DEBUG, "build_route: Contact hop: %s\n", contact);
2840                 /* Look for <: delimited address */
2841                 c = strchr(contact, '<');
2842                 if (c) {
2843                         /* Take to > */
2844                         ++c;
2845                         len = strcspn(c, ">");
2846                 } else {
2847                         /* No <> - just take the lot */
2848                         c = contact; len = strlen(contact);
2849                 }
2850                 thishop = (struct sip_route *)malloc(sizeof(struct sip_route)+len+1);
2851                 if (thishop) {
2852                         strncpy(thishop->hop, c, len);
2853                         thishop->hop[len] = '\0';
2854                         thishop->next = NULL;
2855                         /* Goes at the end */
2856                         if (tail)
2857                                 tail->next = thishop;
2858                         else
2859                                 head = thishop;
2860                 }
2861         }
2862         /* Store as new route */
2863         p->route = head;
2864
2865         /* For debugging dump what we ended up with */
2866         if (sipdebug)
2867                 list_route(p->route);
2868 }
2869
2870 static void md5_hash(char *output, char *input)
2871 {
2872                 struct MD5Context md5;
2873                 unsigned char digest[16];
2874                 char *ptr;
2875                 int x;
2876                 MD5Init(&md5);
2877                 MD5Update(&md5, input, strlen(input));
2878                 MD5Final(digest, &md5);
2879                 ptr = output;
2880                 for (x=0;x<16;x++)
2881                         ptr += sprintf(ptr, "%2.2x", digest[x]);
2882 }
2883
2884 static int check_auth(struct sip_pvt *p, struct sip_request *req, char *randdata, int randlen, char *username, char *secret, char *method, char *uri, int reliable)
2885 {
2886         int res = -1;
2887         /* Always OK if no secret */
2888         if (!strlen(secret))
2889                 return 0;
2890         if (!strlen(randdata) || !strlen(get_header(req, "Proxy-Authorization"))) {
2891                 snprintf(randdata, randlen, "%08x", rand());
2892                 transmit_response_with_auth(p, "407 Proxy Authentication Required", req, randdata, reliable);
2893                 /* Schedule auto destroy in 15 seconds */
2894                 sip_scheddestroy(p, 15000);
2895                 res = 1;
2896         } else {
2897                 /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
2898                    an example in the spec of just what it is you're doing a hash on. */
2899                 char a1[256];
2900                 char a2[256];
2901                 char a1_hash[256];
2902                 char a2_hash[256];
2903                 char resp[256];
2904                 char resp_hash[256];
2905                 char tmp[256] = "";
2906                 char *c;
2907                 char *response ="";
2908                 char *resp_uri ="";
2909
2910                 /* Find their response among the mess that we'r sent for comparison */
2911                 strncpy(tmp, get_header(req, "Proxy-Authorization"), sizeof(tmp) - 1);
2912                 c = tmp;
2913
2914                 while(c) {
2915                         while (*c && (*c < 33)) c++;
2916                         if (!*c)
2917                                 break;
2918                         if (!strncasecmp(c, "response=", strlen("response="))) {
2919                                 c+= strlen("response=");
2920                                 if ((*c == '\"')) {
2921                                         response=++c;
2922                                         if((c = strchr(c,'\"')))
2923                                                 *c = '\0';
2924
2925                                 } else {
2926                                         response=c;
2927                                         if((c = strchr(c,',')))
2928                                                 *c = '\0';
2929                                 }
2930
2931                         } else if (!strncasecmp(c, "uri=", strlen("uri="))) {
2932                                 c+= strlen("uri=");
2933                                 if ((*c == '\"')) {
2934                                         resp_uri=++c;
2935                                         if((c = strchr(c,'\"')))
2936                                                 *c = '\0';
2937                                 } else {
2938                                         resp_uri=c;
2939                                         if((c = strchr(c,',')))
2940                                                 *c = '\0';
2941                                 }
2942
2943                         } else
2944                                 c = strchr(c, ',');
2945                         if (c)
2946                                 c++;
2947                 }
2948                 snprintf(a1, sizeof(a1), "%s:%s:%s", username, "asterisk", secret);
2949                 if(strlen(resp_uri))
2950                         snprintf(a2, sizeof(a2), "%s:%s", method, resp_uri);
2951                 else
2952                         snprintf(a2, sizeof(a2), "%s:%s", method, uri);
2953                 md5_hash(a1_hash, a1);
2954                 md5_hash(a2_hash, a2);
2955                 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, randdata, a2_hash);
2956                 md5_hash(resp_hash, resp);
2957
2958                 /* resp_hash now has the expected response, compare the two */
2959
2960                 if (response && !strncasecmp(response, resp_hash, strlen(resp_hash))) {
2961                         /* Auth is OK */
2962                         res = 0;
2963                 }
2964                 /* Assume success ;-) */
2965                 /* Eliminate random data */
2966                 strcpy(randdata, "");
2967         }
2968         return res;
2969 }
2970
2971 static int cb_extensionstate(char *context, char* exten, int state, void *data)
2972 {
2973     struct sip_pvt *p = data;
2974     if (state == -1) {
2975         sip_scheddestroy(p, 15000);
2976         p->stateid = -1;
2977         return 0;
2978     }
2979     
2980     transmit_state_notify(p, state, 1);
2981     
2982     if (option_debug)
2983         ast_verbose(VERBOSE_PREFIX_1 "Extension Changed %s new state %d for Notify User %s\n", exten, state, p->username);
2984     return 0;
2985 }
2986
2987 static int register_verify(struct sip_pvt *p, struct sockaddr_in *sin, struct sip_request *req, char *uri)
2988 {
2989         int res = -1;
2990         struct sip_peer *peer;
2991         char tmp[256] = "";
2992         char *name, *c;
2993         char *t;
2994         /* Terminate URI */
2995         t = uri;
2996         while(*t && (*t > 32) && (*t != ';'))
2997                 t++;
2998         *t = '\0';
2999         
3000         strncpy(tmp, get_header(req, "To"), sizeof(tmp) - 1);
3001         c = ditch_braces(tmp);
3002         /* Ditch ;user=phone */
3003         name = strchr(c, ';');
3004         if (name)
3005                 *name = '\0';
3006
3007         if (!strncmp(c, "sip:", 4)) {
3008                 name = c + 4;
3009         } else {
3010                 name = c;
3011                 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, inet_ntoa(sin->sin_addr));
3012         }
3013         c = strchr(name, '@');
3014         if (c) 
3015                 *c = '\0';
3016         strncpy(p->exten, name, sizeof(p->exten) - 1);
3017         build_contact(p);
3018         ast_pthread_mutex_lock(&peerl.lock);
3019         peer = peerl.peers;
3020         while(peer) {
3021                 if (!strcasecmp(peer->name, name) && peer->dynamic) {
3022                         p->nat = peer->nat;
3023                         transmit_response(p, "100 Trying", req);
3024                         if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), peer->name, peer->secret, "REGISTER", uri, 0))) {
3025                                 sip_cancel_destroy(p);
3026                                 if (parse_contact(p, peer, req)) {
3027                                         ast_log(LOG_WARNING, "Failed to parse contact info\n");
3028                                 } else {
3029                                         /* Say OK and ask subsystem to retransmit msg counter */
3030                                         transmit_response_with_date(p, "200 OK", req);
3031                                         peer->lastmsgssent = -1;
3032                                         res = 0;
3033                                 }
3034                         } 
3035                         break;
3036                 }       
3037                 peer = peer->next;
3038         }
3039         ast_pthread_mutex_unlock(&peerl.lock);
3040         if (!res) {
3041             ast_device_state_changed("SIP/%s", peer->name);
3042         }
3043         if (res < 0)
3044                 transmit_response(p, "401 Unauthorized", &p->initreq);
3045         return res;
3046 }
3047
3048 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
3049 {
3050         char tmp[256] = "", *c, *a;
3051         struct sip_request *req;
3052         
3053         req = oreq;
3054         if (!req)
3055                 req = &p->initreq;
3056         strncpy(tmp, req->rlPart2, sizeof(tmp) - 1);
3057         c = ditch_braces(tmp);
3058         if (strncmp(c, "sip:", 4)) {
3059                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
3060                 return -1;
3061         }
3062         c += 4;
3063         if ((a = strchr(c, '@')) || (a = strchr(c, ';'))) {
3064                 *a = '\0';
3065         }
3066         if (sipdebug)
3067                 ast_verbose("Looking for %s in %s\n", c, p->context);
3068         if (ast_exists_extension(NULL, p->context, c, 1, NULL) ||
3069                 !strcmp(c, ast_pickup_ext())) {
3070                 if (!oreq)
3071                         strncpy(p->exten, c, sizeof(p->exten) - 1);
3072                 return 0;
3073         }
3074
3075         if (ast_canmatch_extension(NULL, p->context, c, 1, NULL) ||
3076             !strncmp(c, ast_pickup_ext(),strlen(c))) {
3077                 return 1;
3078         }
3079         
3080         return -1;
3081 }
3082
3083 static int get_refer_info(struct sip_pvt *p, struct sip_request *oreq)
3084 {
3085         char tmp[256] = "", *c, *a;
3086         char tmp2[256] = "", *c2, *a2;
3087         char tmp3[256];
3088         char tmp4[256];
3089         char tmp5[256] = "";            /* CallID to replace */
3090         struct sip_request *req;
3091         struct sip_pvt *p2;
3092         
3093         req = oreq;
3094         if (!req)
3095                 req = &p->initreq;
3096         strncpy(tmp, get_header(req, "Refer-To"), sizeof(tmp) - 1);
3097         strncpy(tmp2, get_header(req, "Referred-By"), sizeof(tmp2) - 1);
3098         strncpy(tmp3, get_header(req, "Contact"), sizeof(tmp3) - 1);
3099         strncpy(tmp4, get_header(req, "Remote-Party-ID"), sizeof(tmp4) - 1);
3100         
3101         c = ditch_braces(tmp);
3102         c2 = ditch_braces(tmp2);
3103         
3104                 
3105         if (strncmp(c, "sip:", 4) && strncmp(c2, "sip:", 4)) {
3106                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
3107                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c2);
3108                 return -1;
3109         }
3110         c += 4;
3111         c2 += 4;
3112         if ((a = strchr(c, '?'))) {
3113                 /* Search for arguemnts */
3114                 *a = '\0';
3115                 a++;
3116                 if (!strncasecmp(a, "REPLACES=", strlen("REPLACES="))) {
3117                         strncpy(tmp5, a + strlen("REPLACES="), sizeof(tmp5) - 1);
3