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