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