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