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