Various management updates
[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         /* Find and parse hostname */
1755         h = strchr(uri, '@');
1756         if (h)
1757                 ++h;
1758         else {
1759                 h = uri;
1760                 if (strncmp(h, "sip:", 4) == 0)
1761                         h += 4;
1762                 else if (strncmp(h, "sips:", 5) == 0)
1763                         h += 5;
1764         }
1765         hn = strcspn(h, ":;>");
1766         if (hn>255) hn=255;
1767         strncpy(hostname, h, hn);  hostname[hn] = '\0';
1768         h+=hn;
1769
1770         /* Is "port" present? if not default to 5060 */
1771         if (*h == ':') {
1772                 /* Parse port */
1773                 ++h;
1774                 port = strtol(h, &h, 10);
1775         }
1776         else
1777                 port = 5060;
1778
1779         /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
1780         maddr = strstr(h, "maddr=");
1781         if (maddr) {
1782                 maddr += 6;
1783                 hn = strspn(maddr, "0123456789.");
1784                 if (hn>255) hn=255;
1785                 strncpy(hostname, maddr, hn);  hostname[hn] = '\0';
1786         }
1787         
1788         hp = gethostbyname(hostname);
1789         if (hp == NULL)  {
1790                 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
1791                 return;
1792         }
1793         p->sa.sin_family = AF_INET;
1794         memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
1795         p->sa.sin_port = htons(port);
1796         if (sipdebug)
1797                 ast_verbose("set_destination: set destination to %s, port %d\n", inet_ntoa(p->sa.sin_addr), port);
1798 }
1799
1800 static int init_resp(struct sip_request *req, char *resp, struct sip_request *orig)
1801 {
1802         /* Initialize a response */
1803         if (req->headers || req->len) {
1804                 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1805                 return -1;
1806         }
1807         req->header[req->headers] = req->data + req->len;
1808         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "SIP/2.0 %s\r\n", resp);
1809         req->len += strlen(req->header[req->headers]);
1810         if (req->headers < SIP_MAX_HEADERS)
1811                 req->headers++;
1812         else
1813                 ast_log(LOG_WARNING, "Out of header space\n");
1814         return 0;
1815 }
1816
1817 static int init_req(struct sip_request *req, char *resp, char *recip)
1818 {
1819         /* Initialize a response */
1820         if (req->headers || req->len) {
1821                 ast_log(LOG_WARNING, "Request already initialized?!?\n");
1822                 return -1;
1823         }
1824         req->header[req->headers] = req->data + req->len;
1825         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s SIP/2.0\r\n", resp, recip);
1826         req->len += strlen(req->header[req->headers]);
1827         if (req->headers < SIP_MAX_HEADERS)
1828                 req->headers++;
1829         else
1830                 ast_log(LOG_WARNING, "Out of header space\n");
1831         return 0;
1832 }
1833
1834 static void append_contact(struct sip_request *req, struct sip_pvt *p)
1835 {
1836         /* Add contact header */
1837         char contact2[256] ="", *c, contact[256];
1838         char *from;
1839         if (p->outgoing)
1840                 from = get_header(req, "From");
1841         else
1842                 from = get_header(req, "To");
1843         strncpy(contact2, from, sizeof(contact2)-1);
1844         if (strlen(contact2)) {
1845                 c = ditch_braces(contact2);
1846                 snprintf(contact, sizeof(contact), "<%s>", c);
1847                 add_header(req, "Contact", contact);
1848         }
1849 }
1850
1851 static int respprep(struct sip_request *resp, struct sip_pvt *p, char *msg, struct sip_request *req)
1852 {
1853         char newto[256] = "", *ot;
1854         memset(resp, 0, sizeof(*resp));
1855         init_resp(resp, msg, req);
1856         copy_via_headers(p, resp, req, "Via");
1857         if (msg[0] == '2') copy_all_header(resp, req, "Record-Route");
1858         copy_header(resp, req, "From");
1859         ot = get_header(req, "To");
1860         if (!strstr(ot, "tag=")) {
1861                 /* Add the proper tag if we don't have it already.  If they have specified
1862                    their tag, use it.  Otherwise, use our own tag */
1863                 if (strlen(p->theirtag))
1864                         snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
1865                 else if (p->tag)
1866                         snprintf(newto, sizeof(newto), "%s;tag=%08x", ot, p->tag);
1867                 else
1868                         strncpy(newto, ot, sizeof(newto) - 1);
1869                 ot = newto;
1870         }
1871         add_header(resp, "To", ot);
1872         copy_header(resp, req, "Call-ID");
1873         copy_header(resp, req, "CSeq");
1874         add_header(resp, "User-Agent", "Asterisk PBX");
1875         if (p->expirey) {
1876                 /* For registration responses, we also need expirey and
1877                    contact info */
1878                 char tmp[80];
1879                 char contact[256];
1880                 char *c;
1881                 if ((c=getsipuri(ot))) {
1882                         snprintf(contact, sizeof(contact), "<%s@%s:%d>;expires=%d", c, inet_ntoa(p->ourip), ourport, p->expirey);
1883                         free(c);
1884                 } else {
1885                         snprintf(contact, sizeof(contact), "<%s:%d>;expires=%d", inet_ntoa(p->ourip), ourport, p->expirey);
1886                 }
1887                 snprintf(tmp, sizeof(tmp), "%d", p->expirey);
1888                 add_header(resp, "Expires", tmp);
1889                 add_header(resp, "Contact", contact);
1890         } else {
1891                 char contact[256];
1892                 /* XXX This isn't exactly right and it's implemented
1893                        very stupidly *sigh* XXX */
1894                 char *c;
1895                 if ((c=getsipuri(ot))) {
1896                         snprintf(contact, sizeof(contact), "<%s@%s:%d>", c, inet_ntoa(p->ourip), ourport);
1897                         free(c);
1898                 } else {
1899                         snprintf(contact, sizeof(contact), "<%s:%d>", inet_ntoa(p->ourip), ourport);
1900                 }
1901                 add_header(resp, "Contact", contact);
1902         }
1903         return 0;
1904 }
1905
1906 static int reqprep(struct sip_request *req, struct sip_pvt *p, char *msg, int inc)
1907 {
1908         struct sip_request *orig = &p->initreq;
1909         char stripped[80] ="";
1910         char tmp[80];
1911         char newto[256];
1912         char *c, *n;
1913         char *ot, *of;
1914
1915         memset(req, 0, sizeof(struct sip_request));
1916         
1917         if (inc)
1918                 p->ocseq++;
1919
1920         if (p->outgoing)
1921                 strncpy(stripped, get_header(orig, "To"), sizeof(stripped) - 1);
1922         else
1923                 strncpy(stripped, get_header(orig, "From"), sizeof(stripped) - 1);
1924         
1925         c = strchr(stripped, '<');
1926         if (c) 
1927                 c++;
1928         else
1929                 c = stripped;
1930         n = strchr(c, '>');
1931         if (n)
1932                 *n = '\0';
1933         
1934         init_req(req, msg, c);
1935
1936         snprintf(tmp, sizeof(tmp), "%d %s", p->ocseq, msg);
1937
1938         add_header(req, "Via", p->via);
1939         if (p->route) {
1940                 set_destination(p, p->route->hop);
1941                 add_route(req, p->route->next);
1942         }
1943
1944         ot = get_header(orig, "To");
1945         of = get_header(orig, "From");
1946
1947         /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
1948            as our original request, including tag (or presumably lack thereof) */
1949         if (!strstr(ot, "tag=") && strcasecmp(msg, "CANCEL")) {
1950                 /* Add the proper tag if we don't have it already.  If they have specified
1951                    their tag, use it.  Otherwise, use our own tag */
1952                 if (p->outgoing && strlen(p->theirtag))
1953                         snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
1954                 else if (!p->outgoing)
1955                         snprintf(newto, sizeof(newto), "%s;tag=%08x", ot, p->tag);
1956                 else
1957                         snprintf(newto, sizeof(newto), "%s", ot);
1958                 ot = newto;
1959         }
1960
1961         if (p->outgoing) {
1962                 add_header(req, "From", of);
1963                 add_header(req, "To", ot);
1964         } else {
1965                 add_header(req, "From", ot);
1966                 add_header(req, "To", of);
1967         }
1968         append_contact(req, p);
1969         copy_header(req, orig, "Call-ID");
1970         add_header(req, "CSeq", tmp);
1971
1972         add_header(req, "User-Agent", "Asterisk PBX");
1973         return 0;
1974 }
1975
1976 static int __transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req, int reliable)
1977 {
1978         struct sip_request resp;
1979         int seqno = 0;
1980         if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
1981                 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
1982                 return -1;
1983         }
1984         respprep(&resp, p, msg, req);
1985         add_header(&resp, "Content-Length", "0");
1986         add_blank_header(&resp);
1987         return send_response(p, &resp, reliable, seqno);
1988 }
1989
1990 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req) 
1991 {
1992         return __transmit_response(p, msg, req, 0);
1993 }
1994 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req)
1995 {
1996         return __transmit_response(p, msg, req, 1);
1997 }
1998
1999 static void append_date(struct sip_request *req)
2000 {
2001         char tmpdat[256];
2002         struct tm tm;
2003         time_t t;
2004         time(&t);
2005         gmtime_r(&t, &tm);
2006         strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
2007         add_header(req, "Date", tmpdat);
2008 }
2009
2010 static int transmit_response_with_date(struct sip_pvt *p, char *msg, struct sip_request *req)
2011 {
2012         struct sip_request resp;
2013         respprep(&resp, p, msg, req);
2014         append_date(&resp);
2015         add_header(&resp, "Content-Length", "0");
2016         add_blank_header(&resp);
2017         return send_response(p, &resp, 0, 0);
2018 }
2019
2020 static int transmit_response_with_allow(struct sip_pvt *p, char *msg, struct sip_request *req)
2021 {
2022         struct sip_request resp;
2023         respprep(&resp, p, msg, req);
2024         add_header(&resp, "Allow", "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER");
2025         add_header(&resp, "Accept", "application/sdp");
2026         add_header(&resp, "Content-Length", "0");
2027         add_blank_header(&resp);
2028         return send_response(p, &resp, 0, 0);
2029 }
2030
2031 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *randdata, int reliable)
2032 {
2033         struct sip_request resp;
2034         char tmp[256];
2035         int seqno = 0;
2036         if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
2037                 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
2038                 return -1;
2039         }
2040         snprintf(tmp, sizeof(tmp), "Digest realm=\"asterisk\", nonce=\"%s\"", randdata);
2041         respprep(&resp, p, msg, req);
2042         add_header(&resp, "Proxy-Authenticate", tmp);
2043         add_header(&resp, "Content-Length", "0");
2044         add_blank_header(&resp);
2045         return send_response(p, &resp, reliable, seqno);
2046 }
2047
2048 static int add_text(struct sip_request *req, char *text)
2049 {
2050         /* XXX Convert \n's to \r\n's XXX */
2051         int len = strlen(text);
2052         char clen[256];
2053         snprintf(clen, sizeof(clen), "%d", len);
2054         add_header(req, "Content-Type", "text/plain");
2055         add_header(req, "Content-Length", clen);
2056         add_line(req, text);
2057         return 0;
2058 }
2059
2060 static int add_digit(struct sip_request *req, char digit)
2061 {
2062         char tmp[256];
2063         int len;
2064         char clen[256];
2065         snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=250\r\n", digit);
2066         len = strlen(tmp);
2067         snprintf(clen, sizeof(clen), "%d", len);
2068         add_header(req, "Content-Type", "application/dtmf-relay");
2069         add_header(req, "Content-Length", clen);
2070         add_line(req, tmp);
2071         return 0;
2072 }
2073
2074 static int add_sdp(struct sip_request *resp, struct sip_pvt *p, struct ast_rtp *rtp)
2075 {
2076         int len;
2077         int codec;
2078         int alreadysent = 0;
2079         char costr[80];
2080         struct sockaddr_in sin;
2081         struct sip_codec_pref *cur;
2082         char v[256];
2083         char s[256];
2084         char o[256];
2085         char c[256];
2086         char t[256];
2087         char m[256];
2088         char a[1024] = "";
2089         int x;
2090         struct sockaddr_in dest;
2091         /* XXX We break with the "recommendation" and send our IP, in order that our
2092                peer doesn't have to gethostbyname() us XXX */
2093         len = 0;
2094         if (!p->rtp) {
2095                 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
2096                 return -1;
2097         }
2098         ast_rtp_get_us(p->rtp, &sin);
2099         if (rtp) {
2100                 ast_rtp_get_peer(rtp, &dest);
2101         } else {
2102                 dest.sin_addr = p->ourip;
2103                 dest.sin_port = sin.sin_port;
2104         }
2105         if (sipdebug)
2106                 ast_verbose("We're at %s port %d\n", inet_ntoa(p->ourip), ntohs(sin.sin_port)); 
2107         snprintf(v, sizeof(v), "v=0\r\n");
2108         snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", getpid(), getpid(), inet_ntoa(dest.sin_addr));
2109         snprintf(s, sizeof(s), "s=session\r\n");
2110         snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", inet_ntoa(dest.sin_addr));
2111         snprintf(t, sizeof(t), "t=0 0\r\n");
2112         snprintf(m, sizeof(m), "m=audio %d RTP/AVP", ntohs(dest.sin_port));
2113         /* Start by sending our preferred codecs */
2114         cur = prefs;
2115         while(cur) {
2116                 if (p->capability & cur->codec) {
2117                         if (sipdebug)
2118                                 ast_verbose("Answering with preferred capability %d\n", cur->codec);
2119                         codec = ast_rtp_lookup_code(p->rtp, 1, cur->codec);
2120                         if (codec > -1) {
2121                                 snprintf(costr, sizeof(costr), " %d", codec);
2122                                 strcat(m, costr);
2123                                 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, cur->codec));
2124                                 strcat(a, costr);
2125                         }
2126                 }
2127                 alreadysent |= cur->codec;
2128                 cur = cur->next;
2129         }
2130         /* Now send any other common codecs, and non-codec formats: */
2131         for (x = 1; x <= AST_FORMAT_MAX_AUDIO; x <<= 1) {
2132                 if ((p->capability & x) && !(alreadysent & x)) {
2133                         if (sipdebug)
2134                                 ast_verbose("Answering with capability %d\n", x);       
2135                         codec = ast_rtp_lookup_code(p->rtp, 1, x);
2136                         if (codec > -1) {
2137                         snprintf(costr, sizeof(costr), " %d", codec);
2138                                 strcat(m, costr);
2139                                 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
2140                                 strcat(a, costr);
2141                         }
2142                 }
2143         }
2144         for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
2145                 if (p->noncodeccapability & x) {
2146                         if (sipdebug)
2147                                 ast_verbose("Answering with non-codec capability %d\n", x);
2148                         codec = ast_rtp_lookup_code(p->rtp, 0, x);
2149                         if (codec > -1) {
2150                                 snprintf(costr, sizeof(costr), " %d", codec);
2151                                 strcat(m, costr);
2152                                 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(0, x));
2153                                 strcat(a, costr);
2154                                 if (x == AST_RTP_DTMF) {
2155                                   /* Indicate we support DTMF...  Not sure about 16, but MSN supports it so dang it, we will too... */
2156                                   snprintf(costr, sizeof costr, "a=fmtp:%d 0-16\r\n",
2157                                            codec);
2158                                   strcat(a, costr);
2159                                 }
2160                         }
2161                 }
2162         }
2163         strcat(m, "\r\n");
2164         len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m) + strlen(a);
2165         snprintf(costr, sizeof(costr), "%d", len);
2166         add_header(resp, "Content-Type", "application/sdp");
2167         add_header(resp, "Content-Length", costr);
2168         add_line(resp, v);
2169         add_line(resp, o);
2170         add_line(resp, s);
2171         add_line(resp, c);
2172         add_line(resp, t);
2173         add_line(resp, m);
2174         add_line(resp, a);
2175         return 0;
2176 }
2177
2178 static void copy_request(struct sip_request *dst,struct sip_request *src)
2179 {
2180         long offset;
2181         int x;
2182         offset = ((void *)dst) - ((void *)src);
2183         /* First copy stuff */
2184         memcpy(dst, src, sizeof(*dst));
2185         /* Now fix pointer arithmetic */
2186         for (x=0;x<src->headers;x++)
2187                 dst->header[x] += offset;
2188         for (x=0;x<src->lines;x++)
2189                 dst->line[x] += offset;
2190 }
2191
2192 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
2193 {
2194         struct sip_request resp;
2195         int seqno;
2196         if (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1) {
2197                 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
2198                 return -1;
2199         }
2200         respprep(&resp, p, msg, req);
2201         add_sdp(&resp, p, NULL);
2202         return send_response(p, &resp, retrans, seqno);
2203 }
2204
2205 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp)
2206 {
2207         struct sip_request resp;
2208         if (p->canreinvite == REINVITE_UPDATE)
2209                 reqprep(&resp, p, "UPDATE", 1);
2210         else
2211                 reqprep(&resp, p, "INVITE", 1);
2212         add_sdp(&resp, p, rtp);
2213         return send_request(p, &resp, 1, p->ocseq);
2214 }
2215
2216 static void initreqprep(struct sip_request *req, struct sip_pvt *p, char *cmd, char *vxml_url)
2217 {
2218         char invite[256];
2219         char from[256];
2220         char to[256];
2221         char tmp[80];
2222         char cid[256];
2223         char *l = callerid, *n=NULL;
2224         if (p->owner && p->owner->callerid) {
2225                 strcpy(cid, p->owner->callerid);
2226                 ast_callerid_parse(cid, &n, &l);
2227                 if (l) 
2228                         ast_shrink_phone_number(l);
2229                 if (!l || !ast_isphonenumber(l))
2230                                 l = callerid;
2231         }
2232         if (!n)
2233                 n = l;
2234         if (ourport != 5060)
2235                 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);
2236         else
2237                 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%08x", n, l, strlen(p->fromdomain) ? p->fromdomain : inet_ntoa(p->ourip), p->tag);
2238
2239         if (strlen(p->username)) {
2240                 if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
2241                         snprintf(invite, sizeof(invite), "sip:%s@%s:%d",p->username, inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
2242                 } else {
2243                         snprintf(invite, sizeof(invite), "sip:%s@%s",p->username, inet_ntoa(p->sa.sin_addr));
2244                 }
2245         } else if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
2246                 snprintf(invite, sizeof(invite), "sip:%s:%d", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
2247         } else {
2248                 snprintf(invite, sizeof(invite), "sip:%s", inet_ntoa(p->sa.sin_addr));
2249         }
2250         /* If there is a VXML URL append it to the SIP URL */
2251         if (vxml_url)
2252         {
2253                 snprintf(to, sizeof(to), "<%s>;%s", invite, vxml_url);
2254         }
2255         else
2256         {
2257                 snprintf(to, sizeof(to), "<%s>", invite );
2258         }
2259         memset(req, 0, sizeof(struct sip_request));
2260         init_req(req, cmd, invite);
2261         snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
2262
2263         add_header(req, "Via", p->via);
2264         /* SLD: FIXME?: do Route: here too?  I think not cos this is the first request.
2265          * OTOH, then we won't have anything in p->route anyway */
2266         add_header(req, "From", from);
2267         {
2268                 char contact2[256] ="", *c, contact[256];
2269                 /* XXX This isn't exactly right and it's implemented
2270                        very stupidly *sigh* XXX */
2271                 strncpy(contact2, from, sizeof(contact2)-1);
2272                 c = ditch_braces(contact2);
2273                 snprintf(contact, sizeof(contact), "<%s>", c);
2274                 add_header(req, "Contact", contact);
2275         }
2276         add_header(req, "To", to);
2277         add_header(req, "Call-ID", p->callid);
2278         add_header(req, "CSeq", tmp);
2279         add_header(req, "User-Agent", "Asterisk PBX");
2280 }
2281
2282 static int transmit_invite(struct sip_pvt *p, char *cmd, int sdp, char *auth, char *vxml_url)
2283 {
2284         struct sip_request req;
2285         initreqprep(&req, p, cmd, vxml_url);
2286         if (auth)
2287                 add_header(&req, "Proxy-Authorization", auth);
2288         if (sdp) {
2289                 add_sdp(&req, p, NULL);
2290         } else {
2291                 add_header(&req, "Content-Length", "0");
2292                 add_blank_header(&req);
2293         }
2294         if (!p->initreq.headers) {
2295                 /* Use this as the basis */
2296                 copy_request(&p->initreq, &req);
2297                 parse(&p->initreq);
2298         }
2299         p->lastinvite = p->ocseq;
2300         return send_request(p, &req, 1, p->ocseq);
2301 }
2302
2303 static int transmit_state_notify(struct sip_pvt *p, int state, int full)
2304 {
2305         char tmp[2000];
2306         char from[256], to[256];
2307         char *t, *c, *a;
2308         char *mfrom, *mto;
2309         struct sip_request req;
2310         char clen[20];
2311         
2312         strncpy(from, get_header(&p->initreq, "From"), sizeof(from)-1);
2313
2314         c = ditch_braces(from);
2315         if (strncmp(c, "sip:", 4)) {
2316                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
2317                 return -1;
2318         }
2319         if ((a = strchr(c, ';'))) {
2320                 *a = '\0';
2321         }
2322         mfrom = c;
2323                 
2324         reqprep(&req, p, "NOTIFY", 1);
2325
2326         if (p->subscribed == 1) {
2327             strncpy(to, get_header(&p->initreq, "To"), sizeof(to)-1);
2328
2329             c = ditch_braces(to);
2330             if (strncmp(c, "sip:", 4)) {
2331                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
2332                 return -1;
2333             }
2334             if ((a = strchr(c, ';'))) {
2335                 *a = '\0';
2336             }
2337             mto = c;
2338
2339             add_header(&req, "Content-Type", "application/xpidf+xml");
2340
2341             if ((state==AST_EXTENSION_UNAVAILABLE) || (state==AST_EXTENSION_BUSY))
2342                 state = 2;
2343             else if (state==AST_EXTENSION_INUSE)
2344                 state = 1;
2345             else
2346                 state = 0;
2347             
2348             t = tmp;            
2349             sprintf(t, "<?xml version=\"1.0\"?>\n");
2350             t = tmp + strlen(tmp);
2351             sprintf(t, "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n");
2352             t = tmp + strlen(tmp);
2353             sprintf(t, "<presence>\n");
2354             t = tmp + strlen(tmp);
2355             sprintf(t, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
2356             t = tmp + strlen(tmp);
2357             sprintf(t, "<atom id=\"%s\">\n", p->exten);
2358             t = tmp + strlen(tmp);
2359             sprintf(t, "<address uri=\"%s;user=ip\" priority=\"0,800000\">\n", mto);
2360             t = tmp + strlen(tmp);
2361             sprintf(t, "<status status=\"%s\" />\n", !state ? "open" : (state==1) ? "inuse" : "closed");
2362             t = tmp + strlen(tmp);
2363             sprintf(t, "<msnsubstatus substatus=\"%s\" />\n", !state ? "online" : (state==1) ? "onthephone" : "offline");
2364             t = tmp + strlen(tmp);
2365             sprintf(t, "</address>\n</atom>\n</presence>\n");           
2366         } else {
2367             add_header(&req, "Event", "dialog");
2368             add_header(&req, "Content-Type", "application/dialog-info+xml");
2369         
2370             t = tmp;            
2371             sprintf(t, "<?xml version=\"1.0\"?>\n");
2372             t = tmp + strlen(tmp);
2373             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);
2374             t = tmp + strlen(tmp);
2375             sprintf(t, "<dialog id=\"%s\">\n", p->exten);
2376             t = tmp + strlen(tmp);
2377             sprintf(t, "<state>%s</state>\n", state ? "confirmed" : "terminated");
2378             t = tmp + strlen(tmp);
2379             sprintf(t, "</dialog>\n</dialog-info>\n");  
2380         }
2381
2382         snprintf(clen, sizeof(clen), "%d", strlen(tmp));
2383         add_header(&req, "Content-Length", clen);
2384         add_line(&req, tmp);
2385
2386         return send_request(p, &req, 1, p->ocseq);
2387 }
2388
2389 static int transmit_notify(struct sip_pvt *p, int newmsgs, int oldmsgs)
2390 {
2391         struct sip_request req;
2392         char tmp[256];
2393         char tmp2[256];
2394         char clen[20];
2395         initreqprep(&req, p, "NOTIFY", NULL);
2396         add_header(&req, "Event", "message-summary");
2397         add_header(&req, "Content-Type", "application/simple-message-summary");
2398
2399         snprintf(tmp, sizeof(tmp), "Message-Waiting: %s\n", newmsgs ? "yes" : "no");
2400         snprintf(tmp2, sizeof(tmp2), "Voicemail: %d/%d\n", newmsgs, oldmsgs);
2401         snprintf(clen, sizeof(clen), "%d", strlen(tmp) + strlen(tmp2));
2402         add_header(&req, "Content-Length", clen);
2403         add_line(&req, tmp);
2404         add_line(&req, tmp2);
2405
2406         if (!p->initreq.headers) {
2407                 /* Use this as the basis */
2408                 copy_request(&p->initreq, &req);
2409                 parse(&p->initreq);
2410         }
2411
2412         return send_request(p, &req, 1, p->ocseq);
2413 }
2414
2415 static int transmit_register(struct sip_registry *r, char *cmd, char *auth);
2416
2417 static int sip_reregister(void *data) 
2418 {
2419         /* if we are here, we know that we need to reregister. */
2420         struct sip_registry *r=(struct sip_registry *)data;
2421         return sip_do_register(r);
2422         
2423 }
2424
2425
2426 static int sip_do_register(struct sip_registry *r)
2427 {
2428         int res;
2429         ast_pthread_mutex_lock(&r->lock);
2430         res=transmit_register(r, "REGISTER", NULL);
2431         ast_pthread_mutex_unlock(&r->lock);
2432         return res;
2433 }
2434
2435 static int sip_reg_timeout(void *data)
2436 {
2437         /* if we are here, our registration timed out, so we'll just do it over */
2438         struct sip_registry *r=data;
2439         int res;
2440         ast_pthread_mutex_lock(&r->lock);
2441         ast_log(LOG_NOTICE, "Registration timed out, trying again\n"); 
2442         r->regstate=REG_STATE_UNREGISTERED;
2443         /* cancel ourselves first!!! */
2444         /* ast_sched_del(sched,r->timeout); */
2445         res=transmit_register(r, "REGISTER", NULL);
2446         ast_pthread_mutex_unlock(&r->lock);
2447         return res;
2448 }
2449
2450 static int transmit_register(struct sip_registry *r, char *cmd, char *auth)
2451 {
2452         struct sip_request req;
2453         char from[256];
2454         char to[256];
2455         char tmp[80];
2456         char via[80];
2457         char addr[80];
2458         struct sip_pvt *p;
2459         /* exit if we are already in process with this registrar ?*/
2460         if ( r == NULL || (auth==NULL && r->regstate==REG_STATE_REGSENT) || r->regstate==REG_STATE_AUTHSENT) {
2461                 ast_log(LOG_NOTICE, "Strange, trying to register when registration already pending\n");
2462                 return 0;
2463         }
2464
2465
2466         if (!(p=r->call)) {
2467                 if (!r->callid_valid) {
2468                   build_callid(r->callid, sizeof(r->callid), __ourip);
2469                   r->callid_valid=1;
2470                 }
2471                 p=sip_alloc( r->callid, &r->addr, 0);
2472                 p->outgoing = 1;
2473                 r->call=p;
2474                 p->registry=r;
2475                 strncpy(p->peersecret, r->secret, sizeof(p->peersecret)-1);
2476                 strncpy(p->peername, r->username, sizeof(p->peername)-1);
2477                 strncpy(p->username, r->username, sizeof(p->username)-1);
2478         }
2479
2480         /* set up a timeout */
2481         if (auth==NULL && !r->timeout)  {
2482                 r->timeout = ast_sched_add(sched, 10*1000, sip_reg_timeout, r);
2483                 ast_log(LOG_NOTICE, "Scheduled a timeout # %d\n", r->timeout);
2484         }
2485
2486         snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%08x", r->username, inet_ntoa(r->addr.sin_addr), p->tag);
2487         snprintf(to, sizeof(to),     "<sip:%s@%s>;tag=%08x", r->username, inet_ntoa(r->addr.sin_addr), p->tag);
2488         
2489         snprintf(addr, sizeof(addr), "sip:%s", inet_ntoa(r->addr.sin_addr));
2490
2491         memset(&req, 0, sizeof(req));
2492         init_req(&req, cmd, addr);
2493
2494         snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
2495
2496         snprintf(via, sizeof(via), "SIP/2.0/UDP %s:%d;branch=%08x", inet_ntoa(p->ourip), ourport, p->branch);
2497         add_header(&req, "Via", via);
2498         add_header(&req, "From", from);
2499         add_header(&req, "To", to);
2500         {
2501                 char contact[256];
2502                 snprintf(contact, sizeof(contact), "<sip:%s@%s:%d;transport=udp>", r->contact, inet_ntoa(p->ourip), ourport);
2503                 add_header(&req, "Contact", contact);
2504         }
2505         add_header(&req, "Call-ID", p->callid);
2506         add_header(&req, "CSeq", tmp);
2507         add_header(&req, "User-Agent", "Asterisk PBX");
2508         if (auth) 
2509                 add_header(&req, "Authorization", auth);
2510
2511         snprintf(tmp, sizeof(tmp), "%d", default_expirey);
2512         add_header(&req, "Expires", tmp);
2513         add_header(&req, "Event", "registration");
2514         add_header(&req, "Content-length", "0");
2515         add_blank_header(&req);
2516         copy_request(&p->initreq, &req);
2517         r->regstate=auth?REG_STATE_AUTHSENT:REG_STATE_REGSENT;
2518         return send_request(p, &req, 1, p->ocseq);
2519 }
2520
2521 static int transmit_message_with_text(struct sip_pvt *p, char *text)
2522 {
2523         struct sip_request req;
2524         reqprep(&req, p, "MESSAGE", 1);
2525         add_text(&req, text);
2526         return send_request(p, &req, 1, p->ocseq);
2527 }
2528
2529 static int transmit_info_with_digit(struct sip_pvt *p, char digit)
2530 {
2531         struct sip_request req;
2532         reqprep(&req, p, "INFO", 1);
2533         add_digit(&req, digit);
2534         return send_request(p, &req, 1, p->ocseq);
2535 }
2536
2537 static int transmit_request(struct sip_pvt *p, char *msg, int inc, int reliable)
2538 {
2539         struct sip_request resp;
2540         reqprep(&resp, p, msg, inc);
2541         add_header(&resp, "Content-Length", "0");
2542         add_blank_header(&resp);
2543         return send_request(p, &resp, reliable, p->ocseq);
2544 }
2545
2546 static int expire_register(void *data)
2547 {
2548         struct sip_peer *p = data;
2549         memset(&p->addr, 0, sizeof(p->addr));
2550         p->expire = -1;
2551         ast_device_state_changed("SIP/%s", p->name);
2552         return 0;
2553 }
2554
2555 static int sip_poke_peer(struct sip_peer *peer);
2556
2557 static int parse_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req)
2558 {
2559         char contact[80]= ""; 
2560         char *expires = get_header(req, "Expires");
2561         int expirey = atoi(expires);
2562         char *c, *n, *pt;
2563         int port;
2564         struct hostent *hp;
2565         struct sockaddr_in oldsin;
2566         if (!strlen(expires)) {
2567                 expires = strstr(get_header(req, "Contact"), "expires=");
2568                 if (expires) 
2569                         if (sscanf(expires + 8, "%d;", &expirey) != 1)
2570                                 expirey = 0;
2571         }
2572         /* Look for brackets */
2573         strncpy(contact, get_header(req, "Contact"), sizeof(contact) - 1);
2574         c = contact;
2575         
2576         if ((n=strchr(c, '<'))) {
2577                 c = n + 1;
2578                 n = strchr(c, '>');
2579                 /* Lose the part after the > */
2580                 if (n) 
2581                         *n = '\0';
2582         }
2583         if (!strcasecmp(c, "*") || !expirey) {
2584                 /* This means remove all registrations and return OK */
2585                 memset(&p->addr, 0, sizeof(p->addr));
2586                 if (p->expire > -1)
2587                         ast_sched_del(sched, p->expire);
2588                 p->expire = -1;
2589                 if (option_verbose > 2)
2590                         ast_verbose(VERBOSE_PREFIX_3 "Unregistered SIP '%s'\n", p->username);
2591                 return 0;
2592         }
2593         /* Make sure it's a SIP URL */
2594         if (strncasecmp(c, "sip:", 4)) {
2595                 ast_log(LOG_NOTICE, "'%s' is not a valid SIP contact (missing sip:) trying to use anyway\n", c);
2596         } else
2597                 c += 4;
2598         /* Ditch q */
2599         n = strchr(c, ';');
2600         if (n) 
2601                 *n = '\0';
2602         /* Grab host */
2603         n = strchr(c, '@');
2604         if (!n) {
2605                 n = c;
2606                 c = NULL;
2607         } else {
2608                 *n = '\0';
2609                 n++;
2610         }
2611         pt = strchr(n, ':');
2612         if (pt) {
2613                 *pt = '\0';
2614                 pt++;
2615                 port = atoi(pt);
2616         } else
2617                 port = DEFAULT_SIP_PORT;
2618         memcpy(&oldsin, &p->addr, sizeof(oldsin));
2619         if (!p->nat) {
2620                 /* XXX This could block for a long time XXX */
2621                 hp = gethostbyname(n);
2622                 if (!hp)  {
2623                         ast_log(LOG_WARNING, "Invalid host '%s'\n", n);
2624                         return -1;
2625                 }
2626                 p->addr.sin_family = AF_INET;
2627                 memcpy(&p->addr.sin_addr, hp->h_addr, sizeof(p->addr.sin_addr));
2628                 p->addr.sin_port = htons(port);
2629         } else {
2630                 /* Don't trust the contact field.  Just use what they came to us
2631                    with */
2632                 memcpy(&p->addr, &pvt->recv, sizeof(p->addr));
2633         }
2634         if (c)
2635                 strncpy(p->username, c, sizeof(p->username) - 1);
2636         else
2637                 strcpy(p->username, "");
2638         if (p->expire > -1)
2639                 ast_sched_del(sched, p->expire);
2640         if ((expirey < 1) || (expirey > max_expirey))
2641                 expirey = max_expirey;
2642         p->expire = ast_sched_add(sched, (expirey + 10) * 1000, expire_register, p);
2643         pvt->expirey = expirey;
2644         if (memcmp(&p->addr, &oldsin, sizeof(oldsin))) {
2645                 sip_poke_peer(p);
2646                 if (option_verbose > 2)
2647                         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);
2648         }
2649         return 0;
2650 }
2651
2652 static void free_old_route(struct sip_route *route)
2653 {
2654         struct sip_route *next;
2655         while (route) {
2656                 next = route->next;
2657                 free(route);
2658                 route = next;
2659         }
2660 }
2661
2662 static void list_route(struct sip_route *route)
2663 {
2664         if (!route) {
2665                 ast_verbose("list_route: no route\n");
2666                 return;
2667         }
2668         while (route) {
2669                 ast_verbose("list_route: hop: <%s>\n", route->hop);
2670                 route = route->next;
2671         }
2672 }
2673
2674 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
2675 {
2676         struct sip_route *thishop, *head, *tail;
2677         int start = 0;
2678         int len;
2679         char *rr, *contact, *c;
2680
2681         if (p->route) {
2682                 free_old_route(p->route);
2683                 p->route = NULL;
2684         }
2685         /* We build up head, then assign it to p->route when we're done */
2686         head = NULL;  tail = head;
2687         /* 1st we pass through all the hops in any Record-Route headers */
2688         for (;;) {
2689                 /* Each Record-Route header */
2690                 rr = __get_header(req, "Record-Route", &start);
2691                 if (*rr == '\0') break;
2692                 for (;;) {
2693                         /* Each route entry */
2694                         /* Find < */
2695                         rr = strchr(rr, '<');
2696                         if (!rr) break; /* No more hops */
2697                         ++rr;
2698                         len = strcspn(rr, ">");
2699                         /* Make a struct route */
2700                         thishop = (struct sip_route *)malloc(sizeof(struct sip_route)+len+1);
2701                         if (thishop) {
2702                                 strncpy(thishop->hop, rr, len);
2703                                 thishop->hop[len] = '\0';
2704                                 ast_log(LOG_DEBUG, "build_route: Record-Route hop: <%s>\n", thishop->hop);
2705                                 /* Link in */
2706                                 if (backwards) {
2707                                         /* Link in at head so they end up in reverse order */
2708                                         thishop->next = head;
2709                                         head = thishop;
2710                                         /* If this was the first then it'll be the tail */
2711                                         if (!tail) tail = thishop;
2712                                 } else {
2713                                         thishop->next = NULL;
2714                                         /* Link in at the end */
2715                                         if (tail)
2716                                                 tail->next = thishop;
2717                                         else
2718                                                 head = thishop;
2719                                         tail = thishop;
2720                                 }
2721                         }
2722                         rr += len+1;
2723                 }
2724         }
2725         /* 2nd append the Contact: if there is one */
2726         /* Can be multiple Contact headers, comma separated values - we just take the first */
2727         contact = get_header(req, "Contact");
2728         if (strlen(contact)) {
2729                 ast_log(LOG_DEBUG, "build_route: Contact hop: %s\n", contact);
2730                 /* Look for <: delimited address */
2731                 c = strchr(contact, '<');
2732                 if (c) {
2733                         /* Take to > */
2734                         ++c;
2735                         len = strcspn(c, ">");
2736                 } else {
2737                         /* No <> - just take the lot */
2738                         c = contact; len = strlen(contact);
2739                 }
2740                 thishop = (struct sip_route *)malloc(sizeof(struct sip_route)+len+1);
2741                 if (thishop) {
2742                         strncpy(thishop->hop, c, len);
2743                         thishop->hop[len] = '\0';
2744                         thishop->next = NULL;
2745                         /* Goes at the end */
2746                         if (tail)
2747                                 tail->next = thishop;
2748                         else
2749                                 head = thishop;
2750                 }
2751         }
2752         /* Store as new route */
2753         p->route = head;
2754
2755         /* For debugging dump what we ended up with */
2756         if (sipdebug)
2757                 list_route(p->route);
2758 }
2759
2760 static void md5_hash(char *output, char *input)
2761 {
2762                 struct MD5Context md5;
2763                 unsigned char digest[16];
2764                 char *ptr;
2765                 int x;
2766                 MD5Init(&md5);
2767                 MD5Update(&md5, input, strlen(input));
2768                 MD5Final(digest, &md5);
2769                 ptr = output;
2770                 for (x=0;x<16;x++)
2771                         ptr += sprintf(ptr, "%2.2x", digest[x]);
2772 }
2773
2774 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)
2775 {
2776         int res = -1;
2777         /* Always OK if no secret */
2778         if (!strlen(secret))
2779                 return 0;
2780         if (!strlen(randdata) || !strlen(get_header(req, "Proxy-Authorization"))) {
2781                 snprintf(randdata, randlen, "%08x", rand());
2782                 transmit_response_with_auth(p, "407 Proxy Authentication Required", req, randdata, reliable);
2783                 /* Schedule auto destroy in 15 seconds */
2784                 sip_scheddestroy(p, 15000);
2785                 res = 1;
2786         } else {
2787                 /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
2788                    an example in the spec of just what it is you're doing a hash on. */
2789                 char a1[256];
2790                 char a2[256];
2791                 char a1_hash[256];
2792                 char a2_hash[256];
2793                 char resp[256];
2794                 char resp_hash[256];
2795                 char tmp[256] = "";
2796                 char *c;
2797                 char *response ="";
2798                 char *resp_uri ="";
2799
2800                 /* Find their response among the mess that we'r sent for comparison */
2801                 strncpy(tmp, get_header(req, "Proxy-Authorization"), sizeof(tmp) - 1);
2802                 c = tmp;
2803
2804                 while(c) {
2805                         while (*c && (*c < 33)) c++;
2806                         if (!*c)
2807                                 break;
2808                         if (!strncasecmp(c, "response=", strlen("response="))) {
2809                                 c+= strlen("response=");
2810                                 if ((*c == '\"')) {
2811                                         response=++c;
2812                                         if((c = strchr(c,'\"')))
2813                                                 *c = '\0';
2814
2815                                 } else {
2816                                         response=c;
2817                                         if((c = strchr(c,',')))
2818                                                 *c = '\0';
2819                                 }
2820
2821                         } else if (!strncasecmp(c, "uri=", strlen("uri="))) {
2822                                 c+= strlen("uri=");
2823                                 if ((*c == '\"')) {
2824                                         resp_uri=++c;
2825                                         if((c = strchr(c,'\"')))
2826                                                 *c = '\0';
2827                                 } else {
2828                                         resp_uri=c;
2829                                         if((c = strchr(c,',')))
2830                                                 *c = '\0';
2831                                 }
2832
2833                         } else
2834                                 c = strchr(c, ',');
2835                         if (c)
2836                                 c++;
2837                 }
2838                 snprintf(a1, sizeof(a1), "%s:%s:%s", username, "asterisk", secret);
2839                 if(strlen(resp_uri))
2840                         snprintf(a2, sizeof(a2), "%s:%s", method, resp_uri);
2841                 else
2842                         snprintf(a2, sizeof(a2), "%s:%s", method, uri);
2843                 md5_hash(a1_hash, a1);
2844                 md5_hash(a2_hash, a2);
2845                 snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, randdata, a2_hash);
2846                 md5_hash(resp_hash, resp);
2847
2848                 /* resp_hash now has the expected response, compare the two */
2849
2850                 if (response && !strncasecmp(response, resp_hash, strlen(resp_hash))) {
2851                         /* Auth is OK */
2852                         res = 0;
2853                 }
2854                 /* Assume success ;-) */
2855                 /* Eliminate random data */
2856                 strcpy(randdata, "");
2857         }
2858         return res;
2859 }
2860
2861 static int cb_extensionstate(char *context, char* exten, int state, void *data)
2862 {
2863     struct sip_pvt *p = data;
2864     if (state == -1) {
2865         sip_scheddestroy(p, 15000);
2866         p->stateid = -1;
2867         return 0;
2868     }
2869     
2870     transmit_state_notify(p, state, 1);
2871     
2872     if (option_debug)
2873         ast_verbose(VERBOSE_PREFIX_1 "Extension Changed %s new state %d for Notify User %s\n", exten, state, p->username);
2874     return 0;
2875 }
2876
2877 static int register_verify(struct sip_pvt *p, struct sockaddr_in *sin, struct sip_request *req, char *uri)
2878 {
2879         int res = -1;
2880         struct sip_peer *peer;
2881         char tmp[256] = "";
2882         char *name, *c;
2883         char *t;
2884         /* Terminate URI */
2885         t = uri;
2886         while(*t && (*t > 32) && (*t != ';'))
2887                 t++;
2888         *t = '\0';
2889         
2890         strncpy(tmp, get_header(req, "To"), sizeof(tmp) - 1);
2891         c = ditch_braces(tmp);
2892         if (!strncmp(c, "sip:", 4)) {
2893                 name = c + 4;
2894         } else {
2895                 name = c;
2896                 ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, inet_ntoa(sin->sin_addr));
2897         }
2898         c = strchr(name, '@');
2899         if (c) 
2900                 *c = '\0';
2901         ast_pthread_mutex_lock(&peerl.lock);
2902         peer = peerl.peers;
2903         while(peer) {
2904                 if (!strcasecmp(peer->name, name) && peer->dynamic) {
2905                         p->nat = peer->nat;
2906                         transmit_response(p, "100 Trying", req);
2907                         if (!(res = check_auth(p, req, p->randdata, sizeof(p->randdata), peer->name, peer->secret, "REGISTER", uri, 0))) {
2908                                 sip_cancel_destroy(p);
2909                                 if (parse_contact(p, peer, req)) {
2910                                         ast_log(LOG_WARNING, "Failed to parse contact info\n");
2911                                 } else {
2912                                         /* Say OK and ask subsystem to retransmit msg counter */
2913                                         transmit_response_with_date(p, "200 OK", req);
2914                                         peer->lastmsgssent = -1;
2915                                         res = 0;
2916                                 }
2917                         } 
2918                         break;
2919                 }       
2920                 peer = peer->next;
2921         }
2922         ast_pthread_mutex_unlock(&peerl.lock);
2923         if (!res) {
2924             ast_device_state_changed("SIP/%s", peer->name);
2925         }
2926         if (res < 0)
2927                 transmit_response(p, "401 Unauthorized", &p->initreq);
2928         return res;
2929 }
2930
2931 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
2932 {
2933         char tmp[256] = "", *c, *a;
2934         struct sip_request *req;
2935         
2936         req = oreq;
2937         if (!req)
2938                 req = &p->initreq;
2939         strncpy(tmp, req->rlPart2, sizeof(tmp) - 1);
2940         c = ditch_braces(tmp);
2941         if (strncmp(c, "sip:", 4)) {
2942                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
2943                 return -1;
2944         }
2945         c += 4;
2946         if ((a = strchr(c, '@')) || (a = strchr(c, ';'))) {
2947                 *a = '\0';
2948         }
2949         if (sipdebug)
2950                 ast_verbose("Looking for %s in %s\n", c, p->context);
2951         if (ast_exists_extension(NULL, p->context, c, 1, NULL)) {
2952                 if (!oreq)
2953                         strncpy(p->exten, c, sizeof(p->exten) - 1);
2954                 return 0;
2955         }
2956
2957         if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
2958                 return 1;
2959         }
2960         
2961         return -1;
2962 }
2963
2964 static int get_refer_info(struct sip_pvt *p, struct sip_request *oreq)
2965 {
2966         char tmp[256] = "", *c, *a;
2967         char tmp2[256] = "", *c2, *a2;
2968         char tmp3[256];
2969         char tmp4[256];
2970         char tmp5[256] = "";            /* CallID to replace */
2971         struct sip_request *req;
2972         struct sip_pvt *p2;
2973         
2974         req = oreq;
2975         if (!req)
2976                 req = &p->initreq;
2977         strncpy(tmp, get_header(req, "Refer-To"), sizeof(tmp) - 1);
2978         strncpy(tmp2, get_header(req, "Referred-By"), sizeof(tmp2) - 1);
2979         strncpy(tmp3, get_header(req, "Contact"), sizeof(tmp3) - 1);
2980         strncpy(tmp4, get_header(req, "Remote-Party-ID"), sizeof(tmp4) - 1);
2981         
2982         c = ditch_braces(tmp);
2983         c2 = ditch_braces(tmp2);
2984         
2985                 
2986         if (strncmp(c, "sip:", 4) && strncmp(c2, "sip:", 4)) {
2987                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
2988                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c2);
2989                 return -1;
2990         }
2991         c += 4;
2992         c2 += 4;
2993         if ((a = strchr(c, '?'))) {
2994                 /* Search for arguemnts */
2995                 *a = '\0';
2996                 a++;
2997                 if (!strncasecmp(a, "REPLACES=", strlen("REPLACES="))) {
2998                         strncpy(tmp5, a + strlen("REPLACES="), sizeof(tmp5) - 1);
2999                         if ((a = strchr(tmp5, '%'))) {
3000                                 /* Yuck!  Pingtel converts the '@' to a %40, icky icky!  Convert
3001                                    back to an '@' */
3002                                 if ((a[1] == '4') && (a[2] == '0')) {
3003                                         *a = '@';
3004                                         memmove(a + 1, a+3, strlen(a + 3));
3005                                 }
3006                         }
3007                         if ((a = strchr(tmp5, '%'))) 
3008                                 *a = '\0';
3009                 }
3010         }
3011         
3012         if ((a = strchr(c, '@')))
3013                 *a = '\0';
3014         if ((a = strchr(c, ';'))) 
3015                 *a = '\0';
3016         
3017
3018         if ((a2 = strchr(c2, '@')))
3019                 *a2 = '\0';
3020
3021         if ((a2 = strchr(c2, ';'))) 
3022                 *a2 = '\0';
3023         
3024         
3025         if (sipdebug) {
3026                 ast_verbose("Looking for %s in %s\n", c, p->context);
3027                 ast_verbose("Looking for %s in %s\n", c2, p->context);
3028         }
3029         if (strlen(tmp5)) {     
3030                 /* This is a supervised transfer */
3031                 ast_log(LOG_DEBUG,"Assigning Replace-Call-ID Info %s to REPLACE_CALL_ID\n",tmp5);
3032                 
3033                 strncpy(p->refer_to, "", sizeof(p->refer_to) - 1);
3034                 strncpy(p->referred_by, "", sizeof(p->referred_by) - 1);
3035                 strncpy(p->refer_contact, "", sizeof(p->refer_contact) - 1);
3036                 strncpy(p->remote_party_id, "", sizeof(p->remote_party_id) - 1);
3037                 p->refer_call = NULL;
3038                 ast_pthread_mutex_lock(&iflock);
3039                 /* Search interfaces and find the match */
3040                 p2 = iflist;
3041                 while(p2) {
3042                         if (!strcmp(p2->callid, tmp5)) {
3043                                 /* Go ahead and lock it before returning */
3044                                 ast_pthread_mutex_lock(&p2->lock);
3045                                 p->refer_call = p2;
3046                                 break;
3047                         }
3048                         p2 = p2->next;
3049                 }
3050                 ast_pthread_mutex_unlock(&iflock);
3051                 if (p->refer_call)
3052                         return 0;
3053                 else
3054                         ast_log(LOG_NOTICE, "Supervised transfer requested, but unable to find callid '%s'\n", tmp5);
3055         } else if (ast_exists_extension(NULL, p->context, c, 1, NULL)) {
3056                 /* This is an unsupervised transfer */
3057                 ast_log(LOG_DEBUG,"Assigning Extension %s to REFER-TO\n", c);
3058                 ast_log(LOG_DEBUG,"Assigning Extension %s to REFERRED-BY\n", c2);
3059                 ast_log(LOG_DEBUG,"Assigning Contact Info %s to REFER_CONTACT\n", tmp3);
3060                 ast_log(LOG_DEBUG,"Assigning Remote-Party-ID Info %s to REMOTE_PARTY_ID\n",tmp4);
3061                 strncpy(p->refer_to, c, sizeof(p->refer_to) - 1);
3062                 strncpy(p->referred_by, c2, sizeof(p->referred_by) - 1);
3063                 strncpy(p->refer_contact, tmp3, sizeof(p->refer_contact) - 1);
3064                 strncpy(p->remote_party_id, tmp4, sizeof(p->remote_party_id) - 1);
3065                 p->refer_call = NULL;
3066                 return 0;
3067         } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
3068                 return 1;
3069         }
3070
3071         return -1;
3072 }
3073
3074
3075 static int check_via(struct sip_pvt *p, struct sip_request *req)
3076 {
3077         char via[256] = "";
3078         char *c, *pt;
3079         struct hostent *hp;
3080
3081         memset(via, 0, sizeof(via));
3082         strncpy(via, get_header(req, "Via"), sizeof(via) - 1);
3083         c = strchr(via, ';');
3084         if (c) 
3085                 *c = '\0';
3086         c = strchr(via, ' ');
3087         if (c) {
3088                 *c = '\0';
3089                 c++;
3090                 while(*c && (*c < 33))
3091                         c++;
3092                 if (strcmp(via, "SIP/2.0/UDP")) {
3093                         ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
3094                         return -1;
3095                 }
3096                 pt = strchr(c, ':');
3097                 if (pt) {
3098                         *pt = '\0';
3099                         pt++;
3100                 }
3101                 hp = gethostbyname(c);
3102                 if (!hp) {
3103                         ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
3104                         return -1;
3105                 }
3106                 memset(&p->sa, 0, sizeof(p->sa));
3107                 p->sa.sin_family = AF_INET;
3108                 memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
3109                 p->sa.sin_port = htons(pt ? atoi(pt) : DEFAULT_SIP_PORT);
3110                 if (sipdebug) {
3111                         if (p->nat)
3112                                 ast_verbose("Sending to %s : %d (NAT)\n", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));
3113                         else
3114                                 ast_verbose("Sending to %s : %d (non-NAT)\n", inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port));