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