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