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