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