Add extended Matching functionality (bug #97)
[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 CALLERID_UNKNOWN        "Unknown"
66
67 #define SIP_DTMF_RFC2833        (1 << 0)
68 #define SIP_DTMF_INBAND         (1 << 1)
69 #define SIP_DTMF_INFO           (1 << 2)
70
71 static int max_expiry = DEFAULT_MAX_EXPIRY;
72 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
73
74 #define DEFAULT_MAXMS           2000            /* Must be faster than 2 seconds by default */
75 #define DEFAULT_FREQ_OK         60 * 1000               /* How often to check for the host to be up */
76 #define DEFAULT_FREQ_NOTOK      10 * 1000               /* How often to check, if the host is down... */
77
78 #define DEFAULT_RETRANS         1000                    /* How frequently to retransmit */
79 #define MAX_RETRANS                     5                               /* Try only 5 times for retransmissions */
80
81 static char *desc = "Session Initiation Protocol (SIP)";
82 static char *type = "sip";
83 static char *tdesc = "Session Initiation Protocol (SIP)";
84 static char *config = "sip.conf";
85
86 #define DEFAULT_SIP_PORT        5060    /* From RFC 2543 */
87 #define SIP_MAX_PACKET  1500            /* Also from RFC 2543, should sub headers tho */
88
89 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER"
90
91 static char context[AST_MAX_EXTENSION] = "default";
92
93 static char language[MAX_LANGUAGE] = "";
94
95 static char callerid[AST_MAX_EXTENSION] = "asterisk";
96
97 static char fromdomain[AST_MAX_EXTENSION] = "";
98
99 static char notifymime[AST_MAX_EXTENSION] = "application/simple-message-summary";
100
101 static int srvlookup = 0;
102
103 static int pedanticsipchecking = 0;
104
105 static int usecnt =0;
106 static ast_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
107
108 /* Protect the interface list (of sip_pvt's) */
109 static ast_mutex_t iflock = AST_MUTEX_INITIALIZER;
110
111 /* Protect the monitoring thread, so only one process can kill or start it, and not
112    when it's doing something critical. */
113 static ast_mutex_t netlock = AST_MUTEX_INITIALIZER;
114
115 static ast_mutex_t monlock = AST_MUTEX_INITIALIZER;
116
117 /* This is the thread for the monitor which checks for input on the channels
118    which are not currently in use.  */
119 static pthread_t monitor_thread = 0;
120
121 static int restart_monitor(void);
122
123 /* Codecs that we support by default: */
124 static int capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
125 static int noncodeccapability = AST_RTP_DTMF;
126
127 static char ourhost[256];
128 static struct in_addr __ourip;
129 static int ourport;
130
131 static int sipdebug = 0;
132
133 static int tos = 0;
134
135 static int videosupport = 0;
136
137 static int globaldtmfmode = SIP_DTMF_RFC2833;
138
139 /* Expire slowly */
140 static int expiry = 900;
141
142 static struct sched_context *sched;
143 static struct io_context *io;
144 /* The private structures of the  sip channels are linked for
145    selecting outgoing channels */
146    
147 #define SIP_MAX_HEADERS         64
148 #define SIP_MAX_LINES           64
149
150 static struct sip_codec_pref {
151         int codec;
152         struct sip_codec_pref *next;
153 } *prefs;
154
155 struct sip_request {
156   char *rlPart1; /* SIP Method Name or "SIP/2.0" protocol version */
157   char *rlPart2; /* The Request URI or Response Status */
158         int len;
159         int headers;                                    /* SIP Headers */
160         char *header[SIP_MAX_HEADERS];
161         int lines;                                              /* SDP Content */
162         char *line[SIP_MAX_LINES];
163         char data[SIP_MAX_PACKET];
164 };
165
166 struct sip_pkt;
167
168 struct sip_route {
169         struct sip_route *next;
170         char hop[0];
171 };
172
173 static struct sip_pvt {
174         ast_mutex_t lock;                               /* Channel private lock */
175         char callid[80];                                        /* Global CallID */
176         char randdata[80];      /* Random data */
177         unsigned int ocseq;                                     /* Current outgoing seqno */
178         unsigned int icseq;                                     /* Current incoming seqno */
179         unsigned int callgroup;
180         unsigned int pickupgroup;
181         int lastinvite;                                         /* Last Cseq of invite */
182         int alreadygone;                                        /* Whether or not we've already been destroyed by or peer */
183         int needdestroy;                                        /* if we need to be destroyed */
184         int capability;                                         /* Special capability */
185         int noncodeccapability;
186         int outgoing;                                           /* Outgoing or incoming call? */
187         int authtries;                                          /* Times we've tried to authenticate */
188         int insecure;                                           /* Don't check source port/ip */
189         int expiry;                                             /* How long we take to expire */
190         int branch;                                                     /* One random number */
191         int canreinvite;                                        /* Do we support reinvite */
192         int ringing;                                            /* Have sent 180 ringing */
193         int progress;                                           /* Have sent 183 message progress */
194         int tag;                                                        /* Another random number */
195         int nat;                                                        /* Whether to try to support NAT */
196         struct sockaddr_in sa;                          /* Our peer */
197         struct sockaddr_in redirip;                     /* Where our RTP should be going if not to us */
198         struct sockaddr_in vredirip;            /* Where our Video RTP should be going if not to us */
199         struct sockaddr_in recv;                        /* Received as */
200         struct in_addr ourip;                           /* Our IP */
201         struct ast_channel *owner;                      /* Who owns us */
202         char exten[AST_MAX_EXTENSION];          /* Extention where to start */
203         char refer_to[AST_MAX_EXTENSION];       /* Place to store REFER-TO extension */
204         char referred_by[AST_MAX_EXTENSION];/* Place to store REFERRED-BY extension */
205         char refer_contact[AST_MAX_EXTENSION];/* Place to store Contact info from a REFER extension */
206         struct sip_pvt *refer_call;                     /* Call we are referring */
207         struct sip_route *route;                        /* Head of linked list of routing steps (fm Record-Route) */
208         char remote_party_id[256];
209         char from[256];
210         char context[AST_MAX_EXTENSION];
211         char fromdomain[AST_MAX_EXTENSION];     /* Domain to show in the from field */
212         char fromuser[AST_MAX_EXTENSION];       /* Domain to show in the user field */
213         char tohost[AST_MAX_EXTENSION];         /* Host we should put in the "to" field */
214         char language[MAX_LANGUAGE];
215         char rdnis[256];                                /* Referring DNIS */
216         char theirtag[256];                             /* Their tag */
217         char username[81];
218         char peername[81];
219         char uri[81];                                   /* Original requested URI */
220         char peersecret[81];
221         char callerid[256];                                     /* Caller*ID */
222         int restrictcid;                        /* hide presentation from remote user */
223         char via[256];
224         char accountcode[20];                           /* Account code */
225         char our_contact[256];                          /* Our contact header */
226         char realm[256];                                /* Authorization realm */
227         char nonce[256];                                /* Authorization nonce */
228         char domain[256];                               /* Authorization nonce */
229         int amaflags;                                           /* AMA Flags */
230         int pendinginvite;                                      /* Any pending invite */
231         int pendingbye;                                         /* Need to send bye after we ack? */
232         struct sip_request initreq;                     /* Initial request */
233         
234         int maxtime;                                            /* Max time for first response */
235         int initid;                                                     /* Auto-congest ID if appropriate */
236         int autokillid;                                         /* Auto-kill ID */
237
238         int subscribed;
239         int stateid;
240         int dialogver;
241         
242         int dtmfmode;
243         struct ast_dsp *vad;
244         
245         struct sip_peer *peerpoke;                      /* If this calls is to poke a peer, which one */
246         struct sip_registry *registry;                  /* If this is a REGISTER call, to which registry */
247         struct ast_rtp *rtp;                            /* RTP Session */
248         struct ast_rtp *vrtp;                           /* Video RTP session */
249         struct sip_pkt *packets;                        /* Packets scheduled for re-transmission */
250         struct sip_pvt *next;
251 } *iflist = NULL;
252
253 struct sip_pkt {
254         struct sip_pkt *next;                           /* Next packet */
255         int retrans;                                            /* Retransmission number */
256         int seqno;                                                      /* Sequence number */
257         int resp;                                                       /* non-zero if this is a response packet (e.g. 200 OK) */
258         struct sip_pvt *owner;                          /* Owner call */
259         int retransid;                                          /* Retransmission ID */
260         int packetlen;                                          /* Length of packet */
261         char data[0];
262 };      
263
264 struct sip_user {
265         /* Users who can access various contexts */
266         char name[80];
267         char secret[80];
268         char context[80];
269         char callerid[80];
270         char methods[80];
271         char accountcode[20];
272         unsigned int callgroup;
273         unsigned int pickupgroup;
274         int nat;
275         int hascallerid;
276         int amaflags;
277         int insecure;
278         int canreinvite;
279         int dtmfmode;
280         int inUse;
281         int incominglimit;
282         int restrictcid;
283         struct ast_ha *ha;
284         struct sip_user *next;
285 };
286
287 struct sip_peer {
288         char name[80];
289         char secret[80];
290         char context[80];               /* JK02: peers need context too to allow parking etc */
291         char methods[80];
292         char username[80];
293         char tohost[80];
294         char fromuser[80];
295         char fromdomain[80];
296         char mailbox[AST_MAX_EXTENSION];
297         int lastmsgssent;
298         time_t  lastmsgcheck;
299         int dynamic;
300         int expire;
301         int expiry;
302         int capability;
303         int insecure;
304         int nat;
305         int canreinvite;
306         unsigned int callgroup;
307         unsigned int pickupgroup;
308         int dtmfmode;
309         struct sockaddr_in addr;
310         struct in_addr mask;
311
312         /* Qualification */
313         struct sip_pvt *call;           /* Call pointer */
314         int pokeexpire;                         /* When to expire poke */
315         int lastms;                                     /* How long last response took (in ms), or -1 for no response */
316         int maxms;                                      /* Max ms we will accept for the host to be up, 0 to not monitor */
317         struct timeval ps;                      /* Ping send time */
318         
319         struct sockaddr_in defaddr;
320         struct ast_ha *ha;
321         int delme;
322         int lastmsg;
323         struct sip_peer *next;
324 };
325
326 static struct ast_user_list {
327         struct sip_user *users;
328         ast_mutex_t lock;
329 } userl = { NULL, AST_MUTEX_INITIALIZER };
330
331 static struct ast_peer_list {
332         struct sip_peer *peers;
333         ast_mutex_t lock;
334 } peerl = { NULL, AST_MUTEX_INITIALIZER };
335
336
337 #define REG_STATE_UNREGISTERED 0
338 #define REG_STATE_REGSENT          1
339 #define REG_STATE_AUTHSENT         2
340 #define REG_STATE_REGISTERED   3
341 #define REG_STATE_REJECTED         4
342 #define REG_STATE_TIMEOUT          5
343 #define REG_STATE_NOAUTH           6
344
345 struct sip_registry {
346         ast_mutex_t lock;                               /* Channel private lock */
347         struct sockaddr_in addr;                /* Who we connect to for registration purposes */
348         char username[80];                              /* Who we are registering as */
349         char authuser[80];                              /* Who we *authenticate* as */
350         char hostname[80];
351         char secret[80];                        /* Password or key name in []'s */
352         char contact[80];                       /* Contact extension */
353         char random[80];
354         int expire;                                     /* Sched ID of expiration */
355         int timeout;                                    /* sched id of sip_reg_timeout */
356         int refresh;                                    /* How often to refresh */
357         struct sip_pvt *call;                           /* create a sip_pvt structure for each outbound "registration call" in progress */
358         int regstate;
359         int callid_valid;               /* 0 means we haven't chosen callid for this registry yet. */
360         char callid[80];                /* Global CallID for this registry */
361         unsigned int ocseq;             /* Sequence number we got to for REGISTERs for this registry */
362         struct sockaddr_in us;                  /* Who the server thinks we are */
363         struct sip_registry *next;
364 };
365
366 #define REINVITE_INVITE         1
367 #define REINVITE_UPDATE         2
368
369 static int sip_do_register(struct sip_registry *r);
370 static struct sip_registry *registrations;
371
372 static int sipsock  = -1;
373 static int globalnat = 0;
374 static int globalcanreinvite = REINVITE_INVITE;
375
376
377 static struct sockaddr_in bindaddr;
378
379 static struct ast_frame  *sip_read(struct ast_channel *ast);
380 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
381 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
382 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *rand, int reliable);
383 static int transmit_request(struct sip_pvt *p, char *msg, int inc, int reliable);
384 static int transmit_request_with_auth(struct sip_pvt *p, char *msg, int inc, int reliable);
385 static int transmit_invite(struct sip_pvt *p, char *msg, int sendsdp, char *auth, char *vxml_url,char *distinctive_ring, int init);
386 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp, struct ast_rtp *vrtp);
387 static int transmit_info_with_digit(struct sip_pvt *p, char digit);
388 static int transmit_message_with_text(struct sip_pvt *p, char *text);
389 static int transmit_refer(struct sip_pvt *p, char *dest);
390 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *msg, int init);
391 static char *getsipuri(char *header);
392 static void free_old_route(struct sip_route *route);
393 static int build_reply_digest(struct sip_pvt *p, char *orig_header, char *digest, int digest_len);
394
395 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
396 {
397         int res;
398         if (p->nat)
399             res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->recv, sizeof(struct sockaddr_in));
400         else
401             res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
402         if (res != len) {
403                 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));
404         }
405         return res;
406 }
407
408 static void sip_destroy(struct sip_pvt *p);
409
410 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
411 {
412         if (bindaddr.sin_addr.s_addr)
413                 memcpy(us, &bindaddr.sin_addr, sizeof(struct in_addr));
414         else
415                 return ast_ouraddrfor(them, us);
416         return 0;
417 }
418
419 static int retrans_pkt(void *data)
420 {
421         struct sip_pkt *pkt=data;
422         int res = 0;
423         ast_mutex_lock(&pkt->owner->lock);
424         if (pkt->retrans < MAX_RETRANS) {
425                 pkt->retrans++;
426                 if (sipdebug) {
427                         if (pkt->owner->nat)
428                                 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));
429                         else
430                                 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));
431                 }
432                 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
433                 res = 1;
434         } else {
435                 ast_log(LOG_WARNING, "Maximum retries exceeded on call %s for seqno %d (%s)\n", pkt->owner->callid, pkt->seqno, pkt->resp ? "Response" : "Request");
436                 pkt->retransid = -1;
437                 while(pkt->owner->owner && ast_mutex_lock(&pkt->owner->owner->lock)) {
438                         ast_mutex_unlock(&pkt->owner->lock);
439                         usleep(1);
440                         ast_mutex_lock(&pkt->owner->lock);
441                 }
442                 if (pkt->owner->owner) {
443                         /* XXX Potential deadlocK?? XXX */
444                         ast_queue_hangup(pkt->owner->owner, 0);
445                         ast_mutex_unlock(&pkt->owner->owner->lock);
446                 } else {
447                         /* If no owner, destroy now */
448                         pkt->owner->needdestroy = 1;
449                 }
450         }
451         if (pkt)
452                 ast_mutex_unlock(&pkt->owner->lock);
453         return res;
454 }
455
456 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len)
457 {
458         struct sip_pkt *pkt;
459         pkt = malloc(sizeof(struct sip_pkt) + len);
460         if (!pkt)
461                 return -1;
462         memset(pkt, 0, sizeof(struct sip_pkt));
463         memcpy(pkt->data, data, len);
464         pkt->packetlen = len;
465         pkt->next = p->packets;
466         pkt->owner = p;
467         pkt->seqno = seqno;
468         pkt->resp = resp;
469         /* Schedule retransmission */
470         pkt->retransid = ast_sched_add(sched, DEFAULT_RETRANS, retrans_pkt, pkt);
471         pkt->next = p->packets;
472         p->packets = pkt;
473         __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
474         if (!strncasecmp(pkt->data, "INVITE", 6)) {
475                 /* Note this is a pending invite */
476                 p->pendinginvite = seqno;
477         }
478         return 0;
479 }
480
481 static int __sip_autodestruct(void *data)
482 {
483         struct sip_pvt *p = data;
484         p->autokillid = -1;
485         ast_log(LOG_DEBUG, "Auto destroying call '%s'\n", p->callid);
486         if (p->owner) {
487                 ast_log(LOG_WARNING, "Autodestruct on call '%s' with owner in place\n", p->callid);
488                 ast_queue_hangup(p->owner, 0);
489         } else {
490                 sip_destroy(p);
491         }
492         return 0;
493 }
494
495 static int sip_scheddestroy(struct sip_pvt *p, int ms)
496 {
497         if (p->autokillid > -1)
498                 ast_sched_del(sched, p->autokillid);
499         p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
500         return 0;
501 }
502
503 static int sip_cancel_destroy(struct sip_pvt *p)
504 {
505         if (p->autokillid > -1)
506                 ast_sched_del(sched, p->autokillid);
507         p->autokillid = -1;
508         return 0;
509 }
510
511 static int __sip_ack(struct sip_pvt *p, int seqno, int resp)
512 {
513         struct sip_pkt *cur, *prev = NULL;
514         int res = -1;
515         int resetinvite = 0;
516         cur = p->packets;
517         while(cur) {
518                 if ((cur->seqno == seqno) && (cur->resp == resp)) {
519                         if (!resp && (seqno == p->pendinginvite)) {
520                                 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
521                                 p->pendinginvite = 0;
522                                 resetinvite = 1;
523                         }
524                         /* this is our baby */
525                         if (prev)
526                                 prev->next = cur->next;
527                         else
528                                 p->packets = cur->next;
529                         if (cur->retransid > -1)
530                                 ast_sched_del(sched, cur->retransid);
531                         free(cur);
532                         res = 0;
533                         break;
534                 }
535                 prev = cur;
536                 cur = cur->next;
537         }
538         ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
539         return res;
540 }
541
542 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp)
543 {
544         struct sip_pkt *cur;
545         int res = -1;
546         cur = p->packets;
547         while(cur) {
548                 if ((cur->seqno == seqno) && (cur->resp == resp)) {
549                         /* this is our baby */
550                         if (cur->retransid > -1)
551                                 ast_sched_del(sched, cur->retransid);
552                         cur->retransid = -1;
553                         res = 0;
554                         break;
555                 }
556                 cur = cur->next;
557         }
558         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");
559         return res;
560 }
561
562 static int send_response(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
563 {
564         int res;
565         if (sipdebug) {
566                 if (p->nat)
567                         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));
568                 else
569                         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));
570         }
571         if (reliable)
572                 res = __sip_reliable_xmit(p, seqno, 1, req->data, req->len);
573         else
574                 res = __sip_xmit(p, req->data, req->len);
575         if (res > 0)
576                 res = 0;
577         return res;
578 }
579
580 static int send_request(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
581 {
582         int res;
583         if (sipdebug) {
584                 if (p->nat)
585                         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));
586                 else
587                         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));
588         }
589         if (reliable)
590                 res = __sip_reliable_xmit(p, seqno, 0, req->data, req->len);
591         else
592                 res = __sip_xmit(p, req->data, req->len);
593         return res;
594 }
595
596 static char *ditch_braces(char *tmp)
597 {
598         char *c = tmp;
599         char *n;
600         c = tmp;
601         if ((n = strchr(tmp, '<')) ) {
602                 c = n + 1;
603                 while(*c && *c != '>') c++;
604                 if (*c != '>') {
605                         ast_log(LOG_WARNING, "No closing brace in '%s'\n", tmp);
606                 } else {
607                         *c = '\0';
608                 }
609                 return n+1;
610         }
611         return c;
612 }
613
614 static int sip_sendtext(struct ast_channel *ast, char *text)
615 {
616         struct sip_pvt *p = ast->pvt->pvt;
617         if (sipdebug) 
618                 ast_verbose("Sending text %s on %s\n", text, ast->name);
619         if (!p)
620                 return -1;
621         if (!text || !strlen(text))
622                 return 0;
623         if (sipdebug)
624                 ast_verbose("Really sending text %s on %s\n", text, ast->name);
625         transmit_message_with_text(p, text);
626         return 0;       
627 }
628
629 static int create_addr(struct sip_pvt *r, char *peer)
630 {
631         struct hostent *hp;
632         struct sip_peer *p;
633         int found=0;
634         char *port;
635         int portno;
636         char host[256], *hostn;
637
638         r->sa.sin_family = AF_INET;
639         ast_mutex_lock(&peerl.lock);
640         p = peerl.peers;
641         while(p) {
642                 if (!strcasecmp(p->name, peer)) {
643                         found++;
644                         r->capability = p->capability;
645                         r->nat = p->nat;
646                         if (r->rtp) {
647                                 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", r->nat);
648                                 ast_rtp_setnat(r->rtp, r->nat);
649                         }
650                         if (r->vrtp) {
651                                 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %d\n", r->nat);
652                                 ast_rtp_setnat(r->vrtp, r->nat);
653                         }
654                         strncpy(r->peername, p->username, sizeof(r->peername)-1);
655                         strncpy(r->peersecret, p->secret, sizeof(r->peersecret)-1);
656                         strncpy(r->username, p->username, sizeof(r->username)-1);
657                         strncpy(r->tohost, p->tohost, sizeof(r->tohost)-1);
658                         if (!strlen(r->tohost)) {
659                                 if (p->addr.sin_addr.s_addr)
660                                         snprintf(r->tohost, sizeof(r->tohost), inet_ntoa(p->addr.sin_addr));
661                                 else
662                                         snprintf(r->tohost, sizeof(r->tohost), inet_ntoa(p->defaddr.sin_addr));
663                         }
664                         if (strlen(p->fromdomain))
665                                 strncpy(r->fromdomain, p->fromdomain, sizeof(r->fromdomain)-1);
666                         if (strlen(p->fromuser))
667                                 strncpy(r->fromuser, p->fromuser, sizeof(r->fromuser)-1);
668                         r->insecure = p->insecure;
669                         r->canreinvite = p->canreinvite;
670                         r->maxtime = p->maxms;
671                         r->callgroup = p->callgroup;
672                         r->pickupgroup = p->pickupgroup;
673                         if (p->dtmfmode) {
674                                 r->dtmfmode = p->dtmfmode;
675                                 if (r->dtmfmode & SIP_DTMF_RFC2833)
676                                         r->noncodeccapability |= AST_RTP_DTMF;
677                                 else
678                                         r->noncodeccapability &= ~AST_RTP_DTMF;
679                         }
680                         strncpy(r->context, p->context,sizeof(r->context)-1);
681                         if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
682                                 (!p->maxms || ((p->lastms > 0)  && (p->lastms <= p->maxms)))) {
683                                 if (p->addr.sin_addr.s_addr) {
684                                         r->sa.sin_addr = p->addr.sin_addr;
685                                         r->sa.sin_port = p->addr.sin_port;
686                                 } else {
687                                         r->sa.sin_addr = p->defaddr.sin_addr;
688                                         r->sa.sin_port = p->defaddr.sin_port;
689                                 }
690                                 memcpy(&r->recv, &r->sa, sizeof(r->recv));
691                                 break;
692                         }
693                 }
694                 p = p->next;
695         }
696         ast_mutex_unlock(&peerl.lock);
697         if (!p && !found) {
698                 if ((port=strchr(peer, ':'))) {
699                         *port='\0';
700                         port++;
701                 }
702                 hostn = peer;
703                 if (port)
704                         portno = atoi(port);
705                 else
706                         portno = DEFAULT_SIP_PORT;
707                 if (srvlookup) {
708                         char service[256];
709                         int tportno;
710                         int ret;
711                         snprintf(service, sizeof(service), "_sip._udp.%s", peer);
712                         ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
713                         if (ret > 0) {
714                                 hostn = host;
715                                 portno = tportno;
716                         }
717                 }
718                 hp = gethostbyname(hostn);
719                 if (hp) {
720                         strncpy(r->tohost, peer, sizeof(r->tohost) - 1);
721                         memcpy(&r->sa.sin_addr, hp->h_addr, sizeof(r->sa.sin_addr));
722                         r->sa.sin_port = htons(portno);
723                         memcpy(&r->recv, &r->sa, sizeof(r->recv));
724                         return 0;
725                 } else {
726                         ast_log(LOG_WARNING, "No such host: %s\n", peer);
727                         return -1;
728                 }
729         } else if (!p)
730                 return -1;
731         else
732                 return 0;
733 }
734
735 static int auto_congest(void *nothing)
736 {
737         struct sip_pvt *p = nothing;
738         ast_mutex_lock(&p->lock);
739         p->initid = -1;
740         if (p->owner) {
741                 if (!ast_mutex_trylock(&p->owner->lock)) {
742                         ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
743                         ast_queue_control(p->owner, AST_CONTROL_CONGESTION, 0);
744                         ast_mutex_unlock(&p->owner->lock);
745                 }
746         }
747         ast_mutex_unlock(&p->lock);
748         return 0;
749 }
750
751 static void sip_prefs_free(void)
752 {
753         struct sip_codec_pref *cur, *next;
754         cur = prefs;
755         while(cur) {
756                 next = cur->next;
757                 free(cur);
758                 cur = next;
759         }
760         prefs = NULL;
761 }
762
763 static void sip_pref_remove(int format)
764 {
765         struct sip_codec_pref *cur, *prev=NULL;
766         cur = prefs;
767         while(cur) {
768                 if (cur->codec == format) {
769                         if (prev)
770                                 prev->next = cur->next;
771                         else
772                                 prefs = cur->next;
773                         free(cur);
774                         return;
775                 }
776                 prev = cur;
777                 cur = cur->next;
778         }
779 }
780
781 static int sip_pref_append(int format)
782 {
783         struct sip_codec_pref *cur, *tmp;
784         sip_pref_remove(format);
785         tmp = (struct sip_codec_pref *)malloc(sizeof(struct sip_codec_pref));
786         if (!tmp)
787                 return -1;
788         memset(tmp, 0, sizeof(struct sip_codec_pref));
789         tmp->codec = format;
790         if (prefs) {
791                 cur = prefs;
792                 while(cur->next)
793                         cur = cur->next;
794                 cur->next = tmp;
795         } else
796                 prefs = tmp;
797         return 0;
798 }
799
800 static int sip_codec_choose(int formats)
801 {
802         struct sip_codec_pref *cur;
803         formats &= (AST_FORMAT_MAX_AUDIO - 1);
804         cur = prefs;
805         while(cur) {
806                 if (formats & cur->codec)
807                         return cur->codec;
808                 cur = cur->next;
809         }
810         return ast_best_codec(formats);
811 }
812
813 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
814 {
815         int res;
816         struct sip_pvt *p;
817         char *vxml_url = NULL;
818         char *distinctive_ring = NULL;
819         struct varshead *headp;
820         struct ast_var_t *current;
821         
822         p = ast->pvt->pvt;
823         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
824                 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
825                 return -1;
826         }
827         /* Check whether there is vxml_url, distinctive ring variables */
828
829         headp=&ast->varshead;
830         AST_LIST_TRAVERSE(headp,current,entries) {
831                 /* Check whether there is a VXML_URL variable */
832                 if (strcasecmp(ast_var_name(current),"VXML_URL")==0)
833                 {
834                         vxml_url = ast_var_value(current);
835                         break;
836                 }
837                 /* Check whether there is a ALERT_INFO variable */
838                 if (strcasecmp(ast_var_name(current),"ALERT_INFO")==0)
839                 {
840                         distinctive_ring = ast_var_value(current);
841                         break;
842                 }
843         }
844         
845         res = 0;
846         p->outgoing = 1;
847         p->restrictcid = ast->restrictcid;
848         transmit_invite(p, "INVITE", 1, NULL, vxml_url,distinctive_ring, 1);
849         if (p->maxtime) {
850                 /* Initialize auto-congest time */
851                 p->initid = ast_sched_add(sched, p->maxtime * 2, auto_congest, p);
852         }
853         return res;
854 }
855
856 static void __sip_destroy(struct sip_pvt *p, int lockowner)
857 {
858         struct sip_pvt *cur, *prev = NULL;
859         struct sip_pkt *cp;
860         if (sipdebug)
861                 ast_log(LOG_DEBUG, "Destorying call '%s'\n", p->callid);
862         if (p->stateid > -1)
863                 ast_extension_state_del(p->stateid, NULL);
864         if (p->initid > -1)
865                 ast_sched_del(sched, p->initid);
866         if (p->autokillid > -1)
867                 ast_sched_del(sched, p->autokillid);
868
869         if (p->rtp) {
870                 ast_rtp_destroy(p->rtp);
871         }
872         if (p->vrtp) {
873                 ast_rtp_destroy(p->vrtp);
874         }
875         if (p->route) {
876                 free_old_route(p->route);
877                 p->route = NULL;
878         }
879         if (p->registry) {
880                 p->registry->call=NULL;
881         }
882         /* Unlink us from the owner if we have one */
883         if (p->owner) {
884                 if (lockowner)
885                         ast_mutex_lock(&p->owner->lock);
886                 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
887                 p->owner->pvt->pvt = NULL;
888                 if (lockowner)
889                         ast_mutex_unlock(&p->owner->lock);
890         }
891         cur = iflist;
892         while(cur) {
893                 if (cur == p) {
894                         if (prev)
895                                 prev->next = cur->next;
896                         else
897                                 iflist = cur->next;
898                         break;
899                 }
900                 prev = cur;
901                 cur = cur->next;
902         }
903         if (!cur) {
904                 ast_log(LOG_WARNING, "%p is not in list?!?! \n", cur);
905         } else {
906                 if (p->initid > -1)
907                         ast_sched_del(sched, p->initid);
908                 while((cp = p->packets)) {
909                         p->packets = p->packets->next;
910                         if (cp->retransid > -1)
911                                 ast_sched_del(sched, cp->retransid);
912                         free(cp);
913                 }
914                 free(p);
915         }
916 }
917
918 static int find_user(struct sip_pvt *fup, int event)
919 {
920         char name[256] = "";
921         struct sip_user *u;
922         strncpy(name, fup->username, sizeof(name) - 1);
923         ast_mutex_lock(&userl.lock);
924         u = userl.users;
925         while(u) {
926                 if (!strcasecmp(u->name, name)) {
927                         break;
928                 }
929                 u = u->next;
930         }
931         if (!u) {
932                 ast_log(LOG_DEBUG, "%s is not a local user\n", name);
933                 ast_mutex_unlock(&userl.lock);
934                 return 0;
935         }
936         if(event == 0) {
937                 if ( u->inUse > 0 ) {
938                         u->inUse = u->inUse - 1;
939                 } else {
940                         u->inUse = 0;
941                 }
942         } else {
943                 if (u->incominglimit > 0 ) {
944                         if (u->inUse >= u->incominglimit) {
945                                 ast_log(LOG_ERROR, "Call from user '%s' rejected due to usage limit of %d\n", u->name, u->incominglimit);
946                                 ast_mutex_unlock(&userl.lock);
947                                 return -1; 
948                         }
949                 }
950                 u->inUse++;
951                 ast_log(LOG_DEBUG, "Call from user '%s' is %d out of %d\n", u->name, u->inUse, u->incominglimit);
952         }
953         ast_mutex_unlock(&userl.lock);
954         return 0;
955 }
956
957 static void sip_destroy(struct sip_pvt *p)
958 {
959         ast_mutex_lock(&iflock);
960         __sip_destroy(p, 1);
961         ast_mutex_unlock(&iflock);
962 }
963
964 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req);
965
966
967 static int sip_hangup(struct ast_channel *ast)
968 {
969         struct sip_pvt *p = ast->pvt->pvt;
970         int needcancel = 0;
971         int needdestroy = 0;
972         if (option_debug)
973                 ast_log(LOG_DEBUG, "sip_hangup(%s)\n", ast->name);
974         if (!ast->pvt->pvt) {
975                 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
976                 return 0;
977         }
978         ast_mutex_lock(&p->lock);
979         ast_log(LOG_DEBUG, "find_user(%s)\n", p->username);
980         find_user(p, 0);
981         /* Determine how to disconnect */
982         if (p->owner != ast) {
983                 ast_log(LOG_WARNING, "Huh?  We aren't the owner?\n");
984                 ast_mutex_unlock(&p->lock);
985                 return 0;
986         }
987         if (!ast || (ast->_state != AST_STATE_UP))
988                 needcancel = 1;
989         /* Disconnect */
990         p = ast->pvt->pvt;
991         if (p->vad) {
992             ast_dsp_free(p->vad);
993         }
994         p->owner = NULL;
995         ast->pvt->pvt = NULL;
996
997         needdestroy = 1;
998         /* Start the process if it's not already started */
999         if (!p->alreadygone && strlen(p->initreq.data)) {
1000                 if (needcancel) {
1001                         if (p->outgoing) {
1002                                 transmit_request_with_auth(p, "CANCEL", p->ocseq, 1);
1003                                 /* Actually don't destroy us yet, wait for the 487 on our original 
1004                                    INVITE, but do set an autodestruct just in case. */
1005                                 needdestroy = 0;
1006                                 sip_scheddestroy(p, 15000);
1007                         } else
1008                                 transmit_response_reliable(p, "403 Forbidden", &p->initreq);
1009                 } else {
1010                         if (!p->pendinginvite) {
1011                                 /* Send a hangup */
1012                                 transmit_request_with_auth(p, "BYE", 0, 1);
1013                         } else {
1014                                 /* Note we will need a BYE when this all settles out
1015                                    but we can't send one while we have "INVITE" outstanding. */
1016                                 p->pendingbye = 1;
1017                         }
1018                 }
1019         }
1020         p->needdestroy = needdestroy;
1021         ast_mutex_unlock(&p->lock);
1022         return 0;
1023 }
1024
1025 static int sip_answer(struct ast_channel *ast)
1026 {
1027         int res = 0,fmt;
1028         char *codec;
1029         struct sip_pvt *p = ast->pvt->pvt;
1030
1031         
1032         if (ast->_state != AST_STATE_UP) {
1033         
1034         
1035         
1036                 codec=pbx_builtin_getvar_helper(p->owner,"SIP_CODEC");
1037                 if (codec) {
1038                         ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n",codec);
1039                         fmt=ast_getformatbyname(codec);
1040                         if (fmt) {
1041                                 p->capability=fmt;
1042                         } else ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized codec: %s\n",codec);
1043                 }
1044
1045                 ast_setstate(ast, AST_STATE_UP);
1046                 if (option_debug)
1047                         ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name);
1048                 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, 1);
1049         }
1050         return res;
1051 }
1052
1053 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
1054 {
1055         struct sip_pvt *p = ast->pvt->pvt;
1056         int res = 0;
1057         if (frame->frametype == AST_FRAME_VOICE) {
1058                 if (!(frame->subclass & ast->nativeformats)) {
1059                         ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
1060                                 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
1061                         return -1;
1062                 }
1063                 if (p) {
1064                         ast_mutex_lock(&p->lock);
1065                         if (p->rtp) {
1066                                 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
1067                                         transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1068                                         p->progress = 1;
1069                                 }
1070                                 res =  ast_rtp_write(p->rtp, frame);
1071                         }
1072                         ast_mutex_unlock(&p->lock);
1073                 }
1074         } else if (frame->frametype == AST_FRAME_VIDEO) {
1075                 if (p) {
1076                         ast_mutex_lock(&p->lock);
1077                         if (p->vrtp) {
1078                                 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
1079                                         transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1080                                         p->progress = 1;
1081                                 }
1082                                 res =  ast_rtp_write(p->vrtp, frame);
1083                         }
1084                         ast_mutex_unlock(&p->lock);
1085                 }
1086         } else if (frame->frametype == AST_FRAME_IMAGE) {
1087                 return 0;
1088         } else {
1089                 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
1090                 return 0;
1091         }
1092
1093         return res;
1094 }
1095
1096 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1097 {
1098         struct sip_pvt *p = newchan->pvt->pvt;
1099         ast_mutex_lock(&p->lock);
1100         if (p->owner != oldchan) {
1101                 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
1102                 ast_mutex_unlock(&p->lock);
1103                 return -1;
1104         }
1105         p->owner = newchan;
1106         ast_mutex_unlock(&p->lock);
1107         return 0;
1108 }
1109
1110 static int sip_senddigit(struct ast_channel *ast, char digit)
1111 {
1112         struct sip_pvt *p = ast->pvt->pvt;
1113         if (p && (p->dtmfmode & SIP_DTMF_INFO)) {
1114                 transmit_info_with_digit(p, digit);
1115         }
1116         if (p && p->rtp && (p->dtmfmode & SIP_DTMF_RFC2833)) {
1117                 ast_rtp_senddigit(p->rtp, digit);
1118         }
1119         /* If in-band DTMF is desired, send that */
1120         if (p->dtmfmode & SIP_DTMF_INBAND)
1121                 return -1;
1122         return 0;
1123 }
1124
1125 static int sip_transfer(struct ast_channel *ast, char *dest)
1126 {
1127         struct sip_pvt *p = ast->pvt->pvt;
1128         int res;
1129         res = transmit_refer(p, dest);
1130         return res;
1131 }
1132
1133 static int sip_indicate(struct ast_channel *ast, int condition)
1134 {
1135         struct sip_pvt *p = ast->pvt->pvt;
1136         switch(condition) {
1137         case AST_CONTROL_RINGING:
1138                 if (ast->_state == AST_STATE_RING) {
1139                         if (!p->progress && !p->ringing) {
1140                                 transmit_response(p, "180 Ringing", &p->initreq);
1141                                 p->ringing = 1;
1142                                 break;
1143                         } else {
1144                                 /* Oops, we've sent progress tones.  Let Asterisk do it instead */
1145                         }
1146                 }
1147                 return -1;
1148         case AST_CONTROL_BUSY:
1149                 if (ast->_state != AST_STATE_UP) {
1150                         transmit_response(p, "486 Busy Here", &p->initreq);
1151                         p->alreadygone = 1;
1152                         ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
1153                         break;
1154                 }
1155                 return -1;
1156         case AST_CONTROL_CONGESTION:
1157                 if (ast->_state != AST_STATE_UP) {
1158                         transmit_response(p, "503 Service Unavailable", &p->initreq);
1159                         p->alreadygone = 1;
1160                         ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
1161                         break;
1162                 }
1163                 return -1;
1164         case AST_CONTROL_PROGRESS:
1165                 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
1166                         transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1167                         p->progress = 1;
1168                         break;
1169                 }
1170                 return -1;
1171         case -1:
1172                 return -1;
1173         default:
1174                 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
1175                 return -1;
1176         }
1177         return 0;
1178 }
1179
1180
1181
1182 static struct ast_channel *sip_new(struct sip_pvt *i, int state, char *title)
1183 {
1184         struct ast_channel *tmp;
1185         int fmt;
1186         tmp = ast_channel_alloc(1);
1187         if (tmp) {
1188                 /* Select our native format based on codec preference until we receive
1189                    something from another device to the contrary. */
1190                 if (i->capability)
1191                         tmp->nativeformats = sip_codec_choose(i->capability);
1192                 else 
1193                         tmp->nativeformats = sip_codec_choose(capability);
1194                 fmt = ast_best_codec(tmp->nativeformats);
1195                 if (title)
1196                         snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%04x", title, rand() & 0xffff);
1197                 else
1198                         if (strchr(i->fromdomain,':'))
1199                         {
1200                                 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", strchr(i->fromdomain,':')+1, (int)(i));
1201                         }
1202                         else
1203                         {
1204                                 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", i->fromdomain, (int)(i));
1205                         }
1206                 tmp->type = type;
1207                 if (i->dtmfmode & SIP_DTMF_INBAND) {
1208                     i->vad = ast_dsp_new();
1209                     ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
1210                 }
1211                 tmp->fds[0] = ast_rtp_fd(i->rtp);
1212                 tmp->fds[1] = ast_rtcp_fd(i->rtp);
1213                 if (i->vrtp) {
1214                         tmp->fds[2] = ast_rtp_fd(i->vrtp);
1215                         tmp->fds[3] = ast_rtcp_fd(i->vrtp);
1216                 }
1217                 ast_setstate(tmp, state);
1218                 if (state == AST_STATE_RING)
1219                         tmp->rings = 1;
1220                 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
1221                 tmp->writeformat = fmt;
1222                 tmp->pvt->rawwriteformat = fmt;
1223                 tmp->readformat = fmt;
1224                 tmp->pvt->rawreadformat = fmt;
1225                 tmp->pvt->pvt = i;
1226                 tmp->pvt->send_text = sip_sendtext;
1227                 tmp->pvt->call = sip_call;
1228                 tmp->pvt->hangup = sip_hangup;
1229                 tmp->pvt->answer = sip_answer;
1230                 tmp->pvt->read = sip_read;
1231                 tmp->pvt->write = sip_write;
1232                 tmp->pvt->write_video = sip_write;
1233                 tmp->pvt->indicate = sip_indicate;
1234                 tmp->pvt->transfer = sip_transfer;
1235                 tmp->pvt->fixup = sip_fixup;
1236                 tmp->pvt->send_digit = sip_senddigit;
1237
1238                 tmp->pvt->bridge = ast_rtp_bridge;
1239
1240                 tmp->callgroup = i->callgroup;
1241                 tmp->pickupgroup = i->pickupgroup;
1242                 tmp->restrictcid = i->restrictcid;
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][/contact] 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 user want's his callerid restricted */
2611         if (p->restrictcid)
2612                 l = CALLERID_UNKNOWN;
2613         if (!n || !strlen(n))
2614                 n = l;
2615         /* Allow user to be overridden */
2616         if (strlen(p->fromuser))
2617                 l = p->fromuser;
2618
2619         if ((ourport != 5060) && !strlen(p->fromdomain))
2620                 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);
2621         else
2622                 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=as%08x", n, l, strlen(p->fromdomain) ? p->fromdomain : inet_ntoa(p->ourip), p->tag);
2623
2624         if (strlen(p->username)) {
2625                 if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
2626                         snprintf(invite, sizeof(invite), "sip:%s@%s:%d",p->username, p->tohost, ntohs(p->sa.sin_port));
2627                 } else {
2628                         snprintf(invite, sizeof(invite), "sip:%s@%s",p->username, p->tohost);
2629                 }
2630         } else if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
2631                 snprintf(invite, sizeof(invite), "sip:%s:%d", p->tohost, ntohs(p->sa.sin_port));
2632         } else {
2633                 snprintf(invite, sizeof(invite), "sip:%s", p->tohost);
2634         }
2635         strncpy(p->uri, invite, sizeof(p->uri) - 1);
2636         /* If there is a VXML URL append it to the SIP URL */
2637         if (vxml_url)
2638         {
2639                 snprintf(to, sizeof(to), "<%s>;%s", invite, vxml_url);
2640         }
2641         else
2642         {
2643                 snprintf(to, sizeof(to), "<%s>", invite );
2644         }
2645         memset(req, 0, sizeof(struct sip_request));
2646         init_req(req, cmd, invite);
2647         snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
2648
2649         add_header(req, "Via", p->via);
2650         /* SLD: FIXME?: do Route: here too?  I think not cos this is the first request.
2651          * OTOH, then we won't have anything in p->route anyway */
2652         add_header(req, "From", from);
2653         strncpy(p->exten, l, sizeof(p->exten) - 1);
2654         build_contact(p);
2655         add_header(req, "To", to);
2656         add_header(req, "Contact", p->our_contact);
2657         add_header(req, "Call-ID", p->callid);
2658         add_header(req, "CSeq", tmp);
2659         add_header(req, "User-Agent", "Asterisk PBX");
2660 }
2661
2662 static int transmit_invite(struct sip_pvt *p, char *cmd, int sdp, char *auth, char *vxml_url, char *distinctive_ring, int init)
2663 {
2664         struct sip_request req;
2665         
2666         if (init)
2667                 initreqprep(&req, p, cmd, vxml_url);
2668         else
2669                 reqprep(&req, p, cmd, 0);
2670                 
2671         if (auth)
2672                 add_header(&req, "Proxy-Authorization", auth);
2673         
2674         if (distinctive_ring)
2675         {
2676                 add_header(&req, "Alert-info",distinctive_ring);
2677         }
2678         add_header(&req, "Allow", ALLOWED_METHODS);
2679         if (sdp) {
2680                 add_sdp(&req, p, NULL, NULL);
2681         } else {
2682                 add_header(&req, "Content-Length", "0");
2683                 add_blank_header(&req);
2684         }
2685
2686         if (!p->initreq.headers) {
2687                 /* Use this as the basis */
2688                 copy_request(&p->initreq, &req);
2689                 parse(&p->initreq);
2690                 determine_firstline_parts(&p->initreq);
2691         }
2692         p->lastinvite = p->ocseq;
2693         return send_request(p, &req, 1, p->ocseq);
2694 }
2695
2696 static int transmit_state_notify(struct sip_pvt *p, int state, int full)
2697 {
2698         char tmp[2000];
2699         char from[256], to[256];
2700         char *t, *c, *a;
2701         char *mfrom, *mto;
2702         struct sip_request req;
2703         char clen[20];
2704         
2705         strncpy(from, get_header(&p->initreq, "From"), sizeof(from)-1);
2706
2707         c = ditch_braces(from);
2708         if (strncmp(c, "sip:", 4)) {
2709                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
2710                 return -1;
2711         }
2712         if ((a = strchr(c, ';'))) {
2713                 *a = '\0';
2714         }
2715         mfrom = c;
2716                 
2717         reqprep(&req, p, "NOTIFY", 0);
2718
2719         if (p->subscribed == 1) {
2720             strncpy(to, get_header(&p->initreq, "To"), sizeof(to)-1);
2721
2722             c = ditch_braces(to);
2723             if (strncmp(c, "sip:", 4)) {
2724                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
2725                 return -1;
2726             }
2727             if ((a = strchr(c, ';'))) {
2728                 *a = '\0';
2729             }
2730             mto = c;
2731
2732             add_header(&req, "Content-Type", "application/xpidf+xml");
2733
2734             if ((state==AST_EXTENSION_UNAVAILABLE) || (state==AST_EXTENSION_BUSY))
2735                 state = 2;
2736             else if (state==AST_EXTENSION_INUSE)
2737                 state = 1;
2738             else
2739                 state = 0;
2740             
2741             t = tmp;            
2742             sprintf(t, "<?xml version=\"1.0\"?>\n");
2743             t = tmp + strlen(tmp);
2744             sprintf(t, "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n");
2745             t = tmp + strlen(tmp);
2746             sprintf(t, "<presence>\n");
2747             t = tmp + strlen(tmp);
2748             sprintf(t, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
2749             t = tmp + strlen(tmp);
2750             sprintf(t, "<atom id=\"%s\">\n", p->exten);
2751             t = tmp + strlen(tmp);
2752             sprintf(t, "<address uri=\"%s;user=ip\" priority=\"0,800000\">\n", mto);
2753             t = tmp + strlen(tmp);
2754             sprintf(t, "<status status=\"%s\" />\n", !state ? "open" : (state==1) ? "inuse" : "closed");
2755             t = tmp + strlen(tmp);
2756             sprintf(t, "<msnsubstatus substatus=\"%s\" />\n", !state ? "online" : (state==1) ? "onthephone" : "offline");
2757             t = tmp + strlen(tmp);
2758             sprintf(t, "</address>\n</atom>\n</presence>\n");           
2759         } else {
2760             add_header(&req, "Event", "dialog");
2761             add_header(&req, "Content-Type", "application/dialog-info+xml");
2762         
2763             t = tmp;            
2764             sprintf(t, "<?xml version=\"1.0\"?>\n");
2765             t = tmp + strlen(tmp);
2766             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);
2767             t = tmp + strlen(tmp);
2768             sprintf(t, "<dialog id=\"%s\">\n", p->exten);
2769             t = tmp + strlen(tmp);
2770             sprintf(t, "<state>%s</state>\n", state ? "confirmed" : "terminated");
2771             t = tmp + strlen(tmp);
2772             sprintf(t, "</dialog>\n</dialog-info>\n");  
2773         }
2774
2775         snprintf(clen, sizeof(clen), "%d", strlen(tmp));
2776         add_header(&req, "Content-Length", clen);
2777         add_line(&req, tmp);
2778
2779         return send_request(p, &req, 1, p->ocseq);
2780 }
2781
2782 static int transmit_notify(struct sip_pvt *p, int newmsgs, int oldmsgs)
2783 {
2784         struct sip_request req;
2785         char tmp[256];
2786         char tmp2[256];
2787         char clen[20];
2788         initreqprep(&req, p, "NOTIFY", NULL);
2789         add_header(&req, "Event", "message-summary");
2790         add_header(&req, "Content-Type", notifymime);
2791
2792         snprintf(tmp, sizeof(tmp), "Messages-Waiting: %s\n", newmsgs ? "yes" : "no");
2793         snprintf(tmp2, sizeof(tmp2), "Voicemail: %d/%d\n", newmsgs, oldmsgs);
2794         snprintf(clen, sizeof(clen), "%d", strlen(tmp) + strlen(tmp2));
2795         add_header(&req, "Content-Length", clen);
2796         add_line(&req, tmp);
2797         add_line(&req, tmp2);
2798
2799         if (!p->initreq.headers) {
2800                 /* Use this as the basis */
2801                 copy_request(&p->initreq, &req);
2802                 parse(&p->initreq);
2803                 determine_firstline_parts(&p->initreq);
2804         }
2805
2806         return send_request(p, &req, 1, p->ocseq);
2807 }
2808
2809 static int transmit_register(struct sip_registry *r, char *cmd, char *auth, char *authheader);
2810
2811 static int sip_reregister(void *data) 
2812 {
2813         /* if we are here, we know that we need to reregister. */
2814         struct sip_registry *r=(struct sip_registry *)data;
2815         r->expire = -1;
2816         sip_do_register(r);
2817         return 0;
2818 }
2819
2820
2821 static int sip_do_register(struct sip_registry *r)
2822 {
2823         int res;
2824         ast_mutex_lock(&r->lock);
2825         res=transmit_register(r, "REGISTER", NULL, NULL);
2826         ast_mutex_unlock(&r->lock);
2827         return res;
2828 }
2829
2830 static int sip_reg_timeout(void *data)
2831 {
2832         /* if we are here, our registration timed out, so we'll just do it over */
2833         struct sip_registry *r=data;
2834         struct sip_pvt *p;
2835         int res;
2836         ast_mutex_lock(&r->lock);
2837         ast_log(LOG_NOTICE, "Registration for '%s@%s' timed out, trying again\n", r->username, inet_ntoa(r->addr.sin_addr)); 
2838         if (r->call) {
2839                 /* Unlink us, destroy old call.  Locking is not relevent here because all this happens
2840                    in the single SIP manager thread. */
2841                 p = r->call;
2842                 p->registry = NULL;
2843                 r->call = NULL;
2844                 p->needdestroy = 1;
2845         }
2846         r->regstate=REG_STATE_UNREGISTERED;
2847         r->timeout = -1;
2848         res=transmit_register(r, "REGISTER", NULL, NULL);
2849         ast_mutex_unlock(&r->lock);
2850         return 0;
2851 }
2852
2853 static int transmit_register(struct sip_registry *r, char *cmd, char *auth, char *authheader)
2854 {
2855         struct sip_request req;
2856         char from[256];
2857         char to[256];
2858         char tmp[80];
2859         char via[80];
2860         char addr[80];
2861         struct sip_pvt *p;
2862         /* exit if we are already in process with this registrar ?*/
2863         if ( r == NULL || ((auth==NULL) && (r->regstate==REG_STATE_REGSENT || r->regstate==REG_STATE_AUTHSENT))) {
2864                 ast_log(LOG_NOTICE, "Strange, trying to register when registration already pending\n");
2865                 return 0;
2866         }
2867
2868         if (r->call) {
2869                 if (!auth) {
2870                         ast_log(LOG_WARNING, "Already have a call??\n");
2871                         return 0;
2872                 } else
2873                         p = r->call;
2874         } else {
2875                 if (!r->callid_valid) {
2876                         build_callid(r->callid, sizeof(r->callid), __ourip);
2877                         r->callid_valid = 1;
2878                 }
2879                 p=sip_alloc( r->callid, &r->addr, 0);
2880                 if (!p) {
2881                         ast_log(LOG_WARNING, "Unable to allocate registration call\n");
2882                         return 0;
2883                 }
2884                 p->outgoing = 1;
2885                 r->call=p;
2886                 p->registry=r;
2887                 strncpy(p->peersecret, r->secret, sizeof(p->peersecret)-1);
2888                 if (strlen(r->authuser))
2889                         strncpy(p->peername, r->authuser, sizeof(p->peername)-1);
2890                 else
2891                         strncpy(p->peername, r->username, sizeof(p->peername)-1);
2892                 strncpy(p->username, r->username, sizeof(p->username)-1);
2893                 strncpy(p->exten, r->contact, sizeof(p->exten) - 1);
2894                 /* Always bind to our IP if specified */
2895                 if (bindaddr.sin_addr.s_addr)
2896                         memcpy(&p->ourip, &bindaddr.sin_addr, sizeof(p->ourip));
2897                 build_contact(p);
2898         }
2899
2900         /* set up a timeout */
2901         if (auth==NULL)  {
2902                 if (r->timeout > -1) {
2903                         ast_log(LOG_WARNING, "Still have a timeout, %d\n", r->timeout);
2904                         ast_sched_del(sched, r->timeout);
2905                 }
2906                 r->timeout = ast_sched_add(sched, 20*1000, sip_reg_timeout, r);
2907                 ast_log(LOG_DEBUG, "Scheduled a timeout # %d\n", r->timeout);
2908         }
2909
2910         if (strchr(r->username, '@')) {
2911                 snprintf(from, sizeof(from), "<sip:%s>;tag=as%08x", r->username, p->tag);
2912                 snprintf(to, sizeof(to),     "<sip:%s>", r->username);
2913         } else {
2914                 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=as%08x", r->username, r->hostname, p->tag);
2915                 snprintf(to, sizeof(to),     "<sip:%s@%s>", r->username, r->hostname);
2916         }
2917         
2918         snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
2919         strncpy(p->uri, addr, sizeof(p->uri) - 1);
2920
2921         memset(&req, 0, sizeof(req));
2922         init_req(&req, cmd, addr);
2923
2924         snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, cmd);
2925         p->ocseq = r->ocseq;
2926
2927         /* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
2928         snprintf(via, sizeof(via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
2929         add_header(&req, "Via", via);
2930         add_header(&req, "From", from);
2931         add_header(&req, "To", to);
2932         add_header(&req, "Call-ID", p->callid);
2933         add_header(&req, "CSeq", tmp);
2934         add_header(&req, "User-Agent", "Asterisk PBX");
2935         if (auth) 
2936                 add_header(&req, authheader, auth);
2937
2938         snprintf(tmp, sizeof(tmp), "%d", default_expiry);
2939         add_header(&req, "Expires", tmp);
2940         add_header(&req, "Contact", p->our_contact);
2941         add_header(&req, "Event", "registration");
2942         add_header(&req, "Content-length", "0");
2943         add_blank_header(&req);
2944         copy_request(&p->initreq, &req);
2945         parse(&p->initreq);
2946         determine_firstline_parts(&p->initreq);
2947         r->regstate=auth?REG_STATE_AUTHSENT:REG_STATE_REGSENT;
2948         return send_request(p, &req, 1, p->ocseq);
2949 }
2950
2951 static int transmit_message_with_text(struct sip_pvt *p, char *text)
2952 {
2953         struct sip_request req;
2954         reqprep(&req, p, "MESSAGE", 0);
2955         add_text(&req, text);
2956         return send_request(p, &req, 1, p->ocseq);
2957 }
2958
2959 static int transmit_refer(struct sip_pvt *p, char *dest)
2960 {
2961         struct sip_request req;
2962         char from[256];
2963         char *of, *c;
2964         char referto[256];
2965         if (p->outgoing) 
2966                 of = get_header(&p->initreq, "To");
2967         else
2968                 of = get_header(&p->initreq, "From");
2969         strncpy(from, of, sizeof(from) - 1);
2970         of = ditch_braces(from);
2971         strncpy(p->from,of,sizeof(p->from) - 1);
2972         if (strncmp(of, "sip:", 4)) {
2973                 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
2974         } else
2975                 of += 4;
2976         /* Get just the username part */
2977         if ((c = strchr(of, '@'))) {
2978                 *c = '\0';
2979                 c++;
2980         }
2981         if (c) {
2982                 snprintf(referto, sizeof(referto), "<sip:%s@%s>", dest, c);
2983         } else {
2984                 snprintf(referto, sizeof(referto), "<sip:%s>", dest);
2985         }
2986
2987         reqprep(&req, p, "REFER", 0);
2988         add_header(&req, "Refer-To", referto);
2989         add_header(&req, "Referred-By", callerid);
2990         return send_request(p, &req, 1, p->ocseq);
2991 }
2992
2993 static int transmit_info_with_digit(struct sip_pvt *p, char digit)
2994 {
2995         struct sip_request req;
2996         reqprep(&req, p, "INFO", 0);
2997         add_digit(&req, digit);
2998         return send_request(p, &req, 1, p->ocseq);
2999 }
3000
3001 static int transmit_request(struct sip_pvt *p, char *msg, int seqno, int reliable)
3002 {
3003         struct sip_request resp;
3004         reqprep(&resp, p, msg, seqno);
3005         add_header(&resp, "Content-Length", "0");
3006         add_blank_header(&resp);
3007         return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
3008 }
3009
3010 static int transmit_request_with_auth(struct sip_pvt *p, char *msg, int seqno, int reliable)
3011 {
3012         struct sip_request resp;
3013         reqprep(&resp, p, msg, seqno);
3014         if (*p->realm)
3015         {
3016                 char digest[256];
3017                 memset(digest,0,sizeof(digest));
3018                 build_reply_digest(p, msg, digest, sizeof(digest));
3019                 add_header(&resp, "Proxy-Authorization", digest);
3020         }
3021
3022         add_header(&resp, "Content-Length", "0");
3023         add_blank_header(&resp);
3024         return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);      
3025 }
3026
3027 static int expire_register(void *data)
3028 {
3029         struct sip_peer *p = data;
3030         memset(&p->addr, 0, sizeof(p->addr));
3031         ast_db_del("SIP/Registry", p->name);
3032         p->expire = -1;
3033         ast_device_state_changed("SIP/%s", p->name);
3034         return 0;
3035 }
3036
3037 static int sip_poke_peer(struct sip_peer *peer);
3038
3039 static void reg_source_db(struct sip_peer *p)
3040 {
3041         char data[80];
3042         struct in_addr in;
3043         char *c, *d;
3044         int expiry;
3045         if (!ast_db_get("SIP/Registry", p->name, data, sizeof(data))) {
3046                 c = strchr(data, ':');
3047                 if (c) {
3048                         *c = '\0';
3049                         c++;
3050                         if (inet_aton(data, &in)) {
3051                                 d = strchr(c, ':');
3052                                 if (d) {
3053                                         *d = '\0';
3054                                         d++;
3055                                         ast_verbose(VERBOSE_PREFIX_3 "SIP Seeding '%s' at %s:%d for %d\n", p->name, 
3056                                                 inet_ntoa(in), atoi(c), atoi(d));
3057                                         sip_poke_peer(p);
3058                                         expiry = atoi(d);
3059                                         memset(&p->addr, 0, sizeof(p->addr));
3060                                         p->addr.sin_family = AF_INET;
3061                                         p->addr.sin_addr = in;
3062                                         p->addr.sin_port = htons(atoi(c));
3063                                         if (p->expire > -1)
3064                                                 ast_sched_del(sched, p->expire);
3065                                         p->expire = ast_sched_add(sched, (expiry + 10) * 1000, expire_register, (void *)p);
3066                                 }                                       
3067                                         
3068                         }
3069                 }
3070         }
3071 }
3072
3073 static int parse_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req)
3074 {
3075         char contact[80]= ""; 
3076         char data[256];
3077         char *expires = get_header(req, "Expires");
3078         int expiry = atoi(expires);
3079         char *c, *n, *pt;
3080         int port;
3081         struct hostent *hp;
3082         struct sockaddr_in oldsin;
3083         if (!strlen(expires)) {
3084                 expires = strstr(get_header(req, "Contact"), "expires=");
3085                 if (expires) {
3086                         if (sscanf(expires + 8, "%d;", &expiry) != 1)
3087                                 expiry = default_expiry;
3088                 } else {
3089                         /* Nothing has been specified */
3090                         expiry = default_expiry;
3091                 }
3092         }
3093         /* Look for brackets */
3094         strncpy(contact, get_header(req, "Contact"), sizeof(contact) - 1);
3095         c = contact;
3096         
3097         if ((n=strchr(c, '<'))) {
3098                 c = n + 1;
3099                 n = strchr(c, '>');
3100                 /* Lose the part after the > */
3101                 if (n) 
3102                         *n = '\0';
3103         }
3104         if (!strcasecmp(c, "*") || !expiry) {
3105                 /* This means remove all registrations and return OK */
3106                 memset(&p->addr, 0, sizeof(p->addr));
3107                 if (p->expire > -1)
3108                         ast_sched_del(sched, p->expire);
3109                 p->expir