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