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