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