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