BSD portability enhancements (bug #234)
[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 (1 /* !p->owner->needdestroy */) {
425                 if (pkt->retrans < MAX_RETRANS) {
426                         pkt->retrans++;
427                         if (sipdebug) {
428                                 if (pkt->owner->nat)
429                                         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));
430                                 else
431                                         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));
432                         }
433                         __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
434                         res = 1;
435                 } else {
436                         ast_log(LOG_WARNING, "Maximum retries exceeded on call %s for seqno %d (%s)\n", pkt->owner->callid, pkt->seqno, pkt->resp ? "Response" : "Request");
437                         pkt->retransid = -1;
438                         if (pkt->owner->owner) {
439                                 /* XXX Potential deadlocK?? XXX */
440                                 ast_queue_hangup(pkt->owner->owner, 1);
441                         } else {
442                                 /* If no owner, destroy now */
443                                 pkt->owner->needdestroy = 1;
444                         }
445                 }
446         } else {
447                 /* Don't bother retransmitting.  It's about to be killed anyway */
448                 pkt->retransid = -1;
449                 if (pkt->owner->owner) {
450                         /* XXX Potential deadlocK?? XXX */
451                         ast_queue_hangup(pkt->owner->owner, 1);
452                 } else {
453                         /* If no owner, destroy now */
454                         pkt->owner->needdestroy = 1;
455                 }
456         }
457         if (pkt)
458                 ast_mutex_unlock(&pkt->owner->lock);
459         return res;
460 }
461
462 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len)
463 {
464         struct sip_pkt *pkt;
465         pkt = malloc(sizeof(struct sip_pkt) + len);
466         if (!pkt)
467                 return -1;
468         memset(pkt, 0, sizeof(struct sip_pkt));
469         memcpy(pkt->data, data, len);
470         pkt->packetlen = len;
471         pkt->next = p->packets;
472         pkt->owner = p;
473         pkt->seqno = seqno;
474         pkt->resp = resp;
475         /* Schedule retransmission */
476         pkt->retransid = ast_sched_add(sched, DEFAULT_RETRANS, retrans_pkt, pkt);
477         pkt->next = p->packets;
478         p->packets = pkt;
479         __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
480         if (!strncasecmp(pkt->data, "INVITE", 6)) {
481                 /* Note this is a pending invite */
482                 p->pendinginvite = seqno;
483         }
484         return 0;
485 }
486
487 static int __sip_autodestruct(void *data)
488 {
489         struct sip_pvt *p = data;
490         p->autokillid = -1;
491         ast_log(LOG_DEBUG, "Auto destroying call '%s'\n", p->callid);
492         if (p->owner) {
493                 ast_log(LOG_WARNING, "Autodestruct on call '%s' with owner in place\n", p->callid);
494                 ast_queue_hangup(p->owner, 0);
495         } else {
496                 sip_destroy(p);
497         }
498         return 0;
499 }
500
501 static int sip_scheddestroy(struct sip_pvt *p, int ms)
502 {
503         if (p->autokillid > -1)
504                 ast_sched_del(sched, p->autokillid);
505         p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
506         return 0;
507 }
508
509 static int sip_cancel_destroy(struct sip_pvt *p)
510 {
511         if (p->autokillid > -1)
512                 ast_sched_del(sched, p->autokillid);
513         p->autokillid = -1;
514         return 0;
515 }
516
517 static int __sip_ack(struct sip_pvt *p, int seqno, int resp)
518 {
519         struct sip_pkt *cur, *prev = NULL;
520         int res = -1;
521         int resetinvite = 0;
522         cur = p->packets;
523         while(cur) {
524                 if ((cur->seqno == seqno) && (cur->resp == resp)) {
525                         if (!resp && (seqno == p->pendinginvite)) {
526                                 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
527                                 p->pendinginvite = 0;
528                                 resetinvite = 1;
529                         }
530                         /* this is our baby */
531                         if (prev)
532                                 prev->next = cur->next;
533                         else
534                                 p->packets = cur->next;
535                         if (cur->retransid > -1)
536                                 ast_sched_del(sched, cur->retransid);
537                         free(cur);
538                         res = 0;
539                         break;
540                 }
541                 prev = cur;
542                 cur = cur->next;
543         }
544         ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
545         return res;
546 }
547
548 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp)
549 {
550         struct sip_pkt *cur;
551         int res = -1;
552         cur = p->packets;
553         while(cur) {
554                 if ((cur->seqno == seqno) && (cur->resp == resp)) {
555                         /* this is our baby */
556                         if (cur->retransid > -1)
557                                 ast_sched_del(sched, cur->retransid);
558                         cur->retransid = -1;
559                         res = 0;
560                         break;
561                 }
562                 cur = cur->next;
563         }
564         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");
565         return res;
566 }
567
568 static int send_response(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
569 {
570         int res;
571         if (sipdebug) {
572                 if (p->nat)
573                         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));
574                 else
575                         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));
576         }
577         if (reliable)
578                 res = __sip_reliable_xmit(p, seqno, 1, req->data, req->len);
579         else
580                 res = __sip_xmit(p, req->data, req->len);
581         if (res > 0)
582                 res = 0;
583         return res;
584 }
585
586 static int send_request(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
587 {
588         int res;
589         if (sipdebug) {
590                 if (p->nat)
591                         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));
592                 else
593                         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));
594         }
595         if (reliable)
596                 res = __sip_reliable_xmit(p, seqno, 0, req->data, req->len);
597         else
598                 res = __sip_xmit(p, req->data, req->len);
599         return res;
600 }
601
602 static char *ditch_braces(char *tmp)
603 {
604         char *c = tmp;
605         char *n;
606         c = tmp;
607         if ((n = strchr(tmp, '<')) ) {
608                 c = n + 1;
609                 while(*c && *c != '>') c++;
610                 if (*c != '>') {
611                         ast_log(LOG_WARNING, "No closing brace in '%s'\n", tmp);
612                 } else {
613                         *c = '\0';
614                 }
615                 return n+1;
616         }
617         return c;
618 }
619
620 static int sip_sendtext(struct ast_channel *ast, char *text)
621 {
622         struct sip_pvt *p = ast->pvt->pvt;
623         if (sipdebug) 
624                 ast_verbose("Sending text %s on %s\n", text, ast->name);
625         if (!p)
626                 return -1;
627         if (!text || !strlen(text))
628                 return 0;
629         if (sipdebug)
630                 ast_verbose("Really sending text %s on %s\n", text, ast->name);
631         transmit_message_with_text(p, text);
632         return 0;       
633 }
634
635 static int create_addr(struct sip_pvt *r, char *peer)
636 {
637         struct hostent *hp;
638         struct sip_peer *p;
639         int found=0;
640         char *port;
641         int portno;
642         char host[256], *hostn;
643
644         r->sa.sin_family = AF_INET;
645         ast_mutex_lock(&peerl.lock);
646         p = peerl.peers;
647         while(p) {
648                 if (!strcasecmp(p->name, peer)) {
649                         found++;
650                         r->capability = p->capability;
651                         r->nat = p->nat;
652                         if (r->rtp) {
653                                 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", r->nat);
654                                 ast_rtp_setnat(r->rtp, r->nat);
655                         }
656                         if (r->vrtp) {
657                                 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %d\n", r->nat);
658                                 ast_rtp_setnat(r->vrtp, r->nat);
659                         }
660                         strncpy(r->peername, p->username, sizeof(r->peername)-1);
661                         strncpy(r->peersecret, p->secret, sizeof(r->peersecret)-1);
662                         strncpy(r->username, p->username, sizeof(r->username)-1);
663                         strncpy(r->tohost, p->tohost, sizeof(r->tohost)-1);
664                         if (!strlen(r->tohost)) {
665                                 if (p->addr.sin_addr.s_addr)
666                                         snprintf(r->tohost, sizeof(r->tohost), inet_ntoa(p->addr.sin_addr));
667                                 else
668                                         snprintf(r->tohost, sizeof(r->tohost), inet_ntoa(p->defaddr.sin_addr));
669                         }
670                         if (strlen(p->fromdomain))
671                                 strncpy(r->fromdomain, p->fromdomain, sizeof(r->fromdomain)-1);
672                         if (strlen(p->fromuser))
673                                 strncpy(r->fromuser, p->fromuser, sizeof(r->fromuser)-1);
674                         r->insecure = p->insecure;
675                         r->canreinvite = p->canreinvite;
676                         r->maxtime = p->maxms;
677                         r->callgroup = p->callgroup;
678                         r->pickupgroup = p->pickupgroup;
679                         if (p->dtmfmode) {
680                                 r->dtmfmode = p->dtmfmode;
681                                 if (r->dtmfmode & SIP_DTMF_RFC2833)
682                                         r->noncodeccapability |= AST_RTP_DTMF;
683                                 else
684                                         r->noncodeccapability &= ~AST_RTP_DTMF;
685                         }
686                         strncpy(r->context, p->context,sizeof(r->context)-1);
687                         if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
688                                 (!p->maxms || ((p->lastms > 0)  && (p->lastms <= p->maxms)))) {
689                                 if (p->addr.sin_addr.s_addr) {
690                                         r->sa.sin_addr = p->addr.sin_addr;
691                                         r->sa.sin_port = p->addr.sin_port;
692                                 } else {
693                                         r->sa.sin_addr = p->defaddr.sin_addr;
694                                         r->sa.sin_port = p->defaddr.sin_port;
695                                 }
696                                 memcpy(&r->recv, &r->sa, sizeof(r->recv));
697                                 break;
698                         }
699                 }
700                 p = p->next;
701         }
702         ast_mutex_unlock(&peerl.lock);
703         if (!p && !found) {
704                 if ((port=strchr(peer, ':'))) {
705                         *port='\0';
706                         port++;
707                 }
708                 hostn = peer;
709                 if (port)
710                         portno = atoi(port);
711                 else
712                         portno = DEFAULT_SIP_PORT;
713                 if (srvlookup) {
714                         char service[256];
715                         int tportno;
716                         int ret;
717                         snprintf(service, sizeof(service), "_sip._udp.%s", peer);
718                         ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
719                         if (ret > 0) {
720                                 hostn = host;
721                                 portno = tportno;
722                         }
723                 }
724                 hp = gethostbyname(hostn);
725                 if (hp) {
726                         strncpy(r->tohost, peer, sizeof(r->tohost) - 1);
727                         memcpy(&r->sa.sin_addr, hp->h_addr, sizeof(r->sa.sin_addr));
728                         r->sa.sin_port = htons(portno);
729                         memcpy(&r->recv, &r->sa, sizeof(r->recv));
730                         return 0;
731                 } else {
732                         ast_log(LOG_WARNING, "No such host: %s\n", peer);
733                         return -1;
734                 }
735         } else if (!p)
736                 return -1;
737         else
738                 return 0;
739 }
740
741 static int auto_congest(void *nothing)
742 {
743         struct sip_pvt *p = nothing;
744         ast_mutex_lock(&p->lock);
745         p->initid = -1;
746         if (p->owner) {
747                 if (!ast_mutex_trylock(&p->owner->lock)) {
748                         ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
749                         ast_queue_control(p->owner, AST_CONTROL_CONGESTION, 0);
750                         ast_mutex_unlock(&p->owner->lock);
751                 }
752         }
753         ast_mutex_unlock(&p->lock);
754         return 0;
755 }
756
757 static void sip_prefs_free(void)
758 {
759         struct sip_codec_pref *cur, *next;
760         cur = prefs;
761         while(cur) {
762                 next = cur->next;
763                 free(cur);
764                 cur = next;
765         }
766         prefs = NULL;
767 }
768
769 static void sip_pref_remove(int format)
770 {
771         struct sip_codec_pref *cur, *prev=NULL;
772         cur = prefs;
773         while(cur) {
774                 if (cur->codec == format) {
775                         if (prev)
776                                 prev->next = cur->next;
777                         else
778                                 prefs = cur->next;
779                         free(cur);
780                         return;
781                 }
782                 prev = cur;
783                 cur = cur->next;
784         }
785 }
786
787 static int sip_pref_append(int format)
788 {
789         struct sip_codec_pref *cur, *tmp;
790         sip_pref_remove(format);
791         tmp = (struct sip_codec_pref *)malloc(sizeof(struct sip_codec_pref));
792         if (!tmp)
793                 return -1;
794         memset(tmp, 0, sizeof(struct sip_codec_pref));
795         tmp->codec = format;
796         if (prefs) {
797                 cur = prefs;
798                 while(cur->next)
799                         cur = cur->next;
800                 cur->next = tmp;
801         } else
802                 prefs = tmp;
803         return 0;
804 }
805
806 static int sip_codec_choose(int formats)
807 {
808         struct sip_codec_pref *cur;
809         formats &= (AST_FORMAT_MAX_AUDIO - 1);
810         cur = prefs;
811         while(cur) {
812                 if (formats & cur->codec)
813                         return cur->codec;
814                 cur = cur->next;
815         }
816         return ast_best_codec(formats);
817 }
818
819 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
820 {
821         int res;
822         struct sip_pvt *p;
823         char *vxml_url = NULL;
824         char *distinctive_ring = NULL;
825         struct varshead *headp;
826         struct ast_var_t *current;
827         
828         p = ast->pvt->pvt;
829         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
830                 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
831                 return -1;
832         }
833         /* Check whether there is vxml_url, distinctive ring variables */
834
835         headp=&ast->varshead;
836         AST_LIST_TRAVERSE(headp,current,entries) {
837                 /* Check whether there is a VXML_URL variable */
838                 if (strcasecmp(ast_var_name(current),"VXML_URL")==0)
839                 {
840                         vxml_url = ast_var_value(current);
841                         break;
842                 }
843                 /* Check whether there is a ALERT_INFO variable */
844                 if (strcasecmp(ast_var_name(current),"ALERT_INFO")==0)
845                 {
846                         distinctive_ring = ast_var_value(current);
847                         break;
848                 }
849         }
850         
851         res = 0;
852         p->outgoing = 1;
853         p->restrictcid = ast->restrictcid;
854         transmit_invite(p, "INVITE", 1, NULL, vxml_url,distinctive_ring, 1);
855         if (p->maxtime) {
856                 /* Initialize auto-congest time */
857                 p->initid = ast_sched_add(sched, p->maxtime * 2, auto_congest, p);
858         }
859         return res;
860 }
861
862 static void __sip_destroy(struct sip_pvt *p, int lockowner)
863 {
864         struct sip_pvt *cur, *prev = NULL;
865         struct sip_pkt *cp;
866         if (sipdebug)
867                 ast_log(LOG_DEBUG, "Destorying call '%s'\n", p->callid);
868         if (p->stateid > -1)
869                 ast_extension_state_del(p->stateid, NULL);
870         if (p->initid > -1)
871                 ast_sched_del(sched, p->initid);
872         if (p->autokillid > -1)
873                 ast_sched_del(sched, p->autokillid);
874
875         if (p->rtp) {
876                 ast_rtp_destroy(p->rtp);
877         }
878         if (p->vrtp) {
879                 ast_rtp_destroy(p->vrtp);
880         }
881         if (p->route) {
882                 free_old_route(p->route);
883                 p->route = NULL;
884         }
885         if (p->registry) {
886                 p->registry->call=NULL;
887         }
888         /* Unlink us from the owner if we have one */
889         if (p->owner) {
890                 if (lockowner)
891                         ast_mutex_lock(&p->owner->lock);
892                 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
893                 p->owner->pvt->pvt = NULL;
894                 if (lockowner)
895                         ast_mutex_unlock(&p->owner->lock);
896         }
897         cur = iflist;
898         while(cur) {
899                 if (cur == p) {
900                         if (prev)
901                                 prev->next = cur->next;
902                         else
903                                 iflist = cur->next;
904                         break;
905                 }
906                 prev = cur;
907                 cur = cur->next;
908         }
909         if (!cur) {
910                 ast_log(LOG_WARNING, "%p is not in list?!?! \n", cur);
911         } else {
912                 if (p->initid > -1)
913                         ast_sched_del(sched, p->initid);
914                 while((cp = p->packets)) {
915                         p->packets = p->packets->next;
916                         if (cp->retransid > -1)
917                                 ast_sched_del(sched, cp->retransid);
918                         free(cp);
919                 }
920                 free(p);
921         }
922 }
923
924 static int find_user(struct sip_pvt *fup, int event)
925 {
926         char name[256] = "";
927         struct sip_user *u;
928         strncpy(name, fup->username, sizeof(name) - 1);
929         ast_mutex_lock(&userl.lock);
930         u = userl.users;
931         while(u) {
932                 if (!strcasecmp(u->name, name)) {
933                         break;
934                 }
935                 u = u->next;
936         }
937         if (!u) {
938                 ast_log(LOG_DEBUG, "%s is not a local user\n", name);
939                 ast_mutex_unlock(&userl.lock);
940                 return 0;
941         }
942         if(event == 0) {
943                 if ( u->inUse > 0 ) {
944                         u->inUse = u->inUse - 1;
945                 } else {
946                         u->inUse = 0;
947                 }
948         } else {
949                 if (u->incominglimit > 0 ) {
950                         if (u->inUse >= u->incominglimit) {
951                                 ast_log(LOG_ERROR, "Call from user '%s' rejected due to usage limit of %d\n", u->name, u->incominglimit);
952                                 ast_mutex_unlock(&userl.lock);
953                                 return -1; 
954                         }
955                 }
956                 u->inUse++;
957                 ast_log(LOG_DEBUG, "Call from user '%s' is %d out of %d\n", u->name, u->inUse, u->incominglimit);
958         }
959         ast_mutex_unlock(&userl.lock);
960         return 0;
961 }
962
963 static void sip_destroy(struct sip_pvt *p)
964 {
965         ast_mutex_lock(&iflock);
966         __sip_destroy(p, 1);
967         ast_mutex_unlock(&iflock);
968 }
969
970 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req);
971
972
973 static int sip_hangup(struct ast_channel *ast)
974 {
975         struct sip_pvt *p = ast->pvt->pvt;
976         int needcancel = 0;
977         int needdestroy = 0;
978         if (option_debug)
979                 ast_log(LOG_DEBUG, "sip_hangup(%s)\n", ast->name);
980         if (!ast->pvt->pvt) {
981                 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
982                 return 0;
983         }
984         ast_mutex_lock(&p->lock);
985         ast_log(LOG_DEBUG, "find_user(%s)\n", p->username);
986         find_user(p, 0);
987         /* Determine how to disconnect */
988         if (p->owner != ast) {
989                 ast_log(LOG_WARNING, "Huh?  We aren't the owner?\n");
990                 ast_mutex_unlock(&p->lock);
991                 return 0;
992         }
993         if (!ast || (ast->_state != AST_STATE_UP))
994                 needcancel = 1;
995         /* Disconnect */
996         p = ast->pvt->pvt;
997         if (p->vad) {
998             ast_dsp_free(p->vad);
999         }
1000         p->owner = NULL;
1001         ast->pvt->pvt = NULL;
1002
1003         needdestroy = 1;
1004         /* Start the process if it's not already started */
1005         if (!p->alreadygone && strlen(p->initreq.data)) {
1006                 if (needcancel) {
1007                         if (p->outgoing) {
1008                                 transmit_request_with_auth(p, "CANCEL", p->ocseq, 1);
1009                                 /* Actually don't destroy us yet, wait for the 487 on our original 
1010                                    INVITE, but do set an autodestruct just in case. */
1011                                 needdestroy = 0;
1012                                 sip_scheddestroy(p, 15000);
1013                         } else
1014                                 transmit_response_reliable(p, "403 Forbidden", &p->initreq);
1015                 } else {
1016                         if (!p->pendinginvite) {
1017                                 /* Send a hangup */
1018                                 transmit_request_with_auth(p, "BYE", 0, 1);
1019                         } else {
1020                                 /* Note we will need a BYE when this all settles out
1021                                    but we can't send one while we have "INVITE" outstanding. */
1022                                 p->pendingbye = 1;
1023                         }
1024                 }
1025         }
1026         p->needdestroy = needdestroy;
1027         ast_mutex_unlock(&p->lock);
1028         return 0;
1029 }
1030
1031 static int sip_answer(struct ast_channel *ast)
1032 {
1033         int res = 0,fmt;
1034         char *codec;
1035         struct sip_pvt *p = ast->pvt->pvt;
1036
1037         
1038         if (ast->_state != AST_STATE_UP) {
1039         
1040         
1041         
1042                 codec=pbx_builtin_getvar_helper(p->owner,"SIP_CODEC");
1043                 if (codec) {
1044                         ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n",codec);
1045                         fmt=ast_getformatbyname(codec);
1046                         if (fmt) {
1047                                 p->capability=fmt;
1048                         } else ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized codec: %s\n",codec);
1049                 }
1050
1051                 ast_setstate(ast, AST_STATE_UP);
1052                 if (option_debug)
1053                         ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name);
1054                 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, 1);
1055         }
1056         return res;
1057 }
1058
1059 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
1060 {
1061         struct sip_pvt *p = ast->pvt->pvt;
1062         int res = 0;
1063         if (frame->frametype == AST_FRAME_VOICE) {
1064                 if (!(frame->subclass & ast->nativeformats)) {
1065                         ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
1066                                 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
1067                         return -1;
1068                 }
1069                 if (p) {
1070                         ast_mutex_lock(&p->lock);
1071                         if (p->rtp) {
1072                                 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
1073                                         transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1074                                         p->progress = 1;
1075                                 }
1076                                 res =  ast_rtp_write(p->rtp, frame);
1077                         }
1078                         ast_mutex_unlock(&p->lock);
1079                 }
1080         } else if (frame->frametype == AST_FRAME_VIDEO) {
1081                 if (p) {
1082                         ast_mutex_lock(&p->lock);
1083                         if (p->vrtp) {
1084                                 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
1085                                         transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1086                                         p->progress = 1;
1087                                 }
1088                                 res =  ast_rtp_write(p->vrtp, frame);
1089                         }
1090                         ast_mutex_unlock(&p->lock);
1091                 }
1092         } else if (frame->frametype == AST_FRAME_IMAGE) {
1093                 return 0;
1094         } else {
1095                 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
1096                 return 0;
1097         }
1098
1099         return res;
1100 }
1101
1102 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1103 {
1104         struct sip_pvt *p = newchan->pvt->pvt;
1105         ast_mutex_lock(&p->lock);
1106         if (p->owner != oldchan) {
1107                 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
1108                 ast_mutex_unlock(&p->lock);
1109                 return -1;
1110         }
1111         p->owner = newchan;
1112         ast_mutex_unlock(&p->lock);
1113         return 0;
1114 }
1115
1116 static int sip_senddigit(struct ast_channel *ast, char digit)
1117 {
1118         struct sip_pvt *p = ast->pvt->pvt;
1119         if (p && (p->dtmfmode & SIP_DTMF_INFO)) {
1120                 transmit_info_with_digit(p, digit);
1121         }
1122         if (p && p->rtp && (p->dtmfmode & SIP_DTMF_RFC2833)) {
1123                 ast_rtp_senddigit(p->rtp, digit);
1124         }
1125         /* If in-band DTMF is desired, send that */
1126         if (p->dtmfmode & SIP_DTMF_INBAND)
1127                 return -1;
1128         return 0;
1129 }
1130
1131 static int sip_transfer(struct ast_channel *ast, char *dest)
1132 {
1133         struct sip_pvt *p = ast->pvt->pvt;
1134         int res;
1135         res = transmit_refer(p, dest);
1136         return res;
1137 }
1138
1139 static int sip_indicate(struct ast_channel *ast, int condition)
1140 {
1141         struct sip_pvt *p = ast->pvt->pvt;
1142         switch(condition) {
1143         case AST_CONTROL_RINGING:
1144                 if (ast->_state == AST_STATE_RING) {
1145                         if (!p->progress && !p->ringing) {
1146                                 transmit_response(p, "180 Ringing", &p->initreq);
1147                                 p->ringing = 1;
1148                                 break;
1149                         } else {
1150                                 /* Oops, we've sent progress tones.  Let Asterisk do it instead */
1151                         }
1152                 }
1153                 return -1;
1154         case AST_CONTROL_BUSY:
1155                 if (ast->_state != AST_STATE_UP) {
1156                         transmit_response(p, "486 Busy Here", &p->initreq);
1157                         p->alreadygone = 1;
1158                         ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
1159                         break;
1160                 }
1161                 return -1;
1162         case AST_CONTROL_CONGESTION:
1163                 if (ast->_state != AST_STATE_UP) {
1164                         transmit_response(p, "503 Service Unavailable", &p->initreq);
1165                         p->alreadygone = 1;
1166                         ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
1167                         break;
1168                 }
1169                 return -1;
1170         case AST_CONTROL_PROGRESS:
1171                 if ((ast->_state != AST_STATE_UP) && !p->progress && !p->outgoing) {
1172                         transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
1173                         p->progress = 1;
1174                         break;
1175                 }
1176                 return -1;
1177         case -1:
1178                 return -1;
1179         default:
1180                 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
1181                 return -1;
1182         }
1183         return 0;
1184 }
1185
1186
1187
1188 static struct ast_channel *sip_new(struct sip_pvt *i, int state, char *title)
1189 {
1190         struct ast_channel *tmp;
1191         int fmt;
1192         tmp = ast_channel_alloc(1);
1193         if (tmp) {
1194                 /* Select our native format based on codec preference until we receive
1195                    something from another device to the contrary. */
1196                 if (i->capability)
1197                         tmp->nativeformats = sip_codec_choose(i->capability);
1198                 else 
1199                         tmp->nativeformats = sip_codec_choose(capability);
1200                 fmt = ast_best_codec(tmp->nativeformats);
1201                 if (title)
1202                         snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%04x", title, rand() & 0xffff);
1203                 else
1204                         if (strchr(i->fromdomain,':'))
1205                         {
1206                                 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", strchr(i->fromdomain,':')+1, (int)(i));
1207                         }
1208                         else
1209                         {
1210                                 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", i->fromdomain, (int)(i));
1211                         }
1212                 tmp->type = type;
1213                 if (i->dtmfmode & SIP_DTMF_INBAND) {
1214                     i->vad = ast_dsp_new();
1215                     ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
1216                 }
1217                 tmp->fds[0] = ast_rtp_fd(i->rtp);
1218                 tmp->fds[1] = ast_rtcp_fd(i->rtp);
1219                 if (i->vrtp) {
1220                         tmp->fds[2] = ast_rtp_fd(i->vrtp);
1221                         tmp->fds[3] = ast_rtcp_fd(i->vrtp);
1222                 }
1223                 ast_setstate(tmp, state);
1224                 if (state == AST_STATE_RING)
1225                         tmp->rings = 1;
1226                 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
1227                 tmp->writeformat = fmt;
1228                 tmp->pvt->rawwriteformat = fmt;
1229                 tmp->readformat = fmt;
1230                 tmp->pvt->rawreadformat = fmt;
1231                 tmp->pvt->pvt = i;
1232                 tmp->pvt->send_text = sip_sendtext;
1233                 tmp->pvt->call = sip_call;
1234                 tmp->pvt->hangup = sip_hangup;
1235                 tmp->pvt->answer = sip_answer;
1236                 tmp->pvt->read = sip_read;
1237                 tmp->pvt->write = sip_write;
1238                 tmp->pvt->write_video = sip_write;
1239                 tmp->pvt->indicate = sip_indicate;
1240                 tmp->pvt->transfer = sip_transfer;
1241                 tmp->pvt->fixup = sip_fixup;
1242                 tmp->pvt->send_digit = sip_senddigit;
1243
1244                 tmp->pvt->bridge = ast_rtp_bridge;
1245
1246                 tmp->callgroup = i->callgroup;
1247                 tmp->pickupgroup = i->pickupgroup;
1248                 tmp->restrictcid = i->restrictcid;
1249                 if (strlen(i->accountcode))
1250                         strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
1251                 if (i->amaflags)
1252                         tmp->amaflags = i->amaflags;
1253                 if (strlen(i->language))
1254                         strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
1255                 i->owner = tmp;
1256                 ast_mutex_lock(&usecnt_lock);
1257                 usecnt++;
1258                 ast_mutex_unlock(&usecnt_lock);
1259                 ast_update_use_count();
1260                 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
1261                 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
1262                 if (strlen(i->callerid))
1263                         tmp->callerid = strdup(i->callerid);
1264                 if (strlen(i->rdnis))
1265                         tmp->rdnis = strdup(i->rdnis);
1266                 tmp->priority = 1;
1267                 if (state != AST_STATE_DOWN) {
1268                         if (ast_pbx_start(tmp)) {
1269                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
1270                                 ast_hangup(tmp);
1271                                 tmp = NULL;
1272                         }
1273                 }
1274         } else
1275                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
1276         return tmp;
1277 }
1278
1279 static struct cfalias {
1280         char *fullname;
1281         char *shortname;
1282 } aliases[] = {
1283         { "Content-Type", "c" },
1284         { "Content-Encoding", "e" },
1285         { "From", "f" },
1286         { "Call-ID", "i" },
1287         { "Contact", "m" },
1288         { "Content-Length", "l" },
1289         { "Subject", "s" },
1290         { "To", "t" },
1291         { "Via", "v" },
1292 };
1293
1294 static char* get_sdp_by_line(char* line, char *name, int nameLen) {
1295   if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
1296     char* r = line + nameLen + 1;
1297     while (*r && (*r < 33)) ++r;
1298     return r;
1299   }
1300
1301   return "";
1302 }
1303
1304 static char *get_sdp(struct sip_request *req, char *name) {
1305   int x;
1306   int len = strlen(name);
1307   char *r;
1308
1309   for (x=0; x<req->lines; x++) {
1310     r = get_sdp_by_line(req->line[x], name, len);
1311     if (r[0] != '\0') return r;
1312   }
1313   return "";
1314 }
1315
1316 static void sdpLineNum_iterator_init(int* iterator) {
1317   *iterator = 0;
1318 }
1319
1320 static char* get_sdp_iterate(int* iterator,
1321                              struct sip_request *req, char *name) {
1322   int len = strlen(name);
1323   char *r;
1324   while (*iterator < req->lines) {
1325     r = get_sdp_by_line(req->line[(*iterator)++], name, len);
1326     if (r[0] != '\0') return r;
1327   }
1328   return "";
1329 }
1330
1331 static char *__get_header(struct sip_request *req, char *name, int *start)
1332 {
1333         int x;
1334         int len = strlen(name);
1335         char *r;
1336         for (x=*start;x<req->headers;x++) {
1337                 if (!strncasecmp(req->header[x], name, len) && 
1338                                 (req->header[x][len] == ':')) {
1339                                         r = req->header[x] + len + 1;
1340                                         while(*r && (*r < 33))
1341                                                         r++;
1342                                         *start = x+1;
1343                                         return r;
1344                 }
1345         }
1346         /* Try aliases */
1347         for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++) 
1348                 if (!strcasecmp(aliases[x].fullname, name))
1349                         return __get_header(req, aliases[x].shortname, start);
1350
1351         /* Don't return NULL, so get_header is always a valid pointer */
1352         return "";
1353 }
1354
1355 static char *get_header(struct sip_request *req, char *name)
1356 {
1357         int start = 0;
1358         return __get_header(req, name, &start);
1359 }
1360
1361 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p)
1362 {
1363         /* Retrieve audio/etc from channel.  Assumes p->lock is already held. */
1364         struct ast_frame *f;
1365         static struct ast_frame null_frame = { AST_FRAME_NULL, };
1366         switch(ast->fdno) {
1367         case 0:
1368                 f = ast_rtp_read(p->rtp);
1369                 break;
1370         case 1:
1371                 f = ast_rtcp_read(p->rtp);
1372                 break;
1373         case 2:
1374                 f = ast_rtp_read(p->vrtp);
1375                 break;
1376         case 3:
1377                 f = ast_rtcp_read(p->vrtp);
1378                 break;
1379         default:
1380                 f = &null_frame;
1381         }
1382         /* Don't send RFC2833 if we're not supposed to */
1383         if (f && (f->frametype == AST_FRAME_DTMF) && !(p->dtmfmode & SIP_DTMF_RFC2833))
1384                 return &null_frame;
1385         if (p->owner) {
1386                 /* We already hold the channel lock */
1387                 if (f->frametype == AST_FRAME_VOICE) {
1388                         if (f->subclass != p->owner->nativeformats) {
1389                                 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
1390                                 p->owner->nativeformats = f->subclass;
1391                                 ast_set_read_format(p->owner, p->owner->readformat);
1392                                 ast_set_write_format(p->owner, p->owner->writeformat);
1393                         }
1394             if (p->dtmfmode & SIP_DTMF_INBAND) {
1395                    f = ast_dsp_process(p->owner,p->vad,f,0);
1396             }
1397                 }
1398         }
1399         return f;
1400 }
1401
1402 static struct ast_frame *sip_read(struct ast_channel *ast)
1403 {
1404         struct ast_frame *fr;
1405         struct sip_pvt *p = ast->pvt->pvt;
1406         ast_mutex_lock(&p->lock);
1407         fr = sip_rtp_read(ast, p);
1408         ast_mutex_unlock(&p->lock);
1409         return fr;
1410 }
1411
1412 static void build_callid(char *callid, int len, struct in_addr ourip)
1413 {
1414         int res;
1415         int val;
1416         int x;
1417         for (x=0;x<4;x++) {
1418                 val = rand();
1419                 res = snprintf(callid, len, "%08x", val);
1420                 len -= res;
1421                 callid += res;
1422         }
1423         /* It's not important that we really use our right IP here... */
1424         snprintf(callid, len, "@%s", inet_ntoa(ourip));
1425 }
1426
1427 static struct sip_pvt *sip_alloc(char *callid, struct sockaddr_in *sin, int useglobalnat)
1428 {
1429         struct sip_pvt *p;
1430
1431         p = malloc(sizeof(struct sip_pvt));
1432         if (!p)
1433                 return NULL;
1434         /* Keep track of stuff */
1435         memset(p, 0, sizeof(struct sip_pvt));
1436         p->initid = -1;
1437         p->autokillid = -1;
1438         p->stateid = -1;
1439         p->rtp = ast_rtp_new(sched, io, 1, 0);
1440         if (videosupport)
1441                 p->vrtp = ast_rtp_new(sched, io, 1, 0);
1442         p->branch = rand();     
1443         p->tag = rand();
1444         
1445         /* Start with 101 instead of 1 */
1446         p->ocseq = 101;
1447         if (!p->rtp) {
1448                 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
1449                 free(p);
1450                 return NULL;
1451         }
1452         ast_rtp_settos(p->rtp, tos);
1453         if (p->vrtp)
1454                 ast_rtp_settos(p->vrtp, tos);
1455         if (useglobalnat && sin) {
1456                 /* Setup NAT structure according to global settings if we have an address */
1457                 p->nat = globalnat;
1458                 memcpy(&p->recv, sin, sizeof(p->recv));
1459                 ast_rtp_setnat(p->rtp, p->nat);
1460                 if (p->vrtp)
1461                         ast_rtp_setnat(p->vrtp, p->nat);
1462         }
1463         ast_mutex_init(&p->lock);
1464
1465         if (sin) {
1466                 memcpy(&p->sa, sin, sizeof(p->sa));
1467                 if (ast_sip_ouraddrfor(&p->sa.sin_addr,&p->ourip))
1468                         memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
1469         } else {
1470                 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
1471         }
1472         /* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
1473         snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
1474         if (!callid)
1475                 build_callid(p->callid, sizeof(p->callid), p->ourip);
1476         else
1477                 strncpy(p->callid, callid, sizeof(p->callid) - 1);
1478         /* Assume reinvite OK and via INVITE */
1479         p->canreinvite = globalcanreinvite;
1480         p->dtmfmode = globaldtmfmode;
1481         if (p->dtmfmode & SIP_DTMF_RFC2833)
1482                 p->noncodeccapability |= AST_RTP_DTMF;
1483         strncpy(p->context, context, sizeof(p->context) - 1);
1484         strncpy(p->fromdomain, fromdomain, sizeof(p->fromdomain) - 1);
1485         /* Add to list */
1486         ast_mutex_lock(&iflock);
1487         p->next = iflist;
1488         iflist = p;
1489         ast_mutex_unlock(&iflock);
1490         if (option_debug)
1491                 ast_log(LOG_DEBUG, "Allocating new SIP call for %s\n", callid);
1492         return p;
1493 }
1494
1495 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin)
1496 {
1497         struct sip_pvt *p;
1498         char *callid;
1499         char tmp[256] = "";
1500         char *cmd;
1501         char *tag = "", *c;
1502         int themisfrom;
1503         callid = get_header(req, "Call-ID");
1504
1505         if (pedanticsipchecking) {
1506                 /* In principle Call-ID's uniquely identify a call, however some vendors
1507                    (i.e. Pingtel) send multiple calls with the same Call-ID and different
1508                    tags in order to simplify billing.  The RFC does state that we have to
1509                    compare tags in addition to the call-id, but this generate substantially
1510                    more overhead which is totally unnecessary for the vast majority of sane
1511                    SIP implementations, and thus Asterisk does not enable this behavior
1512                    by default. Short version: You'll need this option to support conferencing
1513                    on the pingtel */
1514                 strncpy(tmp, req->header[0], sizeof(tmp) - 1);
1515                 cmd = tmp;
1516                 c = strchr(tmp, ' ');
1517                 if (c)
1518                         *c = '\0';
1519                 if (!strcasecmp(cmd, "SIP/2.0")) {
1520                         themisfrom = 0;
1521                 } else {
1522                         themisfrom = 1;
1523                 }
1524                 if (themisfrom)
1525                         strncpy(tmp, get_header(req, "From"), sizeof(tmp) - 1);
1526                 else
1527                         strncpy(tmp, get_header(req, "To"), sizeof(tmp) - 1);
1528                 tag = strstr(tmp, "tag=");
1529                 if (tag) {
1530                         tag += 4;
1531                         c = strchr(tag, ';');
1532                         if (c)
1533                                 *c = '\0';
1534                 }
1535                         
1536         }
1537                 
1538         if (!strlen(callid)) {
1539                 ast_log(LOG_WARNING, "Call missing call ID from '%s'\n", inet_ntoa(sin->sin_addr));
1540                 return NULL;
1541         }
1542         ast_mutex_lock(&iflock);
1543         p = iflist;
1544         while(p) {
1545                 if (!strcmp(p->callid, callid) && 
1546                         (!pedanticsipchecking || !strlen(p->theirtag) || !strcmp(p->theirtag, tag))) {
1547                         /* Found the call */
1548                         ast_mutex_lock(&p->lock);
1549                         ast_mutex_unlock(&iflock);
1550                         return p;
1551                 }
1552                 p = p->next;
1553         }
1554         ast_mutex_unlock(&iflock);
1555         p = sip_alloc(callid, sin, 1);
1556         if (p)
1557                 ast_mutex_lock(&p->lock);
1558         return p;
1559 }
1560
1561 static int sip_register(char *value, int lineno)
1562 {
1563         struct sip_registry *reg;
1564         char copy[256] = "";
1565         char *username=NULL, *hostname=NULL, *secret=NULL, *authuser=NULL;
1566         char *porta=NULL;
1567         char *contact=NULL;
1568         char *stringp=NULL;
1569         
1570         struct hostent *hp;
1571         if (!value)
1572                 return -1;
1573         strncpy(copy, value, sizeof(copy)-1);
1574         stringp=copy;
1575         username = stringp;
1576         hostname = strrchr(stringp, '@');
1577         if (hostname) {
1578                 *hostname = '\0';
1579                 hostname++;
1580         }
1581         if (!username || !strlen(username) || !hostname || !strlen(hostname)) {
1582                 ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port] at line %d", lineno);
1583                 return -1;
1584         }
1585         stringp=username;
1586         username = strsep(&stringp, ":");
1587         if (username) {
1588                 secret = strsep(&stringp, ":");
1589                 if (secret) 
1590                         authuser = strsep(&stringp, ":");
1591         }
1592         stringp = hostname;
1593         hostname = strsep(&stringp, "/");
1594         if (hostname) 
1595                 contact = strsep(&stringp, "/");
1596         if (!contact || !strlen(contact))
1597                 contact = "s";
1598         stringp=hostname;
1599         hostname = strsep(&stringp, ":");
1600         porta = strsep(&stringp, ":");
1601         
1602         if (porta && !atoi(porta)) {
1603                 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
1604                 return -1;
1605         }
1606         hp = gethostbyname(hostname);
1607         if (!hp) {
1608                 ast_log(LOG_WARNING, "Host '%s' not found at line %d\n", hostname, lineno);
1609                 return -1;
1610         }
1611         reg = malloc(sizeof(struct sip_registry));
1612         if (reg) {
1613                 memset(reg, 0, sizeof(struct sip_registry));
1614                 strncpy(reg->contact, contact, sizeof(reg->contact) - 1);
1615                 if (username)
1616                         strncpy(reg->username, username, sizeof(reg->username)-1);
1617                 if (hostname)
1618                         strncpy(reg->hostname, hostname, sizeof(reg->hostname)-1);
1619                 if (authuser)
1620                         strncpy(reg->authuser, authuser, sizeof(reg->authuser)-1);
1621                 if (secret)
1622                         strncpy(reg->secret, secret, sizeof(reg->secret)-1);
1623                 reg->expire = -1;
1624                 reg->timeout =  -1;
1625                 reg->refresh = default_expiry;
1626                 reg->addr.sin_family = AF_INET;
1627                 memcpy(&reg->addr.sin_addr, hp->h_addr, sizeof(&reg->addr.sin_addr));
1628                 reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(DEFAULT_SIP_PORT);
1629                 reg->next = registrations;
1630                 reg->callid_valid = 0;
1631                 reg->ocseq = 101;
1632                 registrations = reg;
1633         } else {
1634                 ast_log(LOG_ERROR, "Out of memory\n");
1635                 return -1;
1636         }
1637         return 0;
1638 }
1639
1640 static void parse(struct sip_request *req)
1641 {
1642         /* Divide fields by NULL's */
1643         char *c;
1644         int f = 0;
1645         c = req->data;
1646
1647         /* First header starts immediately */
1648         req->header[f] = c;
1649         while(*c) {
1650                 if (*c == '\n') {
1651                         /* We've got a new header */
1652                         *c = 0;
1653
1654 #if 0
1655                         printf("Header: %s (%d)\n", req->header[f], strlen(req->header[f]));
1656 #endif                  
1657                         if (!strlen(req->header[f])) {
1658                                 /* Line by itself means we're now in content */
1659                                 c++;
1660                                 break;
1661                         }
1662                         if (f >= SIP_MAX_HEADERS - 1) {
1663                                 ast_log(LOG_WARNING, "Too many SIP headers...\n");
1664                         } else
1665                                 f++;
1666                         req->header[f] = c + 1;
1667                 } else if (*c == '\r') {
1668                         /* Ignore but eliminate \r's */
1669                         *c = 0;
1670                 }
1671                 c++;
1672         }
1673         /* Check for last header */
1674         if (strlen(req->header[f])) 
1675                 f++;
1676         req->headers = f;
1677         /* Now we process any mime content */
1678         f = 0;
1679         req->line[f] = c;
1680         while(*c) {
1681                 if (*c == '\n') {
1682                         /* We've got a new line */
1683                         *c = 0;
1684 #if 0
1685                         printf("Line: %s (%d)\n", req->line[f], strlen(req->line[f]));
1686 #endif                  
1687                         if (f >= SIP_MAX_LINES - 1) {
1688                                 ast_log(LOG_WARNING, "Too many SDP lines...\n");
1689                         } else
1690                                 f++;
1691                         req->line[f] = c + 1;
1692                 } else if (*c == '\r') {
1693                         /* Ignore and eliminate \r's */
1694                         *c = 0;
1695                 }
1696                 c++;
1697         }
1698         /* Check for last line */
1699         if (strlen(req->line[f])) 
1700                 f++;
1701         req->lines = f;
1702         if (sipdebug)
1703                 ast_verbose("%d headers, %d lines\n", req->headers, req->lines);
1704         if (*c) 
1705                 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
1706 }
1707
1708 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
1709 {
1710         char *m;
1711         char *c;
1712         char *a;
1713         char host[258];
1714         int len = -1;
1715         int portno=0;
1716         int vportno=0;
1717         int peercapability, peernoncodeccapability;
1718         int vpeercapability=0, vpeernoncodeccapability=0;
1719         struct sockaddr_in sin;
1720         char *codecs;
1721         struct hostent *hp;
1722         int codec;
1723         int iterator;
1724         int x;
1725
1726         /* Get codec and RTP info from SDP */
1727         if (strcasecmp(get_header(req, "Content-Type"), "application/sdp")) {
1728                 ast_log(LOG_NOTICE, "Content is '%s', not 'application/sdp'\n", get_header(req, "Content-Type"));
1729                 return -1;
1730         }
1731         m = get_sdp(req, "m");
1732         c = get_sdp(req, "c");
1733         if (!strlen(m) || !strlen(c)) {
1734                 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
1735                 return -1;
1736         }
1737         if (sscanf(c, "IN IP4 %256s", host) != 1) {
1738                 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
1739                 return -1;
1740         }
1741         /* XXX This could block for a long time, and block the main thread! XXX */
1742         hp = gethostbyname(host);
1743         if (!hp) {
1744                 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
1745                 return -1;
1746         }
1747         sdpLineNum_iterator_init(&iterator);
1748         while ((m = get_sdp_iterate(&iterator, req, "m"))[0] != '\0') {
1749                 if ((sscanf(m, "audio %d RTP/AVP %n", &x, &len) == 1)) {
1750                         portno = x;
1751                         // Scan through the RTP payload types specified in a "m=" line:
1752                         ast_rtp_pt_clear(p->rtp);
1753                         codecs = m + len;
1754                         while(strlen(codecs)) {
1755                                 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
1756                                         ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
1757                                         return -1;
1758                                 }
1759                                 if (sipdebug)
1760                                         ast_verbose("Found audio format %s\n", ast_getformatname(codec));
1761                                 ast_rtp_set_m_type(p->rtp, codec);
1762                                 codecs += len;
1763                                 /* Skip over any whitespace */
1764                                 while(*codecs && (*codecs < 33)) codecs++;
1765                         }
1766                 }
1767                 if (p->vrtp && (sscanf(m, "video %d RTP/AVP %n", &x, &len) == 1)) {
1768                         vportno = x;
1769                         // Scan through the RTP payload types specified in a "m=" line:
1770                         ast_rtp_pt_clear(p->vrtp);
1771                         codecs = m + len;
1772                         while(strlen(codecs)) {
1773                                 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
1774                                         ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
1775                                         return -1;
1776                                 }
1777                                 if (sipdebug)
1778                                         ast_verbose("Found video format %s\n", ast_getformatname(codec));
1779                                 ast_rtp_set_m_type(p->vrtp, codec);
1780                                 codecs += len;
1781                                 /* Skip over any whitespace */
1782                                 while(*codecs && (*codecs < 33)) codecs++;
1783                         }
1784                 }
1785         }
1786         sin.sin_family = AF_INET;
1787         memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
1788         /* Setup audio port number */
1789         sin.sin_port = htons(portno);
1790         if (p->rtp && sin.sin_port)
1791                 ast_rtp_set_peer(p->rtp, &sin);
1792         /* Setup video port number */
1793         sin.sin_port = htons(vportno);
1794         if (p->vrtp && sin.sin_port)
1795                 ast_rtp_set_peer(p->vrtp, &sin);
1796 #if 0
1797         printf("Peer RTP is at port %s:%d\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
1798 #endif  
1799         // Next, scan through each "a=rtpmap:" line, noting each
1800         // specified RTP payload type (with corresponding MIME subtype):
1801         sdpLineNum_iterator_init(&iterator);
1802         while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
1803       char* mimeSubtype = ast_strdupa(a); // ensures we have enough space
1804           if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) != 2) continue;
1805           if (sipdebug)
1806                 ast_verbose("Found description format %s\n", mimeSubtype);
1807           // Note: should really look at the 'freq' and '#chans' params too
1808           ast_rtp_set_rtpmap_type(p->rtp, codec, "audio", mimeSubtype);
1809           if (p->vrtp)
1810                   ast_rtp_set_rtpmap_type(p->vrtp, codec, "video", mimeSubtype);
1811         }
1812
1813         // Now gather all of the codecs that were asked for:
1814         ast_rtp_get_current_formats(p->rtp,
1815                                 &peercapability, &peernoncodeccapability);
1816         if (p->vrtp)
1817                 ast_rtp_get_current_formats(p->vrtp,
1818                                 &vpeercapability, &vpeernoncodeccapability);
1819         p->capability = capability & (peercapability | vpeercapability);
1820         p->noncodeccapability = noncodeccapability & (peernoncodeccapability | vpeernoncodeccapability);
1821         
1822         if (sipdebug) {
1823                 ast_verbose("Capabilities: us - %d, them - %d/%d, combined - %d\n",
1824                             capability, peercapability, vpeercapability, p->capability);
1825                 ast_verbose("Non-codec capabilities: us - %d, them - %d, combined - %d\n",
1826                             noncodeccapability, peernoncodeccapability,
1827                             p->noncodeccapability);
1828         }
1829         if (!p->capability) {
1830                 ast_log(LOG_WARNING, "No compatible codecs!\n");
1831                 return -1;
1832         }
1833         if (p->owner) {
1834                 if (!(p->owner->nativeformats & p->capability)) {
1835                         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);
1836                         p->owner->nativeformats = sip_codec_choose(p->capability);
1837                         ast_set_read_format(p->owner, p->owner->readformat);
1838                         ast_set_write_format(p->owner, p->owner->writeformat);
1839                 }
1840                 if (p->owner->bridge) {
1841                         /* Turn on/off music on hold if we are holding/unholding */
1842                         if (sin.sin_addr.s_addr) {
1843                                 ast_moh_stop(p->owner->bridge);
1844                         } else {
1845                                 ast_moh_start(p->owner->bridge, NULL);
1846                         }
1847                 }
1848         }
1849         return 0;
1850         
1851 }
1852
1853 static int add_header(struct sip_request *req, char *var, char *value)
1854 {
1855         if (req->len >= sizeof(req->data) - 4) {
1856                 ast_log(LOG_WARNING, "Out of space, can't add anymore (%s:%s)\n", var, value);
1857                 return -1;
1858         }
1859         if (req->lines) {
1860                 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1861                 return -1;
1862         }
1863         req->header[req->headers] = req->data + req->len;
1864         snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", var, value);
1865         req->len += strlen(req->header[req->headers]);
1866         if (req->headers < SIP_MAX_HEADERS)
1867                 req->headers++;
1868         else {
1869                 ast_log(LOG_WARNING, "Out of header space\n");
1870                 return -1;
1871         }
1872         return 0;       
1873 }
1874
1875 static int add_blank_header(struct sip_request *req)
1876 {
1877         if (req->len >= sizeof(req->data) - 4) {
1878                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1879                 return -1;
1880         }
1881         if (req->lines) {
1882                 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
1883                 return -1;
1884         }
1885         req->header[req->headers] = req->data + req->len;
1886         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "\r\n");
1887         req->len += strlen(req->header[req->headers]);
1888         if (req->headers < SIP_MAX_HEADERS)
1889                 req->headers++;
1890         else {
1891                 ast_log(LOG_WARNING, "Out of header space\n");
1892                 return -1;
1893         }
1894         return 0;       
1895 }
1896
1897 static int add_line(struct sip_request *req, char *line)
1898 {
1899         if (req->len >= sizeof(req->data) - 4) {
1900                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
1901                 return -1;
1902         }
1903         if (!req->lines) {
1904                 /* Add extra empty return */
1905                 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
1906                 req->len += strlen(req->data + req->len);
1907         }
1908         req->line[req->lines] = req->data + req->len;
1909         snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
1910         req->len += strlen(req->line[req->lines]);
1911         if (req->lines < SIP_MAX_LINES)
1912                 req->lines++;
1913         else {
1914                 ast_log(LOG_WARNING, "Out of line space\n");
1915                 return -1;
1916         }
1917         return 0;       
1918 }
1919
1920 static int copy_header(struct sip_request *req, struct sip_request *orig, char *field)
1921 {
1922         char *tmp;
1923         tmp = get_header(orig, field);
1924         if (strlen(tmp)) {
1925                 /* Add what we're responding to */
1926                 return add_header(req, field, tmp);
1927         }
1928         ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1929         return -1;
1930 }
1931
1932 static int copy_all_header(struct sip_request *req, struct sip_request *orig, char *field)
1933 {
1934         char *tmp;
1935         int start = 0;
1936         int copied = 0;
1937         for (;;) {
1938                 tmp = __get_header(orig, field, &start);
1939                 if (strlen(tmp)) {
1940                         /* Add what we're responding to */
1941                         add_header(req, field, tmp);
1942                         copied++;
1943                 } else
1944                         break;
1945         }
1946         return copied ? 0 : -1;
1947 }
1948
1949 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, struct sip_request *orig, char *field)
1950 {
1951         char *tmp;
1952         int start = 0;
1953         int copied = 0;
1954         char new[256];
1955         for (;;) {
1956                 tmp = __get_header(orig, field, &start);
1957                 if (strlen(tmp)) {
1958                         if (!copied && p->nat) {
1959 #ifdef THE_SIP_AUTHORS_CAN_SUCK_MY_GONADS
1960                                 /* SLD: FIXME: Nice try, but the received= should not have a port */
1961                                 /* SLD: FIXME: See RFC2543 BNF in Section 6.40.5 */
1962                                 /* MAS: Yup, RFC says you can't do it.  No way to indicate PAT...
1963                                    good job fellas. */
1964                                 if (ntohs(p->recv.sin_port) != DEFAULT_SIP_PORT)
1965                                         snprintf(new, sizeof(new), "%s;received=%s:%d", tmp, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
1966                                 else
1967 #endif                          
1968                                         snprintf(new, sizeof(new), "%s;received=%s", tmp, inet_ntoa(p->recv.sin_addr));
1969                                 add_header(req, field, new);
1970                         } else {
1971                                 /* Add what we're responding to */
1972                                 add_header(req, field, tmp);
1973                         }
1974                         copied++;
1975                 } else
1976                         break;
1977         }
1978         if (!copied) {
1979                 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
1980                 return -1;
1981         }
1982         return 0;
1983 }
1984
1985 /* Add Route: header into request per learned route */
1986 static void add_route(struct sip_request *req, struct sip_route *route)
1987 {
1988         char r[256], *p;
1989         int n, rem = 255; /* sizeof(r)-1: Room for terminating 0 */
1990
1991         if (!route) return;
1992
1993         p = r;
1994         while (route) {
1995                 n = strlen(route->hop);
1996                 if ((n+3)>rem) break;
1997                 if (p != r) {
1998                         *p++ = ',';
1999                         --rem;
2000                 }
2001                 *p++ = '<';
2002                 strcpy(p, route->hop);  p += n;
2003                 *p++ = '>';
2004                 rem -= (n+2);
2005                 route = route->next;
2006         }
2007         *p = '\0';
2008         add_header(req, "Route", r);
2009 }
2010
2011 static void set_destination(struct sip_pvt *p, char *uri)
2012 {
2013         char *h, *maddr, hostname[256];
2014         int port, hn;
2015         struct hostent *hp;
2016
2017         /* Parse uri to h (host) and port - uri is already just the part inside the <> */
2018         /* general form we are expecting is sip[s]:username[:password]@host[:port][;...] */
2019
2020         if (sipdebug)
2021                 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
2022
2023         /* Find and parse hostname */
2024         h = strchr(uri, '@');
2025         if (h)
2026                 ++h;
2027         else {
2028                 h = uri;
2029                 if (strncmp(h, "sip:", 4) == 0)
2030                         h += 4;
2031                 else if (strncmp(h, "sips:", 5) == 0)
2032                         h += 5;
2033         }
2034         hn = strcspn(h, ":;>");
2035         if (hn>255) hn=255;
2036         strncpy(hostname, h, hn);  hostname[hn] = '\0';
2037         h+=hn;
2038
2039         /* Is "port" present? if not default to 5060 */
2040         if (*h == ':') {
2041                 /* Parse port */
2042                 ++h;
2043                 port = strtol(h, &h, 10);
2044         }
2045         else
2046                 port = 5060;
2047
2048         /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
2049         maddr = strstr(h, "maddr=");
2050         if (maddr) {
2051                 maddr += 6;
2052                 hn = strspn(maddr, "0123456789.");
2053                 if (hn>255) hn=255;
2054                 strncpy(hostname, maddr, hn);  hostname[hn] = '\0';
2055         }
2056         
2057         hp = gethostbyname(hostname);
2058         if (hp == NULL)  {
2059                 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
2060                 return;
2061         }
2062         p->sa.sin_family = AF_INET;
2063         memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
2064         p->sa.sin_port = htons(port);
2065         if (sipdebug)
2066                 ast_verbose("set_destination: set destination to %s, port %d\n", inet_ntoa(p->sa.sin_addr), port);
2067 }
2068
2069 static int init_resp(struct sip_request *req, char *resp, struct sip_request *orig)
2070 {
2071         /* Initialize a response */
2072         if (req->headers || req->len) {
2073                 ast_log(LOG_WARNING, "Request already initialized?!?\n");
2074                 return -1;
2075         }
2076         req->header[req->headers] = req->data + req->len;
2077         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "SIP/2.0 %s\r\n", resp);
2078         req->len += strlen(req->header[req->headers]);
2079         if (req->headers < SIP_MAX_HEADERS)
2080                 req->headers++;
2081         else
2082                 ast_log(LOG_WARNING, "Out of header space\n");
2083         return 0;
2084 }
2085
2086 static int init_req(struct sip_request *req, char *resp, char *recip)
2087 {
2088         /* Initialize a response */
2089         if (req->headers || req->len) {
2090                 ast_log(LOG_WARNING, "Request already initialized?!?\n");
2091                 return -1;
2092         }
2093         req->header[req->headers] = req->data + req->len;
2094         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s SIP/2.0\r\n", resp, recip);
2095         req->len += strlen(req->header[req->headers]);
2096         if (req->headers < SIP_MAX_HEADERS)
2097                 req->headers++;
2098         else
2099                 ast_log(LOG_WARNING, "Out of header space\n");
2100         return 0;
2101 }
2102
2103 static int respprep(struct sip_request *resp, struct sip_pvt *p, char *msg, struct sip_request *req)
2104 {
2105         char newto[256] = "", *ot;
2106         memset(resp, 0, sizeof(*resp));
2107         init_resp(resp, msg, req);
2108         copy_via_headers(p, resp, req, "Via");
2109         if (msg[0] == '2') copy_all_header(resp, req, "Record-Route");
2110         copy_header(resp, req, "From");
2111         ot = get_header(req, "To");
2112         if (!strstr(ot, "tag=")) {
2113                 /* Add the proper tag if we don't have it already.  If they have specified
2114                    their tag, use it.  Otherwise, use our own tag */
2115                 if (strlen(p->theirtag) && p->outgoing)
2116                         snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
2117                 else if (p->tag && !p->outgoing)
2118                         snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
2119                 else
2120                         strncpy(newto, ot, sizeof(newto) - 1);
2121                 ot = newto;
2122         }
2123         add_header(resp, "To", ot);
2124         copy_header(resp, req, "Call-ID");
2125         copy_header(resp, req, "CSeq");
2126         add_header(resp, "User-Agent", "Asterisk PBX");
2127         add_header(resp, "Allow", ALLOWED_METHODS);
2128         if (p->expiry) {
2129                 /* For registration responses, we also need expiry and
2130                    contact info */
2131                 char contact[256];
2132                 char tmp[256];
2133                 snprintf(contact, sizeof(contact), "%s;expires=%d", p->our_contact, p->expiry);
2134                 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
2135                 add_header(resp, "Expires", tmp);
2136                 add_header(resp, "Contact", contact);
2137         } else {
2138                 add_header(resp, "Contact", p->our_contact);
2139         }
2140         return 0;
2141 }
2142
2143 static int reqprep(struct sip_request *req, struct sip_pvt *p, char *msg, int seqno)
2144 {
2145         struct sip_request *orig = &p->initreq;
2146         char stripped[80] ="";
2147         char tmp[80];
2148         char newto[256];
2149         char *c, *n;
2150         char *ot, *of;
2151
2152         memset(req, 0, sizeof(struct sip_request));
2153         
2154         if (!seqno) {
2155                 p->ocseq++;
2156                 seqno = p->ocseq;
2157         }
2158
2159         if (strlen(p->uri)) {
2160                 c = p->uri;
2161         } else {
2162                 if (p->outgoing)
2163                         strncpy(stripped, get_header(orig, "To"), sizeof(stripped) - 1);
2164                 else
2165                         strncpy(stripped, get_header(orig, "From"), sizeof(stripped) - 1);
2166                 
2167                 c = strchr(stripped, '<');
2168                 if (c) 
2169                         c++;
2170                 else
2171                         c = stripped;
2172                 n = strchr(c, '>');
2173                 if (n)
2174                         *n = '\0';
2175                 n = strchr(c, ';');
2176                 if (n)
2177                         *n = '\0';
2178         }       
2179         init_req(req, msg, c);
2180
2181         snprintf(tmp, sizeof(tmp), "%d %s", seqno, msg);
2182
2183         add_header(req, "Via", p->via);
2184         if (p->route) {
2185                 set_destination(p, p->route->hop);
2186                 add_route(req, p->route->next);
2187         }
2188
2189         ot = get_header(orig, "To");
2190         of = get_header(orig, "From");
2191
2192         /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
2193            as our original request, including tag (or presumably lack thereof) */
2194         if (!strstr(ot, "tag=") && strcasecmp(msg, "CANCEL")) {
2195                 /* Add the proper tag if we don't have it already.  If they have specified
2196                    their tag, use it.  Otherwise, use our own tag */
2197                 if (p->outgoing && strlen(p->theirtag))
2198                         snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
2199                 else if (!p->outgoing)
2200                         snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
2201                 else
2202                         snprintf(newto, sizeof(newto), "%s", ot);
2203                 ot = newto;
2204         }
2205
2206         if (p->outgoing) {
2207                 add_header(req, "From", of);
2208                 add_header(req, "To", ot);
2209         } else {
2210                 add_header(req, "From", ot);
2211                 add_header(req, "To", of);
2212         }
2213         add_header(req, "Contact", p->our_contact);
2214         copy_header(req, orig, "Call-ID");
2215         add_header(req, "CSeq", tmp);
2216
2217         add_header(req, "User-Agent", "Asterisk PBX");
2218         return 0;
2219 }
2220
2221 static int __transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req, int reliable)
2222 {
2223         struct sip_request resp;
2224         int seqno = 0;
2225         if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
2226                 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
2227                 return -1;
2228         }
2229         respprep(&resp, p, msg, req);
2230         add_header(&resp, "Content-Length", "0");
2231         add_blank_header(&resp);
2232         return send_response(p, &resp, reliable, seqno);
2233 }
2234
2235 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req) 
2236 {
2237         return __transmit_response(p, msg, req, 0);
2238 }
2239 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req)
2240 {
2241         return __transmit_response(p, msg, req, 1);
2242 }
2243
2244 static void append_date(struct sip_request *req)
2245 {
2246         char tmpdat[256];
2247         struct tm tm;
2248         time_t t;
2249         time(&t);
2250         gmtime_r(&t, &tm);
2251         strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
2252         add_header(req, "Date", tmpdat);
2253 }
2254
2255 static int transmit_response_with_date(struct sip_pvt *p, char *msg, struct sip_request *req)
2256 {
2257         struct sip_request resp;
2258         respprep(&resp, p, msg, req);
2259         append_date(&resp);
2260         add_header(&resp, "Content-Length", "0");
2261         add_blank_header(&resp);
2262         return send_response(p, &resp, 0, 0);
2263 }
2264
2265 static int transmit_response_with_allow(struct sip_pvt *p, char *msg, struct sip_request *req)
2266 {
2267         struct sip_request resp;
2268         respprep(&resp, p, msg, req);
2269         add_header(&resp, "Accept", "application/sdp");
2270         add_header(&resp, "Content-Length", "0");
2271         add_blank_header(&resp);
2272         return send_response(p, &resp, 0, 0);
2273 }
2274
2275 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *randdata, int reliable)
2276 {
2277         struct sip_request resp;
2278         char tmp[256];
2279         int seqno = 0;
2280         if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
2281                 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
2282                 return -1;
2283         }
2284         snprintf(tmp, sizeof(tmp), "Digest realm=\"asterisk\", nonce=\"%s\"", randdata);
2285         respprep(&resp, p, msg, req);
2286         add_header(&resp, "Proxy-Authenticate", tmp);
2287         add_header(&resp, "Content-Length", "0");
2288         add_blank_header(&resp);
2289         return send_response(p, &resp, reliable, seqno);
2290 }
2291
2292 static int add_text(struct sip_request *req, char *text)
2293 {
2294         /* XXX Convert \n's to \r\n's XXX */
2295         int len = strlen(text);
2296         char clen[256];
2297         snprintf(clen, sizeof(clen), "%d", len);
2298         add_header(req, "Content-Type", "text/plain");
2299         add_header(req, "Content-Length", clen);
2300         add_line(req, text);
2301         return 0;
2302 }
2303
2304 static int add_digit(struct sip_request *req, char digit)
2305 {
2306         char tmp[256];
2307         int len;
2308         char clen[256];
2309         snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=250\r\n", digit);
2310         len = strlen(tmp);
2311         snprintf(clen, sizeof(clen), "%d", len);
2312         add_header(req, "Content-Type", "application/dtmf-relay");
2313         add_header(req, "Content-Length", clen);
2314         add_line(req, tmp);
2315         return 0;
2316 }
2317
2318 static int add_sdp(struct sip_request *resp, struct sip_pvt *p, struct ast_rtp *rtp, struct ast_rtp *vrtp)
2319 {
2320         int len;
2321         int codec;
2322         int alreadysent = 0;
2323         char costr[80];
2324         struct sockaddr_in sin;
2325         struct sockaddr_in vsin;
2326         struct sip_codec_pref *cur;
2327         char v[256];
2328         char s[256];
2329         char o[256];
2330         char c[256];
2331         char t[256];
2332         char m[256];
2333         char m2[256];
2334         char a[1024] = "";
2335         char a2[1024] = "";
2336         int x;
2337         struct sockaddr_in dest;
2338         struct sockaddr_in vdest;
2339         /* XXX We break with the "recommendation" and send our IP, in order that our
2340                peer doesn't have to gethostbyname() us XXX */
2341         len = 0;
2342         if (!p->rtp) {
2343                 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
2344                 return -1;
2345         }
2346         ast_rtp_get_us(p->rtp, &sin);
2347         if (p->vrtp)
2348                 ast_rtp_get_us(p->vrtp, &vsin);
2349
2350         if (p->redirip.sin_addr.s_addr) {
2351                 dest.sin_port = p->redirip.sin_port;
2352                 dest.sin_addr = p->redirip.sin_addr;
2353         } else if (rtp) {
2354                 ast_rtp_get_peer(rtp, &dest);
2355         } else {
2356                 dest.sin_addr = p->ourip;
2357                 dest.sin_port = sin.sin_port;
2358         }
2359
2360         /* Determine video destination */
2361         if (p->vrtp) {
2362                 if (p->vredirip.sin_addr.s_addr) {
2363                         vdest.sin_port = p->vredirip.sin_port;
2364                         vdest.sin_addr = p->vredirip.sin_addr;
2365                 } else if (vrtp) {
2366                         ast_rtp_get_peer(vrtp, &vdest);
2367                 } else {
2368                         vdest.sin_addr = p->ourip;
2369                         vdest.sin_port = vsin.sin_port;
2370                 }
2371         }
2372         if (sipdebug)
2373                 ast_verbose("We're at %s port %d\n", inet_ntoa(p->ourip), ntohs(sin.sin_port)); 
2374         if (sipdebug && p->vrtp)
2375                 ast_verbose("Video is at %s port %d\n", inet_ntoa(p->ourip), ntohs(vsin.sin_port));     
2376         snprintf(v, sizeof(v), "v=0\r\n");
2377         snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", getpid(), getpid(), inet_ntoa(dest.sin_addr));
2378         snprintf(s, sizeof(s), "s=session\r\n");
2379         snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", inet_ntoa(dest.sin_addr));
2380         snprintf(t, sizeof(t), "t=0 0\r\n");
2381         snprintf(m, sizeof(m), "m=audio %d RTP/AVP", ntohs(dest.sin_port));
2382         snprintf(m2, sizeof(m2), "m=video %d RTP/AVP", ntohs(vdest.sin_port));
2383         /* Start by sending our preferred codecs */
2384         cur = prefs;
2385         while(cur) {
2386                 if (p->capability & cur->codec) {
2387                         if (sipdebug)
2388                                 ast_verbose("Answering with preferred capability %d\n", cur->codec);
2389                         codec = ast_rtp_lookup_code(p->rtp, 1, cur->codec);
2390                         if (codec > -1) {
2391                                 snprintf(costr, sizeof(costr), " %d", codec);
2392                                 if (cur->codec < AST_FORMAT_MAX_AUDIO) {
2393                                         strcat(m, costr);
2394                                         snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, cur->codec));
2395                                         strcat(a, costr);
2396                                 } else {
2397                                         strcat(m2, costr);
2398                                         snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/90000\r\n", codec, ast_rtp_lookup_mime_subtype(1, cur->codec));
2399                                         strcat(a2, costr);
2400                                 }
2401                         }
2402                 }
2403                 alreadysent |= cur->codec;
2404                 cur = cur->next;
2405         }
2406         /* Now send any other common codecs, and non-codec formats: */
2407         for (x = 1; x <= AST_FORMAT_MAX_AUDIO; x <<= 1) {
2408                 if ((p->capability & x) && !(alreadysent & x)) {
2409                         if (sipdebug)
2410                                 ast_verbose("Answering with capability %d\n", x);       
2411                         codec = ast_rtp_lookup_code(p->rtp, 1, x);
2412                         if (codec > -1) {
2413                                 snprintf(costr, sizeof(costr), " %d", codec);
2414                                 if (x < AST_FORMAT_MAX_AUDIO) {
2415                                         strcat(m, costr);
2416                                         snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
2417                                         strcat(a, costr);
2418                                 } else {
2419                                         strcat(m2, costr);
2420                                         snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/90000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
2421                                         strcat(a2, costr);
2422                                 }
2423                         }
2424                 }
2425         }
2426         for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
2427                 if (p->noncodeccapability & x) {
2428                         if (sipdebug)
2429                                 ast_verbose("Answering with non-codec capability %d\n", x);
2430                         codec = ast_rtp_lookup_code(p->rtp, 0, x);
2431                         if (codec > -1) {
2432                                 snprintf(costr, sizeof(costr), " %d", codec);
2433                                 strcat(m, costr);
2434                                 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(0, x));
2435                                 strcat(a, costr);
2436                                 if (x == AST_RTP_DTMF) {
2437                                   /* Indicate we support DTMF...  Not sure about 16, but MSN supports it so dang it, we will too... */
2438                                   snprintf(costr, sizeof costr, "a=fmtp:%d 0-16\r\n",
2439                                            codec);
2440                                   strcat(a, costr);
2441                                 }
2442                         }
2443                 }
2444         }
2445         strcat(m, "\r\n");
2446         strcat(m2, "\r\n");
2447         len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m) + strlen(a);
2448         if (p->vrtp)
2449                 len += strlen(m2) + strlen(a2);
2450         snprintf(costr, sizeof(costr), "%d", len);
2451         add_header(resp, "Content-Type", "application/sdp");
2452         add_header(resp, "Content-Length", costr);
2453         add_line(resp, v);
2454         add_line(resp, o);
2455         add_line(resp, s);
2456         add_line(resp, c);
2457         add_line(resp, t);
2458         add_line(resp, m);
2459         add_line(resp, a);
2460         if (p->vrtp) {
2461                 add_line(resp, m2);
2462                 add_line(resp, a2);
2463         }
2464         return 0;
2465 }
2466
2467 static void copy_request(struct sip_request *dst,struct sip_request *src)
2468 {
2469         long offset;
2470         int x;
2471         offset = ((void *)dst) - ((void *)src);
2472         /* First copy stuff */
2473         memcpy(dst, src, sizeof(*dst));
2474         /* Now fix pointer arithmetic */
2475         for (x=0;x<src->headers;x++)
2476                 dst->header[x] += offset;
2477         for (x=0;x<src->lines;x++)
2478                 dst->line[x] += offset;
2479 }
2480
2481 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
2482 {
2483         struct sip_request resp;
2484         int seqno;
2485         if (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1) {
2486                 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
2487                 return -1;
2488         }
2489         respprep(&resp, p, msg, req);
2490         add_sdp(&resp, p, NULL, NULL);
2491         return send_response(p, &resp, retrans, seqno);
2492 }
2493
2494 static int determine_firstline_parts( struct sip_request *req ) {
2495
2496   char *e, *cmd;
2497   int len;
2498   
2499   cmd= req->header[0];
2500   while(*cmd && (*cmd < 33)) {
2501     cmd++;
2502   }
2503   if (!*cmd) {
2504     return -1;
2505   }
2506   e= cmd;
2507   while(*e && (*e > 32)) {
2508     e++;
2509   }
2510   /* Get the command */
2511   if (*e) {
2512     *e = '\0';
2513     e++;
2514   }
2515   req->rlPart1= cmd;
2516   while( *e && ( *e < 33 ) ) {
2517     e++; 
2518   }
2519   if( !*e ) {
2520     return -1;
2521   }
2522     
2523   if ( !strcasecmp(cmd, "SIP/2.0") ) {
2524     /* We have a response */
2525     req->rlPart2= e;
2526     len= strlen( req->rlPart2 );
2527     if( len < 2 ) { return -1; }
2528     e+= len - 1;
2529     while( *e && *e<33 ) {
2530       e--; 
2531     }
2532     *(++e)= '\0';
2533   } else {
2534     /* We have a request */
2535     if( *e == '<' ) { 
2536       e++;
2537       if( !*e ) { return -1; }  
2538     }
2539     req->rlPart2= e;
2540     if( ( e= strrchr( req->rlPart2, 'S' ) ) == NULL ) {
2541       return -1;
2542     }
2543     while( isspace( *(--e) ) ) {}
2544     if( *e == '>' ) {
2545       *e= '\0';
2546     } else {
2547       *(++e)= '\0';
2548     }
2549   }
2550   return 1;
2551 }
2552
2553 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp, struct ast_rtp *vrtp)
2554 {
2555         struct sip_request req;
2556         if (p->canreinvite == REINVITE_UPDATE)
2557                 reqprep(&req, p, "UPDATE", 0);
2558         else
2559                 reqprep(&req, p, "INVITE", 0);
2560         add_header(&req, "Allow", ALLOWED_METHODS);
2561         add_sdp(&req, p, rtp, vrtp);
2562         /* Use this as the basis */
2563         copy_request(&p->initreq, &req);
2564         parse(&p->initreq);
2565         determine_firstline_parts(&p->initreq);
2566         p->lastinvite = p->ocseq;
2567         p->outgoing = 1;
2568         return send_request(p, &req, 1, p->ocseq);
2569 }
2570
2571 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
2572 {
2573         char stripped[256]="";
2574         char *c, *n;
2575         strncpy(stripped, get_header(req, "Contact"), sizeof(stripped) - 1);
2576         c = strchr(stripped, '<');
2577         if (c) 
2578                 c++;
2579         else
2580                 c = stripped;
2581         n = strchr(c, '>');
2582         if (n)
2583                 *n = '\0';
2584         n = strchr(c, ';');
2585         if (n)
2586                 *n = '\0';
2587         if (c && strlen(c))
2588                 strncpy(p->uri, c, sizeof(p->uri) - 1);
2589 }
2590
2591 static void build_contact(struct sip_pvt *p)
2592 {
2593         /* Construct Contact: header */
2594         if (ourport != 5060)
2595                 snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s@%s:%d>", p->exten, inet_ntoa(p->ourip), ourport);
2596         else
2597                 snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s@%s>", p->exten, inet_ntoa(p->ourip));
2598 }
2599
2600 static void initreqprep(struct sip_request *req, struct sip_pvt *p, char *cmd, char *vxml_url)
2601 {
2602         char invite[256];
2603         char from[256];
2604         char to[256];
2605         char tmp[80];
2606         char cid[256];
2607         char *l = callerid, *n=NULL;
2608         if (p->owner && p->owner->callerid) {
2609                 strcpy(cid, p->owner->callerid);
2610                 ast_callerid_parse(cid, &n, &l);
2611                 if (l) 
2612                         ast_shrink_phone_number(l);
2613                 if (!l || !ast_isphonenumber(l))
2614                                 l = callerid;
2615         }
2616         /* if user want's his callerid restricted */
2617         if (p->restrictcid)
2618                 l = CALLERID_UNKNOWN;
2619         if (!n || !strlen(n))
2620                 n = l;
2621         /* Allow user to be overridden */
2622         if (strlen(p->fromuser))
2623                 l = p->fromuser;
2624
2625         if ((ourport != 5060) && !strlen(p->fromdomain))
2626                 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);
2627         else
2628                 snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=as%08x", n, l, strlen(p->fromdomain) ? p->fromdomain : inet_ntoa(p->ourip), p->tag);
2629
2630         if (strlen(p->username)) {
2631                 if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
2632                         snprintf(invite, sizeof(invite), "sip:%s@%s:%d",p->username, p->tohost, ntohs(p->sa.sin_port));
2633                 } else {
2634                         snprintf(invite, sizeof(invite), "sip:%s@%s",p->username, p->tohost);
2635                 }
2636         } else if (ntohs(p->sa.sin_port) != DEFAULT_SIP_PORT) {
2637                 snprintf(invite, sizeof(invite), "sip:%s:%d", p->tohost, ntohs(p->sa.sin_port));
2638         } else {
2639                 snprintf(invite, sizeof(invite), "sip:%s", p->tohost);
2640         }
2641         strncpy(p->uri, invite, sizeof(p->uri) - 1);
2642         /* If there is a VXML URL append it to the SIP URL */
2643         if (vxml_url)
2644         {
2645                 snprintf(to, sizeof(to), "<%s>;%s", invite, vxml_url);
2646         }
2647         else
2648         {
2649                 snprintf(to, sizeof(to), "<%s>", invite );
2650         }
2651         memset(req, 0, sizeof(struct sip_request));
2652         init_req(req, cmd, invite);
2653         snprintf(tmp, sizeof(tmp), "%d %s", ++p->ocseq, cmd);
2654
2655         add_header(req, "Via", p->via);
2656         /* SLD: FIXME?: do Route: here too?  I think not cos this is the first request.
2657          * OTOH, then we won't have anything in p->route anyway */
2658         add_header(req, "From", from);
2659         strncpy(p->exten, l, sizeof(p->exten) - 1);
2660         build_contact(p);
2661         add_header(req, "To", to);
2662         add_header(req, "Contact", p->our_contact);
2663         add_header(req, "Call-ID", p->callid);
2664         add_header(req, "CSeq", tmp);
2665         add_header(req, "User-Agent", "Asterisk PBX");
2666 }
2667
2668 static int transmit_invite(struct sip_pvt *p, char *cmd, int sdp, char *auth, char *vxml_url, char *distinctive_ring, int init)
2669 {
2670         struct sip_request req;
2671         
2672         if (init)
2673                 initreqprep(&req, p, cmd, vxml_url);
2674         else
2675                 reqprep(&req, p, cmd, 0);
2676                 
2677         if (auth)
2678                 add_header(&req, "Proxy-Authorization", auth);
2679         
2680         if (distinctive_ring)
2681         {
2682                 add_header(&req, "Alert-info",distinctive_ring);
2683         }
2684         add_header(&req, "Allow", ALLOWED_METHODS);
2685         if (sdp) {
2686                 add_sdp(&req, p, NULL, NULL);
2687         } else {
2688                 add_header(&req, "Content-Length", "0");
2689                 add_blank_header(&req);
2690         }
2691
2692         if (!p->initreq.headers) {
2693                 /* Use this as the basis */
2694                 copy_request(&p->initreq, &req);
2695                 parse(&p->initreq);
2696                 determine_firstline_parts(&p->initreq);
2697         }
2698         p->lastinvite = p->ocseq;
2699         return send_request(p, &req, 1, p->ocseq);
2700 }
2701
2702 static int transmit_state_notify(struct sip_pvt *p, int state, int full)
2703 {
2704         char tmp[2000];
2705         char from[256], to[256];
2706         char *t, *c, *a;
2707         char *mfrom, *mto;
2708         struct sip_request req;
2709         char clen[20];
2710         
2711         strncpy(from, get_header(&p->initreq, "From"), sizeof(from)-1);
2712
2713         c = ditch_braces(from);
2714         if (strncmp(c, "sip:", 4)) {
2715                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
2716                 return -1;
2717         }
2718         if ((a = strchr(c, ';'))) {
2719                 *a = '\0';
2720         }
2721         mfrom = c;
2722                 
2723         reqprep(&req, p, "NOTIFY", 0);
2724
2725         if (p->subscribed == 1) {
2726             strncpy(to, get_header(&p->initreq, "To"), sizeof(to)-1);
2727
2728             c = ditch_braces(to);
2729             if (strncmp(c, "sip:", 4)) {
2730                 ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
2731                 return -1;
2732             }
2733             if ((a = strchr(c, ';'))) {
2734                 *a = '\0';
2735             }
2736             mto = c;
2737
2738             add_header(&req, "Content-Type", "application/xpidf+xml");
2739
2740             if ((state==AST_EXTENSION_UNAVAILABLE) || (state==AST_EXTENSION_BUSY))
2741                 state = 2;
2742             else if (state==AST_EXTENSION_INUSE)
2743                 state = 1;
2744             else
2745                 state = 0;
2746             
2747             t = tmp;            
2748             sprintf(t, "<?xml version=\"1.0\"?>\n");
2749             t = tmp + strlen(tmp);
2750             sprintf(t, "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n");
2751             t = tmp + strlen(tmp);
2752             sprintf(t, "<presence>\n");
2753             t = tmp + strlen(tmp);
2754             sprintf(t, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
2755             t = tmp + strlen(tmp);
2756             sprintf(t, "<atom id=\"%s\">\n", p->exten);
2757             t = tmp + strlen(tmp);
2758             sprintf(t, "<address uri=\"%s;user=ip\" priority=\"0,800000\">\n", mto);
2759             t = tmp + strlen(tmp);
2760             sprintf(t, "<status status=\"%s\" />\n", !state ? "open" : (state==1) ? "inuse" : "closed");
2761             t = tmp + strlen(tmp);
2762             sprintf(t, "<msnsubstatus substatus=\"%s\" />\n", !state ? "online" : (state==1) ? "onthephone" : "offline");
2763             t = tmp + strlen(tmp);
2764             sprintf(t, "</address>\n</atom>\n</presence>\n");           
2765         } else {
2766             add_header(&req, "Event", "dialog");
2767             add_header(&req, "Content-Type", "application/dialog-info+xml");
2768         
2769             t = tmp;            
2770             sprintf(t, "<?xml version=\"1.0\"?>\n");
2771             t = tmp + strlen(tmp);
2772             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);
2773             t = tmp + strlen(tmp);
2774             sprintf(t, "<dialog id=\"%s\">\n", p->exten);
2775             t = tmp + strlen(tmp);
2776             sprintf(t, "<state>%s</state>\n", state ? "confirmed" : "terminated");
2777             t = tmp + strlen(tmp);
2778             sprintf(t, "</dialog>\n</dialog-info>\n");  
2779         }
2780
2781         snprintf(clen, sizeof(clen), "%d", strlen(tmp));
2782         add_header(&req, "Content-Length", clen);
2783         add_line(&req, tmp);
2784
2785         return send_request(p, &req, 1, p->ocseq);
2786 }
2787
2788 static int transmit_notify(struct sip_pvt *p, int newmsgs, int oldmsgs)
2789 {
2790         struct sip_request req;
2791         char tmp[256];
2792         char tmp2[256];
2793         char clen[20];
2794         initreqprep(&req, p, "NOTIFY", NULL);
2795         add_header(&req, "Event", "message-summary");
2796         add_header(&req, "Content-Type", notifymime);
2797
2798         snprintf(tmp, sizeof(tmp), "Messages-Waiting: %s\n", newmsgs ? "yes" : "no");
2799         snprintf(tmp2, sizeof(tmp2), "Voicemail: %d/%d\n", newmsgs, oldmsgs);
2800         snprintf(clen, sizeof(clen), "%d", strlen(tmp) + strlen(tmp2));
2801         add_header(&req, "Content-Length", clen);
2802         add_line(&req, tmp);
2803         add_line(&req, tmp2);
2804
2805         if (!p->initreq.headers) {
2806                 /* Use this as the basis */
2807                 copy_request(&p->initreq, &req);
2808                 parse(&p->initreq);
2809                 determine_firstline_parts(&p->initreq);
2810         }
2811
2812         return send_request(p, &req, 1, p->ocseq);
2813 }
2814
2815 static int transmit_register(struct sip_registry *r, char *cmd, char *auth, char *authheader);
2816
2817 static int sip_reregister(void *data) 
2818 {
2819         /* if we are here, we know that we need to reregister. */
2820         struct sip_registry *r=(struct sip_registry *)data;
2821         r->expire = -1;
2822         sip_do_register(r);
2823         return 0;
2824 }
2825
2826
2827 static int sip_do_register(struct sip_registry *r)
2828 {
2829         int res;
2830         ast_mutex_lock(&r->lock);
2831         res=transmit_register(r, "REGISTER", NULL, NULL);
2832         ast_mutex_unlock(&r->lock);
2833         return res;
2834 }
2835
2836 static int sip_reg_timeout(void *data)
2837 {
2838         /* if we are here, our registration timed out, so we'll just do it over */
2839         struct sip_registry *r=data;
2840         struct sip_pvt *p;
2841         int res;
2842         ast_mutex_lock(&r->lock);
2843         ast_log(LOG_NOTICE, "Registration for '%s@%s' timed out, trying again\n", r->username, inet_ntoa(r->addr.sin_addr)); 
2844         if (r->call) {
2845                 /* Unlink us, destroy old call.  Locking is not relevent here because all this happens
2846                    in the single SIP manager thread. */
2847                 p = r->call;
2848                 p->registry = NULL;
2849                 r->call = NULL;
2850                 p->needdestroy = 1;
2851         }
2852         r->regstate=REG_STATE_UNREGISTERED;
2853         r->timeout = -1;
2854         res=transmit_register(r, "REGISTER", NULL, NULL);
2855         ast_mutex_unlock(&r->lock);
2856         return 0;
2857 }
2858
2859 static int transmit_register(struct sip_registry *r, char *cmd, char *auth, char *authheader)
2860 {
2861         struct sip_request req;
2862         char from[256];
2863         char to[256];
2864         char tmp[80];
2865         char via[80];
2866         char addr[80];
2867         struct sip_pvt *p;
2868         /* exit if we are already in process with this registrar ?*/
2869         if ( r == NULL || ((auth==NULL) && (r->regstate==REG_STATE_REGSENT || r->regstate==REG_STATE_AUTHSENT))) {
2870                 ast_log(LOG_NOTICE, "Strange, trying to register when registration already pending\n");
2871                 return 0;
2872         }
2873
2874         if (r->call) {
2875                 if (!auth) {
2876                         ast_log(LOG_WARNING, "Already have a call??\n");
2877                         return 0;
2878                 } else
2879                         p = r->call;
2880         } else {
2881                 if (!r->callid_valid) {
2882                         build_callid(r->callid, sizeof(r->callid), __ourip);
2883                         r->callid_valid = 1;
2884                 }
2885                 p=sip_alloc( r->callid, &r->addr, 0);
2886                 if (!p) {
2887                         ast_log(LOG_WARNING, "Unable to allocate registration call\n");
2888                         return 0;
2889                 }
2890                 p->outgoing = 1;
2891                 r->call=p;
2892                 p->registry=r;
2893                 strncpy(p->peersecret, r->secret, sizeof(p->peersecret)-1);
2894                 if (strlen(r->authuser))
2895                         strncpy(p->peername, r->authuser, sizeof(p->peername)-1);
2896                 else
2897                         strncpy(p->peername, r->username, sizeof(p->peername)-1);
2898                 strncpy(p->username, r->username, sizeof(p->username)-1);
2899                 strncpy(p->exten, r->contact, sizeof(p->exten) - 1);
2900                 /* Always bind to our IP if specified */
2901                 if (bindaddr.sin_addr.s_addr)
2902                         memcpy(&p->ourip, &bindaddr.sin_addr, sizeof(p->ourip));
2903                 build_contact(p);
2904         }
2905
2906         /* set up a timeout */
2907         if (auth==NULL)  {
2908                 if (r->timeout > -1) {
2909                         ast_log(LOG_WARNING, "Still have a timeout, %d\n", r->timeout);
2910                         ast_sched_del(sched, r->timeout);
2911                 }
2912                 r->timeout = ast_sched_add(sched, 20*1000, sip_reg_timeout, r);
2913                 ast_log(LOG_DEBUG, "Scheduled a timeout # %d\n", r->timeout);
2914         }
2915
2916         if (strchr(r->username, '@')) {
2917                 snprintf(from, sizeof(from), "<sip:%s>;tag=as%08x", r->username, p->tag);
2918                 snprintf(to, sizeof(to),     "<sip:%s>", r->username);
2919         } else {
2920                 snprintf(from, sizeof(from), "<sip:%s@%s>;tag=as%08x", r->username, r->hostname, p->tag);
2921                 snprintf(to, sizeof(to),     "<sip:%s@%s>", r->username, r->hostname);
2922         }
2923         
2924         snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
2925         strncpy(p->uri, addr, sizeof(p->uri) - 1);
2926
2927         memset(&req, 0, sizeof(req));
2928         init_req(&req, cmd, addr);
2929
2930         snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, cmd);
2931         p->ocseq = r->ocseq;
2932
2933         /* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
2934         snprintf(via, sizeof(via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
2935         add_header(&req, "Via", via);
2936         add_header(&req, "From", from);
2937         add_header(&req, "To", to);
2938         add_header(&req, "Call-ID", p->callid);
2939         add_header(&req, "CSeq", tmp);
2940         add_header(&req, "User-Agent", "Asterisk PBX");
2941         if (auth) 
2942                 add_header(&req, authheader, auth);
2943
2944         snprintf(tmp, sizeof(tmp), "%d", default_expiry);
2945         add_header(&req, "Expires", tmp);
2946         add_header(&req, "Contact", p->our_contact);
2947         add_header(&req, "Event", "registration");
2948         add_header(&req, "Content-length", "0");
2949         add_blank_header(&req);
2950         copy_request(&p->initreq, &req);
2951         parse(&p->initreq);
2952         determine_firstline_parts(&p->initreq);
2953         r->regstate=auth?REG_STATE_AUTHSENT:REG_STATE_REGSENT;
2954         return send_request(p, &req, 1, p->ocseq);
2955 }
2956
2957 static int transmit_message_with_text(struct sip_pvt *p, char *text)
2958 {
2959         struct sip_request req;
2960         reqprep(&req, p, "MESSAGE", 0);
2961         add_text(&req, text);
2962         return send_request(p, &req, 1, p->ocseq);
2963 }
2964
2965 static int transmit_refer(struct sip_pvt *p, char *dest)
2966 {
2967         struct sip_request req;
2968         char from[256];
2969         char *of, *c;
2970         char referto[256];
2971         if (p->outgoing) 
2972                 of = get_header(&p->initreq, "To");
2973         else
2974                 of = get_header(&p->initreq, "From");
2975         strncpy(from, of, sizeof(from) - 1);
2976         of = ditch_braces(from);
2977         strncpy(p->from,of,sizeof(p->from) - 1);
2978         if (strncmp(of, "sip:", 4)) {
2979                 ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
2980         } else
2981                 of += 4;
2982         /* Get just the username part */
2983         if ((c = strchr(of, '@'))) {
2984                 *c = '\0';
2985                 c++;
2986         }
2987         if (c) {
2988                 snprintf(referto, sizeof(referto), "<sip:%s@%s>", dest, c);
2989         } else {
2990                 snprintf(referto, sizeof(referto), "<sip:%s>", dest);
2991         }
2992
2993         reqprep(&req, p, "REFER", 0);
2994         add_header(&req, "Refer-To", referto);
2995         add_header(&req, "Referred-By", callerid);
2996         return send_request(p, &req, 1, p->ocseq);
2997 }
2998
2999 static int transmit_info_with_digit(struct sip_pvt *p, char digit)
3000 {
3001         struct sip_request req;
3002         reqprep(&req, p, "INFO", 0);
3003         add_digit(&req, digit);
3004         return send_request(p, &req, 1, p->ocseq);
3005 }
3006
3007 static int transmit_request(struct sip_pvt *p, char *msg, int seqno, int reliable)
3008 {
3009         struct sip_request resp;
3010         reqprep(&resp, p, msg, seqno);
3011         add_header(&resp, "Content-Length", "0");
3012         add_blank_header(&resp);
3013         return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
3014 }
3015
3016 static int transmit_request_with_auth(struct sip_pvt *p, char *msg, int seqno, int reliable)
3017 {
3018         struct sip_request resp;
3019         reqprep(&resp, p, msg, seqno);
3020         if (*p->realm)
3021         {
3022                 char digest[256];
3023                 memset(digest,0,sizeof(digest));
3024                 build_reply_digest(p, msg, digest, sizeof(digest));
3025                 add_header(&resp, "Proxy-Authorization", digest);
3026         }
3027
3028         add_header(&resp, "Content-Length", "0");
3029         add_blank_header(&resp);
3030         return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);      
3031 }
3032
3033 static int expire_register(void *data)
3034 {
3035         struct sip_peer *p = data;
3036         memset(&p->addr, 0, sizeof(p->addr));
3037         ast_db_del("SIP/Registry", p->name);
3038         p->expire = -1;
3039         ast_device_state_changed("SIP/%s", p->name);
3040         return 0;
3041 }
3042
3043 static int sip_poke_peer(struct sip_peer *peer);
3044
3045 static void reg_source_db(struct sip_peer *p)
3046 {
3047         char data[80];
3048         struct in_addr in;
3049         char *c, *d;
3050         int expiry;
3051         if (!ast_db_get("SIP/Registry", p->name, data, sizeof(data))) {
3052                 c = strchr(data, ':');
3053                 if (c) {
3054                         *c = '\0';
3055                         c++;
3056                         if (inet_aton(data, &in)) {
3057                                 d = strchr(c, ':');
3058                                 if (d) {
3059                                         *d = '\0';
3060                                         d++;
3061                                         ast_verbose(VERBOSE_PREFIX_3 "SIP Seeding '%s' at %s:%d for %d\n", p->name, 
3062                                                 inet_ntoa(in), atoi(c), atoi(d));
3063                                         sip_poke_peer(p);
3064                                         expiry = atoi(d);
3065                                         memset(&p->addr, 0, sizeof(p->addr));
3066                                         p->addr.sin_family = AF_INET;
3067                                         p->addr.sin_addr = in;
3068                                         p->addr.sin_port = htons(atoi(c));
3069                                         if (p->expire > -1)
3070                                                 ast_sched_del(sched, p->expire);
3071                                         p->expire = ast_sched_add(sched, (expiry + 10) * 1000, expire_register, (void *)p);
3072                                 }                                       
3073                                         
3074                         }
3075                 }
3076         }
3077 }
3078
3079 static int parse_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req)
3080 {
3081         char contact[80]= ""; 
3082         char data[256];
3083         char *expires = get_header(req, "Expires");
3084         int expiry = atoi(expires);
3085         char *c, *n, *pt;
3086         int port;
3087         struct hostent *hp;
3088         struct sockaddr_in oldsin;
3089         if (!strlen(expires)) {
3090                 expires = strstr(get_header(req, "Contact"), "expires=");
3091                 if (expires) {
3092                         if (sscanf(expires + 8, "%d;", &expiry) != 1)
3093                                 expiry = default_expiry;
3094                 } else {
3095                         /* Nothing has been specified */
3096                         expiry = default_expiry;
3097                 }
3098         }
3099         /* Look for brackets */
3100         strncpy(contact, get_header(req, "Contact"), sizeof(contact) - 1);
3101         c = contact;
3102         
3103         if ((n=strchr(c, '<'))) {
3104                 c = n + 1;
3105                 n = strchr(c, '>');
3106                 /* Lose the part after the > */
3107 &n