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