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