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