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