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