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