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