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