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