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