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