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