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