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