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