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