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