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