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