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