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