Fix retransmission on BYE
[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 (1 /* !p->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 (sipdebug)
742                 ast_log(LOG_DEBUG, "Destorying call '%s'\n", p->callid);
743         if (p->stateid > -1)
744                 ast_extension_state_del(p->stateid, NULL);
745         if (p->initid > -1)
746                 ast_sched_del(sched, p->initid);
747         if (p->autokillid > -1)
748                 ast_sched_del(sched, p->autokillid);
749
750         if (p->rtp) {
751                 ast_rtp_destroy(p->rtp);
752         }
753         if (p->route) {
754                 free_old_route(p->route);
755                 p->route = NULL;
756         }
757         /* Unlink us from the owner if we have one */
758         if (p->owner) {
759                 if (lockowner)
760                         ast_pthread_mutex_lock(&p->owner->lock);
761                 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
762                 p->owner->pvt->pvt = NULL;
763                 if (lockowner)
764                         ast_pthread_mutex_unlock(&p->owner->lock);
765         }
766         cur = iflist;
767         while(cur) {
768                 if (cur == p) {
769                         if (prev)
770                                 prev->next = cur->next;
771                         else
772                                 iflist = cur->next;
773                         break;
774                 }
775                 prev = cur;
776                 cur = cur->next;
777         }
778         if (!cur) {
779                 ast_log(LOG_WARNING, "%p is not in list?!?! \n", cur);
780         } else {
781                 if (p->initid > -1)
782                         ast_sched_del(sched, p->initid);
783                 while((cp = p->packets)) {
784                         p->packets = p->packets->next;
785                         if (cp->retransid > -1)
786                                 ast_sched_del(sched, cp->retransid);
787                         free(cp);
788                 }
789                 free(p);
790         }
791 }
792 static void sip_destroy(struct sip_pvt *p)
793 {
794         ast_pthread_mutex_lock(&iflock);
795         __sip_destroy(p, 1);
796         ast_pthread_mutex_unlock(&iflock);
797 }
798
799 /* Interface lookup code courtesy Tilghman of DrunkCoder.com.  Thanks! */
800
801 struct my_ifreq {
802         char ifrn_name[IFNAMSIZ];       /* Interface name, e.g. "en0".  */
803         struct sockaddr_in ifru_addr;
804 };
805
806 struct in_addr *lookup_iface(char *iface) {
807         int mysock;
808         int res;
809         static struct  my_ifreq ifreq;
810         memset(&ifreq, 0, sizeof(ifreq));
811         strncpy(ifreq.ifrn_name,iface,sizeof(ifreq.ifrn_name) - 1);
812
813         mysock = socket(PF_INET,SOCK_DGRAM,IPPROTO_IP);
814         res = ioctl(mysock,SIOCGIFADDR,&ifreq);
815         
816         close(mysock);
817         if (res < 0) {
818                 ast_log(LOG_WARNING, "Unable to get IP of %s: %s\n", iface, strerror(errno));
819                 return &__ourip;
820         }
821         return( (struct in_addr *) &ifreq.ifru_addr.sin_addr );
822 }
823
824 static struct in_addr *myaddrfor(struct in_addr *them)
825 {
826         FILE *PROC;
827         struct in_addr *temp = NULL;
828         unsigned int remote_ip;
829         char line[256];
830         remote_ip = them->s_addr;
831         
832         PROC = fopen("/proc/net/route","r");
833         if (!PROC) {
834                 /* If /proc/net/route doesn't exist, fall back to the old method */
835                 return &__ourip;
836         }
837         /* First line contains headers */
838         fgets(line,sizeof(line),PROC);
839
840         while (!feof(PROC)) {
841                 char iface[8];
842                 unsigned int dest, gateway, mask;
843                 int i,aoffset;
844                 char *fields[40];
845
846                 fgets(line,sizeof(line),PROC);
847
848                 aoffset = 0;
849                 for (i=0;i<sizeof(line);i++) {
850                         char *boffset;
851
852                         fields[aoffset++] = line + i;
853                         boffset = strchr(line + i,'\t');
854                         if (boffset == NULL) {
855                                 /* Exit loop */
856                                 break;
857                         } else {
858                                 *boffset = '\0';
859                                 i = boffset - line;
860                         }
861                 }
862
863                 sscanf(fields[0],"%s",iface);
864                 sscanf(fields[1],"%x",&dest);
865                 sscanf(fields[2],"%x",&gateway);
866                 sscanf(fields[7],"%x",&mask);
867 #if 0
868                 printf("Addr: %s %08x Dest: %08x Mask: %08x\n", inet_ntoa(*them), remote_ip, dest, mask);
869 #endif          
870                 if (((remote_ip & mask) ^ dest) == 0) {
871                         if (sipdebug)
872                                 ast_verbose("Interface is %s\n",iface);
873                         temp = lookup_iface(iface);
874                         if (sipdebug)
875                                 ast_verbose("IP Address is %s\n",inet_ntoa(*temp));
876                         break;
877                 }
878         }
879         fclose(PROC);
880         if (!temp) {
881                 ast_log(LOG_WARNING, "Couldn't figure out how to get to %s.  Using default\n", inet_ntoa(*them));
882                 temp = &__ourip;
883         }
884         return temp;
885 }
886
887 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req);
888
889
890 static int sip_hangup(struct ast_channel *ast)
891 {
892         struct sip_pvt *p = ast->pvt->pvt;
893         int needcancel = 0;
894         if (option_debug)
895                 ast_log(LOG_DEBUG, "sip_hangup(%s)\n", ast->name);
896         if (!ast->pvt->pvt) {
897                 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
898                 return 0;
899         }
900         ast_pthread_mutex_lock(&p->lock);
901         /* Determine how to disconnect */
902         if (p->owner != ast) {
903                 ast_log(LOG_WARNING, "Huh?  We aren't the owner?\n");
904                 ast_pthread_mutex_unlock(&p->lock);
905                 return 0;
906         }
907         if (!ast || (ast->_state != AST_STATE_UP))
908                 needcancel = 1;
909         /* Disconnect */
910         p = ast->pvt->pvt;
911         if (p->vad) {
912             ast_dsp_free(p->vad);
913         }
914         p->owner = NULL;
915         ast->pvt->pvt = NULL;
916
917         p->needdestroy = 1;
918         /* Start the process if it's not already started */
919         if (!p->alreadygone && strlen(p->initreq.data)) {
920                 if (needcancel) {
921                         if (p->outgoing) {
922                                 transmit_request_with_auth(p, "CANCEL", p->ocseq, 1);
923                                 /* Actually don't destroy us yet, wait for the 487 on our original 
924                                    INVITE, but do set an autodestruct just in case. */
925                                 p->needdestroy = 0;
926                                 sip_scheddestroy(p, 15000);
927                         } else
928                                 transmit_response_reliable(p, "403 Forbidden", &p->initreq);
929                 } else {
930                         if (!p->pendinginvite) {
931                                 /* Send a hangup */
932                                 transmit_request_with_auth(p, "BYE", 0, 1);
933                         } else {
934                                 /* Note we will need a BYE when this all settles out */
935                                 p->pendingbye = 1;
936                         }
937                 }
938         }
939         ast_pthread_mutex_unlock(&p->lock);
940         return 0;
941 }
942
943 static int sip_answer(struct ast_channel *ast)
944 {
945         int res = 0,fmt;
946         char *codec;
947         struct sip_pvt *p = ast->pvt->pvt;
948
949         
950         if (ast->_state != AST_STATE_UP) {
951         
952         
953         
954                 codec=pbx_builtin_getvar_helper(p->owner,"SIP_CODEC");
955                 if (codec) {
956                         ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n",codec);
957                         fmt=ast_getformatbyname(codec);
958                         if (fmt) {
959                                 p->capability=fmt;
960                         } else ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized codec: %s\n",codec);
961                 }
962
963                 ast_setstate(ast, AST_STATE_UP);
964                 if (option_debug)
965                         ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name);
966                 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, 1);
967         }
968         return res;
969 }
970
971 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
972 {
973         struct sip_pvt *p = ast->pvt->pvt;
974         int res = 0;
975         if (frame->frametype != AST_FRAME_VOICE) {
976                 if (frame->frametype == AST_FRAME_IMAGE)
977                         return 0;
978                 else {
979                         ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
980                         return 0;
981                 }
982         } else {
983                 if (!(frame->subclass & ast->nativeformats)) {
984                         ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
985                                 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
986                         return -1;
987                 }
988         }
989         if (p) {
990                 ast_pthread_mutex_lock(&p->lock);
991                 if (p->rtp) {
992                         if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
993                                 transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
994                                 p->progress = 1;
995                         }
996                         res =  ast_rtp_write(p->rtp, frame);
997                 }
998                 ast_pthread_mutex_unlock(&p->lock);
999         }
1000         return res;
1001 }
1002
1003 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1004 {
1005         struct sip_pvt *p = newchan->pvt->pvt;
1006         ast_pthread_mutex_lock(&p->lock);
1007         if (p->owner != oldchan) {
1008                 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
1009                 ast_pthread_mutex_unlock(&p->lock);
1010                 return -1;
1011         }
1012         p->owner = newchan;
1013         ast_pthread_mutex_unlock(&p->lock);
1014         return 0;
1015 }
1016
1017 static int sip_senddigit(struct ast_channel *ast, char digit)
1018 {
1019         struct sip_pvt *p = ast->pvt->pvt;
1020         if (p && (p->dtmfmode & SIP_DTMF_INFO)) {
1021                 transmit_info_with_digit(p, digit);
1022         }
1023         if (p && p->rtp && (p->dtmfmode & SIP_DTMF_RFC2833)) {
1024                 ast_rtp_senddigit(p->rtp, digit);
1025         }
1026         /* If in-band DTMF is desired, send that */
1027         if (p->dtmfmode & SIP_DTMF_INBAND)
1028                 return -1;
1029         return 0;
1030 }
1031
1032 static int sip_indicate(struct ast_channel *ast, int condition)
1033 {
1034         struct sip_pvt *p = ast->pvt->pvt;
1035         switch(condition) {
1036         case AST_CONTROL_RINGING:
1037                 if (ast->_state == AST_STATE_RING) {
1038                         transmit_response(p, "180 Ringing", &p->initreq);
1039                         break;
1040                 }
1041                 return -1;
1042         case AST_CONTROL_BUSY:
1043                 if (ast->_state != AST_STATE_UP) {
1044                         transmit_response(p, "600 Busy everywhere", &p->initreq);
1045                         p->alreadygone = 1;
1046                         ast_softhangup(ast, AST_SOFTHANGUP_DEV);
1047                         break;
1048                 }
1049                 return -1;
1050         case AST_CONTROL_CONGESTION:
1051                 if (ast->_state != AST_STATE_UP) {
1052                         transmit_response(p, "486 Busy here", &p->initreq);
1053                         p->alreadygone = 1;
1054                         ast_softhangup(ast, AST_SOFTHANGUP_DEV);
1055                         break;
1056                 }
1057                 return -1;
1058         case -1:
1059                 return -1;
1060         default:
1061                 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
1062                 return -1;
1063         }
1064         return 0;
1065 }
1066
1067
1068
1069 static struct ast_channel *sip_new(struct sip_pvt *i, int state, char *title)
1070 {
1071         struct ast_channel *tmp;
1072         int fmt;
1073         tmp = ast_channel_alloc(1);
1074         if (tmp) {
1075                 /* Select our native format based on codec preference until we receive
1076                    something from another device to the contrary. */
1077                 if (i->capability)
1078                         tmp->nativeformats = sip_codec_choose(i->capability);
1079                 else 
1080                         tmp->nativeformats = sip_codec_choose(capability);
1081                 fmt = ast_best_codec(tmp->nativeformats);
1082                 if (title)
1083                         snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%04x", title, rand() & 0xffff);
1084                 else
1085                         snprintf(tmp->name, sizeof(tmp->name), "SIP/%s:%d", inet_ntoa(i->sa.sin_addr), ntohs(i->sa.sin_port));
1086                 tmp->type = type;
1087                 if (i->dtmfmode & SIP_DTMF_INBAND) {
1088                     i->vad = ast_dsp_new();
1089                     ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
1090                 }
1091                 tmp->fds[0] = ast_rtp_fd(i->rtp);
1092                 ast_setstate(tmp, state);
1093                 if (state == AST_STATE_RING)
1094                         tmp->rings = 1;
1095                 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
1096                 tmp->writeformat = fmt;
1097                 tmp->pvt->rawwriteformat = fmt;
1098                 tmp->readformat = fmt;
1099                 tmp->pvt->rawreadformat = fmt;
1100                 tmp->pvt->pvt = i;
1101                 tmp->pvt->send_text = sip_sendtext;
1102                 tmp->pvt->call = sip_call;
1103                 tmp->pvt->hangup = sip_hangup;
1104                 tmp->pvt->answer = sip_answer;
1105                 tmp->pvt->read = sip_read;
1106                 tmp->pvt->write = sip_write;
1107                 tmp->pvt->indicate = sip_indicate;
1108                 tmp->pvt->fixup = sip_fixup;
1109                 tmp->pvt->send_digit = sip_senddigit;
1110                 tmp->pvt->bridge = ast_rtp_bridge;
1111                 if (strlen(i->language))
1112                         strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
1113                 i->owner = tmp;
1114                 ast_pthread_mutex_lock(&usecnt_lock);
1115                 usecnt++;
1116                 ast_pthread_mutex_unlock(&usecnt_lock);
1117                 ast_update_use_count();
1118                 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
1119                 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
1120                 if (strlen(i->callerid))
1121                         tmp->callerid = strdup(i->callerid);
1122                 tmp->priority = 1;
1123                 if (state != AST_STATE_DOWN) {
1124                         if (ast_pbx_start(tmp)) {
1125                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
1126                                 ast_hangup(tmp);
1127                                 tmp = NULL;
1128                         }
1129                 }
1130         } else
1131                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
1132         return tmp;
1133 }
1134
1135 static struct cfalias {
1136         char *fullname;
1137         char *shortname;
1138 } aliases[] = {
1139         { "Content-Type", "c" },
1140         { "Content-Encoding", "e" },
1141         { "From", "f" },
1142         { "Call-ID", "i" },
1143         { "Contact", "m" },
1144         { "Content-Length", "l" },
1145         { "Subject", "s" },
1146         { "To", "t" },
1147         { "Via", "v" },
1148 };
1149
1150 static char* get_sdp_by_line(char* line, char *name, int nameLen) {
1151   if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
1152     char* r = line + nameLen + 1;
1153     while (*r && (*r < 33)) ++r;
1154     return r;
1155   }
1156
1157   return "";
1158 }
1159
1160 static char *get_sdp(struct sip_request *req, char *name) {
1161   int x;
1162   int len = strlen(name);
1163   char *r;
1164
1165   for (x=0; x<req->lines; x++) {
1166     r = get_sdp_by_line(req->line[x], name, len);
1167     if (r[0] != '\0') return r;
1168   }
1169   return "";
1170 }
1171
1172 static void sdpLineNum_iterator_init(int* iterator) {
1173   *iterator = 0;
1174 }
1175
1176 static char* get_sdp_iterate(int* iterator,
1177                              struct sip_request *req, char *name) {
1178   int len = strlen(name);
1179   char *r;
1180   while (*iterator < req->lines) {
1181     r = get_sdp_by_line(req->line[(*iterator)++], name, len);
1182     if (r[0] != '\0') return r;
1183   }
1184   return "";
1185 }
1186
1187 static char *__get_header(struct sip_request *req, char *name, int *start)
1188 {
1189         int x;
1190         int len = strlen(name);
1191         char *r;
1192         for (x=*start;x<req->headers;x++) {
1193                 if (!strncasecmp(req->header[x], name, len) && 
1194                                 (req->header[x][len] == ':')) {
1195                                         r = req->header[x] + len + 1;
1196                                         while(*r && (*r < 33))
1197                                                         r++;
1198                                         *start = x+1;
1199                                         return r;
1200                 }
1201         }
1202         /* Try aliases */
1203         for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++) 
1204                 if (!strcasecmp(aliases[x].fullname, name))
1205                         return __get_header(req, aliases[x].shortname, start);
1206
1207         /* Don't return NULL, so get_header is always a valid pointer */
1208         return "";
1209 }
1210
1211 static char *get_header(struct sip_request *req, char *name)
1212 {
1213         int start = 0;
1214         return __get_header(req, name, &start);
1215 }
1216
1217 static struct ast_frame *sip_rtp_read(struct sip_pvt *p)
1218 {
1219         /* Retrieve audio/etc from channel.  Assumes p->lock is already held. */
1220         struct ast_frame *f;
1221         static struct ast_frame null_frame = { AST_FRAME_NULL, };
1222         f = ast_rtp_read(p->rtp);
1223         /* Don't send RFC2833 if we're not supposed to */
1224         if (f && (f->frametype == AST_FRAME_DTMF) && !(p->dtmfmode & SIP_DTMF_RFC2833))
1225                 return &null_frame;
1226         if (p->owner) {
1227                 /* We already hold the channel lock */
1228                 if (f->frametype == AST_FRAME_VOICE) {
1229                         if (f->subclass != p->owner->nativeformats) {
1230                                 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
1231                                 p->owner->nativeformats = f->subclass;
1232                                 ast_set_read_format(p->owner, p->owner->readformat);
1233                                 ast_set_write_format(p->owner, p->owner->writeformat);
1234                         }
1235             if (p->dtmfmode & SIP_DTMF_INBAND) {
1236                    f = ast_dsp_process(p->owner,p->vad,f,0);
1237             }
1238                 }
1239         }
1240         return f;
1241 }
1242
1243 static struct ast_frame *sip_read(struct ast_channel *ast)
1244 {
1245         struct ast_frame *fr;
1246         struct sip_pvt *p = ast->pvt->pvt;
1247         ast_pthread_mutex_lock(&p->lock);
1248         fr = sip_rtp_read(p);
1249         ast_pthread_mutex_unlock(&p->lock);
1250         return fr;
1251 }
1252
1253 static void build_callid(char *callid, int len, struct in_addr ourip)
1254 {
1255         int res;
1256         int val;
1257         int x;
1258         for (x=0;x<4;x++) {
1259                 val = rand();
1260                 res = snprintf(callid, len, "%08x", val);
1261                 len -= res;
1262                 callid += res;
1263         }
1264         /* It's not important that we really use our right IP here... */
1265         snprintf(callid, len, "@%s", inet_ntoa(ourip));
1266 }
1267
1268 static struct sip_pvt *sip_alloc(char *callid, struct sockaddr_in *sin, int useglobalnat)
1269 {
1270         struct sip_pvt *p;
1271
1272         p = malloc(sizeof(struct sip_pvt));
1273         if (!p)
1274                 return NULL;
1275         /* Keep track of stuff */
1276         memset(p, 0, sizeof(struct sip_pvt));
1277         p->initid = -1;
1278         p->autokillid = -1;
1279         p->stateid = -1;
1280         p->rtp = ast_rtp_new(NULL, NULL);
1281         p->branch = rand();     
1282         p->tag = rand();
1283         
1284         /* Start with 101 instead of 1 */
1285         p->ocseq = 101;
1286         if (!p->rtp) {
1287                 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
1288                 free(p);
1289                 return NULL;
1290         }
1291         ast_rtp_settos(p->rtp, tos);
1292         if (useglobalnat && sin) {
1293                 /* Setup NAT structure according to global settings if we have an address */
1294                 p->nat = globalnat;
1295                 memcpy(&p->recv, sin, sizeof(p->recv));
1296                 ast_rtp_setnat(p->rtp, p->nat);
1297         }
1298         ast_pthread_mutex_init(&p->lock);
1299 #if 0
1300         ast_rtp_set_data(p->rtp, p);
1301         ast_rtp_set_callback(p->rtp, rtpready);
1302 #endif  
1303         if (sin) {
1304                 memcpy(&p->sa, sin, sizeof(p->sa));
1305                 memcpy(&p->ourip, myaddrfor(&p->sa.sin_addr), sizeof(p->ourip));
1306         } else {
1307                 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
1308         }
1309         snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=%08x", inet_ntoa(p->ourip), ourport, p->branch);
1310         if (!callid)
1311                 build_callid(p->callid, sizeof(p->callid), p->ourip);
1312         else
1313                 strncpy(p->callid, callid, sizeof(p->callid) - 1);
1314         /* Assume reinvite OK and via INVITE */
1315         p->canreinvite = REINVITE_INVITE;
1316         p->dtmfmode = globaldtmfmode;
1317         if (p->dtmfmode & SIP_DTMF_RFC2833)
1318                 p->noncodeccapability |= AST_RTP_DTMF;
1319         strncpy(p->context, context, sizeof(p->context) - 1);
1320         strncpy(p->fromdomain, fromdomain, sizeof(p->fromdomain) - 1);
1321         /* Add to list */
1322         ast_pthread_mutex_lock(&iflock);
1323         p->next = iflist;
1324         iflist = p;
1325         ast_pthread_mutex_unlock(&iflock);
1326         if (option_debug)
1327                 ast_log(LOG_DEBUG, "Allocating new SIP call for %s\n", callid);
1328         return p;
1329 }
1330
1331 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin)
1332 {
1333         struct sip_pvt *p;
1334         char *callid;
1335         callid = get_header(req, "Call-ID");
1336         if (!strlen(callid)) {
1337                 ast_log(LOG_WARNING, "Call missing call ID from '%s'\n", inet_ntoa(sin->sin_addr));
1338                 return NULL;
1339         }
1340         ast_pthread_mutex_lock(&iflock);
1341         p = iflist;
1342         while(p) {
1343                 if (!strcmp(p->callid, callid)) {
1344                         /* Found the call */
1345 #if 0
1346                         if (!p->insecure && ((p->sa.sin_addr.s_addr != sin->sin_addr.s_addr) ||
1347                             (p->sa.sin_port != sin->sin_port))) {
1348                                         char orig[80];
1349                                         char new[80];
1350                                         snprintf(orig, sizeof(orig), "%s:%d", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
1351                                         snprintf(new, sizeof(new), "%s:%d", inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
1352                                         ast_log(LOG_WARNING, "Looks like %s is trying to steal call '%s' from %s?\n", new, p->callid, orig);
1353                                         ast_pthread_mutex_unlock(&iflock);
1354                                         return NULL;
1355                         }
1356 #endif
1357                         ast_pthread_mutex_lock(&p->lock);
1358                         ast_pthread_mutex_unlock(&iflock);
1359                         return p;
1360                 }
1361                 p = p->next;
1362         }
1363         ast_pthread_mutex_unlock(&iflock);
1364         return sip_alloc(callid, sin, 1);
1365 }
1366
1367 static int sip_register(char *value, int lineno)
1368 {
1369         struct sip_registry *reg;
1370         char copy[256] = "";
1371         char *username, *hostname, *secret;
1372         char *porta;
1373         char *contact;
1374         char *stringp=NULL;
1375         
1376         struct hostent *hp;
1377         if (!value)
1378                 return -1;
1379         strncpy(copy, value, sizeof(copy)-1);
1380         stringp=copy;
1381         username = stringp;
1382         hostname = strrchr(stringp, '@');
1383         if (hostname) {
1384                 *hostname = '\0';
1385                 hostname++;
1386         }
1387         if (!hostname) {
1388                 ast_log(LOG_WARNING, "Format for registration is user[:secret]@host[:port] at line %d", lineno);
1389                 return -1;
1390         }
1391         stringp=username;
1392         username = strsep(&stringp, ":");
1393         secret = strsep(&stringp, ":");
1394         stringp = hostname;
1395         hostname = strsep(&stringp, "/");
1396         contact = strsep(&stringp, "/");
1397         if (!contact || !strlen(contact))
1398                 contact = "s";
1399         stringp=hostname;
1400         hostname = strsep(&stringp, ":");
1401         porta = strsep(&stringp, ":");
1402         
1403         if (porta && !atoi(porta)) {
1404                 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
1405                 return -1;
1406         }
1407         hp = gethostbyname(hostname);
1408         if (!hp) {
1409                 ast_log(LOG_WARNING, "Host '%s' not found at line %d\n", hostname, lineno);
1410                 return -1;
1411         }
1412         reg = malloc(sizeof(struct sip_registry));
1413         if (reg) {
1414                 memset(reg, 0, sizeof(struct sip_registry));
1415                 strncpy(reg->contact, contact, sizeof(reg->contact) - 1);
1416                 strncpy(reg->username, username, sizeof(reg->username)-1);
1417                 if (secret)
1418                         strncpy(reg->secret, secret, sizeof(reg->secret)-1);
1419                 reg->expire = -1;
1420                 reg->refresh = default_expirey;
1421                 reg->addr.sin_family = AF_INET;
1422                 memcpy(&reg->addr.sin_addr, hp->h_addr, sizeof(&reg->addr.sin_addr));
1423                 reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(DEFAULT_SIP_PORT);
1424                 reg->next = registrations;
1425                 reg->callid_valid = 0;
1426                 registrations = reg;
1427         } else {
1428                 ast_log(LOG_ERROR, "Out of memory\n");
1429                 return -1;
1430         }
1431         return 0;
1432 }
1433
1434 static void parse(struct sip_request *req)
1435 {
1436         /* Divide fields by NULL's */
1437         char *c;
1438         int f = 0;
1439         c = req->data;
1440
1441         /* First header starts immediately */
1442         req->header[f] = c;
1443         while(*c) {
1444                 if (*c == '\n') {
1445                         /* We've got a new header */
1446                         *c = 0;
1447
1448 #if 0
1449                         printf("Header: %s (%d)\n", req->header[f], strlen(req->header[f]));
1450 #endif                  
1451                         if (!strlen(req->header[f])) {
1452                                 /* Line by itself means we're now in content */
1453                                 c++;
1454                                 break;
1455                         }
1456                         if (f >= SIP_MAX_HEADERS - 1) {
1457                                 ast_log(LOG_WARNING, "Too many SIP headers...\n");
1458                         } else
1459                                 f++;
1460                         req->header[f] = c + 1;
1461                 } else if (*c == '\r') {
1462                         /* Ignore but eliminate \r's */
1463                         *c = 0;
1464                 }
1465                 c++;
1466         }
1467         /* Check for last header */
1468         if (strlen(req->header[f])) 
1469                 f++;
1470         req->headers = f;
1471         /* Now we process any mime content */
1472         f = 0;
1473         req->line[f] = c;
1474         while(*c) {
1475                 if (*c == '\n') {
1476                         /* We've got a new line */
1477                         *c = 0;
1478 #if 0
1479                         printf("Line: %s (%d)\n", req->line[f], strlen(req->line[f]));
1480 #endif                  
1481                         if (f >= SIP_MAX_LINES - 1) {
1482                                 ast_log(LOG_WARNING, "Too many SDP lines...\n");
1483                         } else
1484                                 f++;
1485                         req->line[f] = c + 1;
1486                 } else if (*c == '\r') {
1487                         /* Ignore and eliminate \r's */
1488                         *c = 0;
1489                 }
1490                 c++;
1491         }
1492         /* Check for last line */
1493         if (strlen(req->line[f])) 
1494                 f++;
1495         req->lines = f;
1496         if (sipdebug)
1497                 ast_verbose("%d headers, %d lines\n", req->headers, req->lines);
1498         if (*c) 
1499                 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
1500 }
1501
1502 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
1503 {
1504         char *m;
1505         char *c;
1506         char *a;
1507         char host[258];
1508         int len = -1;
1509         int portno;
1510         int peercapability, peernoncodeccapability;
1511         struct sockaddr_in sin;
1512         char *codecs;
1513         struct hostent *hp;
1514         int codec;
1515         int iterator;
1516
1517         /* Get codec and RTP info from SDP */
1518         if (strcasecmp(get_header(req, "Content-Type"), "application/sdp")) {
1519                 ast_log(LOG_NOTICE, "Content is '%s', not 'application/sdp'\n", get_header(req, "Content-Type"));
1520                 return -1;
1521         }
1522         m = get_sdp(req, "m");
1523         c = get_sdp(req, "c");
1524         if (!strlen(m) || !strlen(c)) {
1525                 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
1526                 return -1;
1527         }
1528         if (sscanf(c, "IN IP4 %256s", host) != 1) {
1529                 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
1530                 return -1;
1531         }
1532         /* XXX This could block for a long time, and block the main thread! XXX */
1533         hp = gethostbyname(host);
1534         if (!hp) {
1535                 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
1536                 return -1;
1537         }
1538         if ((sscanf(m, "audio %d RTP/AVP %n", &portno, &len) != 1) || (len < 0)) {
1539                 ast_log(LOG_WARNING, "Unable to determine port number for RTP in '%s'\n", m); 
1540                 return -1;
1541         }
1542         sin.sin_family = AF_INET;
1543         memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
1544         sin.sin_port = htons(portno);
1545         if (p->rtp)
1546                 ast_rtp_set_peer(p->rtp, &sin);
1547 #if 0
1548         printf("Peer RTP is at port %s:%d\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
1549 #endif  
1550         // Scan through the RTP payload types specified in a "m=" line:
1551         ast_rtp_pt_clear(p->rtp);
1552         codecs = m + len;
1553         while(strlen(codecs)) {
1554                 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
1555                         ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
1556                         return -1;
1557                 }
1558                 ast_rtp_set_m_type(p->rtp, codec);
1559                 codecs += len;
1560                 /* Skip over any whitespace */
1561                 while(*codecs && (*codecs < 33)) codecs++;
1562         }
1563
1564         // Next, scan through each "a=rtpmap:" line, noting each
1565         // specified RTP payload type (with corresponding MIME subtype):
1566         sdpLineNum_iterator_init(&iterator);
1567         while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
1568           char* mimeSubtype = strdup(a); // ensures we have enough space
1569           if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) != 2) continue;
1570           // Note: should really look at the 'freq' and '#chans' params too
1571           ast_rtp_set_rtpmap_type(p->rtp, codec, "audio", mimeSubtype);
1572           free(mimeSubtype);
1573         }
1574
1575         // Now gather all of the codecs that were asked for:
1576         ast_rtp_get_current_formats(p->rtp,
1577                                 &peercapability, &peernoncodeccapability);
1578         p->capability = capability & peercapability;
1579         p->noncodeccapability = noncodeccapability & peernoncodeccapability;
1580         if (sipdebug) {
1581                 ast_verbose("Capabilities: us - %d, them - %d, combined - %d\n",
1582                             capability, peercapability, p->capability);
1583                 ast_verbose("Non-codec capabilities: us - %d, them - %d, combined - %d\n",
1584                             noncodeccapability, peernoncodeccapability,
1585                             p->noncodeccapability);
1586         }
1587         if (!p->capability) {
1588                 ast_log(LOG_WARNING, "No compatible codecs!\n");
1589                 return -1;
1590         }
1591         if (p->owner) {
1592                 if (!(p->owner->nativeformats & p->capability)) {
1593                         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);
1594                         p->owner->nativeformats = sip_codec_choose(p->capability);
1595                         ast_set_read_format(p->owner, p->owner->readformat);
1596                         ast_set_write_format(p->owner, p->owner->writeformat);
1597                 }
1598                 if (p->owner->bridge) {
1599                         /* Turn on/off music on hold if we are holding/unholding */
1600                         if (sin.sin_addr.s_addr) {
1601                                 ast_moh_stop(p->owner->bridge);
1602                         } else {
1603                                 ast_moh_start(p->owner->bridge, NULL);
1604                         }
1605                 }
1606         }
1607         return 0;
1608         
1609 }
1610
1611 static int add_header(struct sip_request *req, char *var, char *value)
1612 {
1613         if (req->len >= sizeof(req->data) - 4) {
1614                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1615                 return -1;
1616         }
1617         if (req->lines) {
1618                 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1619                 return -1;
1620         }
1621         req->header[req->headers] = req->data + req->len;
1622         snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", var, value);
1623         req->len += strlen(req->header[req->headers]);
1624         if (req->headers < SIP_MAX_HEADERS)
1625                 req->headers++;
1626         else {
1627                 ast_log(LOG_WARNING, "Out of header space\n");
1628                 return -1;
1629         }
1630         return 0;       
1631 }
1632
1633 static int add_blank_header(struct sip_request *req)
1634 {
1635         if (req->len >= sizeof(req->data) - 4) {
1636                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1637                 return -1;
1638         }
1639         if (req->lines) {
1640                 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1641                 return -1;
1642         }
1643         req->header[req->headers] = req->data + req->len;
1644         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "\r\n");
1645         req->len += strlen(req->header[req->headers]);
1646         if (req->headers < SIP_MAX_HEADERS)
1647                 req->headers++;
1648         else {
1649                 ast_log(LOG_WARNING, "Out of header space\n");
1650                 return -1;
1651         }
1652         return 0;       
1653 }
1654
1655 static int add_line(struct sip_request *req, char *line)
1656 {
1657         if (req->len >= sizeof(req->data) - 4) {
1658                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1659                 return -1;
1660         }
1661         if (!req->lines) {
1662                 /* Add extra empty return */
1663                 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
1664                 req->len += strlen(req->data + req->len);
1665         }
1666         req->line[req->lines] = req->data + req->len;
1667         snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
1668         req->len += strlen(req->line[req->lines]);
1669         if (req->lines < SIP_MAX_LINES)
1670                 req->lines++;
1671         else {
1672                 ast_log(LOG_WARNING, "Out of line space\n");
1673                 return -1;
1674         }
1675         return 0;       
1676 }
1677
1678 static int copy_header(struct sip_request *req, struct sip_request *orig, char *field)
1679 {
1680         char *tmp;
1681         tmp = get_header(orig, field);
1682         if (strlen(tmp)) {
1683                 /* Add what we're responding to */
1684                 return add_header(req, field, tmp);
1685         }
1686         ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1687         return -1;
1688 }
1689
1690 static int copy_all_header(struct sip_request *req, struct sip_request *orig, char *field)
1691 {
1692         char *tmp;
1693         int start = 0;
1694         int copied = 0;
1695         for (;;) {
1696                 tmp = __get_header(orig, field, &start);
1697                 if (strlen(tmp)) {
1698                         /* Add what we're responding to */
1699                         add_header(req, field, tmp);
1700                         copied++;
1701                 } else
1702                         break;
1703         }
1704         return copied ? 0 : -1;
1705 }
1706
1707 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, struct sip_request *orig, char *field)
1708 {
1709         char *tmp;
1710         int start = 0;
1711         int copied = 0;
1712         char new[256];
1713         for (;;) {
1714                 tmp = __get_header(orig, field, &start);
1715                 if (strlen(tmp)) {
1716                         if (!copied && p->nat) {
1717                                 /* SLD: FIXME: Nice try, but the received= should not have a port */
1718                                 /* SLD: FIXME: See RFC2543 BNF in Section 6.40.5 */
1719                                 if (ntohs(p->recv.sin_port) != DEFAULT_SIP_PORT)
1720                                         snprintf(new, sizeof(new), "%s;received=%s:%d", tmp, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
1721                                 else
1722                                         snprintf(new, sizeof(new), "%s;received=%s", tmp, inet_ntoa(p->recv.sin_addr));
1723                                 add_header(req, field, new);
1724                         } else {
1725                                 /* Add what we're responding to */
1726                                 add_header(req, field, tmp);
1727                         }
1728                         copied++;
1729                 } else
1730                         break;
1731         }
1732         if (!copied) {
1733                 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1734                 return -1;
1735         }
1736         return 0;
1737 }
1738
1739 /* Add Route: header into request per learned route */
1740 static void add_route(struct sip_request *req, struct sip_route *route)
1741 {
1742         char r[256], *p;
1743         int n, rem = 255; /* sizeof(r)-1: Room for terminating 0 */
1744
1745         if (!route) return;
1746
1747         p = r;
1748         while (route) {
1749                 n = strlen(route->hop);
1750                 if ((n+3)>rem) break;
1751                 if (p != r) {
1752                         *p++ = ',';
1753                         --rem;
1754                 }
1755                 *p++ = '<';
1756                 strcpy(p, route->hop);  p += n;
1757                 *p++ = '>';
1758                 rem -= (n+2);
1759                 route = route->next;
1760         }
1761         *p = '\0';
1762         add_header(req, "Route", r);
1763 }
1764
1765 static void set_destination(struct sip_pvt *p, char *uri)
1766 {
1767         char *h, *maddr, hostname[256];
1768         int port, hn;
1769         struct hostent *hp;
1770
1771         /* Parse uri to h (host) and port - uri is already just the part inside the <> */
1772         /* general form we are expecting is sip[s]:username[:password]@host[:port][;...] */
1773
1774         if (sipdebug)
1775                 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
1776
1777         /* Find and parse hostname */
1778         h = strchr(uri, '@');
1779         if (h)
1780                 ++h;
1781         else {
1782                 h = uri;
1783                 if (strncmp(h, "sip:", 4) == 0)
1784                         h += 4;
1785                 else if (strncmp(h, "sips:", 5) == 0)
1786                         h += 5;
1787         }
1788         hn = strcspn(h, ":;>");
1789         if (hn>255) hn=255;
1790         strncpy(hostname, h, hn);  hostname[hn] = '\0';
1791         h+=hn;
1792
1793         /* Is "port" present? if not default to 5060 */
1794         if (*h == ':') {
1795                 /* Parse port */
1796                 ++h;
1797                 port = strtol(h, &h, 10);
1798         }
1799         else
1800                 port = 5060;
1801
1802         /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
1803         maddr = strstr(h, "maddr=");
1804         if (maddr) {
1805                 maddr += 6;
1806                 hn = strspn(maddr, "0123456789.");
1807                 if (hn>255) hn=255;
1808                 strncpy(hostname, maddr, hn);  hostname[hn] = '\0';
1809         }
1810         
1811         hp = gethostbyname(hostname);
1812         if (hp == NULL)  {
1813                 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
1814                 return;
1815         }
1816         p->sa.sin_family = AF_INET;
1817         memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
1818         p->sa.sin_port = htons(port);
1819         if (sipdebug)
1820                 ast_verbose("set_destination: set destination to %s, port %d\n", inet_ntoa(p->sa.sin_addr), port);
1821 }
1822
1823 static int init_resp(struct sip_request *req, char *resp, struct sip_request *orig)
1824 {
1825         /* Initialize a response */
1826         if (req->headers || req->len) {
1827                 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1828                 return -1;
1829         }
1830         req->header[req->headers] = req->data + req->len;
1831         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "SIP/2.0 %s\r\n", resp);
1832         req->len += strlen(req->header[req->headers]);
1833         if (req->headers < SIP_MAX_HEADERS)
1834                 req->headers++;
1835         else
1836                 ast_log(LOG_WARNING, "Out of header space\n");
1837         return 0;
1838 }
1839
1840 static int init_req(struct sip_request *req, char *resp, char *recip)
1841 {
1842         /* Initialize a response */
1843         if (req->headers || req->len) {
1844                 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1845                 return -1;
1846         }
1847         req->header[req->headers] = req->data + req->len;
1848         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s SIP/2.0\r\n", resp, recip);
1849         req->len += strlen(req->header[req->headers]);
1850         if (req->headers < SIP_MAX_HEADERS)
1851                 req->headers++;
1852         else
1853                 ast_log(LOG_WARNING, "Out of header space\n");
1854         return 0;
1855 }
1856
1857 static void append_contact(struct sip_request *req, struct sip_pvt *p)
1858 {
1859         /* Add contact header */
1860         char contact2[256] ="", *c, *c2, contact[256];
1861         char *from;
1862         if (p->outgoing)
1863                 from = get_header(req, "From");
1864         else
1865                 from = get_header(req, "To");
1866         strncpy(contact2, from, sizeof(contact2)-1);
1867         if (strlen(contact2)) {
1868                 c = ditch_braces(contact2);
1869                 c2 = strchr(c, ';');
1870                 if (c2) *c2 = '\0';
1871                 snprintf(contact, sizeof(contact), "<%s>", c);
1872                 add_header(req, "Contact", contact);
1873         }
1874 }
1875
1876 static int respprep(struct sip_request *resp, struct sip_pvt *p, char *msg, struct sip_request *req)
1877 {
1878         char newto[256] = "", *ot;
1879         memset(resp, 0, sizeof(*resp));
1880         init_resp(resp, msg, req);
1881         copy_via_headers(p, resp, req, "Via");
1882         if (msg[0] == '2') copy_all_header(resp, req, "Record-Route");
1883         copy_header(resp, req, "From");
1884         ot = get_header(req, "To");
1885         if (!strstr(ot, "tag=")) {
1886                 /* Add the proper tag if we don't have it already.  If they have specified
1887                    their tag, use it.  Otherwise, use our own tag */
1888                 if (strlen(p->theirtag) && p->outgoing)
1889                         snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
1890                 else if (p->tag && !p->outgoing)
1891                         snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
1892                 else
1893                         strncpy(newto, ot, sizeof(newto) - 1);
1894                 ot = newto;
1895         }
1896         add_header(resp, "To", ot);
1897         copy_header(resp, req, "Call-ID");
1898         copy_header(resp, req, "CSeq");
1899         add_header(resp, "User-Agent", "Asterisk PBX");
1900         if (p->expirey) {
1901                 /* For registration responses, we also need expirey and
1902                    contact info */
1903                 char tmp[80];
1904                 char contact[256];
1905                 char *c;
1906                 if ((c=getsipuri(ot))) {
1907                         snprintf(contact, sizeof(contact), "<%s@%s:%d>;expires=%d", c, inet_ntoa(p->ourip), ourport, p->expirey);
1908                         free(c);
1909                 } else {
1910                         snprintf(contact, sizeof(contact), "<%s:%d>;expires=%d", inet_ntoa(p->ourip), ourport, p->expirey);
1911                 }
1912                 snprintf(tmp, sizeof(tmp), "%d", p->expirey);
1913                 add_header(resp, "Expires", tmp);
1914                 add_header(resp, "Contact", contact);
1915         } else {
1916                 char contact[256];
1917                 /* XXX This isn't exactly right and it's implemented
1918                        very stupidly *sigh* XXX */
1919                 char *c;
1920                 if ((c=getsipuri(ot))) {
1921                         snprintf(contact, sizeof(contact), "<%s@%s:%d>", c, inet_ntoa(p->ourip), ourport);
1922                         free(c);
1923                 } else {
1924                         snprintf(contact, sizeof(contact), "<%s:%d>", inet_ntoa(p->ourip), ourport);
1925                 }
1926                 add_header(resp, "Contact", contact);
1927         }
1928         return 0;
1929 }
1930
1931 static int reqprep(struct sip_request *req, struct sip_pvt *p, char *msg, int seqno)
1932 {
1933         struct sip_request *orig = &p->initreq;
1934         char stripped[80] ="";
1935         char tmp[80];
1936         char newto[256];
1937         char *c, *n;
1938         char *ot, *of;
1939
1940         memset(req, 0, sizeof(struct sip_request));
1941         
1942         if (!seqno) {
1943                 p->ocseq++;
1944                 seqno = p->ocseq;
1945         }
1946
1947         if (p->outgoing)
1948                 strncpy(stripped, get_header(orig, "To"), sizeof(stripped) - 1);
1949         else
1950                 strncpy(stripped, get_header(orig, "From"), sizeof(stripped) - 1);
1951         
1952         c = strchr(stripped, '<');
1953         if (c) 
1954                 c++;
1955         else
1956                 c = stripped;
1957         n = strchr(c, '>');
1958         if (n)
1959                 *n = '\0';
1960         n = strchr(c, ';');
1961         if (n)
1962                 *n = '\0';
1963         
1964         init_req(req, msg, c);
1965
1966         snprintf(tmp, sizeof(tmp), "%d %s", seqno, msg);
1967
1968         add_header(req, "Via", p->via);
1969         if (p->route) {
1970                 set_destination(p, p->route->hop);
1971                 add_route(req, p->route->next);
1972         }
1973
1974         ot = get_header(orig, "To");
1975         of = get_header(orig, "From");
1976
1977         /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
1978            as our original request, including tag (or presumably lack thereof) */
1979         if (!strstr(ot, "tag=") && strcasecmp(msg, "CANCEL")) {
1980                 /* Add the proper tag if we don't have it already.  If they have specified
1981                    their tag, use it.  Otherwise, use our own tag */
1982                 if (p->outgoing && strlen(p->theirtag))
1983                         snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
1984                 else if (!p->outgoing)
1985                         snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
1986                 else
1987                         snprintf(newto, sizeof(newto), "%s", ot);
1988                 ot = newto;
1989         }
1990
1991         if (p->outgoing) {
1992                 add_header(req, "From", of);
1993                 add_header(req, "To", ot);
1994         } else {
1995                 add_header(req, "From", ot);
1996                 add_header(req, "To", of);
1997         }
1998         append_contact(req, p);
1999         copy_header(req, orig, "Call-ID");
2000         add_header(req, "CSeq", tmp);
2001
2002         add_header(req, "User-Agent", "Asterisk PBX");
2003         return 0;
2004 }
2005
2006 static int __transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req, int reliable)
2007 {
2008         struct sip_request resp;
2009         int seqno = 0;
2010         if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
2011                 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
2012                 return -1;
2013         }
2014         respprep(&resp, p, msg, req);
2015         add_header(&resp, "Content-Length", "0");
2016         add_blank_header(&resp);
2017         return send_response(p, &resp, reliable, seqno);
2018 }
2019
2020 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req) 
2021 {
2022         return __transmit_response(p, msg, req, 0);
2023 }
2024 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req)
2025 {
2026         return __transmit_response(p, msg, req, 1);
2027 }
2028
2029 static void append_date(struct sip_request *req)
2030 {
2031         char tmpdat[256];
2032         struct tm tm;
2033         time_t t;
2034         time(&t);
2035         gmtime_r(&t, &tm);
2036         strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
2037         add_header(req, "Date", tmpdat);
2038 }
2039
2040 static int transmit_response_with_date(struct sip_pvt *p, char *msg, struct sip_request *req)
2041 {
2042         struct sip_request resp;
2043         respprep(&resp, p, msg, req);
2044         append_date(&resp);
2045         add_header(&resp, "Content-Length", "0");
2046         add_blank_header(&resp);
2047         return send_response(p, &resp, 0, 0);
2048 }
2049
2050 static int transmit_response_with_allow(struct sip_pvt *p, char *msg, struct sip_request *req)
2051 {
2052         struct sip_request resp;
2053         respprep(&resp, p, msg, req);
2054         add_header(&resp, "Allow", "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER");
2055         add_header(&resp, "Accept", "application/sdp");
2056         add_header(&resp, "Content-Length", "0");
2057         add_blank_header(&resp);
2058         return send_response(p, &resp, 0, 0);
2059 }
2060
2061 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *randdata, int reliable)
2062 {
2063         struct sip_request resp;
2064         char tmp[256];
2065         int seqno = 0;
2066         if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
2067                 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
2068                 return -1;
2069         }
2070         snprintf(tmp, sizeof(tmp), "Digest realm=\"asterisk\", nonce=\"%s\"", randdata);
2071         respprep(&resp, p, msg, req);
2072         add_header(&resp, "Proxy-Authenticate", tmp);
2073         add_header(&resp, "Content-Length", "0");
2074         add_blank_header(&resp);
2075         return send_response(p, &resp, reliable, seqno);
2076 }
2077
2078 static int add_text(struct sip_request *req, char *text)
2079 {
2080         /* XXX Convert \n's to \r\n's XXX */
2081         int len = strlen(text);
2082         char clen[256];
2083         snprintf(clen, sizeof(clen), "%d", len);
2084         add_header(req, "Content-Type", "text/plain");
2085         add_header(req, "Content-Length", clen);
2086         add_line(req, text);
2087         return 0;
2088 }
2089
2090 static int add_digit(struct sip_request *req, char digit)
2091 {
2092         char tmp[256];
2093         int len;
2094         char clen[256];
2095         snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=250\r\n", digit);
2096         len = strlen(tmp);
2097         snprintf(clen, sizeof(clen), "%d", len);
2098         add_header(req, "Content-Type", "application/dtmf-relay");
2099         add_header(req, "Content-Length", clen);
2100         add_line(req, tmp);
2101         return 0;
2102 }
2103
2104 static int add_sdp(struct sip_request *resp, struct sip_pvt *p, struct ast_rtp *rtp)
2105 {
2106         int len;
2107         int codec;
2108         int alreadysent = 0;
2109         char costr[80];
2110         struct sockaddr_in sin;
2111         struct sip_codec_pref *cur;
2112         char v[256];
2113         char s[256];
2114         char o[256];
2115         char c[256];
2116         char t[256];
2117         char m[256];
2118         char a[1024] = "";
2119         int x;
2120         struct sockaddr_in dest;
2121         /* XXX We break with the "recommendation" and send our IP, in order that our
2122                peer doesn't have to gethostbyname() us XXX */
2123         len = 0;
2124         if (!p->rtp) {
2125                 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
2126                 return -1;
2127         }
2128         ast_rtp_get_us(p->rtp, &sin);
2129         if (rtp) {
2130                 ast_rtp_get_peer(rtp, &dest);
2131         } else {
2132                 dest.sin_addr = p->ourip;
2133                 dest.sin_port = sin.sin_port;
2134         }
2135         if (sipdebug)
2136                 ast_verbose("We're at %s port %d\n", inet_ntoa(p->ourip), ntohs(sin.sin_port)); 
2137         snprintf(v, sizeof(v), "v=0\r\n");
2138         snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", getpid(), getpid(), inet_ntoa(dest.sin_addr));
2139         snprintf(s, sizeof(s), "s=session\r\n");
2140         snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", inet_ntoa(dest.sin_addr));
2141         snprintf(t, sizeof(t), "t=0 0\r\n");
2142         snprintf(m, sizeof(m), "m=audio %d RTP/AVP", ntohs(dest.sin_port));
2143         /* Start by sending our preferred codecs */
2144         cur = prefs;
2145         while(cur) {
2146                 if (p->capability & cur->codec) {
2147                         if (sipdebug)
2148                                 ast_verbose("Answering with preferred capability %d\n", cur->codec);
2149                         codec = ast_rtp_lookup_code(p->rtp, 1, cur->codec);
2150                         if (codec > -1) {
2151                                 snprintf(costr, sizeof(costr), " %d", codec);
2152                                 strcat(m, costr);
2153                                 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, cur->codec));
2154                                 strcat(a, costr);
2155                         }
2156                 }
2157                 alreadysent |= cur->codec;
2158                 cur = cur->next;
2159         }
2160         /* Now send any other common codecs, and non-codec formats: */
2161         for (x = 1; x <= AST_FORMAT_MAX_AUDIO; x <<= 1) {
2162                 if ((p->capability & x) && !(alreadysent & x)) {
2163                         if (sipdebug)
2164                                 ast_verbose("Answering with capability %d\n", x);       
2165                         codec = ast_rtp_lookup_code(p->rtp, 1, x);
2166                         if (codec > -1) {
2167                         snprintf(costr, sizeof(costr), " %d", codec);
2168                                 strcat(m, costr);
2169                                 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
2170                                 strcat(a, costr);
2171                         }
2172                 }
2173         }
2174         for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
2175                 if (p->noncodeccapability & x) {
2176                         if (sipdebug)
2177                                 ast_verbose("Answering with non-codec capability %d\n", x);
2178                         codec = ast_rtp_lookup_code(p->rtp, 0, x);
2179                         if (codec > -1) {
2180                                 snprintf(costr, sizeof(costr), " %d", codec);
2181                                 strcat(m, costr);
2182                                 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(0, x));
2183                                 strcat(a, costr);
2184                                 if (x == AST_RTP_DTMF) {
2185                                   /* Indicate we support DTMF...  Not sure about 16, but MSN supports it so dang it, we will too... */
2186                                   snprintf(costr, sizeof costr, "a=fmtp:%d 0-16\r\n",
2187                                            codec);
2188                                   strcat(a, costr);
2189                                 }
2190                         }
2191                 }
2192         }
2193         strcat(m, "\r\n");
2194         len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m) + strlen(a);
2195         snprintf(costr, sizeof(costr), "%d", len);
2196         add_header(resp, "Content-Type", "application/sdp");
2197         add_header(resp, "Content-Length", costr);
2198         add_line(resp, v);
2199         add_line(resp, o);
2200         add_line(resp, s);
2201         add_line(resp, c);
2202         add_line(resp, t);
2203         add_line(resp, m);
2204         add_line(resp, a);
2205         return 0;
2206 }
2207
2208 static void copy_request(struct sip_request *dst,struct sip_request *src)
2209 {
2210         long offset;
2211         int x;
2212         offset = ((void *)dst) - ((void *)src);
2213         /* First copy stuff */
2214         memcpy(dst, src, sizeof(*dst));
2215         /* Now fix pointer arithmetic */
2216         for (x=0;x<src->headers;x++)
2217                 dst->header[x] += offset;
2218         for (x=0;x<src->lines;x++)
2219                 dst->line[x] += offset;
2220 }
2221
2222 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
2223 {
2224         struct sip_request resp;
2225         int seqno;
2226         if (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1) {
2227                 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
2228                 return -1;
2229         }
2230         respprep(&resp, p, msg, req);
2231         add_sdp(&resp, p, NULL);
2232         return send_response(p, &resp, retrans, seqno);
2233 }
2234
2235 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp)
2236 {
2237         struct sip_request req;
2238         if (p->canreinvite == REINVITE_UPDATE)
2239                 reqprep(&req, p, "UPDATE", 0);
2240         else
2241                 reqprep(&req, p, "INVITE", 0);
2242         add_sdp(&req, p, rtp);
2243         /* Use this as the basis */
2244         copy_request(&p->initreq, &req);
2245         parse(&p->initreq);
2246         p->lastinvite = p->ocseq;
2247         p->outgoing = 1;
2248         return send_request(p, &req, 1, p->ocseq);
2249 }
2250
2251 static void initreqprep(struct sip_request *req, struct sip_pvt *p, char *cmd, char *vxml_url)
2252 {
2253         char invite[256];
2254         char from[256];
2255         char to[256];
2256         char tmp[80];
2257         char cid[256];
2258         char *l = callerid, *n=NULL;
2259         if (p->owner && p->owner->callerid) {
2260                 strcpy(cid, p->owner->callerid);
2261                 ast_callerid_parse(cid, &n, &l);
2262                 if (l) 
2263                         ast_shrink_phone_number(l);
2264                 if (!l || !ast_isphonenumber(l))
2265                                 l = callerid;
2266         }
2267         if (!n)
2268                 n = l;
2269         if (ourport != 5060)
2270                 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);
2271         else
2272                 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=as%08x", n, l, strlen(p->fromdomain) ? p->fromdomain : inet_ntoa(p->ourip), p->tag);
2273
2274         if (strlen(p->username)) {
2275                 if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
2276                         snprintf(invite, sizeof(invite), "sip:%s@%s:%d",p->username, inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
2277                 } else {
2278                         snprintf(invite, sizeof(invite), "sip:%s@%s",p->username, inet_ntoa(p->sa.sin_addr));
2279                 }
2280         } else if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
2281                 snprintf(invite, sizeof(invite), "sip:%s:%d", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
2282         } else {
2283                 snprintf(invite, sizeof(invite), "sip:%s", inet_ntoa(p->sa.sin_addr));
2284         }
2285         /* If there is a VXML URL append it to the SIP URL */
2286         if (vxml_url)
2287         {
2288                 snprintf(to, sizeof(to), "<%s>;%s", invite, vxml_url);
2289         }
2290         else
2291         {
2292                 snprintf(to, sizeof(to), "<%s>", invite );
2293         }
2294         memset(req, 0, sizeof(struct sip_request));
2295         init_req(req, cmd, invite);
2296         snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
2297
2298         add_header(req, "Via", p->via);
2299         /* SLD: FIXME?: do Route: here too?  I think not cos this is the first request.
2300          * OTOH, then we won't have anything in p->route anyway */
2301         add_header(req, "From", from);
2302         {
2303                 char contact2[256] ="", *c, contact[256];
2304                 /* XXX This isn't exactly right and it's implemented
2305                        very stupidly *sigh* XXX */
2306                 strncpy(contact2, from, sizeof(contact2)-1);
2307                 c = ditch_braces(contact2);
2308                 snprintf(contact, sizeof(contact), "<%s>", c);
2309                 add_header(req, "Contact", contact);
2310         }
2311         add_header(req, "To", to);
2312         add_header(req, "Call-ID", p->callid);
2313         add_header(req, "CSeq", tmp);
2314         add_header(req, "User-Agent", "Asterisk PBX");
2315 }
2316
2317 static int transmit_invite(struct sip_pvt *p, char *cmd, int sdp, char *auth, char *vxml_url)
2318 {
2319         struct sip_request req;
2320         initreqprep(&req, p, cmd, vxml_url);
2321         if (auth)
2322                 add_header(&req, "Proxy-Authorization", auth);
2323         if (sdp) {
2324                 add_sdp(&req, p, NULL);
2325         } else {
2326                 add_header(&req, "Content-Length", "0");
2327                 add_blank_header(&req);
2328         }
2329         if (!p->initreq.headers) {
2330                 /* Use this as the basis */
2331                 copy_request(&p->initreq, &req);
2332                 parse(&p->initreq);
2333         }
2334         p->lastinvite = p->ocseq;
2335         return send_request(p, &req, 1, p->ocseq);
2336 }
2337
2338 static int transmit_state_notify(struct sip_pvt *p, int state, int full)
2339 {
2340         char tmp[2000];
2341         char from[256], to[256];
2342         char *t, *c, *a;
2343         char *mfrom, *mto;
2344         struct sip_request req;
2345         char clen[20];
2346         
2347         strncpy(from, get_header(&p->initreq, "From"), sizeof(from)-1);
2348
2349         c = ditch_braces(from);
2350         if (strncmp(c, "sip:", 4)) {
2351                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
2352                 return -1;
2353         }
2354         if ((a = strchr(c, ';'))) {
2355                 *a = '\0';
2356         }
2357         mfrom = c;
2358                 
2359         reqprep(&req, p, "NOTIFY", 0);
2360
2361         if (p->subscribed == 1) {
2362             strncpy(to, get_header(&p->initreq, "To"), sizeof(to)-1);
2363
2364             c = ditch_braces(to);
2365             if (strncmp(c, "sip:", 4)) {
2366                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
2367                 return -1;
2368             }
2369             if ((a = strchr(c, ';'))) {
2370                 *a = '\0';
2371             }
2372             mto = c;
2373
2374             add_header(&req, "Content-Type", "application/xpidf+xml");
2375
2376             if ((state==AST_EXTENSION_UNAVAILABLE) || (state==AST_EXTENSION_BUSY))
2377                 state = 2;
2378             else if (state==AST_EXTENSION_INUSE)
2379                 state = 1;
2380             else
2381                 state = 0;
2382             
2383             t = tmp;            
2384             sprintf(t, "<?xml version=\"1.0\"?>\n");
2385             t = tmp + strlen(tmp);
2386             sprintf(t, "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n");
2387             t = tmp + strlen(tmp);
2388             sprintf(t, "<presence>\n");
2389             t = tmp + strlen(tmp);
2390             sprintf(t, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
2391             t = tmp + strlen(tmp);
2392             sprintf(t, "<atom id=\"%s\">\n", p->exten);
2393             t = tmp + strlen(tmp);
2394             sprintf(t, "<address uri=\"%s;user=ip\" priority=\"0,800000\">\n", mto);
2395             t = tmp + strlen(tmp);
2396             sprintf(t, "<status status=\"%s\" />\n", !state ? "open" : (state==1) ? "inuse" : "closed");
2397             t = tmp + strlen(tmp);
2398             sprintf(t, "<msnsubstatus substatus=\"%s\" />\n", !state ? "online" : (state==1) ? "onthephone" : "offline");
2399             t = tmp + strlen(tmp);
2400             sprintf(t, "</address>\n</atom>\n</presence>\n");           
2401         } else {
2402             add_header(&req, "Event", "dialog");
2403             add_header(&req, "Content-Type", "application/dialog-info+xml");
2404         
2405             t = tmp;            
2406             sprintf(t, "<?xml version=\"1.0\"?>\n");
2407             t = tmp + strlen(tmp);
2408             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);
2409             t = tmp + strlen(tmp);
2410             sprintf(t, "<dialog id=\"%s\">\n", p->exten);
2411             t = tmp + strlen(tmp);
2412             sprintf(t, "<state>%s</state>\n", state ? "confirmed" : "terminated");
2413             t = tmp + strlen(tmp);
2414             sprintf(t, "</dialog>\n</dialog-info>\n");  
2415         }
2416
2417         snprintf(clen, sizeof(clen), "%d", strlen(tmp));
2418         add_header(&req, "Content-Length", clen);
2419         add_line(&req, tmp);
2420
2421         return send_request(p, &req, 1, p->ocseq);
2422 }
2423
2424 static int transmit_notify(struct sip_pvt *p, int newmsgs, int oldmsgs)
2425 {
2426         struct sip_request req;
2427         char tmp[256];
2428         char tmp2[256];
2429         char clen[20];
2430         initreqprep(&req, p, "NOTIFY", NULL);
2431         add_header(&req, "Event", "message-summary");
2432         add_header(&req, "Content-Type", "application/simple-message-summary");
2433
2434         snprintf(tmp, sizeof(tmp), "Message-Waiting: %s\n", newmsgs ? "yes" : "no");
2435         snprintf(tmp2, sizeof(tmp2), "Voicemail: %d/%d\n", newmsgs, oldmsgs);
2436         snprintf(clen, sizeof(clen), "%d", strlen(tmp) + strlen(tmp2));
2437         add_header(&req, "Content-Length", clen);
2438         add_line(&req, tmp);
2439         add_line(&req, tmp2);
2440
2441         if (!p->initreq.headers) {
2442                 /* Use this as the basis */
2443                 copy_request(&p->initreq, &req);
2444                 parse(&p->initreq);
2445         }
2446
2447         return send_request(p, &req, 1, p->ocseq);
2448 }
2449
2450 static int transmit_register(struct sip_registry *r, char *cmd, char *auth);
2451
2452 static int sip_reregister(void *data) 
2453 {
2454         /* if we are here, we know that we need to reregister. */
2455         struct sip_registry *r=(struct sip_registry *)data;
2456         return sip_do_register(r);
2457         
2458 }
2459
2460
2461 static int sip_do_register(struct sip_registry *r)
2462 {
2463         int res;
2464         ast_pthread_mutex_lock(&r->lock);
2465         res=transmit_register(r, "REGISTER", NULL);
2466         ast_pthread_mutex_unlock(&r->lock);
2467         return res;
2468 }
2469
2470 static int sip_reg_timeout(void *data)
2471 {
2472         /* if we are here, our registration timed out, so we'll just do it over */
2473         struct sip_registry *r=data;
2474         int res;
2475         ast_pthread_mutex_lock(&r->lock);
2476         ast_log(LOG_NOTICE, "Registration timed out, trying again\n"); 
2477         r->regstate=REG_STATE_UNREGISTERED;
2478         /* cancel ourselves first!!! */
2479         /* ast_sched_del(sched,r->timeout); */
2480         res=transmit_register(r, "REGISTER", NULL);
2481         ast_pthread_mutex_unlock(&r->lock);
2482         return res;
2483 }
2484
2485 static int transmit_register(struct sip_registry *r, char *cmd, char *auth)
2486 {
2487         struct sip_request req;
2488         char from[256];
2489         char to[256];
2490         char tmp[80];
2491         char via[80];
2492         char addr[80];
2493         struct sip_pvt *p;
2494         /* exit if we are already in process with this registrar ?*/
2495         if ( r == NULL || (auth==NULL && r->regstate==REG_STATE_REGSENT) || r->regstate==REG_STATE_AUTHSENT) {
2496                 ast_log(LOG_NOTICE, "Strange, trying to register when registration already pending\n");
2497                 return 0;
2498         }
2499
2500
2501         if (!(p=r->call)) {
2502                 if (!r->callid_valid) {
2503                   build_callid(r->callid, sizeof(r->callid), __ourip);
2504                   r->callid_valid=1;
2505                 }
2506                 p=sip_alloc( r->callid, &r->addr, 0);
2507                 p->outgoing = 1;
2508                 r->call=p;
2509                 p->registry=r;
2510                 strncpy(p->peersecret, r->secret, sizeof(p->peersecret)-1);
2511                 strncpy(p->peername, r->username, sizeof(p->peername)-1);
2512                 strncpy(p->username, r->username, sizeof(p->username)-1);
2513         }
2514
2515         /* set up a timeout */
2516         if (auth==NULL && !r->timeout)  {
2517                 r->timeout = ast_sched_add(sched, 10*1000, sip_reg_timeout, r);
2518                 ast_log(LOG_NOTICE, "Scheduled a timeout # %d\n", r->timeout);
2519         }
2520
2521         snprintf(from, sizeof(from), "<sip:%s@%s>;tag=as%08x", r->username, inet_ntoa(r->addr.sin_addr), p->tag);
2522         snprintf(to, sizeof(to),     "<sip:%s@%s>;tag=as%08x", r->username, inet_ntoa(r->addr.sin_addr), p->tag);
2523         
2524         snprintf(addr, sizeof(addr), "sip:%s", inet_ntoa(r->addr.sin_addr));
2525
2526         memset(&req, 0, sizeof(req));
2527         init_req(&req, cmd, addr);
2528
2529         snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
2530
2531         snprintf(via, sizeof(via), "SIP/2.0/UDP %s:%d;branch=%08x", inet_ntoa(p->ourip), ourport, p->branch);
2532         add_header(&req, "Via", via);
2533         add_header(&req, "From", from);
2534         add_header(&req, "To", to);
2535         {
2536                 char contact[256];
2537                 snprintf(contact, sizeof(contact), "<sip:%s@%s:%d;transport=udp>", r->contact, inet_ntoa(p->ourip), ourport);
2538                 add_header(&req, "Contact", contact);
2539         }
2540         add_header(&req, "Call-ID", p->callid);
2541         add_header(&req, "CSeq", tmp);
2542         add_header(&req, "User-Agent", "Asterisk PBX");
2543         if (auth) 
2544                 add_header(&req, "Authorization", auth);
2545
2546         snprintf(tmp, sizeof(tmp), "%d", default_expirey);
2547         add_header(&req, "Expires", tmp);
2548         add_header(&req, "Event", "registration");
2549         add_header(&req, "Content-length", "0");
2550         add_blank_header(&req);
2551         copy_request(&p->initreq, &req);
2552         r->regstate=auth?REG_STATE_AUTHSENT:REG_STATE_REGSENT;
2553         return send_request(p, &req, 1, p->ocseq);
2554 }
2555
2556 static int transmit_message_with_text(struct sip_pvt *p, char *text)
2557 {
2558         struct sip_request req;
2559         reqprep(&req, p, "MESSAGE", 0);
2560         add_text(&req, text);
2561         return send_request(p, &req, 1, p->ocseq);
2562 }
2563
2564 static int transmit_info_with_digit(struct sip_pvt *p, char digit)
2565 {
2566         struct sip_request req;
2567         reqprep(&req, p, "INFO", 0);
2568         add_digit(&req, digit);
2569         return send_request(p, &req, 1, p->ocseq);
2570 }
2571
2572 static int transmit_request(struct sip_pvt *p, char *msg, int seqno, int reliable)
2573 {
2574         struct sip_request resp;
2575         reqprep(&resp, p, msg, seqno);
2576         add_header(&resp, "Content-Length", "0");
2577         add_blank_header(&resp);
2578         return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
2579 }
2580
2581 static int transmit_request_with_auth(struct sip_pvt *p, char *msg, int seqno, int reliable)
2582 {
2583         struct sip_request resp;
2584         reqprep(&resp, p, msg, seqno);
2585         if (*p->realm)
2586         {
2587                 char digest[256];
2588                 memset(digest,0,sizeof(digest));
2589                 build_reply_digest(p, msg, digest, sizeof(digest));
2590                 add_header(&resp, "Proxy-Authorization", digest);
2591         }
2592
2593         add_header(&resp, "Content-Length", "0");
2594         add_blank_header(&resp);
2595         return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);      
2596 }
2597
2598 static int expire_register(void *data)
2599 {
2600         struct sip_peer *p = data;
2601         memset(&p->addr, 0, sizeof(p->addr));
2602         p->expire = -1;
2603         ast_device_state_changed("SIP/%s", p->name);
2604         return 0;
2605 }
2606
2607 static int sip_poke_peer(struct sip_peer *peer);
2608
2609 static int parse_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req)
2610 {
2611         char contact[80]= ""; 
2612         char *expires = get_header(req, "Expires");
2613         int expirey = atoi(expires);
2614         char *c, *n, *pt;
2615         int port;
2616         struct hostent *hp;
2617         struct sockaddr_in oldsin;
2618         if (!strlen(expires)) {
2619                 expires = strstr(get_header(req, "Contact"), "expires=");
2620                 if (expires) 
2621                         if (sscanf(expires + 8, "%d;", &expirey) != 1)
2622                                 expirey = 0;
2623         }
2624         /* Look for brackets */
2625         strncpy(contact, get_header(req, "Contact"), sizeof(contact) - 1);
2626         c = contact;
2627         
2628         if ((n=strchr(c, '<'))) {
2629                 c = n + 1;
2630                 n = strchr(c, '>');
2631                 /* Lose the part after the > */
2632                 if (n) 
2633                         *n = '\0';
2634         }
2635         if (!strcasecmp(c, "*") || !expirey) {
2636                 /* This means remove all registrations and return OK */
2637                 memset(&p->addr, 0, sizeof(p->addr));
2638                 if (p->expire > -1)
2639                         ast_sched_del(sched, p->expire);
2640                 p->expire = -1;
2641                 if (option_verbose > 2)
2642                         ast_verbose(VERBOSE_PREFIX_3 "Unregistered SIP '%s'\n", p->username);
2643                 return 0;
2644         }
2645         /* Make sure it's a SIP URL */
2646         if (strncasecmp(c, "sip:", 4)) {
2647                 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", c);
2648         } else
2649                 c += 4;
2650         /* Ditch q */
2651         n = strchr(c, ';');
2652         if (n) 
2653                 *n = '\0';
2654         /* Grab host */
2655         n = strchr(c, '@');
2656         if (!n) {
2657                 n = c;
2658                 c = NULL;
2659         } else {
2660                 *n = '\0';
2661                 n++;
2662         }
2663         pt = strchr(n, ':');
2664         if (pt) {
2665                 *pt = '\0';
2666                 pt++;
2667                 port = atoi(pt);
2668         } else
2669                 port = DEFAULT_SIP_PORT;
2670         memcpy(&oldsin, &p->addr, sizeof(oldsin));
2671         if (!p->nat) {
2672                 /* XXX This could block for a long time XXX */
2673                 hp = gethostbyname(n);
2674                 if (!hp)  {
2675                         ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
2676                         return -1;
2677                 }
2678                 p->addr.sin_family = AF_INET;
2679                 memcpy(&p->addr.sin_addr, hp->h_addr, sizeof(p->addr.sin_addr));
2680                 p->addr.sin_port = htons(port);
2681         } else {
2682                 /* Don't trust the contact field.  Just use what they came to us
2683                    with */
2684                 memcpy(&p->addr, &pvt->recv, sizeof(p->addr));
2685         }
2686         if (c)
2687                 strncpy(p->username, c, sizeof(p->username) - 1);
2688         else
2689                 strcpy(p->username, "");
2690         if (p->expire > -1)
2691                 ast_sched_del(sched, p->expire);
2692         if ((expirey < 1) || (expirey > max_expirey))
2693                 expirey = max_expirey;
2694         p->expire = ast_sched_add(sched, (expirey + 10) * 1000, expire_register, p);
2695         pvt->expirey = expirey;
2696         if (memcmp(&p->addr, &oldsin, sizeof(oldsin))) {
2697                 sip_poke_peer(p);
2698                 if (option_verbose > 2)
2699                         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);
2700         }
2701         return 0;
2702 }
2703
2704 static void free_old_route(struct sip_route *route)
2705 {
2706         struct sip_route *next;
2707         while (route) {
2708                 next = route->next;
2709                 free(route);
2710                 route = next;
2711         }
2712 }
2713
2714 static void list_route(struct sip_route *route)
2715 {
2716         if (!route) {
2717                 ast_verbose("list_route: no route\n");
2718                 return;
2719         }
2720         while (route) {
2721                 ast_verbose("list_route: hop: <%s>\n", route->hop);
2722                 route = route->next;
2723         }
2724 }
2725
2726 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
2727 {
2728         struct sip_route *thishop, *head, *tail;
2729         int start = 0;
2730         int len;
2731         char *rr, *contact, *c;
2732
2733         if (p->route) {
2734                 free_old_route(p->route);
2735                 p->route = NULL;
2736         }
2737         /* We build up head, then assign it to p->route when we're done */
2738         head = NULL;  tail = head;
2739         /* 1st we pass through all the hops in any Record-Route headers */
2740         for (;;) {
2741                 /* Each Record-Route header */
2742                 rr = __get_header(req, "Record-Route", &start);
2743                 if (*rr == '\0') break;
2744                 for (;;) {
2745                         /* Each route entry */
2746                         /* Find < */
2747                         rr = strchr(rr, '<');
2748                         if (!rr) break; /* No more hops */
2749                         ++rr;
2750                         len = strcspn(rr, ">");
2751                         /* Make a struct route */
2752                         thishop = (struct sip_route *)malloc(sizeof(struct sip_route)+len+1);
2753                         if (thishop) {
2754                                 strncpy(thishop->hop, rr, len);
2755                                 thishop->hop[len] = '\0';
2756                                 ast_log(LOG_DEBUG, "build_route: Record-Route hop: <%s>\n", thishop->hop);
2757                                 /* Link in */
2758                                 if (backwards) {
2759                                         /* Link in at head so they end up in reverse order */
2760                                         thishop->next = head;
2761                                         head = thishop;
2762                                         /* If this was the first then it'll be the tail */
2763                                         if (!tail) tail = thishop;
2764                                 } else {
2765                                         thishop->next = NULL;
2766                                         /* Link in at the end */
2767                                         if (tail)
2768                                                 tail->next = thishop;
2769                                         else
2770                                                 head = thishop;
2771                                         tail = thishop;
2772                                 }
2773                         }
2774                         rr += len+1;
2775                 }
2776         }
2777         /* 2nd append the Contact: if there is one */
2778         /* Can be multiple Contact headers, comma separated values - we just take the first */
2779         contact = get_header(req, "Contact");
2780         if (strlen(contact)) {
2781                 ast_log(LOG_DEBUG, "build_route: Contact hop: %s\n", contact);
2782                 /* Look for <: delimited address */
2783                 c = strchr(contact, '<');
2784                 if (c) {
2785                         /* Take to > */
2786                         ++c;
2787                         len = strcspn(c, ">");
2788                 } else {
2789                         /* No <> - just take the lot */
2790                         c = contact; len = strlen(contact);
2791                 }
2792                 thishop = (struct sip_route *)malloc(sizeof(struct sip_route)+len+1);
2793                 if (thishop) {
2794                         strncpy(thishop->hop, c, len);
2795                         thishop->hop[len] = '\0';
2796                         thishop->next = NULL;
2797                         /* Goes at the end */
2798                         if (tail)
2799                                 tail->next = thishop;
2800                         else
2801                                 head = thishop;
2802                 }
2803         }
2804         /* Store as new route */
2805         p->route = head;
2806
2807         /* For debugging dump what we ended up with */
2808         if (sipdebug)
2809                 list_route(p->route);
2810 }
2811
2812 static void md5_hash(char *output, char *input)
2813 {
2814                 struct MD5Context md5;
2815                 unsigned char digest[16];
2816                 char *ptr;
2817                 int x;
2818                 MD5Init(&md5);
2819                 MD5Update(&md5, input, strlen(input));
2820                 MD5Final(digest, &md5);
2821                 ptr = output;
2822                 for (x=0;x<16;x++)
2823                         ptr += sprintf(ptr, "%2.2x", digest[x]);
2824 }
2825
2826 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)
2827 {
2828         int res = -1;
2829         /* Always OK if no secret */
2830         if (!strlen(secret))
2831                 return 0;
2832         if (!strlen(randdata) || !strlen(get_header(req, "Proxy-Authorization"))) {
2833                 snprintf(randdata, randlen, "%08x", rand());
2834                 transmit_response_with_auth(p, "407 Proxy Authentication Required", req, randdata, reliable);
2835                 /* Schedule auto destroy in 15 seconds */
2836                 sip_scheddestroy(p, 15000);
2837                 res = 1;
2838         } else {
2839                 /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
2840                    an example in the spec of just what it is you're doing a hash on. */
2841                 char a1[256];
2842                 char a2[256];
2843                 char a1_hash[256];
2844                 char a2_hash[256];
2845                 char resp[256];
2846                 char resp_hash[256];
2847                 char tmp[256] = "";
2848                 char *c;
2849                 char *response ="";
2850                 char *resp_uri ="";
2851
2852                 /* Find their response among the mess that we'r sent for comparison */
2853                 strncpy(tmp, get_header(req, "Proxy-Authorization"), sizeof(tmp) - 1);
2854                 c = tmp;
2855
2856                 while(c) {
2857                         while (*c && (*c < 33)) c++;
2858                         if (!*c)
2859                                 break;
2860                         if (!strncasecmp(c, "response=", strlen("response="))) {
2861                                 c+= strlen("response=");
2862                                 if ((*c == '\"')) {
2863                                         response=++c;
2864                                         if((c = strchr(c,'\"')))
2865                                                 *c = '\0';
2866
2867                                 } else {
2868                                         response=c;
2869                                         if((c = strchr(c,',')))
2870                                                 *c = '\0';
2871                                 }
2872
2873                         } else if (!strncasecmp(c, "uri=", strlen("uri="))) {
2874                                 c+= strlen("uri=");
2875                                 if ((*c == '\"')) {
2876                                         resp_uri=++c;
2877                                         if((c = strchr(c,'\"')))
2878                                                 *c = '\0';
2879                                 } else {
2880                                         resp_uri=c;
2881                                         if((c = strchr(c,',')))
2882                                                 *c = '\0';
2883                                 }
2884
2885                         } else
2886                                 c = strchr(c, ',');
2887                         if (c)
2888                                 c++;
2889                 }
2890                 snprintf(a1, sizeof(a1), "%s:%s:%s", username, "asterisk", secret);
2891                 if(strlen(resp_uri))
2892                         snprintf(a2, sizeof(a2), "%s:%s", method, resp_uri);
2893                 else
2894                         snprintf(a2, sizeof(a2), "%s:%s", method, uri);
2895                 md5_hash(a1_hash, a1);
2896                 md5_hash(a2_hash, a2);
2897                 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, randdata, a2_hash);
2898                 md5_hash(resp_hash, resp);
2899
2900                 /* resp_hash now has the expected response, compare the two */
2901
2902                 if (response && !strncasecmp(response, resp_hash, strlen(resp_hash))) {
2903                         /* Auth is OK */
2904                         res = 0;
2905                 }
2906                 /* Assume success ;-) */
2907                 /* Eliminate random data */
2908                 strcpy(randdata, "");
2909         }
2910         return res;
2911 }
2912
2913 static int cb_extensionstate(char *context, char* exten, int state, void *data)
2914 {
2915     struct sip_pvt *p = data;
2916     if (state == -1) {
2917         sip_scheddestroy(p, 15000);
2918         p->stateid = -1;
2919         return 0;
2920     }
2921     
2922     transmit_state_notify(p, state, 1);
2923     
2924     if (option_debug)
2925         ast_verbose(VERBOSE_PREFIX_1 "Extension Changed %s new state %d for Notify User %s\n", exten, state, p->username);
2926     return 0;
2927 }
2928
2929 static int register_verify(struct sip_pvt *p, struct sockaddr_in *sin, struct sip_request *req, char *uri)
2930 {
2931         int res = -1;
2932         struct sip_peer *peer;
2933         char tmp[256] = "";
2934         char *name, *c;
2935         char *t;
2936         /* Terminate URI */
2937         t = uri;
2938         while(*t && (*t > 32) && (*t != ';'))
2939                 t++;
2940         *t = '\0';
2941         
2942         strncpy(tmp, get_header(req, "To"), sizeof(tmp) - 1);
2943         c = ditch_braces(tmp);
2944         if (!strncmp(c, "sip:", 4)) {
2945                 name = c + 4;
2946         } else {
2947                 name = c;
2948                 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, inet_ntoa(sin->sin_addr));
2949         }
2950         c = strchr(name, '@');
2951         if (c) 
2952                 *c = '\0';
2953         ast_pthread_mutex_lock(&peerl.lock);
2954         peer = peerl.peers;
2955         while(peer) {
2956                 if (!strcasecmp(peer->name, name) && peer->dynamic) {
2957                         p->nat = peer->nat;
2958                         transmit_response(p, "100 Trying", req);
2959                         if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), peer->name, peer->secret, "REGISTER", uri, 0))) {
2960                                 sip_cancel_destroy(p);
2961                                 if (parse_contact(p, peer, req)) {
2962                                         ast_log(LOG_WARNING, "Failed to parse contact info\n");
2963                                 } else {
2964                                         /* Say OK and ask subsystem to retransmit msg counter */
2965                                         transmit_response_with_date(p, "200 OK", req);
2966                                         peer->lastmsgssent = -1;
2967                                         res = 0;
2968                                 }
2969                         } 
2970                         break;
2971                 }       
2972                 peer = peer->next;
2973         }
2974         ast_pthread_mutex_unlock(&peerl.lock);
2975         if (!res) {
2976             ast_device_state_changed("SIP/%s", peer->name);
2977         }
2978         if (res < 0)
2979                 transmit_response(p, "401 Unauthorized", &p->initreq);
2980         return res;
2981 }
2982
2983 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
2984 {
2985         char tmp[256] = "", *c, *a;
2986         struct sip_request *req;
2987         
2988         req = oreq;
2989         if (!req)
2990                 req = &p->initreq;
2991         strncpy(tmp, req->rlPart2, sizeof(tmp) - 1);
2992         c = ditch_braces(tmp);
2993         if (strncmp(c, "sip:", 4)) {
2994                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
2995                 return -1;
2996         }
2997         c += 4;
2998         if ((a = strchr(c, '@')) || (a = strchr(c, ';'))) {
2999                 *a = '\0';
3000         }
3001         if (sipdebug)
3002                 ast_verbose("Looking for %s in %s\n", c, p->context);
3003         if (ast_exists_extension(NULL, p->context, c, 1, NULL)) {
3004                 if (!oreq)
3005                         strncpy(p->exten, c, sizeof(p->exten) - 1);
3006                 return 0;
3007         }
3008
3009         if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
3010                 return 1;
3011         }
3012         
3013         return -1;
3014 }
3015
3016 static int get_refer_info(struct sip_pvt *p, struct sip_request *oreq)
3017 {
3018         char tmp[256] = "", *c, *a;
3019         char tmp2[256] = "", *c2, *a2;
3020         char tmp3[256];
3021         char tmp4[256];
3022         char tmp5[256] = "";            /* CallID to replace */
3023         struct sip_request *req;
3024         struct sip_pvt *p2;
3025         
3026         req = oreq;
3027         if (!req)
3028                 req = &p->initreq;
3029         strncpy(tmp, get_header(req, "Refer-To"), sizeof(tmp) - 1);
3030         strncpy(tmp2, get_header(req, "Referred-By"), sizeof(tmp2) - 1);
3031         strncpy(tmp3, get_header(req, "Contact"), sizeof(tmp3) - 1);
3032         strncpy(tmp4, get_header(req, "Remote-Party-ID"), sizeof(tmp4) - 1);
3033         
3034         c = ditch_braces(tmp);
3035         c2 = ditch_braces(tmp2);
3036         
3037                 
3038         if (strncmp(c, "sip:", 4) && strncmp(c2, "sip:", 4)) {
3039                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
3040                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c2);
3041                 return -1;
3042         }
3043         c += 4;
3044         c2 += 4;
3045         if ((a = strchr(c, '?'))) {
3046                 /* Search for arguemnts */
3047                 *a = '\0';
3048                 a++;
3049                 if (!strncasecmp(a, "REPLACES=", strlen("REPLACES="))) {
3050                         strncpy(tmp5, a + strlen("REPLACES="), sizeof(tmp5) - 1);
3051                         if ((a = strchr(tmp5, '%'))) {
3052                                 /* Yuck!  Pingtel converts the '@' to a %40, icky icky!  Convert
3053                                    back to an '@' */
3054                                 if ((a[1] == '4') && (a[2] == '0')) {
3055                                         *a = '@';
3056                                         memmove(a + 1, a+3, strlen(a + 3));
3057                                 }
3058                         }
3059                         if ((a = strchr(tmp5, '%'))) 
3060                                 *a = '\0';
3061                 }
3062         }
3063         
3064         if ((a = strchr(c, '@')))
3065                 *a = '\0';
3066         if ((a = strchr(c, ';'))) 
3067                 *a = '\0';
3068         
3069
3070         if ((a2 = strchr(c2, '@')))
3071                 *a2 = '\0';
3072
3073         if ((a2 = strchr(c2, ';'))) 
3074                 *a2 = '\0';
3075         
3076         
3077         if (sipdebug) {
3078                 ast_verbose("Looking for %s in %s\n", c, p->context);
3079                 ast_verbose("Looking for %s in %s\n", c2, p->context);
3080         }
3081         if (strlen(tmp5)) {     
3082                 /* This is a supervised transfer */
3083                 ast_log(LOG_DEBUG,"Assigning Replace-Call-ID Info %s to REPLACE_CALL_ID\n",tmp5);
3084                 
3085                 strncpy(p->refer_to, "", sizeof(p->refer_to) - 1);
3086                 strncpy(p->referred_by, "", sizeof(p->referred_by) - 1);
3087                 strncpy(p->refer_contact, "", sizeof(p->refer_contact) - 1);
3088                 strncpy(p->remote_party_id, "", sizeof(p->remote_party_id) - 1);
3089                 p->refer_call = NULL;
3090                 ast_pthread_mutex_lock(&iflock);
3091                 /* Search interfaces and find the match */
3092                 p2 = iflist;
3093                 while(p2) {
3094                         if (!strcmp(p2->callid, tmp5)) {
3095                                 /* Go ahead and lock it before returning */
3096                                 ast_pthread_mutex_lock(&p2->lock);
3097                                 p->refer_call = p2;
3098                                 break;
3099                         }
3100                         p2 = p2->next;
3101                 }
3102                 ast_pthread_mutex_unlock(&iflock);
3103                 if (p->refer_call)
3104                         return 0;
3105                 else
3106                         ast_log(LOG_NOTICE, "Supervised transfer requested, but unable to find callid '%s'\n", tmp5);
3107         } else if (ast_exists_extension(NULL, p->context, c, 1, NULL)) {
3108                 /* This is an unsupervised transfer */
3109                 ast_log(LOG_DEBUG,"Assigning Extension %s to REFER-TO\n", c);
3110                 ast_log(LOG_DEBUG,"Assigning Extension %s to REFERRED-BY\n", c2);
3111                 ast_log(LOG_DEBUG,"Assigning Contact Info %s to REFER_CONTACT\n", tmp3);