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