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