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