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