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