Add white space condensing to pedantic mode of chan_sip.
[asterisk/asterisk.git] / channels / chan_sip.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Implementation of Session Initiation Protocol
5  * 
6  * Copyright (C) 1999, Mark Spencer
7  *
8  * Mark Spencer <markster@linux-support.net>
9  *
10  * This program is free software, distributed under the terms of
11  * the GNU General Public License
12  */
13
14 #include <stdio.h>
15 #include <ctype.h>
16 #include <pthread.h>
17 #include <string.h>
18 #include <asterisk/lock.h>
19 #include <asterisk/channel.h>
20 #include <asterisk/channel_pvt.h>
21 #include <asterisk/config.h>
22 #include <asterisk/logger.h>
23 #include <asterisk/module.h>
24 #include <asterisk/pbx.h>
25 #include <asterisk/options.h>
26 #include <asterisk/lock.h>
27 #include <asterisk/sched.h>
28 #include <asterisk/io.h>
29 #include <asterisk/rtp.h>
30 #include <asterisk/acl.h>
31 #include <asterisk/callerid.h>
32 #include <asterisk/cli.h>
33 #include <asterisk/md5.h>
34 #include <asterisk/app.h>
35 #include <asterisk/musiconhold.h>
36 #include <asterisk/dsp.h>
37 #include <asterisk/parking.h>
38 #include <asterisk/acl.h>
39 #include <asterisk/srv.h>
40 #include <asterisk/astdb.h>
41 #include <asterisk/causes.h>
42 #include <sys/socket.h>
43 #include <sys/ioctl.h>
44 #include <net/if.h>
45 #include <errno.h>
46 #include <unistd.h>
47 #include <stdlib.h>
48 #include <fcntl.h>
49 #include <netdb.h>
50 #include <arpa/inet.h>
51 #include <pthread.h>
52 #include <signal.h>
53 #include <sys/signal.h>
54 #include <netinet/in_systm.h>
55 #include <netinet/ip.h>
56
57 #ifdef SIP_MYSQL_FRIENDS
58 #define MYSQL_FRIENDS
59 #include <mysql/mysql.h>
60 #endif
61
62 #define VIDEO_CODEC_MASK        0x1fc0000 /* Video codecs from H.261 thru AST_FORMAT_MAX_VIDEO */
63 #ifndef IPTOS_MINCOST
64 #define IPTOS_MINCOST 0x02
65 #endif
66
67 /* #define VOCAL_DATA_HACK */
68
69 #define SIPDUMPER
70 #define DEFAULT_DEFAULT_EXPIRY  120
71 #define DEFAULT_MAX_EXPIRY      3600
72 #define EXPIRY_GUARD_SECS       15
73
74 #define CALLERID_UNKNOWN        "Unknown"
75
76 #define SIP_DTMF_RFC2833        (1 << 0)
77 #define SIP_DTMF_INBAND         (1 << 1)
78 #define SIP_DTMF_INFO           (1 << 2)
79
80 static int max_expiry = DEFAULT_MAX_EXPIRY;
81 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
82
83 #define DEFAULT_MAXMS           2000            /* Must be faster than 2 seconds by default */
84 #define DEFAULT_FREQ_OK         60 * 1000               /* How often to check for the host to be up */
85 #define DEFAULT_FREQ_NOTOK      10 * 1000               /* How often to check, if the host is down... */
86
87 #define DEFAULT_RETRANS         1000                    /* How frequently to retransmit */
88 #define MAX_RETRANS                     5                               /* Try only 5 times for retransmissions */
89
90 #ifdef MYSQL_FRIENDS
91 static ast_mutex_t mysqllock = AST_MUTEX_INITIALIZER;
92 static MYSQL *mysql;
93 static char mydbuser[80];
94 static char mydbpass[80];
95 static char mydbhost[80];
96 static char mydbname[80];
97 #endif
98
99 static char *desc = "Session Initiation Protocol (SIP)";
100 static char *type = "SIP";
101 static char *tdesc = "Session Initiation Protocol (SIP)";
102 static char *config = "sip.conf";
103
104 #define DEFAULT_SIP_PORT        5060    /* From RFC 2543 */
105 #define SIP_MAX_PACKET  1500            /* Also from RFC 2543, should sub headers tho */
106
107 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER"
108
109 static char context[AST_MAX_EXTENSION] = "default";
110
111 static char language[MAX_LANGUAGE] = "";
112
113 static char callerid[AST_MAX_EXTENSION] = "asterisk";
114
115 static char fromdomain[AST_MAX_EXTENSION] = "";
116
117 static char notifymime[AST_MAX_EXTENSION] = "application/simple-message-summary";
118
119 static int srvlookup = 0;
120
121 static int pedanticsipchecking = 0;
122
123 static int autocreatepeer = 0;
124
125 static int 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                 ast_setstate(tmp, state);
1561                 if (state == AST_STATE_RING)
1562                         tmp->rings = 1;
1563                 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
1564                 tmp->writeformat = fmt;
1565                 tmp->pvt->rawwriteformat = fmt;
1566                 tmp->readformat = fmt;
1567                 tmp->pvt->rawreadformat = fmt;
1568                 tmp->pvt->pvt = i;
1569                 tmp->pvt->send_text = sip_sendtext;
1570                 tmp->pvt->call = sip_call;
1571                 tmp->pvt->hangup = sip_hangup;
1572                 tmp->pvt->answer = sip_answer;
1573                 tmp->pvt->read = sip_read;
1574                 tmp->pvt->write = sip_write;
1575                 tmp->pvt->write_video = sip_write;
1576                 tmp->pvt->indicate = sip_indicate;
1577                 tmp->pvt->transfer = sip_transfer;
1578                 tmp->pvt->fixup = sip_fixup;
1579                 tmp->pvt->send_digit = sip_senddigit;
1580
1581                 tmp->pvt->bridge = ast_rtp_bridge;
1582
1583                 tmp->callgroup = i->callgroup;
1584                 tmp->pickupgroup = i->pickupgroup;
1585                 tmp->restrictcid = i->restrictcid;
1586                 if (strlen(i->accountcode))
1587                         strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
1588                 if (i->amaflags)
1589                         tmp->amaflags = i->amaflags;
1590                 if (strlen(i->language))
1591                         strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
1592                 i->owner = tmp;
1593                 ast_mutex_lock(&usecnt_lock);
1594                 usecnt++;
1595                 ast_mutex_unlock(&usecnt_lock);
1596                 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
1597                 strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
1598                 if (strlen(i->callerid))
1599                         tmp->callerid = strdup(i->callerid);
1600                 if (strlen(i->rdnis))
1601                         tmp->rdnis = strdup(i->rdnis);
1602                 if (strlen(i->exten) && strcmp(i->exten, "s"))
1603                         tmp->dnid = strdup(i->exten);
1604                 tmp->priority = 1;
1605                 if (strlen(i->domain)) {
1606                         pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
1607                 }
1608                                                 
1609                 if (state != AST_STATE_DOWN) {
1610                         if (ast_pbx_start(tmp)) {
1611                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
1612                                 ast_hangup(tmp);
1613                                 tmp = NULL;
1614                         }
1615                 }
1616         } else
1617                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
1618         return tmp;
1619 }
1620
1621 static struct cfalias {
1622         char *fullname;
1623         char *shortname;
1624 } aliases[] = {
1625         { "Content-Type", "c" },
1626         { "Content-Encoding", "e" },
1627         { "From", "f" },
1628         { "Call-ID", "i" },
1629         { "Contact", "m" },
1630         { "Content-Length", "l" },
1631         { "Subject", "s" },
1632         { "To", "t" },
1633         { "Via", "v" },
1634 };
1635
1636 static char* get_sdp_by_line(char* line, char *name, int nameLen) {
1637   if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
1638     char* r = line + nameLen + 1;
1639     while (*r && (*r < 33)) ++r;
1640     return r;
1641   }
1642
1643   return "";
1644 }
1645
1646 static char *get_sdp(struct sip_request *req, char *name) {
1647   int x;
1648   int len = strlen(name);
1649   char *r;
1650
1651   for (x=0; x<req->lines; x++) {
1652     r = get_sdp_by_line(req->line[x], name, len);
1653     if (r[0] != '\0') return r;
1654   }
1655   return "";
1656 }
1657
1658 static void sdpLineNum_iterator_init(int* iterator) {
1659   *iterator = 0;
1660 }
1661
1662 static char* get_sdp_iterate(int* iterator,
1663                              struct sip_request *req, char *name) {
1664   int len = strlen(name);
1665   char *r;
1666   while (*iterator < req->lines) {
1667     r = get_sdp_by_line(req->line[(*iterator)++], name, len);
1668     if (r[0] != '\0') return r;
1669   }
1670   return "";
1671 }
1672
1673 static char *__get_header(struct sip_request *req, char *name, int *start)
1674 {
1675         int x;
1676         int len = strlen(name);
1677         char *r;
1678         for (x=*start;x<req->headers;x++) {
1679                 if (!strncasecmp(req->header[x], name, len) && 
1680                                 (req->header[x][len] == ':')) {
1681                                         r = req->header[x] + len + 1;
1682                                         while(*r && (*r < 33))
1683                                                         r++;
1684                                         *start = x+1;
1685                                         return r;
1686                 }
1687         }
1688         /* Try aliases */
1689         for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++) 
1690                 if (!strcasecmp(aliases[x].fullname, name))
1691                         return __get_header(req, aliases[x].shortname, start);
1692
1693         /* Don't return NULL, so get_header is always a valid pointer */
1694         return "";
1695 }
1696
1697 static char *get_header(struct sip_request *req, char *name)
1698 {
1699         int start = 0;
1700         return __get_header(req, name, &start);
1701 }
1702
1703 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p)
1704 {
1705         /* Retrieve audio/etc from channel.  Assumes p->lock is already held. */
1706         struct ast_frame *f;
1707         static struct ast_frame null_frame = { AST_FRAME_NULL, };
1708         switch(ast->fdno) {
1709         case 0:
1710                 f = ast_rtp_read(p->rtp);
1711                 break;
1712         case 1:
1713                 f = ast_rtcp_read(p->rtp);
1714                 break;
1715         case 2:
1716                 f = ast_rtp_read(p->vrtp);
1717                 break;
1718         case 3:
1719                 f = ast_rtcp_read(p->vrtp);
1720                 break;
1721         default:
1722                 f = &null_frame;
1723         }
1724         /* Don't send RFC2833 if we're not supposed to */
1725         if (f && (f->frametype == AST_FRAME_DTMF) && !(p->dtmfmode & SIP_DTMF_RFC2833))
1726                 return &null_frame;
1727         if (p->owner) {
1728                 /* We already hold the channel lock */
1729                 if (f->frametype == AST_FRAME_VOICE) {
1730                         if (f->subclass != p->owner->nativeformats) {
1731                                 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
1732                                 p->owner->nativeformats = f->subclass;
1733                                 ast_set_read_format(p->owner, p->owner->readformat);
1734                                 ast_set_write_format(p->owner, p->owner->writeformat);
1735                         }
1736             if ((p->dtmfmode & SIP_DTMF_INBAND) && p->vad) {
1737                    f = ast_dsp_process(p->owner,p->vad,f);
1738             }
1739                 }
1740         }
1741         return f;
1742 }
1743
1744 static struct ast_frame *sip_read(struct ast_channel *ast)
1745 {
1746         struct ast_frame *fr;
1747         struct sip_pvt *p = ast->pvt->pvt;
1748         ast_mutex_lock(&p->lock);
1749         fr = sip_rtp_read(ast, p);
1750         ast_mutex_unlock(&p->lock);
1751         return fr;
1752 }
1753
1754 static void build_callid(char *callid, int len, struct in_addr ourip)
1755 {
1756         int res;
1757         int val;
1758         int x;
1759         for (x=0;x<4;x++) {
1760                 val = rand();
1761                 res = snprintf(callid, len, "%08x", val);
1762                 len -= res;
1763                 callid += res;
1764         }
1765         /* It's not important that we really use our right IP here... */
1766         snprintf(callid, len, "@%s", inet_ntoa(ourip));
1767 }
1768
1769 static struct sip_pvt *sip_alloc(char *callid, struct sockaddr_in *sin, int useglobalnat)
1770 {
1771         struct sip_pvt *p;
1772
1773         p = malloc(sizeof(struct sip_pvt));
1774         if (!p)
1775                 return NULL;
1776         /* Keep track of stuff */
1777         memset(p, 0, sizeof(struct sip_pvt));
1778         p->initid = -1;
1779         p->autokillid = -1;
1780         p->stateid = -1;
1781         p->rtp = ast_rtp_new(sched, io, 1, 0);
1782         if (videosupport)
1783                 p->vrtp = ast_rtp_new(sched, io, 1, 0);
1784         p->branch = rand();     
1785         p->tag = rand();
1786         
1787         /* Start with 101 instead of 1 */
1788         p->ocseq = 101;
1789         if (!p->rtp) {
1790                 ast_log(LOG_WARNING, "Unable to create RTP session: %s\n", strerror(errno));
1791                 free(p);
1792                 return NULL;
1793         }
1794         ast_rtp_settos(p->rtp, tos);
1795         if (p->vrtp)
1796                 ast_rtp_settos(p->vrtp, tos);
1797         if (useglobalnat && sin) {
1798                 /* Setup NAT structure according to global settings if we have an address */
1799                 p->nat = globalnat;
1800                 memcpy(&p->recv, sin, sizeof(p->recv));
1801                 ast_rtp_setnat(p->rtp, p->nat);
1802                 if (p->vrtp)
1803                         ast_rtp_setnat(p->vrtp, p->nat);
1804         }
1805         ast_mutex_init(&p->lock);
1806
1807         if (sin) {
1808                 memcpy(&p->sa, sin, sizeof(p->sa));
1809                 if (ast_sip_ouraddrfor(&p->sa.sin_addr,&p->ourip))
1810                         memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
1811         } else {
1812                 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
1813         }
1814         /* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
1815         snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
1816         if (!callid)
1817                 build_callid(p->callid, sizeof(p->callid), p->ourip);
1818         else
1819                 strncpy(p->callid, callid, sizeof(p->callid) - 1);
1820         /* Assume reinvite OK and via INVITE */
1821         p->canreinvite = globalcanreinvite;
1822         p->dtmfmode = globaldtmfmode;
1823         p->capability = capability;
1824         if (p->dtmfmode & SIP_DTMF_RFC2833)
1825                 p->noncodeccapability |= AST_RTP_DTMF;
1826         strncpy(p->context, context, sizeof(p->context) - 1);
1827         strncpy(p->fromdomain, fromdomain, sizeof(p->fromdomain) - 1);
1828         /* Add to list */
1829         ast_mutex_lock(&iflock);
1830         p->next = iflist;
1831         iflist = p;
1832         ast_mutex_unlock(&iflock);
1833         if (option_debug)
1834                 ast_log(LOG_DEBUG, "Allocating new SIP call for %s\n", callid);
1835         return p;
1836 }
1837
1838 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin)
1839 {
1840         struct sip_pvt *p;
1841         char *callid;
1842         char tmp[256] = "";
1843         char *cmd;
1844         char *tag = "", *c;
1845         int themisfrom;
1846         callid = get_header(req, "Call-ID");
1847
1848         if (pedanticsipchecking) {
1849                 /* In principle Call-ID's uniquely identify a call, however some vendors
1850                    (i.e. Pingtel) send multiple calls with the same Call-ID and different
1851                    tags in order to simplify billing.  The RFC does state that we have to
1852                    compare tags in addition to the call-id, but this generate substantially
1853                    more overhead which is totally unnecessary for the vast majority of sane
1854                    SIP implementations, and thus Asterisk does not enable this behavior
1855                    by default. Short version: You'll need this option to support conferencing
1856                    on the pingtel */
1857                 strncpy(tmp, req->header[0], sizeof(tmp) - 1);
1858                 cmd = tmp;
1859                 c = strchr(tmp, ' ');
1860                 if (c)
1861                         *c = '\0';
1862                 if (!strcasecmp(cmd, "SIP/2.0")) {
1863                         themisfrom = 0;
1864                 } else {
1865                         themisfrom = 1;
1866                 }
1867                 if (themisfrom)
1868                         strncpy(tmp, get_header(req, "From"), sizeof(tmp) - 1);
1869                 else
1870                         strncpy(tmp, get_header(req, "To"), sizeof(tmp) - 1);
1871                 tag = strstr(tmp, "tag=");
1872                 if (tag) {
1873                         tag += 4;
1874                         c = strchr(tag, ';');
1875                         if (c)
1876                                 *c = '\0';
1877                 }
1878                         
1879         }
1880                 
1881         if (!strlen(callid)) {
1882                 ast_log(LOG_WARNING, "Call missing call ID from '%s'\n", inet_ntoa(sin->sin_addr));
1883                 return NULL;
1884         }
1885         ast_mutex_lock(&iflock);
1886         p = iflist;
1887         while(p) {
1888                 if (!strcmp(p->callid, callid) && 
1889                         (!pedanticsipchecking || !tag || !strlen(p->theirtag) || !strcmp(p->theirtag, tag))) {
1890                         /* Found the call */
1891                         ast_mutex_lock(&p->lock);
1892                         ast_mutex_unlock(&iflock);
1893                         return p;
1894                 }
1895                 p = p->next;
1896         }
1897         ast_mutex_unlock(&iflock);
1898         p = sip_alloc(callid, sin, 1);
1899         if (p)
1900                 ast_mutex_lock(&p->lock);
1901         return p;
1902 }
1903
1904 static int sip_register(char *value, int lineno)
1905 {
1906         struct sip_registry *reg;
1907         char copy[256] = "";
1908         char *username=NULL, *hostname=NULL, *secret=NULL, *authuser=NULL;
1909         char *porta=NULL;
1910         char *contact=NULL;
1911         char *stringp=NULL;
1912         
1913         struct hostent *hp;
1914         struct ast_hostent ahp;
1915         if (!value)
1916                 return -1;
1917         strncpy(copy, value, sizeof(copy)-1);
1918         stringp=copy;
1919         username = stringp;
1920         hostname = strrchr(stringp, '@');
1921         if (hostname) {
1922                 *hostname = '\0';
1923                 hostname++;
1924         }
1925         if (!username || !strlen(username) || !hostname || !strlen(hostname)) {
1926                 ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port][/contact] at line %d", lineno);
1927                 return -1;
1928         }
1929         stringp=username;
1930         username = strsep(&stringp, ":");
1931         if (username) {
1932                 secret = strsep(&stringp, ":");
1933                 if (secret) 
1934                         authuser = strsep(&stringp, ":");
1935         }
1936         stringp = hostname;
1937         hostname = strsep(&stringp, "/");
1938         if (hostname) 
1939                 contact = strsep(&stringp, "/");
1940         if (!contact || !strlen(contact))
1941                 contact = "s";
1942         stringp=hostname;
1943         hostname = strsep(&stringp, ":");
1944         porta = strsep(&stringp, ":");
1945         
1946         if (porta && !atoi(porta)) {
1947                 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
1948                 return -1;
1949         }
1950         hp = ast_gethostbyname(hostname, &ahp);
1951         if (!hp) {
1952                 ast_log(LOG_WARNING, "Host '%s' not found at line %d\n", hostname, lineno);
1953                 return -1;
1954         }
1955         reg = malloc(sizeof(struct sip_registry));
1956         if (reg) {
1957                 memset(reg, 0, sizeof(struct sip_registry));
1958                 strncpy(reg->contact, contact, sizeof(reg->contact) - 1);
1959                 if (username)
1960                         strncpy(reg->username, username, sizeof(reg->username)-1);
1961                 if (hostname)
1962                         strncpy(reg->hostname, hostname, sizeof(reg->hostname)-1);
1963                 if (authuser)
1964                         strncpy(reg->authuser, authuser, sizeof(reg->authuser)-1);
1965                 if (secret)
1966                         strncpy(reg->secret, secret, sizeof(reg->secret)-1);
1967                 reg->expire = -1;
1968                 reg->timeout =  -1;
1969                 reg->refresh = default_expiry;
1970                 reg->addr.sin_family = AF_INET;
1971                 memcpy(&reg->addr.sin_addr, hp->h_addr, sizeof(&reg->addr.sin_addr));
1972                 reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(DEFAULT_SIP_PORT);
1973                 reg->callid_valid = 0;
1974                 reg->ocseq = 101;
1975                 ast_mutex_lock(&regl.lock);
1976                 reg->next = regl.registrations;
1977                 regl.registrations = reg;
1978                 ast_mutex_unlock(&regl.lock);
1979         } else {
1980                 ast_log(LOG_ERROR, "Out of memory\n");
1981                 return -1;
1982         }
1983         return 0;
1984 }
1985
1986 static int lws2sws(char *msgbuf, int len) 
1987
1988         int h = 0, t = 0; 
1989         int lws = 0; 
1990
1991         for (; h < len;) { 
1992                 /* Eliminate all CRs */ 
1993                 if (msgbuf[h] == '\r') { 
1994                         h++; 
1995                         continue; 
1996                 } 
1997                 /* Check for end-of-line */ 
1998                 if (msgbuf[h] == '\n') { 
1999                 /* Check for end-of-message */ 
2000                         if (h + 1 == len) 
2001                         break; 
2002                 /* Check for a continuation line */ 
2003                 if (msgbuf[h + 1] == ' ') { 
2004                 /* Merge continuation line */ 
2005                         h++; 
2006                         continue; 
2007                 } 
2008                 /* Propagate LF and start new line */ 
2009                 msgbuf[t++] = msgbuf[h++]; 
2010                 lws = 0;
2011                 continue; 
2012         } 
2013
2014         if (msgbuf[h] == ' ' || msgbuf[h] == '\t') { 
2015                 if (lws) { 
2016                         h++; 
2017                         continue; 
2018                 } 
2019                 msgbuf[t++] = msgbuf[h++]; 
2020                 lws = 1; 
2021                 continue; 
2022         } 
2023         msgbuf[t++] = msgbuf[h++]; 
2024         if (lws) 
2025                 lws = 0; 
2026         } 
2027         msgbuf[t] = '\0'; 
2028         return t; 
2029 }
2030
2031 static void parse(struct sip_request *req)
2032 {
2033         /* Divide fields by NULL's */
2034         char *c;
2035         int f = 0;
2036         c = req->data;
2037
2038         /* First header starts immediately */
2039         req->header[f] = c;
2040         while(*c) {
2041                 if (*c == '\n') {
2042                         /* We've got a new header */
2043                         *c = 0;
2044
2045 #if 0
2046                         printf("Header: %s (%d)\n", req->header[f], strlen(req->header[f]));
2047 #endif                  
2048                         if (!strlen(req->header[f])) {
2049                                 /* Line by itself means we're now in content */
2050                                 c++;
2051                                 break;
2052                         }
2053                         if (f >= SIP_MAX_HEADERS - 1) {
2054                                 ast_log(LOG_WARNING, "Too many SIP headers...\n");
2055                         } else
2056                                 f++;
2057                         req->header[f] = c + 1;
2058                 } else if (*c == '\r') {
2059                         /* Ignore but eliminate \r's */
2060                         *c = 0;
2061                 }
2062                 c++;
2063         }
2064         /* Check for last header */
2065         if (strlen(req->header[f])) 
2066                 f++;
2067         req->headers = f;
2068         /* Now we process any mime content */
2069         f = 0;
2070         req->line[f] = c;
2071         while(*c) {
2072                 if (*c == '\n') {
2073                         /* We've got a new line */
2074                         *c = 0;
2075 #if 0
2076                         printf("Line: %s (%d)\n", req->line[f], strlen(req->line[f]));
2077 #endif                  
2078                         if (f >= SIP_MAX_LINES - 1) {
2079                                 ast_log(LOG_WARNING, "Too many SDP lines...\n");
2080                         } else
2081                                 f++;
2082                         req->line[f] = c + 1;
2083                 } else if (*c == '\r') {
2084                         /* Ignore and eliminate \r's */
2085                         *c = 0;
2086                 }
2087                 c++;
2088         }
2089         /* Check for last line */
2090         if (strlen(req->line[f])) 
2091                 f++;
2092         req->lines = f;
2093         if (sipdebug)
2094                 ast_verbose("%d headers, %d lines\n", req->headers, req->lines);
2095         if (*c) 
2096                 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
2097 }
2098
2099 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
2100 {
2101         char *m;
2102         char *c;
2103         char *a;
2104         char host[258];
2105         int len = -1;
2106         int portno=0;
2107         int vportno=0;
2108         int peercapability, peernoncodeccapability;
2109         int vpeercapability=0, vpeernoncodeccapability=0;
2110         struct sockaddr_in sin;
2111         char *codecs;
2112         struct hostent *hp;
2113         struct ast_hostent ahp;
2114         int codec;
2115         int iterator;
2116         int sendonly = 0;
2117         int x;
2118
2119         /* Get codec and RTP info from SDP */
2120         if (strcasecmp(get_header(req, "Content-Type"), "application/sdp")) {
2121                 ast_log(LOG_NOTICE, "Content is '%s', not 'application/sdp'\n", get_header(req, "Content-Type"));
2122                 return -1;
2123         }
2124         m = get_sdp(req, "m");
2125         c = get_sdp(req, "c");
2126         if (!strlen(m) || !strlen(c)) {
2127                 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
2128                 return -1;
2129         }
2130         if (sscanf(c, "IN IP4 %256s", host) != 1) {
2131                 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
2132                 return -1;
2133         }
2134         /* XXX This could block for a long time, and block the main thread! XXX */
2135         hp = ast_gethostbyname(host, &ahp);
2136         if (!hp) {
2137                 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
2138                 return -1;
2139         }
2140         sdpLineNum_iterator_init(&iterator);
2141         while ((m = get_sdp_iterate(&iterator, req, "m"))[0] != '\0') {
2142                 if ((sscanf(m, "audio %d RTP/AVP %n", &x, &len) == 1)) {
2143                         portno = x;
2144                         /* Scan through the RTP payload types specified in a "m=" line: */
2145                         ast_rtp_pt_clear(p->rtp);
2146                         codecs = m + len;
2147                         while(strlen(codecs)) {
2148                                 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
2149                                         ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
2150                                         return -1;
2151                                 }
2152                                 if (sipdebug)
2153                                         ast_verbose("Found audio format %s\n", ast_getformatname(codec));
2154                                 ast_rtp_set_m_type(p->rtp, codec);
2155                                 codecs += len;
2156                                 /* Skip over any whitespace */
2157                                 while(*codecs && (*codecs < 33)) codecs++;
2158                         }
2159                 }
2160                 if (p->vrtp)
2161                         ast_rtp_pt_clear(p->vrtp);  /* Must be cleared in case no m=video line exists */
2162
2163                 if (p->vrtp && (sscanf(m, "video %d RTP/AVP %n", &x, &len) == 1)) {
2164                         vportno = x;
2165                         /* Scan through the RTP payload types specified in a "m=" line: */
2166                         codecs = m + len;
2167                         while(strlen(codecs)) {
2168                                 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
2169                                         ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
2170                                         return -1;
2171                                 }
2172                                 if (sipdebug)
2173                                         ast_verbose("Found video format %s\n", ast_getformatname(codec));
2174                                 ast_rtp_set_m_type(p->vrtp, codec);
2175                                 codecs += len;
2176                                 /* Skip over any whitespace */
2177                                 while(*codecs && (*codecs < 33)) codecs++;
2178                         }
2179                 }
2180         }
2181         sin.sin_family = AF_INET;
2182         memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
2183         /* Setup audio port number */
2184         sin.sin_port = htons(portno);
2185         if (p->rtp && sin.sin_port)
2186                 ast_rtp_set_peer(p->rtp, &sin);
2187         /* Setup video port number */
2188         sin.sin_port = htons(vportno);
2189         if (p->vrtp && sin.sin_port)
2190                 ast_rtp_set_peer(p->vrtp, &sin);
2191 #if 0
2192         printf("Peer RTP is at port %s:%d\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
2193 #endif  
2194         /* Next, scan through each "a=rtpmap:" line, noting each
2195          * specified RTP payload type (with corresponding MIME subtype):
2196          */
2197         sdpLineNum_iterator_init(&iterator);
2198         while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
2199       char* mimeSubtype = ast_strdupa(a); /* ensures we have enough space */
2200           if (!strcasecmp(a, "sendonly")) {
2201                 sendonly=1;
2202                 continue;
2203           }
2204           if (!strcasecmp(a, "sendrecv")) {
2205                 sendonly=0;
2206           }
2207           if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) != 2) continue;
2208           if (sipdebug)
2209                 ast_verbose("Found description format %s\n", mimeSubtype);
2210           /* Note: should really look at the 'freq' and '#chans' params too */
2211           ast_rtp_set_rtpmap_type(p->rtp, codec, "audio", mimeSubtype);
2212           if (p->vrtp)
2213                   ast_rtp_set_rtpmap_type(p->vrtp, codec, "video", mimeSubtype);
2214         }
2215
2216         /* Now gather all of the codecs that were asked for: */
2217         ast_rtp_get_current_formats(p->rtp,
2218                                 &peercapability, &peernoncodeccapability);
2219         if (p->vrtp)
2220                 ast_rtp_get_current_formats(p->vrtp,
2221                                 &vpeercapability, &vpeernoncodeccapability);
2222         p->jointcapability = p->capability & (peercapability | vpeercapability);
2223         p->noncodeccapability = noncodeccapability & (peernoncodeccapability | vpeernoncodeccapability);
2224         
2225         if (sipdebug) {
2226                 ast_verbose("Capabilities: us - %d, them - %d/%d, combined - %d\n",
2227                             p->capability, peercapability, vpeercapability, p->jointcapability);
2228                 ast_verbose("Non-codec capabilities: us - %d, them - %d, combined - %d\n",
2229                             noncodeccapability, peernoncodeccapability,
2230                             p->noncodeccapability);
2231         }
2232         if (!p->jointcapability) {
2233                 ast_log(LOG_WARNING, "No compatible codecs!\n");
2234                 return -1;
2235         }
2236         if (p->owner) {
2237                 if (!(p->owner->nativeformats & p->jointcapability)) {
2238                         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);
2239                         p->owner->nativeformats = sip_codec_choose(p->jointcapability);
2240                         ast_set_read_format(p->owner, p->owner->readformat);
2241                         ast_set_write_format(p->owner, p->owner->writeformat);
2242                 }
2243                 if (p->owner->bridge) {
2244                         /* Turn on/off music on hold if we are holding/unholding */
2245                         if (sin.sin_addr.s_addr && !sendonly) {
2246                                 ast_moh_stop(p->owner->bridge);
2247                         } else {
2248                                 ast_moh_start(p->owner->bridge, NULL);
2249                         }
2250                 }
2251         }
2252         return 0;
2253         
2254 }
2255
2256 static int add_header(struct sip_request *req, char *var, char *value)
2257 {
2258         if (req->len >= sizeof(req->data) - 4) {
2259                 ast_log(LOG_WARNING, "Out of space, can't add anymore (%s:%s)\n", var, value);
2260                 return -1;
2261         }
2262         if (req->lines) {
2263                 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
2264                 return -1;
2265         }
2266         req->header[req->headers] = req->data + req->len;
2267         snprintf(req->header[req->headers], sizeof(req->data) - req->len - 4, "%s: %s\r\n", var, value);
2268         req->len += strlen(req->header[req->headers]);
2269         if (req->headers < SIP_MAX_HEADERS)
2270                 req->headers++;
2271         else {
2272                 ast_log(LOG_WARNING, "Out of header space\n");
2273                 return -1;
2274         }
2275         return 0;       
2276 }
2277
2278 static int add_blank_header(struct sip_request *req)
2279 {
2280         if (req->len >= sizeof(req->data) - 4) {
2281                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
2282                 return -1;
2283         }
2284         if (req->lines) {
2285                 ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
2286                 return -1;
2287         }
2288         req->header[req->headers] = req->data + req->len;
2289         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "\r\n");
2290         req->len += strlen(req->header[req->headers]);
2291         if (req->headers < SIP_MAX_HEADERS)
2292                 req->headers++;
2293         else {
2294                 ast_log(LOG_WARNING, "Out of header space\n");
2295                 return -1;
2296         }
2297         return 0;       
2298 }
2299
2300 static int add_line(struct sip_request *req, char *line)
2301 {
2302         if (req->len >= sizeof(req->data) - 4) {
2303                 ast_log(LOG_WARNING, "Out of space, can't add anymore\n");
2304                 return -1;
2305         }
2306         if (!req->lines) {
2307                 /* Add extra empty return */
2308                 snprintf(req->data + req->len, sizeof(req->data) - req->len, "\r\n");
2309                 req->len += strlen(req->data + req->len);
2310         }
2311         req->line[req->lines] = req->data + req->len;
2312         snprintf(req->line[req->lines], sizeof(req->data) - req->len, "%s", line);
2313         req->len += strlen(req->line[req->lines]);
2314         if (req->lines < SIP_MAX_LINES)
2315                 req->lines++;
2316         else {
2317                 ast_log(LOG_WARNING, "Out of line space\n");
2318                 return -1;
2319         }
2320         return 0;       
2321 }
2322
2323 static int copy_header(struct sip_request *req, struct sip_request *orig, char *field)
2324 {
2325         char *tmp;
2326         tmp = get_header(orig, field);
2327         if (strlen(tmp)) {
2328                 /* Add what we're responding to */
2329                 return add_header(req, field, tmp);
2330         }
2331         ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
2332         return -1;
2333 }
2334
2335 static int copy_all_header(struct sip_request *req, struct sip_request *orig, char *field)
2336 {
2337         char *tmp;
2338         int start = 0;
2339         int copied = 0;
2340         for (;;) {
2341                 tmp = __get_header(orig, field, &start);
2342                 if (strlen(tmp)) {
2343                         /* Add what we're responding to */
2344                         add_header(req, field, tmp);
2345                         copied++;
2346                 } else
2347                         break;
2348         }
2349         return copied ? 0 : -1;
2350 }
2351
2352 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, struct sip_request *orig, char *field)
2353 {
2354         char *tmp;
2355         int start = 0;
2356         int copied = 0;
2357         char new[256];
2358         for (;;) {
2359                 tmp = __get_header(orig, field, &start);
2360                 if (strlen(tmp)) {
2361                         if (!copied && p->nat) {
2362 #ifdef THE_SIP_AUTHORS_CAN_SUCK_MY_GONADS
2363                                 /* SLD: FIXME: Nice try, but the received= should not have a port */
2364                                 /* SLD: FIXME: See RFC2543 BNF in Section 6.40.5 */
2365                                 /* MAS: Yup, RFC says you can't do it.  No way to indicate PAT...
2366                                    good job fellas. */
2367                                 if (ntohs(p->recv.sin_port) != DEFAULT_SIP_PORT)
2368                                         snprintf(new, sizeof(new), "%s;received=%s:%d", tmp, inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
2369                                 else
2370 #endif                          
2371                                         snprintf(new, sizeof(new), "%s;received=%s", tmp, inet_ntoa(p->recv.sin_addr));
2372                                 add_header(req, field, new);
2373                         } else {
2374                                 /* Add what we're responding to */
2375                                 add_header(req, field, tmp);
2376                         }
2377                         copied++;
2378                 } else
2379                         break;
2380         }
2381         if (!copied) {
2382                 ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
2383                 return -1;
2384         }
2385         return 0;
2386 }
2387
2388 /* Add Route: header into request per learned route */
2389 static void add_route(struct sip_request *req, struct sip_route *route)
2390 {
2391         char r[256], *p;
2392         int n, rem = 255; /* sizeof(r)-1: Room for terminating 0 */
2393
2394         if (!route) return;
2395
2396         p = r;
2397         while (route) {
2398                 n = strlen(route->hop);
2399                 if ((n+3)>rem) break;
2400                 if (p != r) {
2401                         *p++ = ',';
2402                         --rem;
2403                 }
2404                 *p++ = '<';
2405                 strcpy(p, route->hop);  p += n;
2406                 *p++ = '>';
2407                 rem -= (n+2);
2408                 route = route->next;
2409         }
2410         *p = '\0';
2411         add_header(req, "Route", r);
2412 }
2413
2414 static void set_destination(struct sip_pvt *p, char *uri)
2415 {
2416         char *h, *maddr, hostname[256];
2417         int port, hn;
2418         struct hostent *hp;
2419         struct ast_hostent ahp;
2420
2421         /* Parse uri to h (host) and port - uri is already just the part inside the <> */
2422         /* general form we are expecting is sip[s]:username[:password]@host[:port][;...] */
2423
2424         if (sipdebug)
2425                 ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
2426
2427         /* Find and parse hostname */
2428         h = strchr(uri, '@');
2429         if (h)
2430                 ++h;
2431         else {
2432                 h = uri;
2433                 if (strncmp(h, "sip:", 4) == 0)
2434                         h += 4;
2435                 else if (strncmp(h, "sips:", 5) == 0)
2436                         h += 5;
2437         }
2438         hn = strcspn(h, ":;>");
2439         if (hn>255) hn=255;
2440         strncpy(hostname, h, hn);  hostname[hn] = '\0';
2441         h+=hn;
2442
2443         /* Is "port" present? if not default to 5060 */
2444         if (*h == ':') {
2445                 /* Parse port */
2446                 ++h;
2447                 port = strtol(h, &h, 10);
2448         }
2449         else
2450                 port = 5060;
2451
2452         /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
2453         maddr = strstr(h, "maddr=");
2454         if (maddr) {
2455                 maddr += 6;
2456                 hn = strspn(maddr, "0123456789.");
2457                 if (hn>255) hn=255;
2458                 strncpy(hostname, maddr, hn);  hostname[hn] = '\0';
2459         }
2460         
2461         hp = ast_gethostbyname(hostname, &ahp);
2462         if (hp == NULL)  {
2463                 ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
2464                 return;
2465         }
2466         p->sa.sin_family = AF_INET;
2467         memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
2468         p->sa.sin_port = htons(port);
2469         if (sipdebug)
2470                 ast_verbose("set_destination: set destination to %s, port %d\n", inet_ntoa(p->sa.sin_addr), port);
2471 }
2472
2473 static int init_resp(struct sip_request *req, char *resp, struct sip_request *orig)
2474 {
2475         /* Initialize a response */
2476         if (req->headers || req->len) {
2477                 ast_log(LOG_WARNING, "Request already initialized?!?\n");
2478                 return -1;
2479         }
2480         req->header[req->headers] = req->data + req->len;
2481         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "SIP/2.0 %s\r\n", resp);
2482         req->len += strlen(req->header[req->headers]);
2483         if (req->headers < SIP_MAX_HEADERS)
2484                 req->headers++;
2485         else
2486                 ast_log(LOG_WARNING, "Out of header space\n");
2487         return 0;
2488 }
2489
2490 static int init_req(struct sip_request *req, char *resp, char *recip)
2491 {
2492         /* Initialize a response */
2493         if (req->headers || req->len) {
2494                 ast_log(LOG_WARNING, "Request already initialized?!?\n");
2495                 return -1;
2496         }
2497         req->header[req->headers] = req->data + req->len;
2498         snprintf(req->header[req->headers], sizeof(req->data) - req->len, "%s %s SIP/2.0\r\n", resp, recip);
2499         req->len += strlen(req->header[req->headers]);
2500         if (req->headers < SIP_MAX_HEADERS)
2501                 req->headers++;
2502         else
2503                 ast_log(LOG_WARNING, "Out of header space\n");
2504         return 0;
2505 }
2506
2507 static int respprep(struct sip_request *resp, struct sip_pvt *p, char *msg, struct sip_request *req)
2508 {
2509         char newto[256] = "", *ot;
2510         memset(resp, 0, sizeof(*resp));
2511         init_resp(resp, msg, req);
2512         copy_via_headers(p, resp, req, "Via");
2513         if (msg[0] == '2') copy_all_header(resp, req, "Record-Route");
2514         copy_header(resp, req, "From");
2515         ot = get_header(req, "To");
2516         if (!strstr(ot, "tag=")) {
2517                 /* Add the proper tag if we don't have it already.  If they have specified
2518                    their tag, use it.  Otherwise, use our own tag */
2519                 if (strlen(p->theirtag) && p->outgoing)
2520                         snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
2521                 else if (p->tag && !p->outgoing)
2522                         snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
2523                 else
2524                         strncpy(newto, ot, sizeof(newto) - 1);
2525                 ot = newto;
2526         }
2527         add_header(resp, "To", ot);
2528         copy_header(resp, req, "Call-ID");
2529         copy_header(resp, req, "CSeq");
2530         add_header(resp, "User-Agent", "Asterisk PBX");
2531         add_header(resp, "Allow", ALLOWED_METHODS);
2532         if (p->expiry) {
2533                 /* For registration responses, we also need expiry and
2534                    contact info */
2535                 char contact[256];
2536                 char tmp[256];
2537                 snprintf(contact, sizeof(contact), "%s;expires=%d", p->our_contact, p->expiry);
2538                 snprintf(tmp, sizeof(tmp), "%d", p->expiry);
2539                 add_header(resp, "Expires", tmp);
2540                 add_header(resp, "Contact", contact);
2541         } else {
2542                 add_header(resp, "Contact", p->our_contact);
2543         }
2544         return 0;
2545 }
2546
2547 static int reqprep(struct sip_request *req, struct sip_pvt *p, char *msg, int seqno, int newbranch)
2548 {
2549         struct sip_request *orig = &p->initreq;
2550         char stripped[80] ="";
2551         char tmp[80];
2552         char newto[256];
2553         char *c, *n;
2554         char *ot, *of;
2555
2556         memset(req, 0, sizeof(struct sip_request));
2557         
2558         snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", msg);
2559         
2560         if (!seqno) {
2561                 p->ocseq++;
2562                 seqno = p->ocseq;
2563         }
2564         
2565         if (newbranch) {
2566                 p->branch ^= rand();
2567                 snprintf(p->via, sizeof(p->via), "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", inet_ntoa(p->ourip), ourport, p->branch);
2568         }
2569
2570         if (strlen(p->uri)) {
2571                 c = p->uri;
2572         } else {
2573                 if (p->outgoing)
2574                         strncpy(stripped, get_header(orig, "To"), sizeof(stripped) - 1);
2575                 else
2576                         strncpy(stripped, get_header(orig, "From"), sizeof(stripped) - 1);
2577                 
2578                 c = strchr(stripped, '<');
2579                 if (c) 
2580                         c++;
2581                 else
2582                         c = stripped;
2583                 n = strchr(c, '>');
2584                 if (n)
2585                         *n = '\0';
2586                 n = strchr(c, ';');
2587                 if (n)
2588                         *n = '\0';
2589         }       
2590         init_req(req, msg, c);
2591
2592         snprintf(tmp, sizeof(tmp), "%d %s", seqno, msg);
2593
2594         add_header(req, "Via", p->via);
2595         if (p->route) {
2596                 set_destination(p, p->route->hop);
2597                 add_route(req, p->route->next);
2598         }
2599
2600         ot = get_header(orig, "To");
2601         of = get_header(orig, "From");
2602
2603         /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
2604            as our original request, including tag (or presumably lack thereof) */
2605         if (!strstr(ot, "tag=") && strcasecmp(msg, "CANCEL")) {
2606                 /* Add the proper tag if we don't have it already.  If they have specified
2607                    their tag, use it.  Otherwise, use our own tag */
2608                 if (p->outgoing && strlen(p->theirtag))
2609                         snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
2610                 else if (!p->outgoing)
2611                         snprintf(newto, sizeof(newto), "%s;tag=as%08x", ot, p->tag);
2612                 else
2613                         snprintf(newto, sizeof(newto), "%s", ot);
2614                 ot = newto;
2615         }
2616
2617         if (p->outgoing) {
2618                 add_header(req, "From", of);
2619                 add_header(req, "To", ot);
2620         } else {
2621                 add_header(req, "From", ot);
2622                 add_header(req, "To", of);
2623         }
2624         add_header(req, "Contact", p->our_contact);
2625         copy_header(req, orig, "Call-ID");
2626         add_header(req, "CSeq", tmp);
2627
2628         add_header(req, "User-Agent", "Asterisk PBX");
2629         return 0;
2630 }
2631
2632 static int __transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req, int reliable)
2633 {
2634         struct sip_request resp;
2635         int seqno = 0;
2636         if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
2637                 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
2638                 return -1;
2639         }
2640         respprep(&resp, p, msg, req);
2641         add_header(&resp, "Content-Length", "0");
2642         add_blank_header(&resp);
2643         return send_response(p, &resp, reliable, seqno);
2644 }
2645
2646 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req) 
2647 {
2648         return __transmit_response(p, msg, req, 0);
2649 }
2650 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req, int fatal)
2651 {
2652         return __transmit_response(p, msg, req, fatal ? 2 : 1);
2653 }
2654
2655 static void append_date(struct sip_request *req)
2656 {
2657         char tmpdat[256];
2658         struct tm tm;
2659         time_t t;
2660         time(&t);
2661         gmtime_r(&t, &tm);
2662         strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
2663         add_header(req, "Date", tmpdat);
2664 }
2665
2666 static int transmit_response_with_date(struct sip_pvt *p, char *msg, struct sip_request *req)
2667 {
2668         struct sip_request resp;
2669         respprep(&resp, p, msg, req);
2670         append_date(&resp);
2671         add_header(&resp, "Content-Length", "0");
2672         add_blank_header(&resp);
2673         return send_response(p, &resp, 0, 0);
2674 }
2675
2676 static int transmit_response_with_allow(struct sip_pvt *p, char *msg, struct sip_request *req)
2677 {
2678         struct sip_request resp;
2679         respprep(&resp, p, msg, req);
2680         add_header(&resp, "Accept", "application/sdp");
2681         add_header(&resp, "Content-Length", "0");
2682         add_blank_header(&resp);
2683         return send_response(p, &resp, 0, 0);
2684 }
2685
2686 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *randdata, int reliable)
2687 {
2688         struct sip_request resp;
2689         char tmp[256];
2690         int seqno = 0;
2691         if (reliable && (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1)) {
2692                 ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
2693                 return -1;
2694         }
2695         snprintf(tmp, sizeof(tmp), "Digest realm=\"asterisk\", nonce=\"%s\"", randdata);
2696         respprep(&resp, p, msg, req);
2697         add_header(&resp, "Proxy-Authenticate", tmp);
2698         add_header(&resp, "Content-Length", "0");
2699         add_blank_header(&resp);
2700         return send_response(p, &resp, reliable, seqno);
2701 }
2702
2703 static int add_text(struct sip_request *req, char *text)
2704 {
2705         /* XXX Convert \n's to \r\n's XXX */
2706         int len = strlen(text);
2707         char clen[256];
2708         snprintf(clen, sizeof(clen), "%d", len);
2709         add_header(req, "Content-Type", "text/plain");
2710         add_header(req, "Content-Length", clen);
2711         add_line(req, text);
2712         return 0;
2713 }
2714
2715 static int add_digit(struct sip_request *req, char digit)
2716 {
2717         char tmp[256];
2718         int len;
2719         char clen[256];
2720         snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=250\r\n", digit);
2721         len = strlen(tmp);
2722         snprintf(clen, sizeof(clen), "%d", len);
2723         add_header(req, "Content-Type", "application/dtmf-relay");
2724         add_header(req, "Content-Length", clen);
2725         add_line(req, tmp);
2726         return 0;
2727 }
2728
2729 static int add_sdp(struct sip_request *resp, struct sip_pvt *p, struct ast_rtp *rtp, struct ast_rtp *vrtp)
2730 {
2731         int len;
2732         int codec;
2733         int alreadysent = 0;
2734         char costr[80];
2735         struct sockaddr_in sin;
2736         struct sockaddr_in vsin;
2737         struct sip_codec_pref *cur;
2738         char v[256];
2739         char s[256];
2740         char o[256];
2741         char c[256];
2742         char t[256];
2743         char m[256];
2744         char m2[256];
2745         char a[1024] = "";
2746         char a2[1024] = "";
2747         int x;
2748         struct sockaddr_in dest;
2749         struct sockaddr_in vdest = { 0, };
2750         /* XXX We break with the "recommendation" and send our IP, in order that our
2751                peer doesn't have to ast_gethostbyname() us XXX */
2752         len = 0;
2753         if (!p->rtp) {
2754                 ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
2755                 return -1;
2756         }
2757         if (!p->sessionid) {
2758                 p->sessionid = getpid();
2759                 p->sessionversion = p->sessionid;
2760         } else
2761                 p->sessionversion++;
2762         ast_rtp_get_us(p->rtp, &sin);
2763         if (p->vrtp)
2764                 ast_rtp_get_us(p->vrtp, &vsin);
2765
2766         if (p->redirip.sin_addr.s_addr) {
2767                 dest.sin_port = p->redirip.sin_port;
2768                 dest.sin_addr = p->redirip.sin_addr;
2769         } else if (rtp) {
2770                 ast_rtp_get_peer(rtp, &dest);
2771         } else {
2772                 dest.sin_addr = p->ourip;
2773                 dest.sin_port = sin.sin_port;
2774         }
2775
2776         /* Determine video destination */
2777         if (p->vrtp) {
2778                 if (p->vredirip.sin_addr.s_addr) {
2779                         vdest.sin_port = p->vredirip.sin_port;
2780                         vdest.sin_addr = p->vredirip.sin_addr;
2781                 } else if (vrtp) {
2782                         ast_rtp_get_peer(vrtp, &vdest);
2783                 } else {
2784                         vdest.sin_addr = p->ourip;
2785                         vdest.sin_port = vsin.sin_port;
2786                 }
2787         }
2788         if (sipdebug)
2789                 ast_verbose("We're at %s port %d\n", inet_ntoa(p->ourip), ntohs(sin.sin_port)); 
2790         if (sipdebug && p->vrtp)
2791                 ast_verbose("Video is at %s port %d\n", inet_ntoa(p->ourip), ntohs(vsin.sin_port));     
2792         snprintf(v, sizeof(v), "v=0\r\n");
2793         snprintf(o, sizeof(o), "o=root %d %d IN IP4 %s\r\n", p->sessionid, p->sessionversion, inet_ntoa(dest.sin_addr));
2794         snprintf(s, sizeof(s), "s=session\r\n");
2795         snprintf(c, sizeof(c), "c=IN IP4 %s\r\n", inet_ntoa(dest.sin_addr));
2796         snprintf(t, sizeof(t), "t=0 0\r\n");
2797         snprintf(m, sizeof(m), "m=audio %d RTP/AVP", ntohs(dest.sin_port));
2798         snprintf(m2, sizeof(m2), "m=video %d RTP/AVP", ntohs(vdest.sin_port));
2799         if (p->jointcapability & p->prefcodec) {
2800                 if (sipdebug)
2801                         ast_verbose("Answering/Requesting with root capability %d\n", p->prefcodec);
2802                 codec = ast_rtp_lookup_code(p->rtp, 1, p->prefcodec);
2803                 if (codec > -1) {
2804                         snprintf(costr, sizeof(costr), " %d", codec);
2805                         if (p->prefcodec <= AST_FORMAT_MAX_AUDIO) {
2806                                 strncat(m, costr, sizeof(m) - strlen(m));
2807                                 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, p->prefcodec));
2808                                 strncat(a, costr, sizeof(a));
2809                         } else {
2810                                 strncat(m2, costr, sizeof(m2) - strlen(m2));
2811                                 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/90000\r\n", codec, ast_rtp_lookup_mime_subtype(1, p->prefcodec));
2812                                 strncat(a2, costr, sizeof(a2));
2813                         }
2814                 }
2815                 alreadysent |= p->prefcodec;
2816         }
2817         /* Start by sending our preferred codecs */
2818         cur = prefs;
2819         while(cur) {
2820                 if (p->jointcapability & cur->codec) {
2821                         if (sipdebug)
2822                                 ast_verbose("Answering/Requesting with preferred capability %d\n", cur->codec);
2823                         codec = ast_rtp_lookup_code(p->rtp, 1, cur->codec);
2824                         if (codec > -1) {
2825                                 snprintf(costr, sizeof(costr), " %d", codec);
2826                                 if (cur->codec <= AST_FORMAT_MAX_AUDIO) {
2827                                         strncat(m, costr, sizeof(m) - strlen(m));
2828                                         snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, cur->codec));
2829                                         strncat(a, costr, sizeof(a));
2830                                 } else {
2831                                         strncat(m2, costr, sizeof(m2) - strlen(m2));
2832                                         snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/90000\r\n", codec, ast_rtp_lookup_mime_subtype(1, cur->codec));
2833                                         strncat(a2, costr, sizeof(a2));
2834                                 }
2835                         }
2836                 }
2837                 alreadysent |= cur->codec;
2838                 cur = cur->next;
2839         }
2840         /* Now send any other common codecs, and non-codec formats: */
2841         for (x = 1; x <= (videosupport ? AST_FORMAT_MAX_VIDEO : AST_FORMAT_MAX_AUDIO); x <<= 1) {
2842                 if ((p->jointcapability & x) && !(alreadysent & x)) {
2843                         if (sipdebug)
2844                                 ast_verbose("Answering with capability %d\n", x);       
2845                         codec = ast_rtp_lookup_code(p->rtp, 1, x);
2846                         if (codec > -1) {
2847                                 snprintf(costr, sizeof(costr), " %d", codec);
2848                                 if (x <= AST_FORMAT_MAX_AUDIO) {
2849                                         strncat(m, costr, sizeof(m) - strlen(m));
2850                                         snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
2851                                         strncat(a, costr, sizeof(a) - strlen(a));
2852                                 } else {
2853                                         strncat(m2, costr, sizeof(m2) - strlen(m2));
2854                                         snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/90000\r\n", codec, ast_rtp_lookup_mime_subtype(1, x));
2855                                         strncat(a2, costr, sizeof(a2) - strlen(a2));
2856                                 }
2857                         }
2858                 }
2859         }
2860         for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
2861                 if (p->noncodeccapability & x) {
2862                         if (sipdebug)
2863                                 ast_verbose("Answering with non-codec capability %d\n", x);
2864                         codec = ast_rtp_lookup_code(p->rtp, 0, x);
2865                         if (codec > -1) {
2866                                 snprintf(costr, sizeof(costr), " %d", codec);
2867                                 strncat(m, costr, sizeof(m) - strlen(m));
2868                                 snprintf(costr, sizeof(costr), "a=rtpmap:%d %s/8000\r\n", codec, ast_rtp_lookup_mime_subtype(0, x));
2869                                 strncat(a, costr, sizeof(a) - strlen(a));
2870                                 if (x == AST_RTP_DTMF) {
2871                                   /* Indicate we support DTMF...  Not sure about 16, but MSN supports it so dang it, we will too... */
2872                                   snprintf(costr, sizeof costr, "a=fmtp:%d 0-16\r\n",
2873                                            codec);
2874                                   strncat(a, costr, sizeof(a) - strlen(a));
2875                                 }
2876                         }
2877                 }
2878         }
2879         strncat(a, "a=silenceSupp:off - - - -\r\n", sizeof(a) - strlen(a));
2880         if (strlen(m) < sizeof(m) - 2)
2881                 strcat(m, "\r\n");
2882         if (strlen(m2) < sizeof(m2) - 2)
2883                 strcat(m2, "\r\n");
2884         if ((sizeof(m) <= strlen(m) - 2) || (sizeof(m2) <= strlen(m2) - 2) || (sizeof(a) == strlen(a)) || (sizeof(a2) == strlen(a2)))
2885                 ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
2886         len = strlen(v) + strlen(s) + strlen(o) + strlen(c) + strlen(t) + strlen(m) + strlen(a);
2887         if ((p->vrtp) && (p->jointcapability & VIDEO_CODEC_MASK)) /* only if video response is appropriate */
2888                 len += strlen(m2) + strlen(a2);
2889         snprintf(costr, sizeof(costr), "%d", len);
2890         add_header(resp, "Content-Type", "application/sdp");
2891         add_header(resp, "Content-Length", costr);
2892         add_line(resp, v);
2893         add_line(resp, o);
2894         add_line(resp, s);
2895         add_line(resp, c);
2896         add_line(resp, t);
2897         add_line(resp, m);
2898         add_line(resp, a);
2899         if ((p->vrtp) && (p->jointcapability & VIDEO_CODEC_MASK)) { /* only if video response is appropriate */
2900                 add_line(resp, m2);
2901                 add_line(resp, a2);
2902         }
2903         return 0;
2904 }
2905
2906 static void copy_request(struct sip_request *dst,struct sip_request *src)
2907 {
2908         long offset;
2909         int x;
2910         offset = ((void *)dst) - ((void *)src);
2911         /* First copy stuff */
2912         memcpy(dst, src, sizeof(*dst));
2913         /* Now fix pointer arithmetic */
2914         for (x=0;x<src->headers;x++)
2915                 dst->header[x] += offset;
2916         for (x=0;x<src->lines;x++)
2917                 dst->line[x] += offset;
2918 }
2919
2920 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
2921 {
2922         struct sip_request resp;
2923         int seqno;
2924         if (sscanf(get_header(req, "CSeq"), "%i ", &seqno) != 1) {
2925                 ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
2926                 return -1;
2927         }
2928         respprep(&resp, p, msg, req);
2929         add_sdp(&resp, p, NULL, NULL);
2930         return send_response(p, &resp, retrans, seqno);
2931 }
2932
2933 static int determine_firstline_parts( struct sip_request *req ) {
2934
2935   char *e, *cmd;
2936   int len;
2937   
2938   cmd= req->header[0];
2939   while(*cmd && (*cmd < 33)) {
2940     cmd++;
2941   }
2942   if (!*cmd) {
2943     return -1;
2944   }
2945   e= cmd;
2946   while(*e && (*e > 32)) {
2947     e++;
2948   }
2949   /* Get the command */
2950   if (*e) {
2951     *e = '\0';
2952     e++;
2953   }
2954   req->rlPart1= cmd;
2955   while( *e && ( *e < 33 ) ) {
2956     e++; 
2957   }
2958   if( !*e ) {
2959     return -1;
2960   }
2961     
2962   if ( !strcasecmp(cmd, "SIP/2.0") ) {
2963     /* We have a response */
2964     req->rlPart2= e;
2965     len= strlen( req->rlPart2 );
2966     if( len < 2 ) { return -1; }
2967     e+= len - 1;
2968     while( *e && *e<33 ) {
2969       e--; 
2970     }
2971     *(++e)= '\0';
2972   } else {
2973     /* We have a request */
2974     if( *e == '<' ) { 
2975       e++;
2976       if( !*e ) { return -1; }  
2977     }
2978     req->rlPart2= e;
2979     if( ( e= strrchr( req->rlPart2, 'S' ) ) == NULL ) {
2980       return -1;
2981     }
2982     while( isspace( *(--e) ) ) {}
2983     if( *e == '>' ) {
2984       *e= '\0';
2985     } else {
2986       *(++e)= '\0';
2987     }
2988   }
2989   return 1;
2990 }
2991
2992 static int transmit_reinvite_with_sdp(struct sip_pvt *p, struct ast_rtp *rtp, struct ast_rtp *vrtp)
2993 {
2994         struct sip_request req;
2995         if (p->canreinvite == REINVITE_UPDATE)
2996                 reqprep(&req, p, "UPDATE", 0, 1);
2997         else 
2998                 reqprep(&req, p, "INVITE", 0, 1);
2999         
3000         add_header(&req, "Allow", ALLOWED_METHODS);
3001         add_sdp(&req, p, rtp, vrtp);
3002         /* Use this as the basis */
3003         copy_request(&p->initreq, &req);
3004         parse(&p->initreq);
3005         determine_firstline_parts(&p->initreq);
3006         p->lastinvite = p->ocseq;
3007         p->outgoing = 1;
3008         return send_request(p, &req, 1, p->ocseq);
3009 }
3010
3011 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
3012 {
3013         char stripped[256]="";
3014         char *c, *n;
3015         strncpy(stripped, get_header(req, "Contact"), sizeof(stripped) - 1);
3016         c = strchr(stripped, '<');
3017         if (c) 
3018                 c++;
3019         else
3020                 c = stripped;
3021         n = strchr(c, '>');
3022         if (n)
3023                 *n = '\0';
3024         n = strchr(c, ';');
3025         if (n)
3026                 *n = '\0';
3027         if (c && strlen(c))
3028                 strncpy(p->uri, c, sizeof(p->uri) - 1);
3029 }
3030
3031 static void build_contact(struct sip_pvt *p)
3032 {
3033         /* Construct Contact: header */
3034         if (ourport != 5060)
3035                 snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s@%s:%d>", p->exten, inet_ntoa(p->ourip), ourport);
3036         else
3037                 snprintf(p->our_contact, sizeof(p->our_contact), "<sip:%s@%s>", p->exten, inet_ntoa(p->ourip));
3038 }
3039
3040 static void initreqprep(struct sip_request *req, struct sip_pvt *p, char *cmd, char *vxml_url)
3041 {
3042         char invite[256];
3043         char from[256];
3044         char to[256];
3045         char tmp[80];
3046         char cid[256];
3047         char *l = callerid, *n=NULL;
3048
3049         snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", cmd);
3050
3051         if (p->owner && p->owner->callerid) {
3052                 strcpy(cid, p->owner->callerid);
3053                 ast_callerid_parse(cid, &n, &l);
3054                 if (l) 
3055                         ast_shrink_phone_number(l);
3056                 if (!l || !ast_isphonenumber(l))
3057                                 l = callerid;
3058      &nbs