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