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