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