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