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