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