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