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