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