fix authentication header extra space (issue #5329)
[asterisk/asterisk.git] / channels / chan_sip.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2005, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*
20  *
21  * Implementation of Session Initiation Protocol
22  * 
23  */
24
25
26 #include <stdio.h>
27 #include <ctype.h>
28 #include <string.h>
29 #include <unistd.h>
30 #include <sys/socket.h>
31 #include <sys/ioctl.h>
32 #include <net/if.h>
33 #include <errno.h>
34 #include <stdlib.h>
35 #include <fcntl.h>
36 #include <netdb.h>
37 #include <signal.h>
38 #include <sys/signal.h>
39 #include <netinet/in.h>
40 #include <netinet/in_systm.h>
41 #include <arpa/inet.h>
42 #include <netinet/ip.h>
43 #include <regex.h>
44
45 #include "asterisk.h"
46
47 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
48
49 #include "asterisk/lock.h"
50 #include "asterisk/channel.h"
51 #include "asterisk/config.h"
52 #include "asterisk/logger.h"
53 #include "asterisk/module.h"
54 #include "asterisk/pbx.h"
55 #include "asterisk/options.h"
56 #include "asterisk/lock.h"
57 #include "asterisk/sched.h"
58 #include "asterisk/io.h"
59 #include "asterisk/rtp.h"
60 #include "asterisk/acl.h"
61 #include "asterisk/manager.h"
62 #include "asterisk/callerid.h"
63 #include "asterisk/cli.h"
64 #include "asterisk/app.h"
65 #include "asterisk/musiconhold.h"
66 #include "asterisk/dsp.h"
67 #include "asterisk/features.h"
68 #include "asterisk/acl.h"
69 #include "asterisk/srv.h"
70 #include "asterisk/astdb.h"
71 #include "asterisk/causes.h"
72 #include "asterisk/utils.h"
73 #include "asterisk/file.h"
74 #include "asterisk/astobj.h"
75 #include "asterisk/dnsmgr.h"
76 #include "asterisk/devicestate.h"
77 #include "asterisk/linkedlists.h"
78
79 #ifdef OSP_SUPPORT
80 #include "asterisk/astosp.h"
81 #endif
82
83 #ifndef DEFAULT_USERAGENT
84 #define DEFAULT_USERAGENT "Asterisk PBX"
85 #endif
86  
87 #define VIDEO_CODEC_MASK        0x1fc0000 /* Video codecs from H.261 thru AST_FORMAT_MAX_VIDEO */
88 #ifndef IPTOS_MINCOST
89 #define IPTOS_MINCOST           0x02
90 #endif
91
92 /* #define VOCAL_DATA_HACK */
93
94 #define SIPDUMPER
95 #define DEFAULT_DEFAULT_EXPIRY  120
96 #define DEFAULT_MAX_EXPIRY      3600
97 #define DEFAULT_REGISTRATION_TIMEOUT    20
98 #define DEFAULT_REGATTEMPTS_MAX 10
99
100 /* guard limit must be larger than guard secs */
101 /* guard min must be < 1000, and should be >= 250 */
102 #define EXPIRY_GUARD_SECS       15      /* How long before expiry do we reregister */
103 #define EXPIRY_GUARD_LIMIT      30      /* Below here, we use EXPIRY_GUARD_PCT instead of 
104                                            EXPIRY_GUARD_SECS */
105 #define EXPIRY_GUARD_MIN        500     /* This is the minimum guard time applied. If 
106                                            GUARD_PCT turns out to be lower than this, it 
107                                            will use this time instead.
108                                            This is in milliseconds. */
109 #define EXPIRY_GUARD_PCT        0.20    /* Percentage of expires timeout to use when 
110                                            below EXPIRY_GUARD_LIMIT */
111
112 static int max_expiry = DEFAULT_MAX_EXPIRY;
113 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
114
115 #ifndef MAX
116 #define MAX(a,b) ((a) > (b) ? (a) : (b))
117 #endif
118
119 #define CALLERID_UNKNOWN        "Unknown"
120
121
122
123 #define DEFAULT_MAXMS           2000            /* Must be faster than 2 seconds by default */
124 #define DEFAULT_FREQ_OK         60 * 1000       /* How often to check for the host to be up */
125 #define DEFAULT_FREQ_NOTOK      10 * 1000       /* How often to check, if the host is down... */
126
127 #define DEFAULT_RETRANS         1000            /* How frequently to retransmit */
128                                                 /* 2 * 500 ms in RFC 3261 */
129 #define MAX_RETRANS             6               /* Try only 6 times for retransmissions, a total of 7 transmissions */
130 #define MAX_AUTHTRIES           3               /* Try authentication three times, then fail */
131
132
133 #define DEBUG_READ      0                       /* Recieved data        */
134 #define DEBUG_SEND      1                       /* Transmit data        */
135
136 static const char desc[] = "Session Initiation Protocol (SIP)";
137 static const char channeltype[] = "SIP";
138 static const char config[] = "sip.conf";
139 static const char notify_config[] = "sip_notify.conf";
140
141 #define RTP     1
142 #define NO_RTP  0
143
144 /* Do _NOT_ make any changes to this enum, or the array following it;
145    if you think you are doing the right thing, you are probably
146    not doing the right thing. If you think there are changes
147    needed, get someone else to review them first _before_
148    submitting a patch. If these two lists do not match properly
149    bad things will happen.
150 */
151
152 enum subscriptiontype { 
153         NONE = 0,
154         TIMEOUT,
155         XPIDF_XML,
156         DIALOG_INFO_XML,
157         CPIM_PIDF_XML,
158         PIDF_XML
159 };
160
161 static const struct cfsubscription_types {
162         enum subscriptiontype type;
163         const char * const event;
164         const char * const mediatype;
165         const char * const text;
166 } subscription_types[] = {
167         { NONE,            "-",        "unknown",                         "unknown" },
168         /* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
169         { DIALOG_INFO_XML, "dialog",   "application/dialog-info+xml", "dialog-info+xml" },
170         { CPIM_PIDF_XML,   "presence", "application/cpim-pidf+xml",   "cpim-pidf+xml" },  /* RFC 3863 */
171         { PIDF_XML,        "presence", "application/pidf+xml",        "pidf+xml" },       /* RFC 3863 */
172         { XPIDF_XML,       "presence", "application/xpidf+xml",       "xpidf+xml" }       /* Pre-RFC 3863 with MS additions */
173 };
174
175 enum sipmethod {
176         SIP_UNKNOWN,
177         SIP_RESPONSE,
178         SIP_REGISTER,
179         SIP_OPTIONS,
180         SIP_NOTIFY,
181         SIP_INVITE,
182         SIP_ACK,
183         SIP_PRACK,
184         SIP_BYE,
185         SIP_REFER,
186         SIP_SUBSCRIBE,
187         SIP_MESSAGE,
188         SIP_UPDATE,
189         SIP_INFO,
190         SIP_CANCEL,
191         SIP_PUBLISH,
192 } sip_method_list;
193
194 static const struct  cfsip_methods { 
195         enum sipmethod id;
196         int need_rtp;           /* when this is the 'primary' use for a pvt structure, does it need RTP? */
197         char * const text;
198 } sip_methods[] = {
199         { SIP_UNKNOWN,   RTP,    "-UNKNOWN-" },
200         { SIP_RESPONSE,  NO_RTP, "SIP/2.0" },
201         { SIP_REGISTER,  NO_RTP, "REGISTER" },
202         { SIP_OPTIONS,   NO_RTP, "OPTIONS" },
203         { SIP_NOTIFY,    NO_RTP, "NOTIFY" },
204         { SIP_INVITE,    RTP,    "INVITE" },
205         { SIP_ACK,       NO_RTP, "ACK" },
206         { SIP_PRACK,     NO_RTP, "PRACK" },
207         { SIP_BYE,       NO_RTP, "BYE" },
208         { SIP_REFER,     NO_RTP, "REFER" },
209         { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE" },
210         { SIP_MESSAGE,   NO_RTP, "MESSAGE" },
211         { SIP_UPDATE,    NO_RTP, "UPDATE" },
212         { SIP_INFO,      NO_RTP, "INFO" },
213         { SIP_CANCEL,    NO_RTP, "CANCEL" },
214         { SIP_PUBLISH,   NO_RTP, "PUBLISH" }
215 };
216
217 /* Structure for conversion between compressed SIP and "normal" SIP */
218 static const struct cfalias {
219         char * const fullname;
220         char * const shortname;
221 } aliases[] = {
222         { "Content-Type", "c" },
223         { "Content-Encoding", "e" },
224         { "From", "f" },
225         { "Call-ID", "i" },
226         { "Contact", "m" },
227         { "Content-Length", "l" },
228         { "Subject", "s" },
229         { "To", "t" },
230         { "Supported", "k" },
231         { "Refer-To", "r" },
232         { "Referred-By", "b" },
233         { "Allow-Events", "u" },
234         { "Event", "o" },
235         { "Via", "v" },
236         { "Accept-Contact",      "a" },
237         { "Reject-Contact",      "j" },
238         { "Request-Disposition", "d" },
239         { "Session-Expires",     "x" },
240 };
241
242 /* Define SIP option tags, used in Require: and Supported: headers */
243 /*      We need to be aware of these properties in the phones to use 
244         the replace: header. We should not do that without knowing
245         that the other end supports it... 
246         This is nothing we can configure, we learn by the dialog
247         Supported: header on the REGISTER (peer) or the INVITE
248         (other devices)
249         We are not using many of these today, but will in the future.
250         This is documented in RFC 3261
251 */
252 #define SUPPORTED               1
253 #define NOT_SUPPORTED           0
254
255 #define SIP_OPT_REPLACES        (1 << 0)
256 #define SIP_OPT_100REL          (1 << 1)
257 #define SIP_OPT_TIMER           (1 << 2)
258 #define SIP_OPT_EARLY_SESSION   (1 << 3)
259 #define SIP_OPT_JOIN            (1 << 4)
260 #define SIP_OPT_PATH            (1 << 5)
261 #define SIP_OPT_PREF            (1 << 6)
262 #define SIP_OPT_PRECONDITION    (1 << 7)
263 #define SIP_OPT_PRIVACY         (1 << 8)
264 #define SIP_OPT_SDP_ANAT        (1 << 9)
265 #define SIP_OPT_SEC_AGREE       (1 << 10)
266 #define SIP_OPT_EVENTLIST       (1 << 11)
267 #define SIP_OPT_GRUU            (1 << 12)
268 #define SIP_OPT_TARGET_DIALOG   (1 << 13)
269
270 /* List of well-known SIP options. If we get this in a require,
271    we should check the list and answer accordingly. */
272 static const struct cfsip_options {
273         int id;                 /* Bitmap ID */
274         int supported;          /* Supported by Asterisk ? */
275         char * const text;      /* Text id, as in standard */
276 } sip_options[] = {
277         /* Replaces: header for transfer */
278         { SIP_OPT_REPLACES,     SUPPORTED,      "replaces" },   
279         /* RFC3262: PRACK 100% reliability */
280         { SIP_OPT_100REL,       NOT_SUPPORTED,  "100rel" },     
281         /* SIP Session Timers */
282         { SIP_OPT_TIMER,        NOT_SUPPORTED,  "timer" },
283         /* RFC3959: SIP Early session support */
284         { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED, "early-session" },
285         /* SIP Join header support */
286         { SIP_OPT_JOIN,         NOT_SUPPORTED,  "join" },
287         /* RFC3327: Path support */
288         { SIP_OPT_PATH,         NOT_SUPPORTED,  "path" },
289         /* RFC3840: Callee preferences */
290         { SIP_OPT_PREF,         NOT_SUPPORTED,  "pref" },
291         /* RFC3312: Precondition support */
292         { SIP_OPT_PRECONDITION, NOT_SUPPORTED,  "precondition" },
293         /* RFC3323: Privacy with proxies*/
294         { SIP_OPT_PRIVACY,      NOT_SUPPORTED,  "privacy" },
295         /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
296         { SIP_OPT_SDP_ANAT,     NOT_SUPPORTED,  "sdp-anat" },
297         /* RFC3329: Security agreement mechanism */
298         { SIP_OPT_SEC_AGREE,    NOT_SUPPORTED,  "sec_agree" },
299         /* SIMPLE events:  draft-ietf-simple-event-list-07.txt */
300         { SIP_OPT_EVENTLIST,    NOT_SUPPORTED,  "eventlist" },
301         /* GRUU: Globally Routable User Agent URI's */
302         { SIP_OPT_GRUU,         NOT_SUPPORTED,  "gruu" },
303         /* Target-dialog: draft-ietf-sip-target-dialog-00.txt */
304         { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED,  "target-dialog" },
305 };
306
307
308 /* SIP Methods we support */
309 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY"
310
311 /* SIP Extensions we support */
312 #define SUPPORTED_EXTENSIONS "replaces" 
313
314 #define DEFAULT_SIP_PORT        5060    /* From RFC 3261 (former 2543) */
315 #define SIP_MAX_PACKET          4096    /* Also from RFC 3261 (2543), should sub headers tho */
316
317 static char default_useragent[AST_MAX_EXTENSION] = DEFAULT_USERAGENT;
318
319 #define DEFAULT_CONTEXT "default"
320 static char default_context[AST_MAX_CONTEXT] = DEFAULT_CONTEXT;
321 static char default_subscribecontext[AST_MAX_CONTEXT];
322
323 #define DEFAULT_VMEXTEN "asterisk"
324 static char global_vmexten[AST_MAX_EXTENSION] = DEFAULT_VMEXTEN;
325
326 static char default_language[MAX_LANGUAGE] = "";
327
328 #define DEFAULT_CALLERID "asterisk"
329 static char default_callerid[AST_MAX_EXTENSION] = DEFAULT_CALLERID;
330
331 static char default_fromdomain[AST_MAX_EXTENSION] = "";
332
333 #define DEFAULT_NOTIFYMIME "application/simple-message-summary"
334 static char default_notifymime[AST_MAX_EXTENSION] = DEFAULT_NOTIFYMIME;
335
336 static int global_notifyringing = 1;    /* Send notifications on ringing */
337
338 static int default_qualify = 0;         /* Default Qualify= setting */
339
340 static struct ast_flags global_flags = {0};             /* global SIP_ flags */
341 static struct ast_flags global_flags_page2 = {0};       /* more global SIP_ flags */
342
343 static int srvlookup = 0;               /* SRV Lookup on or off. Default is off, RFC behavior is on */
344
345 static int pedanticsipchecking = 0;     /* Extra checking ?  Default off */
346
347 static int autocreatepeer = 0;          /* Auto creation of peers at registration? Default off. */
348
349 static int relaxdtmf = 0;
350
351 static int global_rtptimeout = 0;
352
353 static int global_rtpholdtimeout = 0;
354
355 static int global_rtpkeepalive = 0;
356
357 static int global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;   
358 static int global_regattempts_max = DEFAULT_REGATTEMPTS_MAX;
359
360 /* Object counters */
361 static int suserobjs = 0;
362 static int ruserobjs = 0;
363 static int speerobjs = 0;
364 static int rpeerobjs = 0;
365 static int apeerobjs = 0;
366 static int regobjs = 0;
367
368 static int global_allowguest = 1;    /* allow unauthenticated users/peers to connect? */
369
370 #define DEFAULT_MWITIME 10
371 static int global_mwitime = DEFAULT_MWITIME;    /* Time between MWI checks for peers */
372
373 static int usecnt =0;
374 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
375
376
377 /* Protect the interface list (of sip_pvt's) */
378 AST_MUTEX_DEFINE_STATIC(iflock);
379
380 /* Protect the monitoring thread, so only one process can kill or start it, and not
381    when it's doing something critical. */
382 AST_MUTEX_DEFINE_STATIC(netlock);
383
384 AST_MUTEX_DEFINE_STATIC(monlock);
385
386 /* This is the thread for the monitor which checks for input on the channels
387    which are not currently in use.  */
388 static pthread_t monitor_thread = AST_PTHREADT_NULL;
389
390 static int restart_monitor(void);
391
392 /* Codecs that we support by default: */
393 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
394 static int noncodeccapability = AST_RTP_DTMF;
395
396 static struct in_addr __ourip;
397 static struct sockaddr_in outboundproxyip;
398 static int ourport;
399
400 #define SIP_DEBUG_CONFIG 1 << 0
401 #define SIP_DEBUG_CONSOLE 1 << 1
402 static int sipdebug = 0;
403 static struct sockaddr_in debugaddr;
404
405 static int tos = 0;
406
407 static int videosupport = 0;
408
409 static int compactheaders = 0;                          /* send compact sip headers */
410
411 static int recordhistory = 0;                           /* Record SIP history. Off by default */
412 static int dumphistory = 0;                             /* Dump history to verbose before destroying SIP dialog */
413
414 static char global_musicclass[MAX_MUSICCLASS] = "";     /* Global music on hold class */
415 #define DEFAULT_REALM   "asterisk"
416 static char global_realm[MAXHOSTNAMELEN] = DEFAULT_REALM;       /* Default realm */
417 static char regcontext[AST_MAX_CONTEXT] = "";           /* Context for auto-extensions */
418
419 /* Expire slowly */
420 #define DEFAULT_EXPIRY 900
421 static int expiry = DEFAULT_EXPIRY;
422
423 static struct sched_context *sched;
424 static struct io_context *io;
425 /* The private structures of the  sip channels are linked for
426    selecting outgoing channels */
427    
428 #define SIP_MAX_HEADERS         64
429 #define SIP_MAX_LINES           64
430
431 #define DEC_CALL_LIMIT  0
432 #define INC_CALL_LIMIT  1
433
434 static struct ast_codec_pref prefs;
435
436
437 /* sip_request: The data grabbed from the UDP socket */
438 struct sip_request {
439         char *rlPart1;          /* SIP Method Name or "SIP/2.0" protocol version */
440         char *rlPart2;          /* The Request URI or Response Status */
441         int len;                /* Length */
442         int headers;            /* # of SIP Headers */
443         int method;             /* Method of this request */
444         char *header[SIP_MAX_HEADERS];
445         int lines;              /* SDP Content */
446         char *line[SIP_MAX_LINES];
447         char data[SIP_MAX_PACKET];
448         int debug;              /* Debug flag for this packet */
449 };
450
451 struct sip_pkt;
452
453 /* Parameters to the transmit_invite function */
454 struct sip_invite_param {
455         char *distinctive_ring;
456         char *osptoken;
457         int addsipheaders;
458        char *uri_options;
459         char *vxml_url;
460         char *auth;
461         char *authheader;
462 };
463
464 struct sip_route {
465         struct sip_route *next;
466         char hop[0];
467 };
468
469 enum domain_mode {
470         SIP_DOMAIN_AUTO,
471         SIP_DOMAIN_CONFIG,
472 };
473
474 struct domain {
475         char domain[MAXHOSTNAMELEN];
476         char context[AST_MAX_EXTENSION];
477         enum domain_mode mode;
478         AST_LIST_ENTRY(domain) list;
479 };
480
481 static AST_LIST_HEAD_STATIC(domain_list, domain);
482
483 int allow_external_domains;
484
485 /* sip_history: Structure for saving transactions within a SIP dialog */
486 struct sip_history {
487         char event[80];
488         struct sip_history *next;
489 };
490
491 /* sip_auth: Creadentials for authentication to other SIP services */
492 struct sip_auth {
493         char realm[AST_MAX_EXTENSION];  /* Realm in which these credentials are valid */
494         char username[256];             /* Username */
495         char secret[256];               /* Secret */
496         char md5secret[256];            /* MD5Secret */
497         struct sip_auth *next;          /* Next auth structure in list */
498 };
499
500 #define SIP_ALREADYGONE         (1 << 0)        /* Whether or not we've already been destroyed by our peer */
501 #define SIP_NEEDDESTROY         (1 << 1)        /* if we need to be destroyed */
502 #define SIP_NOVIDEO             (1 << 2)        /* Didn't get video in invite, don't offer */
503 #define SIP_RINGING             (1 << 3)        /* Have sent 180 ringing */
504 #define SIP_PROGRESS_SENT       (1 << 4)        /* Have sent 183 message progress */
505 #define SIP_NEEDREINVITE        (1 << 5)        /* Do we need to send another reinvite? */
506 #define SIP_PENDINGBYE          (1 << 6)        /* Need to send bye after we ack? */
507 #define SIP_GOTREFER            (1 << 7)        /* Got a refer? */
508 #define SIP_PROMISCREDIR        (1 << 8)        /* Promiscuous redirection */
509 #define SIP_TRUSTRPID           (1 << 9)        /* Trust RPID headers? */
510 #define SIP_USEREQPHONE         (1 << 10)       /* Add user=phone to numeric URI. Default off */
511 #define SIP_REALTIME            (1 << 11)       /* Flag for realtime users */
512 #define SIP_USECLIENTCODE       (1 << 12)       /* Trust X-ClientCode info message */
513 #define SIP_OUTGOING            (1 << 13)       /* Is this an outgoing call? */
514 #define SIP_SELFDESTRUCT        (1 << 14)       
515 #define SIP_DYNAMIC             (1 << 15)       /* Is this a dynamic peer? */
516 /* --- Choices for DTMF support in SIP channel */
517 #define SIP_DTMF                (3 << 16)       /* three settings, uses two bits */
518 #define SIP_DTMF_RFC2833        (0 << 16)       /* RTP DTMF */
519 #define SIP_DTMF_INBAND         (1 << 16)       /* Inband audio, only for ULAW/ALAW */
520 #define SIP_DTMF_INFO           (2 << 16)       /* SIP Info messages */
521 #define SIP_DTMF_AUTO           (3 << 16)       /* AUTO switch between rfc2833 and in-band DTMF */
522 /* NAT settings */
523 #define SIP_NAT                 (3 << 18)       /* four settings, uses two bits */
524 #define SIP_NAT_NEVER           (0 << 18)       /* No nat support */
525 #define SIP_NAT_RFC3581         (1 << 18)
526 #define SIP_NAT_ROUTE           (2 << 18)
527 #define SIP_NAT_ALWAYS          (3 << 18)
528 /* re-INVITE related settings */
529 #define SIP_REINVITE            (3 << 20)       /* two bits used */
530 #define SIP_CAN_REINVITE        (1 << 20)       /* allow peers to be reinvited to send media directly p2p */
531 #define SIP_REINVITE_UPDATE     (2 << 20)       /* use UPDATE (RFC3311) when reinviting this peer */
532 /* "insecure" settings */
533 #define SIP_INSECURE_PORT       (1 << 22)       /* don't require matching port for incoming requests */
534 #define SIP_INSECURE_INVITE     (1 << 23)       /* don't require authentication for incoming INVITEs */
535 /* Sending PROGRESS in-band settings */
536 #define SIP_PROG_INBAND         (3 << 24)       /* three settings, uses two bits */
537 #define SIP_PROG_INBAND_NEVER   (0 << 24)
538 #define SIP_PROG_INBAND_NO      (1 << 24)
539 #define SIP_PROG_INBAND_YES     (2 << 24)
540 /* Open Settlement Protocol authentication */
541 #define SIP_OSPAUTH             (3 << 26)       /* four settings, uses two bits */
542 #define SIP_OSPAUTH_NO          (0 << 26)
543 #define SIP_OSPAUTH_GATEWAY     (1 << 26)
544 #define SIP_OSPAUTH_PROXY       (2 << 26)
545 #define SIP_OSPAUTH_EXCLUSIVE   (3 << 26)
546 /* Call states */
547 #define SIP_CALL_ONHOLD         (1 << 28)        
548 #define SIP_CALL_LIMIT          (1 << 29)
549 /* Remote Party-ID Support */
550 #define SIP_SENDRPID            (1 << 30)
551
552 #define SIP_FLAGS_TO_COPY \
553         (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
554          SIP_PROG_INBAND | SIP_OSPAUTH | SIP_USECLIENTCODE | SIP_NAT | \
555          SIP_INSECURE_PORT | SIP_INSECURE_INVITE)
556
557 /* a new page of flags for peer */
558 #define SIP_PAGE2_RTCACHEFRIENDS        (1 << 0)
559 #define SIP_PAGE2_RTUPDATE              (1 << 1)
560 #define SIP_PAGE2_RTAUTOCLEAR           (1 << 2)
561 #define SIP_PAGE2_RTIGNOREREGEXPIRE     (1 << 3)
562
563 static int global_rtautoclear = 120;
564
565 /* sip_pvt: PVT structures are used for each SIP conversation, ie. a call  */
566 static struct sip_pvt {
567         ast_mutex_t lock;                       /* Channel private lock */
568         int method;                             /* SIP method of this packet */
569         char callid[80];                        /* Global CallID */
570         char randdata[80];                      /* Random data */
571         struct ast_codec_pref prefs;            /* codec prefs */
572         unsigned int ocseq;                     /* Current outgoing seqno */
573         unsigned int icseq;                     /* Current incoming seqno */
574         ast_group_t callgroup;                  /* Call group */
575         ast_group_t pickupgroup;                /* Pickup group */
576         int lastinvite;                         /* Last Cseq of invite */
577         unsigned int flags;                     /* SIP_ flags */        
578         int timer_t1;                           /* SIP timer T1, ms rtt */
579         unsigned int sipoptions;                /* Supported SIP sipoptions on the other end */
580         int capability;                         /* Special capability (codec) */
581         int jointcapability;                    /* Supported capability at both ends (codecs ) */
582         int peercapability;                     /* Supported peer capability */
583         int prefcodec;                          /* Preferred codec (outbound only) */
584         int noncodeccapability;
585         int callingpres;                        /* Calling presentation */
586         int authtries;                          /* Times we've tried to authenticate */
587         int expiry;                             /* How long we take to expire */
588         int branch;                             /* One random number */
589         char tag[11];                           /* Another random number */
590         int sessionid;                          /* SDP Session ID */
591         int sessionversion;                     /* SDP Session Version */
592         struct sockaddr_in sa;                  /* Our peer */
593         struct sockaddr_in redirip;             /* Where our RTP should be going if not to us */
594         struct sockaddr_in vredirip;            /* Where our Video RTP should be going if not to us */
595         int redircodecs;                        /* Redirect codecs */
596         struct sockaddr_in recv;                /* Received as */
597         struct in_addr ourip;                   /* Our IP */
598         struct ast_channel *owner;              /* Who owns us */
599         char exten[AST_MAX_EXTENSION];          /* Extension where to start */
600         char refer_to[AST_MAX_EXTENSION];       /* Place to store REFER-TO extension */
601         char referred_by[AST_MAX_EXTENSION];    /* Place to store REFERRED-BY extension */
602         char refer_contact[AST_MAX_EXTENSION];  /* Place to store Contact info from a REFER extension */
603         struct sip_pvt *refer_call;             /* Call we are referring */
604         struct sip_route *route;                /* Head of linked list of routing steps (fm Record-Route) */
605         int route_persistant;                   /* Is this the "real" route? */
606         char from[256];                         /* The From: header */
607         char useragent[256];                    /* User agent in SIP request */
608         char context[AST_MAX_CONTEXT];          /* Context for this call */
609         char subscribecontext[AST_MAX_CONTEXT]; /* Subscribecontext */
610         char fromdomain[MAXHOSTNAMELEN];        /* Domain to show in the from field */
611         char fromuser[AST_MAX_EXTENSION];       /* User to show in the user field */
612         char fromname[AST_MAX_EXTENSION];       /* Name to show in the user field */
613         char tohost[MAXHOSTNAMELEN];            /* Host we should put in the "to" field */
614         char language[MAX_LANGUAGE];            /* Default language for this call */
615         char musicclass[MAX_MUSICCLASS];          /* Music on Hold class */
616         char rdnis[256];                        /* Referring DNIS */
617         char theirtag[256];                     /* Their tag */
618         char username[256];                     /* [user] name */
619         char peername[256];                     /* [peer] name, not set if [user] */
620         char authname[256];                     /* Who we use for authentication */
621         char uri[256];                          /* Original requested URI */
622         char okcontacturi[256];                 /* URI from the 200 OK on INVITE */
623         char peersecret[256];                   /* Password */
624         char peermd5secret[256];
625         struct sip_auth *peerauth;              /* Realm authentication */
626         char cid_num[256];                      /* Caller*ID */
627         char cid_name[256];                     /* Caller*ID */
628         char via[256];                          /* Via: header */
629         char fullcontact[128];                  /* The Contact: that the UA registers with us */
630         char accountcode[AST_MAX_ACCOUNT_CODE]; /* Account code */
631         char our_contact[256];                  /* Our contact header */
632         char *rpid;                             /* Our RPID header */
633         char *rpid_from;                        /* Our RPID From header */
634         char realm[MAXHOSTNAMELEN];             /* Authorization realm */
635         char nonce[256];                        /* Authorization nonce */
636         char opaque[256];                       /* Opaque nonsense */
637         char qop[80];                           /* Quality of Protection, since SIP wasn't complicated enough yet. */
638         char domain[MAXHOSTNAMELEN];            /* Authorization domain */
639         char lastmsg[256];                      /* Last Message sent/received */
640         int amaflags;                           /* AMA Flags */
641         int pendinginvite;                      /* Any pending invite */
642 #ifdef OSP_SUPPORT
643         int osphandle;                          /* OSP Handle for call */
644         time_t ospstart;                        /* OSP Start time */
645         unsigned int osptimelimit;              /* OSP call duration limit */
646 #endif
647         struct sip_request initreq;             /* Initial request */
648         
649         int maxtime;                            /* Max time for first response */
650         int maxforwards;                        /* keep the max-forwards info */
651         int initid;                             /* Auto-congest ID if appropriate */
652         int autokillid;                         /* Auto-kill ID */
653         time_t lastrtprx;                       /* Last RTP received */
654         time_t lastrtptx;                       /* Last RTP sent */
655         int rtptimeout;                         /* RTP timeout time */
656         int rtpholdtimeout;                     /* RTP timeout when on hold */
657         int rtpkeepalive;                       /* Send RTP packets for keepalive */
658         enum subscriptiontype subscribed;       /* Is this call a subscription?  */
659         int stateid;
660         int laststate;                          /* Last known extension state */
661         int dialogver;
662         
663         struct ast_dsp *vad;                    /* Voice Activation Detection dsp */
664         
665         struct sip_peer *peerpoke;              /* If this calls is to poke a peer, which one */
666         struct sip_registry *registry;          /* If this is a REGISTER call, to which registry */
667         struct ast_rtp *rtp;                    /* RTP Session */
668         struct ast_rtp *vrtp;                   /* Video RTP session */
669         struct sip_pkt *packets;                /* Packets scheduled for re-transmission */
670         struct sip_history *history;            /* History of this SIP dialog */
671         struct ast_variable *chanvars;          /* Channel variables to set for call */
672         struct sip_pvt *next;                   /* Next call in chain */
673         struct sip_invite_param *options;       /* Options for INVITE */
674 } *iflist = NULL;
675
676 #define FLAG_RESPONSE (1 << 0)
677 #define FLAG_FATAL (1 << 1)
678
679 /* sip packet - read in sipsock_read, transmitted in send_request */
680 struct sip_pkt {
681         struct sip_pkt *next;                   /* Next packet */
682         int retrans;                            /* Retransmission number */
683         int method;                             /* SIP method for this packet */
684         int seqno;                              /* Sequence number */
685         unsigned int flags;                     /* non-zero if this is a response packet (e.g. 200 OK) */
686         struct sip_pvt *owner;                  /* Owner call */
687         int retransid;                          /* Retransmission ID */
688         int timer_a;                            /* SIP timer A, retransmission timer */
689         int timer_t1;                           /* SIP Timer T1, estimated RTT or 500 ms */
690         int packetlen;                          /* Length of packet */
691         char data[0];
692 };      
693
694 /* Structure for SIP user data. User's place calls to us */
695 struct sip_user {
696         /* Users who can access various contexts */
697         ASTOBJ_COMPONENTS(struct sip_user);
698         char secret[80];                /* Password */
699         char md5secret[80];             /* Password in md5 */
700         char context[AST_MAX_CONTEXT];  /* Default context for incoming calls */
701         char subscribecontext[AST_MAX_CONTEXT]; /* Default context for subscriptions */
702         char cid_num[80];               /* Caller ID num */
703         char cid_name[80];              /* Caller ID name */
704         char accountcode[AST_MAX_ACCOUNT_CODE]; /* Account code */
705         char language[MAX_LANGUAGE];    /* Default language for this user */
706         char musicclass[MAX_MUSICCLASS];/* Music on Hold class */
707         char useragent[256];            /* User agent in SIP request */
708         struct ast_codec_pref prefs;    /* codec prefs */
709         ast_group_t callgroup;          /* Call group */
710         ast_group_t pickupgroup;        /* Pickup Group */
711         unsigned int flags;             /* SIP flags */ 
712         unsigned int sipoptions;        /* Supported SIP options */
713         struct ast_flags flags_page2;   /* SIP_PAGE2 flags */
714         int amaflags;                   /* AMA flags for billing */
715         int callingpres;                /* Calling id presentation */
716         int capability;                 /* Codec capability */
717         int inUse;                      /* Number of calls in use */
718         int call_limit;                 /* Limit of concurrent calls */
719         struct ast_ha *ha;              /* ACL setting */
720         struct ast_variable *chanvars;  /* Variables to set for channel created by user */
721 };
722
723 /* Structure for SIP peer data, we place calls to peers if registered  or fixed IP address (host) */
724 struct sip_peer {
725         ASTOBJ_COMPONENTS(struct sip_peer);     /* name, refcount, objflags,  object pointers */
726                                         /* peer->name is the unique name of this object */
727         char secret[80];                /* Password */
728         char md5secret[80];             /* Password in MD5 */
729         struct sip_auth *auth;          /* Realm authentication list */
730         char context[AST_MAX_CONTEXT];  /* Default context for incoming calls */
731         char subscribecontext[AST_MAX_CONTEXT]; /* Default context for subscriptions */
732         char username[80];              /* Temporary username until registration */ 
733         char accountcode[AST_MAX_ACCOUNT_CODE]; /* Account code */
734         int amaflags;                   /* AMA Flags (for billing) */
735         char tohost[MAXHOSTNAMELEN];    /* If not dynamic, IP address */
736         char regexten[AST_MAX_EXTENSION]; /* Extension to register (if regcontext is used) */
737         char fromuser[80];              /* From: user when calling this peer */
738         char fromdomain[MAXHOSTNAMELEN];        /* From: domain when calling this peer */
739         char fullcontact[256];          /* Contact registered with us (not in sip.conf) */
740         char cid_num[80];               /* Caller ID num */
741         char cid_name[80];              /* Caller ID name */
742         int callingpres;                /* Calling id presentation */
743         int inUse;                      /* Number of calls in use */
744         int call_limit;                 /* Limit of concurrent calls */
745         char vmexten[AST_MAX_EXTENSION];        /* Dialplan extension for MWI notify message*/
746         char mailbox[AST_MAX_EXTENSION]; /* Mailbox setting for MWI checks */
747         char language[MAX_LANGUAGE];    /* Default language for prompts */
748         char musicclass[MAX_MUSICCLASS];/* Music on Hold class */
749         char useragent[256];            /* User agent in SIP request (saved from registration) */
750         struct ast_codec_pref prefs;    /* codec prefs */
751         int lastmsgssent;
752         time_t  lastmsgcheck;           /* Last time we checked for MWI */
753         unsigned int flags;             /* SIP flags */ 
754         unsigned int sipoptions;        /* Supported SIP options */
755         struct ast_flags flags_page2;   /* SIP_PAGE2 flags */
756         int expire;                     /* When to expire this peer registration */
757         int capability;                 /* Codec capability */
758         int rtptimeout;                 /* RTP timeout */
759         int rtpholdtimeout;             /* RTP Hold Timeout */
760         int rtpkeepalive;               /* Send RTP packets for keepalive */
761         ast_group_t callgroup;          /* Call group */
762         ast_group_t pickupgroup;        /* Pickup group */
763         struct ast_dnsmgr_entry *dnsmgr;/* DNS refresh manager for peer */
764         struct sockaddr_in addr;        /* IP address of peer */
765
766         /* Qualification */
767         struct sip_pvt *call;           /* Call pointer */
768         int pokeexpire;                 /* When to expire poke (qualify= checking) */
769         int lastms;                     /* How long last response took (in ms), or -1 for no response */
770         int maxms;                      /* Max ms we will accept for the host to be up, 0 to not monitor */
771         struct timeval ps;              /* Ping send time */
772         
773         struct sockaddr_in defaddr;     /* Default IP address, used until registration */
774         struct ast_ha *ha;              /* Access control list */
775         struct ast_variable *chanvars;  /* Variables to set for channel created by user */
776         int lastmsg;
777 };
778
779 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
780 static int sip_reloading = 0;
781
782 /* States for outbound registrations (with register= lines in sip.conf */
783 #define REG_STATE_UNREGISTERED          0
784 #define REG_STATE_REGSENT               1
785 #define REG_STATE_AUTHSENT              2
786 #define REG_STATE_REGISTERED            3
787 #define REG_STATE_REJECTED              4
788 #define REG_STATE_TIMEOUT               5
789 #define REG_STATE_NOAUTH                6
790 #define REG_STATE_FAILED                7
791
792
793 /* sip_registry: Registrations with other SIP proxies */
794 struct sip_registry {
795         ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
796         int portno;                     /* Optional port override */
797         char username[80];              /* Who we are registering as */
798         char authuser[80];              /* Who we *authenticate* as */
799         char hostname[MAXHOSTNAMELEN];  /* Domain or host we register to */
800         char secret[80];                /* Password or key name in []'s */      
801         char md5secret[80];
802         char contact[256];              /* Contact extension */
803         char random[80];
804         int expire;                     /* Sched ID of expiration */
805         int regattempts;                /* Number of attempts (since the last success) */
806         int timeout;                    /* sched id of sip_reg_timeout */
807         int refresh;                    /* How often to refresh */
808         struct sip_pvt *call;           /* create a sip_pvt structure for each outbound "registration call" in progress */
809         int regstate;                   /* Registration state (see above) */
810         int callid_valid;               /* 0 means we haven't chosen callid for this registry yet. */
811         char callid[80];                /* Global CallID for this registry */
812         unsigned int ocseq;             /* Sequence number we got to for REGISTERs for this registry */
813         struct sockaddr_in us;          /* Who the server thinks we are */
814         
815                                         /* Saved headers */
816         char realm[MAXHOSTNAMELEN];     /* Authorization realm */
817         char nonce[256];                /* Authorization nonce */
818         char domain[MAXHOSTNAMELEN];    /* Authorization domain */
819         char opaque[256];               /* Opaque nonsense */
820         char qop[80];                   /* Quality of Protection. */
821  
822         char lastmsg[256];              /* Last Message sent/received */
823 };
824
825 /*--- The user list: Users and friends ---*/
826 static struct ast_user_list {
827         ASTOBJ_CONTAINER_COMPONENTS(struct sip_user);
828 } userl;
829
830 /*--- The peer list: Peers and Friends ---*/
831 static struct ast_peer_list {
832         ASTOBJ_CONTAINER_COMPONENTS(struct sip_peer);
833 } peerl;
834
835 /*--- The register list: Other SIP proxys we register with and call ---*/
836 static struct ast_register_list {
837         ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
838         int recheck;
839 } regl;
840
841
842 static int __sip_do_register(struct sip_registry *r);
843
844 static int sipsock  = -1;
845
846
847 static struct sockaddr_in bindaddr;
848 static struct sockaddr_in externip;
849 static char externhost[MAXHOSTNAMELEN] = "";
850 static time_t externexpire = 0;
851 static int externrefresh = 10;
852 static struct ast_ha *localaddr;
853
854 /* The list of manual NOTIFY types we know how to send */
855 struct ast_config *notify_types;
856
857 static struct sip_auth *authl;          /* Authentication list */
858
859
860 static struct ast_frame  *sip_read(struct ast_channel *ast);
861 static int transmit_response(struct sip_pvt *p, char *msg, struct sip_request *req);
862 static int transmit_response_with_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
863 static int transmit_response_with_unsupported(struct sip_pvt *p, char *msg, struct sip_request *req, char *unsupported);
864 static int transmit_response_with_auth(struct sip_pvt *p, char *msg, struct sip_request *req, char *rand, int reliable, char *header, int stale);
865 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, int reliable, int newbranch);
866 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int inc, int reliable, int newbranch);
867 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sendsdp, int init);
868 static int transmit_reinvite_with_sdp(struct sip_pvt *p);
869 static int transmit_info_with_digit(struct sip_pvt *p, char digit);
870 static int transmit_info_with_vidupdate(struct sip_pvt *p);
871 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
872 static int transmit_refer(struct sip_pvt *p, const char *dest);
873 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
874 static struct sip_peer *temp_peer(const char *name);
875 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, char *header, char *respheader, int sipmethod, int init);
876 static void free_old_route(struct sip_route *route);
877 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
878 static int update_call_counter(struct sip_pvt *fup, int event);
879 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, int realtime);
880 static struct sip_user *build_user(const char *name, struct ast_variable *v, int realtime);
881 static int sip_do_reload(void);
882 static int expire_register(void *data);
883 static int callevents = 0;
884
885 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
886 static int sip_devicestate(void *data);
887 static int sip_sendtext(struct ast_channel *ast, const char *text);
888 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
889 static int sip_hangup(struct ast_channel *ast);
890 static int sip_answer(struct ast_channel *ast);
891 static struct ast_frame *sip_read(struct ast_channel *ast);
892 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
893 static int sip_indicate(struct ast_channel *ast, int condition);
894 static int sip_transfer(struct ast_channel *ast, const char *dest);
895 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
896 static int sip_senddigit(struct ast_channel *ast, char digit);
897 static int clear_realm_authentication(struct sip_auth *authlist);                            /* Clear realm authentication list (at reload) */
898 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, char *configuration, int lineno);   /* Add realm authentication in list */
899 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, char *realm);         /* Find authentication for a specific realm */
900 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
901 static void append_date(struct sip_request *req);       /* Append date to SIP packet */
902 static int determine_firstline_parts(struct sip_request *req);
903 static void sip_dump_history(struct sip_pvt *dialog);   /* Dump history to LOG_DEBUG at end of dialog, before destroying data */
904 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
905 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int substate);
906
907 /* Definition of this channel for channel registration */
908 static const struct ast_channel_tech sip_tech = {
909         .type = channeltype,
910         .description = "Session Initiation Protocol (SIP)",
911         .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
912         .properties = AST_CHAN_TP_WANTSJITTER,
913         .requester = sip_request_call,
914         .devicestate = sip_devicestate,
915         .call = sip_call,
916         .hangup = sip_hangup,
917         .answer = sip_answer,
918         .read = sip_read,
919         .write = sip_write,
920         .write_video = sip_write,
921         .indicate = sip_indicate,
922         .transfer = sip_transfer,
923         .fixup = sip_fixup,
924         .send_digit = sip_senddigit,
925         .bridge = ast_rtp_bridge,
926         .send_text = sip_sendtext,
927 };
928
929 /*--- find_sip_method: Find SIP method from header */
930 int find_sip_method(char *msg)
931 {
932         int i, res = 0;
933         
934         if (!msg || ast_strlen_zero(msg))
935                 return 0;
936
937         /* Strictly speaking, SIP methods are case SENSITIVE, but we don't check */
938         /* following Jon Postel's rule: Be gentle in what you accept, strict with what you send */
939         for (i = 1; (i < (sizeof(sip_methods) / sizeof(sip_methods[0]))) && !res; i++) {
940                 if (!strcasecmp(sip_methods[i].text, msg)) 
941                         res = sip_methods[i].id;
942         }
943         return res;
944 }
945
946 /*--- parse_sip_options: Parse supported header in incoming packet */
947 unsigned int parse_sip_options(struct sip_pvt *pvt, char *supported)
948 {
949         char *next = NULL;
950         char *sep = NULL;
951         char *temp = ast_strdupa(supported);
952         int i;
953         unsigned int profile = 0;
954
955         if (!supported || ast_strlen_zero(supported) )
956                 return 0;
957
958         if (option_debug > 2 && sipdebug)
959                 ast_log(LOG_DEBUG, "Begin: parsing SIP \"Supported: %s\"\n", supported);
960
961         next = temp;
962         while (next) {
963                 char res=0;
964                 if ( (sep = strchr(next, ',')) != NULL) {
965                         *sep = '\0';
966                         sep++;
967                 }
968                 while (*next == ' ')    /* Skip spaces */
969                         next++;
970                 if (option_debug > 2 && sipdebug)
971                         ast_log(LOG_DEBUG, "Found SIP option: -%s-\n", next);
972                 for (i=0; (i < (sizeof(sip_options) / sizeof(sip_options[0]))) && !res; i++) {
973                         if (!strcasecmp(next, sip_options[i].text)) {
974                                 profile |= sip_options[i].id;
975                                 res = 1;
976                                 if (option_debug > 2 && sipdebug)
977                                         ast_log(LOG_DEBUG, "Matched SIP option: %s\n", next);
978                         }
979                 }
980                 if (!res) 
981                         if (option_debug > 2 && sipdebug)
982                                 ast_log(LOG_DEBUG, "Found no match for SIP option: %s (Please file bug report!)\n", next);
983                 next = sep;
984         }
985         if (pvt) {
986                 pvt->sipoptions = profile;
987                 if (option_debug)
988                         ast_log(LOG_DEBUG, "* SIP extension value: %d for call %s\n", profile, pvt->callid);
989         }
990         return profile;
991 }
992
993 /*--- sip_debug_test_addr: See if we pass debug IP filter */
994 static inline int sip_debug_test_addr(struct sockaddr_in *addr) 
995 {
996         if (sipdebug == 0)
997                 return 0;
998         if (debugaddr.sin_addr.s_addr) {
999                 if (((ntohs(debugaddr.sin_port) != 0)
1000                         && (debugaddr.sin_port != addr->sin_port))
1001                         || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
1002                         return 0;
1003         }
1004         return 1;
1005 }
1006
1007 /*--- sip_debug_test_pvt: Test PVT for debugging output */
1008 static inline int sip_debug_test_pvt(struct sip_pvt *p) 
1009 {
1010         if (sipdebug == 0)
1011                 return 0;
1012         return sip_debug_test_addr(((ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE) ? &p->recv : &p->sa));
1013 }
1014
1015
1016 /*--- __sip_xmit: Transmit SIP message ---*/
1017 static int __sip_xmit(struct sip_pvt *p, char *data, int len)
1018 {
1019         int res;
1020         char iabuf[INET_ADDRSTRLEN];
1021
1022         if (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE)
1023                 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->recv, sizeof(struct sockaddr_in));
1024         else
1025                 res=sendto(sipsock, data, len, 0, (struct sockaddr *)&p->sa, sizeof(struct sockaddr_in));
1026         if (res != len) {
1027                 ast_log(LOG_WARNING, "sip_xmit of %p (len %d) to %s returned %d: %s\n", data, len, ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), res, strerror(errno));
1028         }
1029         return res;
1030 }
1031
1032 static void sip_destroy(struct sip_pvt *p);
1033
1034 /*--- build_via: Build a Via header for a request ---*/
1035 static void build_via(struct sip_pvt *p, char *buf, int len)
1036 {
1037         char iabuf[INET_ADDRSTRLEN];
1038
1039         /* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
1040         if (ast_test_flag(p, SIP_NAT) & SIP_NAT_RFC3581)
1041                 snprintf(buf, len, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x;rport", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport, p->branch);
1042         else /* Work around buggy UNIDEN UIP200 firmware */
1043                 snprintf(buf, len, "SIP/2.0/UDP %s:%d;branch=z9hG4bK%08x", ast_inet_ntoa(iabuf, sizeof(iabuf), p->ourip), ourport, p->branch);
1044 }
1045
1046 /*--- ast_sip_ouraddrfor: NAT fix - decide which IP address to use for ASterisk server? ---*/
1047 /* Only used for outbound registrations */
1048 static int ast_sip_ouraddrfor(struct in_addr *them, struct in_addr *us)
1049 {
1050         /*
1051          * Using the localaddr structure built up with localnet statements
1052          * apply it to their address to see if we need to substitute our
1053          * externip or can get away with our internal bindaddr
1054          */
1055         struct sockaddr_in theirs;
1056         theirs.sin_addr = *them;
1057         if (localaddr && externip.sin_addr.s_addr &&
1058            ast_apply_ha(localaddr, &theirs)) {
1059                 char iabuf[INET_ADDRSTRLEN];
1060                 if (externexpire && (time(NULL) >= externexpire)) {
1061                         struct ast_hostent ahp;
1062                         struct hostent *hp;
1063                         time(&externexpire);
1064                         externexpire += externrefresh;
1065                         if ((hp = ast_gethostbyname(externhost, &ahp))) {
1066                                 memcpy(&externip.sin_addr, hp->h_addr, sizeof(externip.sin_addr));
1067                         } else
1068                                 ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
1069                 }
1070                 memcpy(us, &externip.sin_addr, sizeof(struct in_addr));
1071                 ast_inet_ntoa(iabuf, sizeof(iabuf), *(struct in_addr *)&them->s_addr);
1072                 ast_log(LOG_DEBUG, "Target address %s is not local, substituting externip\n", iabuf);
1073         }
1074         else if (bindaddr.sin_addr.s_addr)
1075                 memcpy(us, &bindaddr.sin_addr, sizeof(struct in_addr));
1076         else
1077                 return ast_ouraddrfor(them, us);
1078         return 0;
1079 }
1080
1081 /*--- append_history: Append to SIP dialog history */
1082 /*      Always returns 0 */
1083 static int append_history(struct sip_pvt *p, const char *event, const char *data)
1084 {
1085         struct sip_history *hist, *prev;
1086         char *c;
1087
1088         if (!recordhistory || !p)
1089                 return 0;
1090         if(!(hist = malloc(sizeof(struct sip_history)))) {
1091                 ast_log(LOG_WARNING, "Can't allocate memory for history");
1092                 return 0;
1093         }
1094         memset(hist, 0, sizeof(struct sip_history));
1095         snprintf(hist->event, sizeof(hist->event), "%-15s %s", event, data);
1096         /* Trim up nicely */
1097         c = hist->event;
1098         while(*c) {
1099                 if ((*c == '\r') || (*c == '\n')) {
1100                         *c = '\0';
1101                         break;
1102                 }
1103                 c++;
1104         }
1105         /* Enqueue into history */
1106         prev = p->history;
1107         if (prev) {
1108                 while(prev->next)
1109                         prev = prev->next;
1110                 prev->next = hist;
1111         } else {
1112                 p->history = hist;
1113         }
1114         return 0;
1115 }
1116
1117 /*--- retrans_pkt: Retransmit SIP message if no answer ---*/
1118 static int retrans_pkt(void *data)
1119 {
1120         struct sip_pkt *pkt=data, *prev, *cur = NULL;
1121         char iabuf[INET_ADDRSTRLEN];
1122         int reschedule = DEFAULT_RETRANS;
1123
1124         /* Lock channel */
1125         ast_mutex_lock(&pkt->owner->lock);
1126
1127         if (pkt->retrans < MAX_RETRANS) {
1128                 char buf[80];
1129
1130                 pkt->retrans++;
1131                 if (!pkt->timer_t1) {   /* Re-schedule using timer_a and timer_t1 */
1132                         if (sipdebug && option_debug > 3)
1133                                 ast_log(LOG_DEBUG, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n", pkt->retransid, sip_methods[pkt->method].text, pkt->method);
1134                 } else {
1135                         int siptimer_a;
1136
1137                         if (sipdebug && option_debug > 3)
1138                                 ast_log(LOG_DEBUG, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
1139                         if (!pkt->timer_a)
1140                                 pkt->timer_a = 2 ;
1141                         else
1142                                 pkt->timer_a = 2 * pkt->timer_a;
1143  
1144                         /* For non-invites, a maximum of 4 secs */
1145                         siptimer_a = pkt->timer_t1 * pkt->timer_a;      /* Double each time */
1146                         if (pkt->method != SIP_INVITE && siptimer_a > 4000)
1147                                 siptimer_a = 4000;
1148                 
1149                         /* Reschedule re-transmit */
1150                         reschedule = siptimer_a;
1151                         if (option_debug > 3)
1152                                 ast_log(LOG_DEBUG, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n", pkt->retrans +1, siptimer_a, pkt->timer_t1, pkt->retransid);
1153                 } 
1154
1155                 if (pkt->owner && sip_debug_test_pvt(pkt->owner)) {
1156                         if (ast_test_flag(pkt->owner, SIP_NAT) & SIP_NAT_ROUTE)
1157                                 ast_verbose("Retransmitting #%d (NAT) to %s:%d:\n%s\n---\n", pkt->retrans, ast_inet_ntoa(iabuf, sizeof(iabuf), pkt->owner->recv.sin_addr), ntohs(pkt->owner->recv.sin_port), pkt->data);
1158                         else
1159                                 ast_verbose("Retransmitting #%d (no NAT) to %s:%d:\n%s\n---\n", pkt->retrans, ast_inet_ntoa(iabuf, sizeof(iabuf), pkt->owner->sa.sin_addr), ntohs(pkt->owner->sa.sin_port), pkt->data);
1160                 }
1161                 snprintf(buf, sizeof(buf), "ReTx %d", reschedule);
1162
1163                 append_history(pkt->owner, buf, pkt->data);
1164                 __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
1165                 ast_mutex_unlock(&pkt->owner->lock);
1166                 return  reschedule;
1167         } 
1168         /* Too many retries */
1169         if (pkt->owner && pkt->method != SIP_OPTIONS) {
1170                 if (ast_test_flag(pkt, FLAG_FATAL) || sipdebug) /* Tell us if it's critical or if we're debugging */
1171                         ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %s for seqno %d (%s %s)\n", pkt->owner->callid, pkt->seqno, (ast_test_flag(pkt, FLAG_FATAL)) ? "Critical" : "Non-critical", (ast_test_flag(pkt, FLAG_RESPONSE)) ? "Response" : "Request");
1172         } else {
1173                 if (pkt->method == SIP_OPTIONS && sipdebug)
1174                         ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) \n", pkt->owner->callid);
1175         }
1176         append_history(pkt->owner, "MaxRetries", (ast_test_flag(pkt, FLAG_FATAL)) ? "(Critical)" : "(Non-critical)");
1177                 
1178         pkt->retransid = -1;
1179
1180         if (ast_test_flag(pkt, FLAG_FATAL)) {
1181                 while(pkt->owner->owner && ast_mutex_trylock(&pkt->owner->owner->lock)) {
1182                         ast_mutex_unlock(&pkt->owner->lock);
1183                         usleep(1);
1184                         ast_mutex_lock(&pkt->owner->lock);
1185                 }
1186                 if (pkt->owner->owner) {
1187                         ast_set_flag(pkt->owner, SIP_ALREADYGONE);
1188                         ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet.\n", pkt->owner->callid);
1189                         ast_queue_hangup(pkt->owner->owner);
1190                         ast_mutex_unlock(&pkt->owner->owner->lock);
1191                 } else {
1192                         /* If no channel owner, destroy now */
1193                         ast_set_flag(pkt->owner, SIP_NEEDDESTROY);      
1194                 }
1195         }
1196         /* In any case, go ahead and remove the packet */
1197         prev = NULL;
1198         cur = pkt->owner->packets;
1199         while(cur) {
1200                 if (cur == pkt)
1201                         break;
1202                 prev = cur;
1203                 cur = cur->next;
1204         }
1205         if (cur) {
1206                 if (prev)
1207                         prev->next = cur->next;
1208                 else
1209                         pkt->owner->packets = cur->next;
1210                 ast_mutex_unlock(&pkt->owner->lock);
1211                 free(cur);
1212                 pkt = NULL;
1213         } else
1214                 ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
1215         if (pkt)
1216                 ast_mutex_unlock(&pkt->owner->lock);
1217         return 0;
1218 }
1219
1220 /*--- __sip_reliable_xmit: transmit packet with retransmits ---*/
1221 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, char *data, int len, int fatal, int sipmethod)
1222 {
1223         struct sip_pkt *pkt;
1224         int siptimer_a = DEFAULT_RETRANS;
1225
1226         pkt = malloc(sizeof(struct sip_pkt) + len + 1);
1227         if (!pkt)
1228                 return -1;
1229         memset(pkt, 0, sizeof(struct sip_pkt));
1230         memcpy(pkt->data, data, len);
1231         pkt->method = sipmethod;
1232         pkt->packetlen = len;
1233         pkt->next = p->packets;
1234         pkt->owner = p;
1235         pkt->seqno = seqno;
1236         pkt->flags = resp;
1237         pkt->data[len] = '\0';
1238         pkt->timer_t1 = p->timer_t1;    /* Set SIP timer T1 */
1239         if (fatal)
1240                 ast_set_flag(pkt, FLAG_FATAL);
1241         if (pkt->timer_t1)
1242                 siptimer_a = pkt->timer_t1 * 2;
1243
1244         /* Schedule retransmission */
1245         pkt->retransid = ast_sched_add_variable(sched, siptimer_a, retrans_pkt, pkt, 1);
1246         if (option_debug > 3 && sipdebug)
1247                 ast_log(LOG_DEBUG, "*** SIP TIMER: Initalizing retransmit timer on packet: Id  #%d\n", pkt->retransid);
1248         pkt->next = p->packets;
1249         p->packets = pkt;
1250
1251         __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);      /* Send packet */
1252         if (sipmethod == SIP_INVITE) {
1253                 /* Note this is a pending invite */
1254                 p->pendinginvite = seqno;
1255         }
1256         return 0;
1257 }
1258
1259 /*--- __sip_autodestruct: Kill a call (called by scheduler) ---*/
1260 static int __sip_autodestruct(void *data)
1261 {
1262         struct sip_pvt *p = data;
1263
1264         p->autokillid = -1;
1265
1266         /* If this is a subscription, tell the phone that we got a timeout */
1267         if (p->subscribed) {
1268                 p->subscribed = TIMEOUT;
1269                 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, 1);      /* Send first notification */
1270                 p->subscribed = NONE;
1271                 append_history(p, "Subscribestatus", "timeout");
1272                 return 10000;   /* Reschedule this destruction so that we know that it's gone */
1273         }
1274         ast_log(LOG_DEBUG, "Auto destroying call '%s'\n", p->callid);
1275         append_history(p, "AutoDestroy", "");
1276         if (p->owner) {
1277                 ast_log(LOG_WARNING, "Autodestruct on call '%s' with owner in place\n", p->callid);
1278                 ast_queue_hangup(p->owner);
1279         } else {
1280                 sip_destroy(p);
1281         }
1282         return 0;
1283 }
1284
1285 /*--- sip_scheddestroy: Schedule destruction of SIP call ---*/
1286 static int sip_scheddestroy(struct sip_pvt *p, int ms)
1287 {
1288         char tmp[80];
1289         if (sip_debug_test_pvt(p))
1290                 ast_verbose("Scheduling destruction of call '%s' in %d ms\n", p->callid, ms);
1291         if (recordhistory) {
1292                 snprintf(tmp, sizeof(tmp), "%d ms", ms);
1293                 append_history(p, "SchedDestroy", tmp);
1294         }
1295
1296         if (p->autokillid > -1)
1297                 ast_sched_del(sched, p->autokillid);
1298         p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, p);
1299         return 0;
1300 }
1301
1302 /*--- sip_cancel_destroy: Cancel destruction of SIP call ---*/
1303 static int sip_cancel_destroy(struct sip_pvt *p)
1304 {
1305         if (p->autokillid > -1)
1306                 ast_sched_del(sched, p->autokillid);
1307         append_history(p, "CancelDestroy", "");
1308         p->autokillid = -1;
1309         return 0;
1310 }
1311
1312 /*--- __sip_ack: Acknowledges receipt of a packet and stops retransmission ---*/
1313 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
1314 {
1315         struct sip_pkt *cur, *prev = NULL;
1316         int res = -1;
1317         int resetinvite = 0;
1318         /* Just in case... */
1319         char *msg;
1320
1321         msg = sip_methods[sipmethod].text;
1322
1323         cur = p->packets;
1324         while(cur) {
1325                 if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) &&
1326                         ((ast_test_flag(cur, FLAG_RESPONSE)) || 
1327                          (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
1328                         ast_mutex_lock(&p->lock);
1329                         if (!resp && (seqno == p->pendinginvite)) {
1330                                 ast_log(LOG_DEBUG, "Acked pending invite %d\n", p->pendinginvite);
1331                                 p->pendinginvite = 0;
1332                                 resetinvite = 1;
1333                         }
1334                         /* this is our baby */
1335                         if (prev)
1336                                 prev->next = cur->next;
1337                         else
1338                                 p->packets = cur->next;
1339                         if (cur->retransid > -1) {
1340                                 if (sipdebug && option_debug > 3)
1341                                         ast_log(LOG_DEBUG, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
1342                                 ast_sched_del(sched, cur->retransid);
1343                         }
1344                         free(cur);
1345                         ast_mutex_unlock(&p->lock);
1346                         res = 0;
1347                         break;
1348                 }
1349                 prev = cur;
1350                 cur = cur->next;
1351         }
1352         ast_log(LOG_DEBUG, "Stopping retransmission on '%s' of %s %d: Match %s\n", p->callid, resp ? "Response" : "Request", seqno, res ? "Not Found" : "Found");
1353         return res;
1354 }
1355
1356 /* Pretend to ack all packets */
1357 static int __sip_pretend_ack(struct sip_pvt *p)
1358 {
1359         struct sip_pkt *cur=NULL;
1360
1361         while(p->packets) {
1362                 if (cur == p->packets) {
1363                         ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
1364                         return -1;
1365                 }
1366                 cur = p->packets;
1367                 if (cur->method)
1368                         __sip_ack(p, p->packets->seqno, (ast_test_flag(p->packets, FLAG_RESPONSE)), cur->method);
1369                 else {  /* Unknown packet type */
1370                         char *c;
1371                         char method[128];
1372                         ast_copy_string(method, p->packets->data, sizeof(method));
1373                         c = ast_skip_blanks(method); /* XXX what ? */
1374                         *c = '\0';
1375                         __sip_ack(p, p->packets->seqno, (ast_test_flag(p->packets, FLAG_RESPONSE)), find_sip_method(method));
1376                 }
1377         }
1378         return 0;
1379 }
1380
1381 /*--- __sip_semi_ack: Acks receipt of packet, keep it around (used for provisional responses) ---*/
1382 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
1383 {
1384         struct sip_pkt *cur;
1385         int res = -1;
1386         char *msg = sip_methods[sipmethod].text;
1387
1388         cur = p->packets;
1389         while(cur) {
1390                 if ((cur->seqno == seqno) && ((ast_test_flag(cur, FLAG_RESPONSE)) == resp) &&
1391                         ((ast_test_flag(cur, FLAG_RESPONSE)) || 
1392                          (!strncasecmp(msg, cur->data, strlen(msg)) && (cur->data[strlen(msg)] < 33)))) {
1393                         /* this is our baby */
1394                         if (cur->retransid > -1) {
1395                                 if (option_debug > 3 && sipdebug)
1396                                         ast_log(LOG_DEBUG, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, msg);
1397                                 ast_sched_del(sched, cur->retransid);
1398                         }
1399                         cur->retransid = -1;
1400                         res = 0;
1401                         break;
1402                 }
1403                 cur = cur->next;
1404         }
1405         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");
1406         return res;
1407 }
1408
1409 static void parse_request(struct sip_request *req);
1410 static char *get_header(struct sip_request *req, char *name);
1411 static void copy_request(struct sip_request *dst,struct sip_request *src);
1412
1413 /*--- parse_copy: Copy SIP request, parse it */
1414 static void parse_copy(struct sip_request *dst, struct sip_request *src)
1415 {
1416         memset(dst, 0, sizeof(*dst));
1417         memcpy(dst->data, src->data, sizeof(dst->data));
1418         dst->len = src->len;
1419         parse_request(dst);
1420 }
1421
1422 /*--- send_response: Transmit response on SIP request---*/
1423 static int send_response(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
1424 {
1425         int res;
1426         char iabuf[INET_ADDRSTRLEN];
1427         struct sip_request tmp;
1428         char tmpmsg[80];
1429
1430         if (sip_debug_test_pvt(p)) {
1431                 if (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE)
1432                         ast_verbose("%sTransmitting (NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr), ntohs(p->recv.sin_port), req->data);
1433                 else
1434                         ast_verbose("%sTransmitting (no NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), ntohs(p->sa.sin_port), req->data);
1435         }
1436         if (reliable) {
1437                 if (recordhistory) {
1438                         parse_copy(&tmp, req);
1439                         snprintf(tmpmsg, sizeof(tmpmsg), "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
1440                         append_history(p, "TxRespRel", tmpmsg);
1441                 }
1442                 res = __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable > 1), req->method);
1443         } else {
1444                 if (recordhistory) {
1445                         parse_copy(&tmp, req);
1446                         snprintf(tmpmsg, sizeof(tmpmsg), "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
1447                         append_history(p, "TxResp", tmpmsg);
1448                 }
1449                 res = __sip_xmit(p, req->data, req->len);
1450         }
1451         if (res > 0)
1452                 return 0;
1453         return res;
1454 }
1455
1456 /*--- send_request: Send SIP Request to the other part of the dialogue ---*/
1457 static int send_request(struct sip_pvt *p, struct sip_request *req, int reliable, int seqno)
1458 {
1459         int res;
1460         char iabuf[INET_ADDRSTRLEN];
1461         struct sip_request tmp;
1462         char tmpmsg[80];
1463
1464         if (sip_debug_test_pvt(p)) {
1465                 if (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE)
1466                         ast_verbose("%sTransmitting (NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(iabuf, sizeof(iabuf), p->recv.sin_addr), ntohs(p->recv.sin_port), req->data);
1467                 else
1468                         ast_verbose("%sTransmitting (no NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(iabuf, sizeof(iabuf), p->sa.sin_addr), ntohs(p->sa.sin_port), req->data);
1469         }
1470         if (reliable) {
1471                 if (recordhistory) {
1472                         parse_copy(&tmp, req);
1473                         snprintf(tmpmsg, sizeof(tmpmsg), "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
1474                         append_history(p, "TxReqRel", tmpmsg);
1475                 }
1476                 res = __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable > 1), req->method);
1477         } else {
1478                 if (recordhistory) {
1479                         parse_copy(&tmp, req);
1480                         snprintf(tmpmsg, sizeof(tmpmsg), "%s / %s", tmp.data, get_header(&tmp, "CSeq"));
1481                         append_history(p, "TxReq", tmpmsg);
1482                 }
1483                 res = __sip_xmit(p, req->data, req->len);
1484         }
1485         return res;
1486 }
1487
1488 /*--- get_in_brackets: Pick out text in brackets from character string ---*/
1489 /* returns pointer to terminated stripped string. modifies input string. */
1490 static char *get_in_brackets(char *tmp)
1491 {
1492         char *parse;
1493         char *first_quote;
1494         char *first_bracket;
1495         char *second_bracket;
1496         char last_char;
1497
1498         parse = tmp;
1499         while (1) {
1500                 first_quote = strchr(parse, '"');
1501                 first_bracket = strchr(parse, '<');
1502                 if (first_quote && first_bracket && (first_quote < first_bracket)) {
1503                         last_char = '\0';
1504                         for (parse = first_quote + 1; *parse; parse++) {
1505                                 if ((*parse == '"') && (last_char != '\\'))
1506                                         break;
1507                                 last_char = *parse;
1508                         }
1509                         if (!*parse) {
1510                                 ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
1511                                 return tmp;
1512                         }
1513                         parse++;
1514                         continue;
1515                 }
1516                 if (first_bracket) {
1517                         second_bracket = strchr(first_bracket + 1, '>');
1518                         if (second_bracket) {
1519                                 *second_bracket = '\0';
1520                                 return first_bracket + 1;
1521                         } else {
1522                                 ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
1523                                 return tmp;
1524                         }
1525                 }
1526                 return tmp;
1527         }
1528 }
1529
1530 /*--- sip_sendtext: Send SIP MESSAGE text within a call ---*/
1531 /*      Called from PBX core text message functions */
1532 static int sip_sendtext(struct ast_channel *ast, const char *text)
1533 {
1534         struct sip_pvt *p = ast->tech_pvt;
1535         int debug=sip_debug_test_pvt(p);
1536
1537         if (debug)
1538                 ast_verbose("Sending text %s on %s\n", text, ast->name);
1539         if (!p)
1540                 return -1;
1541         if (!text || ast_strlen_zero(text))
1542                 return 0;
1543         if (debug)
1544                 ast_verbose("Really sending text %s on %s\n", text, ast->name);
1545         transmit_message_with_text(p, text);
1546         return 0;       
1547 }
1548
1549 /*--- realtime_update_peer: Update peer object in realtime storage ---*/
1550 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, int expirey)
1551 {
1552         char port[10];
1553         char ipaddr[20];
1554         char regseconds[20] = "0";
1555         
1556         if (expirey) {  /* Registration */
1557                 time_t nowtime;
1558                 time(&nowtime);
1559                 nowtime += expirey;
1560                 snprintf(regseconds, sizeof(regseconds), "%ld", nowtime);       /* Expiration time */
1561                 ast_inet_ntoa(ipaddr, sizeof(ipaddr), sin->sin_addr);
1562                 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
1563         }
1564         ast_update_realtime("sippeers", "name", peername, "ipaddr", ipaddr, "port", port, "regseconds", regseconds, "username", username, NULL);
1565 }
1566
1567 /*--- register_peer_exten: Automatically add peer extension to dial plan ---*/
1568 static void register_peer_exten(struct sip_peer *peer, int onoff)
1569 {
1570         char multi[256];
1571         char *stringp, *ext;
1572         if (!ast_strlen_zero(regcontext)) {
1573                 ast_copy_string(multi, ast_strlen_zero(peer->regexten) ? peer->name : peer->regexten, sizeof(multi));
1574                 stringp = multi;
1575                 while((ext = strsep(&stringp, "&"))) {
1576                         if (onoff)
1577                                 ast_add_extension(regcontext, 1, ext, 1, NULL, NULL, "Noop", strdup(peer->name), free, channeltype);
1578                         else
1579                                 ast_context_remove_extension(regcontext, ext, 1, NULL);
1580                 }
1581         }
1582 }
1583
1584 /*--- sip_destroy_peer: Destroy peer object from memory */
1585 static void sip_destroy_peer(struct sip_peer *peer)
1586 {
1587         /* Delete it, it needs to disappear */
1588         if (peer->call)
1589                 sip_destroy(peer->call);
1590         if (peer->chanvars) {
1591                 ast_variables_destroy(peer->chanvars);
1592                 peer->chanvars = NULL;
1593         }
1594         if (peer->expire > -1)
1595                 ast_sched_del(sched, peer->expire);
1596         if (peer->pokeexpire > -1)
1597                 ast_sched_del(sched, peer->pokeexpire);
1598         register_peer_exten(peer, 0);
1599         ast_free_ha(peer->ha);
1600         if (ast_test_flag(peer, SIP_SELFDESTRUCT))
1601                 apeerobjs--;
1602         else if (ast_test_flag(peer, SIP_REALTIME))
1603                 rpeerobjs--;
1604         else
1605                 speerobjs--;
1606         clear_realm_authentication(peer->auth);
1607         peer->auth = (struct sip_auth *) NULL;
1608         if (peer->dnsmgr)
1609                 ast_dnsmgr_release(peer->dnsmgr);
1610         free(peer);
1611 }
1612
1613 /*--- update_peer: Update peer data in database (if used) ---*/
1614 static void update_peer(struct sip_peer *p, int expiry)
1615 {
1616         if (ast_test_flag((&global_flags_page2), SIP_PAGE2_RTUPDATE) &&
1617                 (ast_test_flag(p, SIP_REALTIME) || 
1618                  ast_test_flag(&(p->flags_page2), SIP_PAGE2_RTCACHEFRIENDS))) {
1619                 realtime_update_peer(p->name, &p->addr, p->username, expiry);
1620         }
1621 }
1622
1623
1624 /*--- realtime_peer: Get peer from realtime storage ---*/
1625 /* Checks the "sippeers" realtime family from extconfig.conf */
1626 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
1627 {
1628         struct sip_peer *peer=NULL;
1629         struct ast_variable *var;
1630         struct ast_variable *tmp;
1631         char *newpeername = (char *) peername;
1632         char iabuf[80];
1633
1634         /* First check on peer name */
1635         if (newpeername) 
1636                 var = ast_load_realtime("sippeers", "name", peername, NULL);
1637         else if (sin) { /* Then check on IP address */
1638                 ast_inet_ntoa(iabuf, sizeof(iabuf), sin->sin_addr);
1639                 var = ast_load_realtime("sippeers", "ipaddr", iabuf, NULL);
1640         } else
1641                 return NULL;
1642
1643         if (!var)
1644                 return NULL;
1645
1646         tmp = var;
1647         /* If this is type=user, then skip this object. */
1648         while(tmp) {
1649                 if (!strcasecmp(tmp->name, "type") &&
1650                     !strcasecmp(tmp->value, "user")) {
1651                         ast_variables_destroy(var);
1652                         return NULL;
1653                 } else if (!newpeername && !strcasecmp(tmp->name, "name")) {
1654                         newpeername = tmp->value;
1655                 }
1656                 tmp = tmp->next;
1657         }
1658         
1659         if (!newpeername) {     /* Did not find peer in realtime */
1660                 ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", iabuf);
1661                 ast_variables_destroy(var);
1662                 return (struct sip_peer *) NULL;
1663         }
1664                 
1665         /* Peer found in realtime, now build it in memory */
1666         peer = build_peer(newpeername, var, !ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS));
1667
1668         if (!peer) {
1669                 ast_variables_destroy(var);
1670                 return (struct sip_peer *) NULL;
1671         }
1672         if (ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS)) {
1673                 /* Cache peer */
1674                 ast_copy_flags((&peer->flags_page2),(&global_flags_page2), SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
1675                 if (ast_test_flag((&global_flags_page2), SIP_PAGE2_RTAUTOCLEAR)) {
1676                         if (peer->expire > -1) {
1677                                 ast_sched_del(sched, peer->expire);
1678                         }
1679                         peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_register, (void *)peer);
1680                 }
1681                 ASTOBJ_CONTAINER_LINK(&peerl,peer);
1682         } else {
1683                 ast_set_flag(peer, SIP_REALTIME);
1684         }
1685         ast_variables_destroy(var);
1686         return peer;
1687 }
1688
1689 /*--- sip_addrcmp: Support routine for find_peer ---*/
1690 static int sip_addrcmp(char *name, struct sockaddr_in *sin)
1691 {
1692         /* We know name is the first field, so we can cast */
1693         struct sip_peer *p = (struct sip_peer *)name;
1694         return  !(!inaddrcmp(&p->addr, sin) || 
1695                                         (ast_test_flag(p, SIP_INSECURE_PORT) &&
1696                                         (p->addr.sin_addr.s_addr == sin->sin_addr.s_addr)));
1697 }
1698
1699 /*--- find_peer: Locate peer by name or ip address */
1700 /*      This is used on incoming SIP message to find matching peer on ip
1701         or outgoing message to find matching peer on name */
1702 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime)
1703 {
1704         struct sip_peer *p = NULL;
1705
1706         if (peer)
1707                 p = ASTOBJ_CONTAINER_FIND(&peerl,peer);
1708         else
1709                 p = ASTOBJ_CONTAINER_FIND_FULL(&peerl,sin,name,sip_addr_hashfunc,1,sip_addrcmp);
1710
1711         if (!p && realtime) {
1712                 p = realtime_peer(peer, sin);
1713         }
1714
1715         return p;
1716 }
1717
1718 /*--- sip_destroy_user: Remove user object from in-memory storage ---*/
1719 static void sip_destroy_user(struct sip_user *user)
1720 {
1721         ast_free_ha(user->ha);
1722         if (user->chanvars) {
1723                 ast_variables_destroy(user->chanvars);
1724                 user->chanvars = NULL;
1725         }
1726         if (ast_test_flag(user, SIP_REALTIME))
1727                 ruserobjs--;
1728         else
1729                 suserobjs--;
1730         free(user);
1731 }
1732
1733 /*--- realtime_user: Load user from realtime storage ---*/
1734 /* Loads user from "sipusers" category in realtime (extconfig.conf) */
1735 /* Users are matched on From: user name (the domain in skipped) */
1736 static struct sip_user *realtime_user(const char *username)
1737 {
1738         struct ast_variable *var;
1739         struct ast_variable *tmp;
1740         struct sip_user *user = NULL;
1741
1742         var = ast_load_realtime("sipusers", "name", username, NULL);
1743
1744         if (!var)
1745                 return NULL;
1746
1747         tmp = var;
1748         while (tmp) {
1749                 if (!strcasecmp(tmp->name, "type") &&
1750                         !strcasecmp(tmp->value, "peer")) {
1751                         ast_variables_destroy(var);
1752                         return NULL;
1753                 }
1754                 tmp = tmp->next;
1755         }
1756         
1757
1758
1759         user = build_user(username, var, !ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS));
1760         
1761         if (!user) {    /* No user found */
1762                 ast_variables_destroy(var);
1763                 return NULL;
1764         }
1765
1766         if (ast_test_flag((&global_flags_page2), SIP_PAGE2_RTCACHEFRIENDS)) {
1767                 ast_set_flag((&user->flags_page2), SIP_PAGE2_RTCACHEFRIENDS);
1768                 suserobjs++;
1769                 ASTOBJ_CONTAINER_LINK(&userl,user);
1770         } else {
1771                 /* Move counter from s to r... */
1772                 suserobjs--;
1773                 ruserobjs++;
1774                 ast_set_flag(user, SIP_REALTIME);
1775         }
1776         ast_variables_destroy(var);
1777         return user;
1778 }
1779
1780 /*--- find_user: Locate user by name ---*/
1781 /* Locates user by name (From: sip uri user name part) first
1782    from in-memory list (static configuration) then from 
1783    realtime storage (defined in extconfig.conf) */
1784 static struct sip_user *find_user(const char *name, int realtime)
1785 {
1786         struct sip_user *u = NULL;
1787         u = ASTOBJ_CONTAINER_FIND(&userl,name);
1788         if (!u && realtime) {
1789                 u = realtime_user(name);
1790         }
1791         return u;
1792 }
1793
1794 /*--- create_addr_from_peer: create address structure from peer reference ---*/
1795 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer)
1796 {
1797         char *callhost;
1798
1799         if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
1800             (!peer->maxms || ((peer->lastms >= 0)  && (peer->lastms <= peer->maxms)))) {
1801                 if (peer->addr.sin_addr.s_addr) {
1802                         r->sa.sin_family = peer->addr.sin_family;
1803                         r->sa.sin_addr = peer->addr.sin_addr;
1804                         r->sa.sin_port = peer->addr.sin_port;
1805                 } else {
1806                         r->sa.sin_family = peer->defaddr.sin_family;
1807                         r->sa.sin_addr = peer->defaddr.sin_addr;
1808                         r->sa.sin_port = peer->defaddr.sin_port;
1809                 }
1810                 memcpy(&r->recv, &r->sa, sizeof(r->recv));
1811         } else {
1812                 return -1;
1813         }
1814
1815         ast_copy_flags(r, peer, SIP_FLAGS_TO_COPY);
1816         r->capability = peer->capability;
1817         r->prefs = peer->prefs;
1818         if (r->rtp) {
1819                 ast_log(LOG_DEBUG, "Setting NAT on RTP to %d\n", (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
1820                 ast_rtp_setnat(r->rtp, (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
1821         }
1822         if (r->vrtp) {
1823                 ast_log(LOG_DEBUG, "Setting NAT on VRTP to %d\n", (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
1824                 ast_rtp_setnat(r->vrtp, (ast_test_flag(r, SIP_NAT) & SIP_NAT_ROUTE));
1825         }
1826         ast_copy_string(r->peername, peer->username, sizeof(r->peername));
1827         ast_copy_string(r->authname, peer->username, sizeof(r->authname));
1828         ast_copy_string(r->username, peer->username, sizeof(r->username));
1829         ast_copy_string(r->peersecret, peer->secret, sizeof(r->peersecret));
1830         ast_copy_string(r->peermd5secret, peer->md5secret, sizeof(r->peermd5secret));
1831         ast_copy_string(r->tohost, peer->tohost, sizeof(r->tohost));
1832         ast_copy_string(r->fullcontact, peer->fullcontact, sizeof(r->fullcontact));
1833         if (!r->initreq.headers && !ast_strlen_zero(peer->fromdomain)) {
1834                 if ((callhost = strchr(r->callid, '@'))) {
1835                         strncpy(callhost + 1, peer->fromdomain, sizeof(r->callid) - (callhost - r->callid) - 2);
1836                 }
1837         }
1838         if (ast_strlen_zero(r->tohost)) {
1839                 if (peer->addr.sin_addr.s_addr)
1840                         ast_inet_ntoa(r->tohost, sizeof(r->tohost), peer->addr.sin_addr);
1841                 else
1842                         ast_inet_ntoa(r->tohost, sizeof(r->tohost), peer->defaddr.sin_addr);
1843         }
1844         if (!ast_strlen_zero(peer->fromdomain))
1845                 ast_copy_string(r->fromdomain, peer->fromdomain, sizeof(r->fromdomain));
1846         if (!ast_strlen_zero(peer->fromuser))
1847                 ast_copy_string(r->fromuser, peer->fromuser, sizeof(r->fromuser));
1848         r->maxtime = peer->maxms;
1849         r->callgroup = peer->callgroup;
1850         r->pickupgroup = peer->pickupgroup;
1851         /* Set timer T1 to RTT for this peer (if known by qualify=) */
1852         if (peer->maxms && peer->lastms)
1853                 r->timer_t1 = peer->lastms;
1854         if ((ast_test_flag(r, SIP_DTMF) == SIP_DTMF_RFC2833) || (ast_test_flag(r, SIP_DTMF) == SIP_DTMF_AUTO))
1855                 r->noncodeccapability |= AST_RTP_DTMF;
1856         else
1857                 r->noncodeccapability &= ~AST_RTP_DTMF;
1858         ast_copy_string(r->context, peer->context,sizeof(r->context));
1859         r->rtptimeout = peer->rtptimeout;
1860         r->rtpholdtimeout = peer->rtpholdtimeout;
1861         r->rtpkeepalive = peer->rtpkeepalive;
1862         if (peer->call_limit)
1863                 ast_set_flag(r, SIP_CALL_LIMIT);
1864
1865         return 0;
1866 }
1867
1868 /*--- create_addr: create address structure from peer name ---*/
1869 /*      Or, if peer not found, find it in the global DNS */
1870 /*      returns TRUE (-1) on failure, FALSE on success */
1871 static int create_addr(struct sip_pvt *dialog, char *opeer)
1872 {
1873         struct hostent *hp;
1874         struct ast_hostent ahp;
1875         struct sip_peer *p;
1876         int found=0;
1877         char *port;
1878         int portno;
1879         char host[MAXHOSTNAMELEN], *hostn;
1880         char peer[256];
1881
1882         ast_copy_string(peer, opeer, sizeof(peer));
1883         port = strchr(peer, ':');
1884         if (port) {
1885                 *port = '\0';
1886                 port++;
1887         }
1888         dialog->sa.sin_family = AF_INET;
1889         dialog->timer_t1 = 500; /* Default SIP retransmission timer T1 (RFC 3261) */
1890         p = find_peer(peer, NULL, 1);
1891
1892         if (p) {
1893                 found++;
1894                 if (create_addr_from_peer(dialog, p))
1895                         ASTOBJ_UNREF(p, sip_destroy_peer);
1896         }
1897         if (!p) {
1898                 if (found)
1899                         return -1;
1900
1901                 hostn = peer;
1902                 if (port)
1903                         portno = atoi(port);
1904                 else
1905                         portno = DEFAULT_SIP_PORT;
1906                 if (srvlookup) {
1907                         char service[MAXHOSTNAMELEN];
1908                         int tportno;
1909                         int ret;
1910                         snprintf(service, sizeof(service), "_sip._udp.%s", peer);
1911                         ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
1912                         if (ret > 0) {
1913                                 hostn = host;
1914                                 portno = tportno;
1915                         }
1916                 }
1917                 hp = ast_gethostbyname(hostn, &ahp);
1918                 if (hp) {
1919                         ast_copy_string(dialog->tohost, peer, sizeof(dialog->tohost));
1920                         memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
1921                         dialog->sa.sin_port = htons(portno);
1922                         memcpy(&dialog->recv, &dialog->sa, sizeof(dialog->recv));
1923                         return 0;
1924                 } else {
1925                         ast_log(LOG_WARNING, "No such host: %s\n", peer);
1926                         return -1;
1927                 }
1928         } else {
1929                 ASTOBJ_UNREF(p, sip_destroy_peer);
1930                 return 0;
1931         }
1932 }
1933
1934 /*--- auto_congest: Scheduled congestion on a call ---*/
1935 static int auto_congest(void *nothing)
1936 {
1937         struct sip_pvt *p = nothing;
1938         ast_mutex_lock(&p->lock);
1939         p->initid = -1;
1940         if (p->owner) {
1941                 if (!ast_mutex_trylock(&p->owner->lock)) {
1942                         ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
1943                         ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
1944                         ast_mutex_unlock(&p->owner->lock);
1945                 }
1946         }
1947         ast_mutex_unlock(&p->lock);
1948         return 0;
1949 }
1950
1951
1952
1953
1954 /*--- sip_call: Initiate SIP call from PBX ---*/
1955 /*      used from the dial() application      */
1956 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
1957 {
1958         int res;
1959         struct sip_pvt *p;
1960 #ifdef OSP_SUPPORT
1961         char *osphandle = NULL;
1962 #endif  
1963         struct varshead *headp;
1964         struct ast_var_t *current;
1965         
1966
1967         
1968         p = ast->tech_pvt;
1969         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
1970                 ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
1971                 return -1;
1972         }
1973
1974
1975         /* Check whether there is vxml_url, distinctive ring variables */
1976
1977         headp=&ast->varshead;
1978         AST_LIST_TRAVERSE(headp,current,entries) {
1979                 /* Check whether there is a VXML_URL variable */
1980                 if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
1981                         p->options->vxml_url = ast_var_value(current);
1982                } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
1983                        p->options->uri_options = ast_var_value(current);
1984                 } else if (!p->options->distinctive_ring && !strcasecmp(ast_var_name(current), "ALERT_INFO")) {
1985                         /* Check whether there is a ALERT_INFO variable */
1986                         p->options->distinctive_ring = ast_var_value(current);
1987                 } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
1988                         /* Check whether there is a variable with a name starting with SIPADDHEADER */
1989                         p->options->addsipheaders = 1;
1990                 }
1991
1992                 
1993 #ifdef OSP_SUPPORT
1994                 else if (!p->options->osptoken && !strcasecmp(ast_var_name(current), "OSPTOKEN")) {
1995                         p->options->osptoken = ast_var_value(current);
1996                 } else if (!osphandle && !strcasecmp(ast_var_name(current), "OSPHANDLE")) {
1997                         osphandle = ast_var_value(current);
1998                 }
1999 #endif
2000         }
2001         
2002         res = 0;
2003         ast_set_flag(p, SIP_OUTGOING);
2004 #ifdef OSP_SUPPORT
2005         if (!p->options->osptoken || !osphandle || (sscanf(osphandle, "%d", &p->osphandle) != 1)) {
2006                 /* Force Disable OSP support */
2007                 ast_log(LOG_DEBUG, "Disabling OSP support for this call. osptoken = %s, osphandle = %s\n", p->options->osptoken, osphandle);
2008                 p->options->osptoken = NULL;
2009                 osphandle = NULL;
2010                 p->osphandle = -1;
2011         }
2012 #endif
2013         ast_log(LOG_DEBUG, "Outgoing Call for %s\n", p->username);
2014         res = update_call_counter(p, INC_CALL_LIMIT);
2015         if ( res != -1 ) {
2016                 p->callingpres = ast->cid.cid_pres;
2017                 p->jointcapability = p->capability;
2018                 transmit_invite(p, SIP_INVITE, 1, 2);
2019                 if (p->maxtime) {
2020                         /* Initialize auto-congest time */
2021                         p->initid = ast_sched_add(sched, p->maxtime * 4, auto_congest, p);
2022                 }
2023         }
2024         return res;
2025 }
2026
2027 /*--- sip_registry_destroy: Destroy registry object ---*/
2028 /*      Objects created with the register= statement in static configuration */
2029 static void sip_registry_destroy(struct sip_registry *reg)
2030 {
2031         /* Really delete */
2032         if (reg->call) {
2033                 /* Clear registry before destroying to ensure
2034                    we don't get reentered trying to grab the registry lock */
2035                 reg->call->registry = NULL;
2036                 sip_destroy(reg->call);
2037         }
2038         if (reg->expire > -1)
2039                 ast_sched_del(sched, reg->expire);
2040         if (reg->timeout > -1)
2041                 ast_sched_del(sched, reg->timeout);
2042         regobjs--;
2043         free(reg);
2044         
2045 }
2046
2047 /*---  __sip_destroy: Execute destrucion of call structure, release memory---*/
2048 static void __sip_destroy(struct sip_pvt *p, int lockowner)
2049 {
2050         struct sip_pvt *cur, *prev = NULL;
2051         struct sip_pkt *cp;
2052         struct sip_history *hist;
2053
2054         if (sip_debug_test_pvt(p))
2055                 ast_verbose("Destroying call '%s'\n", p->callid);
2056
2057         if (dumphistory)
2058                 sip_dump_history(p);
2059
2060         if (p->options)
2061                 free(p->options);
2062
2063         if (p->stateid > -1)
2064                 ast_extension_state_del(p->stateid, NULL);
2065         if (p->initid > -1)
2066                 ast_sched_del(sched, p->initid);
2067         if (p->autokillid > -1)
2068                 ast_sched_del(sched, p->autokillid);
2069
2070         if (p->rtp) {
2071                 ast_rtp_destroy(p->rtp);
2072         }
2073         if (p->vrtp) {
2074                 ast_rtp_destroy(p->vrtp);
2075         }
2076         if (p->route) {
2077                 free_old_route(p->route);
2078                 p->route = NULL;
2079         }
2080         if (p->registry) {
2081                 if (p->registry->call == p)
2082                         p->registry->call = NULL;
2083                 ASTOBJ_UNREF(p->registry,sip_registry_destroy);
2084         }
2085
2086         if (p->rpid)
2087                 free(p->rpid);
2088
2089         if (p->rpid_from)
2090                 free(p->rpid_from);
2091
2092         /* Unlink us from the owner if we have one */
2093         if (p->owner) {
2094                 if (lockowner)
2095                         ast_mutex_lock(&p->owner->lock);
2096                 ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
2097                 p->owner->tech_pvt = NULL;
2098                 if (lockowner)
2099                         ast_mutex_unlock(&p->owner->lock);
2100         }
2101         /* Clear history */
2102         while(p->history) {
2103                 hist = p->history;
2104                 p->history = p->history->next;
2105                 free(hist);
2106         }
2107
2108         cur = iflist;
2109         while(cur) {
2110                 if (cur == p) {
2111                         if (prev)
2112                                 prev->next = cur->next;
2113                         else
2114                                 iflist = cur->next;
2115                         break;
2116                 }
2117                 prev = cur;
2118                 cur = cur->next;
2119         }
2120         if (!cur) {
2121                 ast_log(LOG_WARNING, "Trying to destroy \"%s\", not found in dialog list?!?! \n", p->callid);
2122                 return;
2123         } 
2124         if (p->initid > -1)
2125                 ast_sched_del(sched, p->initid);
2126
2127         while((cp = p->packets)) {
2128                 p->packets = p->packets->next;
2129                 if (cp->retransid > -1) {
2130                         ast_sched_del(sched, cp->retransid);
2131                 }
2132                 free(cp);
2133         }
2134         if (p->chanvars) {
2135                 ast_variables_destroy(p->chanvars);
2136                 p->chanvars = NULL;
2137         }
2138         ast_mutex_destroy(&p->lock);
2139         free(p);
2140 }
2141
2142 /*--- update_call_counter: Handle call_limit for SIP users ---*/
2143 /* Note: This is going to be replaced by app_groupcount */
2144 /* Thought: For realtime, we should propably update storage with inuse counter... */
2145 static int update_call_counter(struct sip_pvt *fup, int event)
2146 {
2147         char name[256];
2148         int *inuse, *call_limit;
2149         int outgoing = ast_test_flag(fup, SIP_OUTGOING);
2150         struct sip_user *u = NULL;
2151         struct sip_peer *p = NULL;
2152
2153         if (option_debug > 2)
2154                 ast_log(LOG_DEBUG, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
2155         /* Test if we need to check call limits, in order to avoid 
2156            realtime lookups if we do not need it */
2157         if (!ast_test_flag(fup, SIP_CALL_LIMIT))
2158                 return 0;
2159
2160         ast_copy_string(name, fup->username, sizeof(name));
2161
2162         /* Check the list of users */
2163         u = find_user(name, 1);
2164         if (u) {
2165                 inuse = &u->inUse;
2166                 call_limit = &u->call_limit;
2167                 p = NULL;
2168         } else {
2169                 /* Try to find peer */
2170                 if (!p)
2171                         p = find_peer(fup->peername, NULL, 1);
2172                 if (p) {
2173                         inuse = &p->inUse;
2174                         call_limit = &p->call_limit;
2175                         ast_copy_string(name, fup->peername, sizeof(name));
2176                 } else {
2177                         if (option_debug > 1)
2178                                 ast_log(LOG_DEBUG, "%s is not a local user, no call limit\n", name);
2179                         return 0;
2180                 }
2181         }
2182         switch(event) {
2183                 /* incoming and outgoing affects the inUse counter */
2184                 case DEC_CALL_LIMIT:
2185                         if ( *inuse > 0 ) {
2186                                 (*inuse)--;
2187                         } else {
2188                                 *inuse = 0;
2189                         }
2190                         if (option_debug > 1 || sipdebug) {
2191                                 ast_log(LOG_DEBUG, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit);
2192                         }
2193                         break;
2194                 case INC_CALL_LIMIT:
2195                         if (*call_limit > 0 ) {
2196                                 if (*inuse >= *call_limit) {
2197                                         ast_log(LOG_ERROR, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *call_limit);
2198                                         /* inc inUse as well */
2199                                         if ( event == INC_CALL_LIMIT ) {
2200                                                 (*inuse)++;
2201                                         }
2202                                         if (u)
2203                                                 ASTOBJ_UNREF(u,sip_destroy_user);
2204                                         else
2205                                                 ASTOBJ_UNREF(p,sip_destroy_peer);
2206                                         return -1; 
2207                                 }
2208                         }
2209                         (*inuse)++;
2210                         if (option_debug > 1 || sipdebug) {
2211                                 ast_log(LOG_DEBUG, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", u ? "user":"peer", name, *inuse, *call_limit);
2212                         }
2213                         break;
2214                 default:
2215                         ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
2216         }
2217         if (u)
2218                 ASTOBJ_UNREF(u,sip_destroy_user);
2219         else
2220                 ASTOBJ_UNREF(p,sip_destroy_peer);
2221         return 0;
2222 }
2223
2224 /*--- sip_destroy: Destroy SIP call structure ---*/
2225 static void sip_destroy(struct sip_pvt *p)
2226 {
2227         ast_mutex_lock(&iflock);
2228         __sip_destroy(p, 1);
2229         ast_mutex_unlock(&iflock);
2230 }
2231
2232
2233 static int transmit_response_reliable(struct sip_pvt *p, char *msg, struct sip_request *req, int fatal);
2234
2235 /*--- hangup_sip2cause: Convert SIP hangup causes to Asterisk hangup causes ---*/
2236 static int hangup_sip2cause(int cause)
2237 {
2238 /* Possible values taken from causes.h */
2239
2240         switch(cause) {
2241                 case 403:       /* Not found */
2242                         return AST_CAUSE_CALL_REJECTED;
2243                 case 404:       /* Not found */
2244                         return AST_CAUSE_UNALLOCATED;
2245                 case 408:       /* No reaction */
2246                         return AST_CAUSE_NO_USER_RESPONSE;
2247                 case 480:       /* No answer */
2248                         return AST_CAUSE_FAILURE;
2249                 case 483:       /* Too many hops */
2250                         return AST_CAUSE_NO_ANSWER;
2251                 case 486:       /* Busy everywhere */
2252                         return AST_CAUSE_BUSY;
2253                 case 488:       /* No codecs approved */
2254                         return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
2255                 case 500:       /* Server internal failure */
2256                         return AST_CAUSE_FAILURE;
2257                 case 501:       /* Call rejected */
2258                         return AST_CAUSE_FACILITY_REJECTED;
2259                 case 502:       
2260                         return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
2261                 case 503:       /* Service unavailable */
2262                         return AST_CAUSE_CONGESTION;
2263                 default:
2264                         return AST_CAUSE_NORMAL;
2265         }
2266         /* Never reached */
2267         return 0;
2268 }
2269
2270
2271 /*--- hangup_cause2sip: Convert Asterisk hangup causes to SIP codes ---*/
2272 /* Possible values from causes.h
2273         AST_CAUSE_NOTDEFINED    AST_CAUSE_NORMAL        AST_CAUSE_BUSY
2274         AST_CAUSE_FAILURE       AST_CAUSE_CONGESTION    AST_CAUSE_UNALLOCATED
2275
2276         In addition to these, a lot of PRI codes is defined in causes.h 
2277         ...should we take care of them too ?
2278         
2279         Quote RFC 3398
2280
2281    ISUP Cause value                        SIP response
2282    ----------------                        ------------
2283    1  unallocated number                   404 Not Found
2284    2  no route to network                  404 Not found
2285    3  no route to destination              404 Not found
2286    16 normal call clearing                 --- (*)
2287    17 user busy                            486 Busy here
2288    18 no user responding                   408 Request Timeout
2289    19 no answer from the user              480 Temporarily unavailable
2290    20 subscriber absent                    480 Temporarily unavailable
2291    21 call rejected                        403 Forbidden (+)
2292    22 number changed (w/o diagnostic)      410 Gone
2293    22 number changed (w/ diagnostic)       301 Moved Permanently
2294    23 redirection to new destination       410 Gone
2295    26 non-selected user clearing           404 Not Found (=)
2296    27 destination out of order             502 Bad Gateway
2297    28 address incomplete                   484 Address incomplete
2298    29 facility rejected                    501 Not implemented
2299    31 normal unspecified                   480 Temporarily unavailable
2300 */
2301 static char *hangup_cause2sip(int cause)
2302 {
2303         switch(cause)
2304         {
2305                 case AST_CAUSE_UNALLOCATED:             /* 1 */
2306                 case AST_CAUSE_NO_ROUTE_DESTINATION:    /* 3 IAX2: Can't find extension in context */
2307                 case AST_CAUSE_NO_ROUTE_TRANSIT_NET:    /* 2 */
2308                         return "404 Not Found";
2309                 case AST_CAUSE_CONGESTION:              /* 34 */
2310                 case AST_CAUSE_SWITCH_CONGESTION:       /* 42 */
2311                         return "503 Service Unavailable";
2312                 case AST_CAUSE_NO_USER_RESPONSE:        /* 18 */
2313                         return "408 Request Timeout";
2314                 case AST_CAUSE_NO_ANSWER:               /* 19 */
2315                         return "480 Temporarily unavailable";
2316                 case AST_CAUSE_CALL_REJECTED:           /* 21 */
2317                         return "403 Forbidden";
2318                 case AST_CAUSE_NUMBER_CHANGED:          /* 22 */
2319                         return "410 Gone";
2320                 case AST_CAUSE_NORMAL_UNSPECIFIED:      /* 31 */
2321                         return "480 Temporarily unavailable";
2322                 case AST_CAUSE_INVALID_NUMBER_FORMAT:
2323                         return "484 Address incomplete";
2324                 case AST_CAUSE_USER_BUSY:
2325                         return "486 Busy here";
2326                 case AST_CAUSE_FAILURE:
2327                         return "500 Server internal failure";
2328                 case AST_CAUSE_FACILITY_REJECTED:       /* 29 */
2329                         return "501 Not Implemented";
2330                 case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
2331                         return "503 Service Unavailable";
2332                 /* Used in chan_iax2 */
2333                 case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
2334                         return "502 Bad Gateway";
2335                 case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL:       /* Can't find codec to connect to host */
2336                         return "488 Not Acceptable Here";
2337                         
2338                 case AST_CAUSE_NOTDEFINED:
2339                 default:
2340                         ast_log(LOG_DEBUG, "AST hangup cause %d (no match found in SIP)\n", cause);
2341                         return NULL;
2342         }
2343
2344         /* Never reached */
2345         return 0;
2346 }
2347
2348
2349 /*--- sip_hangup: Hangup SIP call ---*/
2350 /* Part of PBX interface */
2351 static int sip_hangup(struct ast_channel *ast)
2352 {
2353         struct sip_pvt *p = ast->tech_pvt;
2354         int needcancel = 0;
2355         struct ast_flags locflags = {0};
2356
2357         if (!p) {
2358                 ast_log(LOG_DEBUG, "Asked to hangup channel not connected\n");
2359                 return 0;
2360         }
2361         if (option_debug)
2362                 ast_log(LOG_DEBUG, "Hangup call %s, SIP callid %s)\n", ast->name, p->callid);
2363
2364         ast_mutex_lock(&p->lock);
2365 #ifdef OSP_SUPPORT
2366         if ((p->osphandle > -1) && (ast->_state == AST_STATE_UP)) {
2367                 ast_osp_terminate(p->osphandle, AST_CAUSE_NORMAL, p->ospstart, time(NULL) - p->ospstart);
2368         }
2369 #endif  
2370         ast_log(LOG_DEBUG, "update_call_counter(%s) - decrement call limit counter\n", p->username);
2371         update_call_counter(p, DEC_CALL_LIMIT);
2372         /* Determine how to disconnect */
2373         if (p->owner != ast) {
2374                 ast_log(LOG_WARNING, "Huh?  We aren't the owner? Can't hangup call.\n");
2375                 ast_mutex_unlock(&p->lock);
2376                 return 0;
2377         }
2378         /* If the call is not UP, we need to send CANCEL instead of BYE */
2379         if (ast->_state != AST_STATE_UP)
2380                 needcancel = 1;
2381
2382         /* Disconnect */
2383         p = ast->tech_pvt;
2384         if (p->vad) {
2385                 ast_dsp_free(p->vad);
2386         }
2387         p->owner = NULL;
2388         ast->tech_pvt = NULL;
2389
2390         ast_mutex_lock(&usecnt_lock);
2391         usecnt--;
2392         ast_mutex_unlock(&usecnt_lock);
2393         ast_update_use_count();
2394
2395         ast_set_flag(&locflags, SIP_NEEDDESTROY);       
2396
2397         /* Start the process if it's not already started */
2398         if (!ast_test_flag(p, SIP_ALREADYGONE) && !ast_strlen_zero(p->initreq.data)) {
2399                 if (needcancel) {       /* Outgoing call, not up */
2400                         if (ast_test_flag(p, SIP_OUTGOING)) {
2401                                 transmit_request_with_auth(p, SIP_CANCEL, p->ocseq, 1, 0);
2402                                 /* Actually don't destroy us yet, wait for the 487 on our original 
2403                                    INVITE, but do set an autodestruct just in case we never get it. */
2404                                 ast_clear_flag(&locflags, SIP_NEEDDESTROY);
2405                                 sip_scheddestroy(p, 15000);
2406                                 /* stop retransmitting an INVITE that has not received a response */
2407                                 __sip_pretend_ack(p);
2408                                 if ( p->initid != -1 ) {
2409                                         /* channel still up - reverse dec of inUse counter
2410                                            only if the channel is not auto-congested */
2411                                         update_call_counter(p, INC_CALL_LIMIT);
2412                                 }
2413                         } else {        /* Incoming call, not up */
2414                                 char *res;
2415                                 if (ast->hangupcause && ((res = hangup_cause2sip(ast->hangupcause)))) {
2416                                         transmit_response_reliable(p, res, &p->initreq, 1);
2417                                 } else 
2418                                         transmit_response_reliable(p, "403 Forbidden", &p->initreq, 1);
2419                         }
2420                 } else {        /* Call is in UP state, send BYE */
2421                         if (!p->pendinginvite) {
2422                                 /* Send a hangup */
2423                                 transmit_request_with_auth(p, SIP_BYE, 0, 1, 1);
2424                         } else {
2425                                 /* Note we will need a BYE when this all settles out
2426                                    but we can't send one while we have "INVITE" outstanding. */
2427                                 ast_set_flag(p, SIP_PENDINGBYE);        
2428                                 ast_clear_flag(p, SIP_NEEDREINVITE);    
2429                         }
2430                 }
2431         }
2432         ast_copy_flags(p, (&locflags), SIP_NEEDDESTROY);        
2433         ast_mutex_unlock(&p->lock);
2434         return 0;
2435 }
2436
2437 /*--- sip_answer: Answer SIP call , send 200 OK on Invite ---*/
2438 /* Part of PBX interface */
2439 static int sip_answer(struct ast_channel *ast)
2440 {
2441         int res = 0,fmt;
2442         char *codec;
2443         struct sip_pvt *p = ast->tech_pvt;
2444
2445         ast_mutex_lock(&p->lock);
2446         if (ast->_state != AST_STATE_UP) {
2447 #ifdef OSP_SUPPORT      
2448                 time(&p->ospstart);
2449 #endif
2450         
2451                 codec=pbx_builtin_getvar_helper(p->owner,"SIP_CODEC");
2452                 if (codec) {
2453                         fmt=ast_getformatbyname(codec);
2454                         if (fmt) {
2455                                 ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC) variable\n",codec);
2456                                 if (p->jointcapability & fmt) {
2457                                         p->jointcapability &= fmt;
2458                                         p->capability &= fmt;
2459                                 } else
2460                                         ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
2461                         } else ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n",codec);
2462                 }
2463
2464                 ast_setstate(ast, AST_STATE_UP);
2465                 if (option_debug)
2466                         ast_log(LOG_DEBUG, "sip_answer(%s)\n", ast->name);
2467                 res = transmit_response_with_sdp(p, "200 OK", &p->initreq, 1);
2468         }
2469         ast_mutex_unlock(&p->lock);
2470         return res;
2471 }
2472
2473 /*--- sip_write: Send frame to media channel (rtp) ---*/
2474 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
2475 {
2476         struct sip_pvt *p = ast->tech_pvt;
2477         int res = 0;
2478         switch (frame->frametype) {
2479         case AST_FRAME_VOICE:
2480                 if (!(frame->subclass & ast->nativeformats)) {
2481                         ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
2482                                 frame->subclass, ast->nativeformats, ast->readformat, ast->writeformat);
2483                         return 0;
2484                 }
2485                 if (p) {
2486                         ast_mutex_lock(&p->lock);
2487                         if (p->rtp) {
2488                                 /* If channel is not up, activate early media session */
2489                                 if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) {
2490                                         transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
2491                                         ast_set_flag(p, SIP_PROGRESS_SENT);     
2492                                 }
2493                                 time(&p->lastrtptx);
2494                                 res =  ast_rtp_write(p->rtp, frame);
2495                         }
2496                         ast_mutex_unlock(&p->lock);
2497                 }
2498                 break;
2499         case AST_FRAME_VIDEO:
2500                 if (p) {
2501                         ast_mutex_lock(&p->lock);
2502                         if (p->vrtp) {
2503                                 /* Activate video early media */
2504                                 if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) {
2505                                         transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
2506                                         ast_set_flag(p, SIP_PROGRESS_SENT);     
2507                                 }
2508                                 time(&p->lastrtptx);
2509                                 res =  ast_rtp_write(p->vrtp, frame);
2510                         }
2511                         ast_mutex_unlock(&p->lock);
2512                 }
2513                 break;
2514         case AST_FRAME_IMAGE:
2515                 return 0;
2516                 break;
2517         default: 
2518                 ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
2519                 return 0;
2520         }
2521
2522         return res;
2523 }
2524
2525 /*--- sip_fixup: Fix up a channel:  If a channel is consumed, this is called.
2526         Basically update any ->owner links ----*/
2527 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
2528 {
2529         struct sip_pvt *p = newchan->tech_pvt;
2530         ast_mutex_lock(&p->lock);
2531         if (p->owner != oldchan) {
2532                 ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
2533                 ast_mutex_unlock(&p->lock);
2534                 return -1;
2535         }
2536         p->owner = newchan;
2537         ast_mutex_unlock(&p->lock);
2538         return 0;
2539 }
2540
2541 /*--- sip_senddigit: Send DTMF character on SIP channel */
2542 /*    within one call, we're able to transmit in many methods simultaneously */
2543 static int sip_senddigit(struct ast_channel *ast, char digit)
2544 {
2545         struct sip_pvt *p = ast->tech_pvt;
2546         int res = 0;
2547         ast_mutex_lock(&p->lock);
2548         switch (ast_test_flag(p, SIP_DTMF)) {
2549         case SIP_DTMF_INFO:
2550                 transmit_info_with_digit(p, digit);
2551                 break;
2552         case SIP_DTMF_RFC2833:
2553                 if (p->rtp)
2554                         ast_rtp_senddigit(p->rtp, digit);
2555                 break;
2556         case SIP_DTMF_INBAND:
2557                 res = -1;
2558                 break;
2559         }
2560         ast_mutex_unlock(&p->lock);
2561         return res;
2562 }
2563
2564 #define DEFAULT_MAX_FORWARDS    70
2565
2566
2567 /*--- sip_transfer: Transfer SIP call */
2568 static int sip_transfer(struct ast_channel *ast, const char *dest)
2569 {
2570         struct sip_pvt *p = ast->tech_pvt;
2571         int res;
2572
2573         ast_mutex_lock(&p->lock);
2574         if (ast->_state == AST_STATE_RING)
2575                 res = sip_sipredirect(p, dest);
2576         else
2577                 res = transmit_refer(p, dest);
2578         ast_mutex_unlock(&p->lock);
2579         return res;
2580 }
2581
2582 /*--- sip_indicate: Play indication to user */
2583 /* With SIP a lot of indications is sent as messages, letting the device play
2584    the indication - busy signal, congestion etc */
2585 static int sip_indicate(struct ast_channel *ast, int condition)
2586 {
2587         struct sip_pvt *p = ast->tech_pvt;
2588         int res = 0;
2589
2590         ast_mutex_lock(&p->lock);
2591         switch(condition) {
2592         case AST_CONTROL_RINGING:
2593                 if (ast->_state == AST_STATE_RING) {
2594                         if (!ast_test_flag(p, SIP_PROGRESS_SENT) ||
2595                             (ast_test_flag(p, SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {
2596                                 /* Send 180 ringing if out-of-band seems reasonable */
2597                                 transmit_response(p, "180 Ringing", &p->initreq);
2598                                 ast_set_flag(p, SIP_RINGING);
2599                                 if (ast_test_flag(p, SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
2600                                         break;
2601                         } else {
2602                                 /* Well, if it's not reasonable, just send in-band */
2603                         }
2604                 }
2605                 res = -1;
2606                 break;
2607         case AST_CONTROL_BUSY:
2608                 if (ast->_state != AST_STATE_UP) {
2609                         transmit_response(p, "486 Busy Here", &p->initreq);
2610                         ast_set_flag(p, SIP_ALREADYGONE);       
2611                         ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
2612                         break;
2613                 }
2614                 res = -1;
2615                 break;
2616         case AST_CONTROL_CONGESTION:
2617                 if (ast->_state != AST_STATE_UP) {
2618                         transmit_response(p, "503 Service Unavailable", &p->initreq);
2619                         ast_set_flag(p, SIP_ALREADYGONE);       
2620                         ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
2621                         break;
2622                 }
2623                 res = -1;
2624                 break;
2625         case AST_CONTROL_PROGRESS:
2626         case AST_CONTROL_PROCEEDING:
2627                 if ((ast->_state != AST_STATE_UP) && !ast_test_flag(p, SIP_PROGRESS_SENT) && !ast_test_flag(p, SIP_OUTGOING)) {
2628                         transmit_response_with_sdp(p, "183 Session Progress", &p->initreq, 0);
2629                         ast_set_flag(p, SIP_PROGRESS_SENT);     
2630                         break;
2631                 }
2632                 res = -1;
2633                 break;
2634         case AST_CONTROL_HOLD:  /* The other part of the bridge are put on hold */
2635                 if (sipdebug)
2636                         ast_log(LOG_DEBUG, "Bridged channel now on hold%s\n", p->callid);
2637                 res = -1;
2638                 break;
2639         case AST_CONTROL_UNHOLD:        /* The other part of the bridge are back from hold */
2640                 if (sipdebug)
2641                         ast_log(LOG_DEBUG, "Bridged channel is back from hold, let's talk! : %s\n", p->callid);
2642                 res = -1;
2643                 break;
2644         case AST_CONTROL_VIDUPDATE:     /* Request a video frame update */
2645                 if (p->vrtp && !ast_test_flag(p, SIP_NOVIDEO)) {
2646                         transmit_info_with_vidupdate(p);
2647                         res = 0;
2648                 } else
2649                         res = -1;
2650                 break;
2651         case -1:
2652                 res = -1;
2653                 break;
2654         default:
2655                 ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
2656                 res = -1;
2657                 break;
2658         }
2659         ast_mutex_unlock(&p->lock);
2660         return res;
2661 }
2662
2663
2664
2665 /*--- sip_new: Initiate a call in the SIP channel */
2666 /*      called from sip_request_call (calls from the pbx ) */
2667 static struct ast_channel *sip_new(struct sip_pvt *i, int state, char *title)
2668 {
2669         struct ast_channel *tmp;
2670         struct ast_variable *v = NULL;
2671         int fmt;
2672 #ifdef OSP_SUPPORT
2673         char iabuf[INET_ADDRSTRLEN];
2674         char peer[MAXHOSTNAMELEN];
2675 #endif  
2676         
2677         ast_mutex_unlock(&i->lock);
2678         /* Don't hold a sip pvt lock while we allocate a channel */
2679         tmp = ast_channel_alloc(1);
2680         ast_mutex_lock(&i->lock);
2681         if (!tmp) {
2682                 ast_log(LOG_WARNING, "Unable to allocate SIP channel structure\n");
2683                 return NULL;
2684         }
2685         tmp->tech = &sip_tech;
2686         /* Select our native format based on codec preference until we receive
2687            something from another device to the contrary. */
2688         ast_mutex_lock(&i->lock);
2689         if (i->jointcapability)
2690                 tmp->nativeformats = ast_codec_choose(&i->prefs, i->jointcapability, 1);
2691         else if (i->capability)
2692                 tmp->nativeformats = ast_codec_choose(&i->prefs, i->capability, 1);
2693         else
2694                 tmp->nativeformats = ast_codec_choose(&i->prefs, global_capability, 1);
2695         ast_mutex_unlock(&i->lock);
2696         fmt = ast_best_codec(tmp->nativeformats);
2697
2698         if (title)
2699                 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%04x", title, rand() & 0xffff);
2700         else if (strchr(i->fromdomain,':'))
2701                 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", strchr(i->fromdomain,':')+1, (int)(long)(i));
2702         else
2703                 snprintf(tmp->name, sizeof(tmp->name), "SIP/%s-%08x", i->fromdomain, (int)(long)(i));
2704
2705         tmp->type = channeltype;
2706         if (ast_test_flag(i, SIP_DTMF) ==  SIP_DTMF_INBAND) {
2707                 i->vad = ast_dsp_new();
2708                 ast_dsp_set_features(i->vad, DSP_FEATURE_DTMF_DETECT);
2709                 if (relaxdtmf)
2710                         ast_dsp_digitmode(i->vad, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
2711         }
2712         if (i->rtp) {
2713                 tmp->fds[0] = ast_rtp_fd(i->rtp);
2714                 tmp->fds[1] = ast_rtcp_fd(i->rtp);
2715         }
2716         if (i->vrtp) {
2717                 tmp->fds[2] = ast_rtp_fd(i->vrtp);
2718                 tmp->fds[3] = ast_rtcp_fd(i->vrtp);
2719         }
2720         if (state == AST_STATE_RING)
2721                 tmp->rings = 1;
2722         tmp->adsicpe = AST_ADSI_UNAVAILABLE;
2723         tmp->writeformat = fmt;
2724         tmp->rawwriteformat = fmt;
2725         tmp->readformat = fmt;
2726         tmp->rawreadformat = fmt;
2727         tmp->tech_pvt = i;
2728
2729         tmp->callgroup = i->callgroup;
2730         tmp->pickupgroup = i->pickupgroup;
2731         tmp->cid.cid_pres = i->callingpres;
2732         if (!ast_strlen_zero(i->accountcode))
2733                 ast_copy_string(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode));
2734         if (i->amaflags)
2735                 tmp->amaflags = i->amaflags;
2736         if (!ast_strlen_zero(i->language))
2737                 ast_copy_string(tmp->language, i->language, sizeof(tmp->language));
2738         if (!ast_strlen_zero(i->musicclass))
2739                 ast_copy_string(tmp->musicclass, i->musicclass, sizeof(tmp->musicclass));
2740         i->owner = tmp;
2741         ast_mutex_lock(&usecnt_lock);
2742         usecnt++;
2743         ast_mutex_unlock(&usecnt_lock);
2744         ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
2745         ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
2746         if (!ast_strlen_zero(i->cid_num)) 
2747                 tmp->cid.cid_num = strdup(i->cid_num);
2748         if (!ast_strlen_zero(i->cid_name))
2749                 tmp->cid.cid_name = strdup(i->cid_name);
2750         if (!ast_strlen_zero(i->rdnis))
2751                 tmp->cid.cid_rdnis = strdup(i->rdnis);
2752         if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
2753                 tmp->cid.cid_dnid = strdup(i->exten);
2754         tmp->priority = 1;
2755         if (!ast_strlen_zero(i->uri)) {
2756                 pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
2757         }
2758         if (!ast_strlen_zero(i->domain)) {
2759                 pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
2760         }
2761         if (!ast_strlen_zero(i->useragent)) {
2762                 pbx_builtin_setvar_helper(tmp, "SIPUSERAGENT", i->useragent);
2763         }
2764         if (!ast_strlen_zero(i->callid)) {
2765                 pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
2766         }
2767 #ifdef OSP_SUPPORT
2768         snprintf(peer, sizeof(peer), "[%s]:%d", ast_inet_ntoa(iabuf, sizeof(iabuf), i->sa.sin_addr), ntohs(i->sa.sin_port));
2769         pbx_builtin_setvar_helper(tmp, "OSPPEER", peer);
2770 #endif
2771         ast_setstate(tmp, state);
2772         if (state != AST_STATE_DOWN) {
2773                 if (ast_pbx_start(tmp)) {
2774                         ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
2775                         ast_hangup(tmp);
2776                         tmp = NULL;
2777                 }
2778         }
2779         /* Set channel variables for this call from configuration */
2780         for (v = i->chanvars ; v ; v = v->next)
2781                 pbx_builtin_setvar_helper(tmp,v->name,v->value);
2782                                 
2783         return tmp;
2784 }
2785
2786 /*--- get_sdp_by_line: Reads one line of SIP message body */
2787 static char* get_sdp_by_line(char* line, char *name, int nameLen)
2788 {
2789         if (strncasecmp(line, name, nameLen) == 0 && line[nameLen] == '=') {
2790                 return ast_skip_blanks(line + nameLen + 1);
2791         }
2792         return "";
2793 }
2794
2795 /*--- get_sdp: Gets all kind of SIP message bodies, including SDP,
2796    but the name wrongly applies _only_ sdp */
2797 static char *get_sdp(struct sip_request *req, char *name) 
2798 {
2799         int x;
2800         int len = strlen(name);
2801         char *r;
2802
2803         for (x=0; x<req->lines; x++) {
2804                 r = get_sdp_by_line(req->line[x], name, len);
2805                 if (r[0] != '\0')
2806                         return r;
2807         }
2808         return "";
2809 }
2810
2811
2812 static void sdpLineNum_iterator_init(int* iterator) 
2813 {
2814         *iterator = 0;
2815 }
2816
2817 static char* get_sdp_iterate(int* iterator,
2818                              struct sip_request *req, char *name)
2819 {
2820         int len = strlen(name);
2821         char *r;
2822
2823         while (*iterator < req->lines) {
2824                 r = get_sdp_by_line(req->line[(*iterator)++], name, len);
2825                 if (r[0] != '\0')
2826                         return r;
2827         }
2828         return "";
2829 }
2830
2831 static char *find_alias(const char *name, char *_default)
2832 {
2833         int x;
2834         for (x=0;x<sizeof(aliases) / sizeof(aliases[0]); x++) 
2835                 if (!strcasecmp(aliases[x].fullname, name))
2836                         return aliases[x].shortname;
2837         return _default;
2838 }
2839
2840 static char *__get_header(struct sip_request *req, char *name, int *start)
2841 {
2842         int pass;
2843
2844         /*
2845          * Technically you can place arbitrary whitespace both before and after the ':' in
2846          * a header, although RFC3261 clearly says you shouldn't before, and place just
2847          * one afterwards.  If you shouldn't do it, what absolute idiot decided it was 
2848          * a good idea to say you can do it, and if you can do it, why in the hell would.
2849          * you say you shouldn't.
2850          * Anyways, pedanticsipchecking controls whether we allow spaces before ':',
2851          * and we always allow spaces after that for compatibility.
2852          */
2853         for (pass = 0; name && pass < 2;pass++) {
2854                 int x, len = strlen(name);
2855                 for (x=*start; x<req->headers; x++) {
2856                         if (!strncasecmp(req->header[x], name, len)) {
2857                                 char *r = req->header[x] + len; /* skip name */
2858                                 if (pedanticsipchecking)
2859                                         r = ast_skip_blanks(r);
2860
2861                                 if (*r == ':') {
2862                                         *start = x+1;
2863                                         return ast_skip_blanks(r+1);
2864                                 }
2865                         }
2866                 }
2867                 if (pass == 0) /* Try aliases */
2868                         name = find_alias(name, NULL);
2869         }
2870
2871         /* Don't return NULL, so get_header is always a valid pointer */
2872         return "";
2873 }
2874
2875 /*--- get_header: Get header from SIP request ---*/
2876 static char *get_header(struct sip_request *req, char *name)
2877 {
2878         int start = 0;
2879         return __get_header(req, name, &start);
2880 }
2881
2882 /*--- sip_rtp_read: Read RTP from network ---*/
2883 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p)
2884 {
2885         /* Retrieve audio/etc from channel.  Assumes p->lock is already held. */
2886         struct ast_frame *f;
2887         static struct ast_frame null_frame = { AST_FRAME_NULL, };
2888         
2889         if (!p->rtp) {
2890                 /* We have no RTP allocated for this channel */
2891                 return &null_frame;
2892         }
2893
2894         switch(ast->fdno) {
2895         case 0:
2896                 f = ast_rtp_read(p->rtp);       /* RTP Audio */
2897                 break;
2898         case 1:
2899                 f = ast_rtcp_read(p->rtp);      /* RTCP Control Channel */
2900                 break;
2901         case 2:
2902                 f = ast_rtp_read(p->vrtp);      /* RTP Video */
2903                 break;
2904         case 3:
2905                 f = ast_rtcp_read(p->vrtp);     /* RTCP Control Channel for video */
2906                 break;
2907         default:
2908                 f = &null_frame;
2909         }
2910         /* Don't forward RFC2833 if we're not supposed to */
2911         if (f && (f->frametype == AST_FRAME_DTMF) && (ast_test_flag(p, SIP_DTMF) != SIP_DTMF_RFC2833))
2912                 return &null_frame;
2913         if (p->owner) {
2914                 /* We already hold the channel lock */
2915                 if (f->frametype == AST_FRAME_VOICE) {
2916                         if (f->subclass != p->owner->nativeformats) {
2917                                 ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
2918                                 p->owner->nativeformats = f->subclass;
2919                                 ast_set_read_format(p->owner, p->owner->readformat);
2920                                 ast_set_write_format(p->owner, p->owner->writeformat);
2921                         }
2922                         if ((ast_test_flag(p, SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
2923                                 f = ast_dsp_process(p->owner, p->vad, f);
2924                                 if (f && (f->frametype == AST_FRAME_DTMF)) 
2925                                         ast_log(LOG_DEBUG, "* Detected inband DTMF '%c'\n", f->subclass);
2926                         }
2927                 }
2928         }
2929         return f;
2930 }
2931
2932 /*--- sip_read: Read SIP RTP from channel */
2933 static struct ast_frame *sip_read(struct ast_channel *ast)
2934 {
2935         struct ast_frame *fr;
2936         struct sip_pvt *p = ast->tech_pvt;
2937         ast_mutex_lock(&p->lock);
2938         fr = sip_rtp_read(ast, p);
2939         time(&p->lastrtprx);
2940         ast_mutex_unlock(&p->lock);
2941         return fr;
2942 }
2943
2944 /*--- build_callid: Build SIP CALLID header ---*/
2945 static void build_callid(char *callid, int len, struct in_addr ourip, char *fromdomain)
2946 {
2947         int res;
2948         int val;
2949         int x;
2950         char iabuf[INET_ADDRSTRLEN];
2951         for (x=0; x<4; x++) {
2952                 val = rand();
2953                 res = snprintf(callid, len, "%08x", val);
2954                 len -= res;
2955                 callid += res;
2956         }
2957         if (!ast_strlen_zero(fromdomain))
2958                 snprintf(callid, len, "@%s", fromdomain);
2959         else
2960         /* It's not important that we really use our right IP here... */
2961                 snprintf(callid, len, "@%s", ast_inet_ntoa(iabuf, sizeof(iabuf), ourip));
2962 }
2963
2964 static void make_our_tag(char *tagbuf, size_t len)
2965 {
2966         snprintf(tagbuf, len, "as%08x", rand());
2967 }
2968
2969 /*--- sip_alloc: Allocate SIP_PVT structure and set defaults ---*/
2970 static struct sip_pvt *sip_alloc(char *callid, struct sockaddr_in *sin, int useglobal_nat, const int intended_method)
2971 {
2972         struct sip_pvt *p;
2973
2974         if (!(p = calloc(1, sizeof(*p))))
2975                 return NULL;
2976
2977         ast_mutex_init(&p->lock);
2978
2979         p->method = intended_method;
2980         p->initid = -1;
2981         p->autokillid = -1;
2982         p->subscribed = NONE;
2983         p->stateid = -1;
2984         p->prefs = prefs;
2985         if (intended_method != SIP_OPTIONS)     /* Peerpoke has it's own system */
2986                 p->timer_t1 = 500;      /* Default SIP retransmission timer T1 (RFC 3261) */
2987 #ifdef OSP_SUPPORT
2988         p->osphandle = -1;
2989         p->osptimelimit = 0;
2990 #endif  
2991         if (sin) {
2992                 memcpy(&p->sa, sin, sizeof(p->sa));
2993                 if (ast_sip_ouraddrfor(&p->sa.sin_addr,&p->ourip))
2994                         memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
2995         } else {
2996                 memcpy(&p->ourip, &__ourip, sizeof(p->ourip));
2997         }
2998
2999         p->branch = rand();     
3000         make_our_tag(p->tag, sizeof(p->tag));
3001         /* Start with 101 instead of 1 */
3002         p->ocseq = 101;
3003
3004         if (sip_methods[intended_method].need_rtp) {
3005                 p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
3006                 if (videosupport)
3007                         p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
3008                 if (!p->rtp || (videosupport && !p->vrtp)) {
3009                         ast_log(LOG_WARNING, "Unable to create RTP audio %s session: %s\n", videosupport ? "and video" : "", strerror(errno));
3010                         ast_mutex_destroy(&p->lock);
3011                         if (p->chanvars) {
3012                                 ast_variables_destroy(p->chanvars);
3013                                 p->chanvars = NULL;
3014                         }
3015                         free(p);
3016                         return NULL;
3017                 }
3018                 ast_rtp_settos(p->rtp, tos);
3019                 if (p->vrtp)
3020                         ast_rtp_settos(p->vrtp, tos);
3021                 p->rtptimeout = global_rtptimeout;
3022                 p->rtpholdtimeout = global_rtpholdtimeout;
3023                 p->rtpkeepalive = global_rtpkeepalive;
3024         }
3025
3026         if (useglobal_nat && sin) {
3027                 /* Setup NAT structure according to global settings if we have an address */
3028                 ast_copy_flags(p, &global_flags, SIP_NAT);
3029                 memcpy(&p->recv, sin, sizeof(p->recv));
3030                 if (p->rtp)
3031                         ast_rtp_setnat(p->rtp, (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE));
3032                 if (p->vrtp)
3033                         ast_rtp_setnat(p->vrtp, (ast_test_flag(p, SIP_NAT) & SIP_NAT_ROUTE));
3034         }
3035
3036         if (p->method != SIP_REGISTER)
3037                 ast_copy_string(p->fromdomain, default_fromdomain, sizeof(p->fromdomain));
3038         build_via(p, p->via, sizeof(p->via));
3039         if (!callid)
3040                 build_callid(p->callid, sizeof(p->callid), p->ourip, p->fromdomain);
3041         else
3042                 ast_copy_string(p->callid, callid, sizeof(p->callid));
3043         ast_copy_flags(p, &global_flags, SIP_FLAGS_TO_COPY);
3044         /* Assign default music on hold class */
3045         strcpy(p->musicclass, global_musicclass);
3046         p->capability = global_capability;
3047         if ((ast_test_flag(p, SIP_DTMF) == SIP_DTMF_RFC2833) || (ast_test_flag(p, SIP_DTMF) == SIP_DTMF_AUTO))
3048                 p->noncodeccapability |= AST_RTP_DTMF;
3049         strcpy(p->context, default_context);
3050
3051         /* Add to active dialog list */
3052         ast_mutex_lock(&iflock);
3053         p->next = iflist;
3054         iflist = p;
3055         ast_mutex_unlock(&iflock);
3056         if (option_debug)
3057                 ast_log(LOG_DEBUG, "Allocating new SIP dialog for %s - %s (%s)\n", callid ? callid : "(No Call-ID)", sip_methods[intended_method].text, p->rtp ? "With RTP" : "No RTP");
3058         return p;
3059 }
3060
3061 /*--- find_call: Connect incoming SIP message to current dialog or create new dialog structure */
3062 /*               Called by handle_request ,sipsock_read */
3063 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method)
3064 {
3065         struct sip_pvt *p;
3066         char *callid;
3067         char tmp[256];
3068         char *tag = "", *c;
3069
3070         callid = get_header(req, "Call-ID");
3071
3072         if (pedanticsipchecking) {
3073                 /* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
3074                    we need more to identify a branch - so we have to check branch, from
3075                    and to tags to identify a call leg.
3076                      For Asterisk to behave correctly, you need to turn on pedanticsipchecking
3077                    in sip.conf
3078                    */
3079                 if (req->method == SIP_RESPONSE)
3080                         ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
3081                 else
3082                         ast_copy_string(tmp, get_header(req, "From"), sizeof(tmp));
3083                 tag = strcasestr(tmp, "tag=");
3084                 if (tag) {
3085                         tag += 4;
3086                         c = strchr(tag, ';');
3087                         if (c)
3088                                 *c = '\0';
3089                 }
3090                         
3091         }
3092                 
3093         ast_mutex_lock(&iflock);
3094         p = iflist;
3095         while(p) {
3096                 int found = 0;
3097                 if (req->method == SIP_REGISTER)
3098                         found = (!strcmp(p->callid, callid));
3099                 else 
3100                         found = (!strcmp(p->callid, callid) && 
3101                         (!pedanticsipchecking || !tag || ast_strlen_zero(p->theirtag) || !strcmp(p->theirtag, tag))) ;
3102                 if (found) {
3103                         /* Found the call */
3104                         ast_mutex_lock(&p->lock);
3105                         ast_mutex_unlock(&iflock);
3106                         return p;
3107                 }
3108                 p = p->next;
3109         }
3110         ast_mutex_unlock(&iflock);
3111         p = sip_alloc(callid, sin, 1, intended_method);
3112         if (p)
3113                 ast_mutex_lock(&p->lock);
3114         return p;
3115 }
3116
3117 /*--- sip_register: Parse register=> line in sip.conf and add to registry */
3118 static int sip_register(char *value, int lineno)
3119 {
3120         struct sip_registry *reg;
3121         char copy[256];
3122         char *username=NULL, *hostname=NULL, *secret=NULL, *authuser=NULL;
3123         char *porta=NULL;
3124         char *contact=NULL;
3125         char *stringp=NULL;
3126         
3127         if (!value)
3128                 return -1;
3129         ast_copy_string(copy, value, sizeof(copy));
3130         stringp=copy;
3131         username = stringp;
3132         hostname = strrchr(stringp, '@');
3133         if (hostname) {
3134                 *hostname = '\0';
3135                 hostname++;
3136         }
3137         if (!username || ast_strlen_zero(username) || !hostname || ast_strlen_zero(hostname)) {
3138                 ast_log(LOG_WARNING, "Format for registration is user[:secret[:authuser]]@host[:port][/contact] at line %d\n", lineno);
3139                 return -1;
3140         }
3141         stringp=username;
3142         username = strsep(&stringp, ":");
3143         if (username) {
3144                 secret = strsep(&stringp, ":");
3145                 if (secret) 
3146                         authuser = strsep(&stringp, ":");
3147         }
3148         stringp = hostname;
3149         hostname = strsep(&stringp, "/");
3150         if (hostname) 
3151                 contact = strsep(&stringp, "/");
3152         if (!contact || ast_strlen_zero(contact))
3153                 contact = "s";
3154         stringp=hostname;
3155         hostname = strsep(&stringp, ":");
3156         porta = strsep(&stringp, ":");
3157         
3158         if (porta && !atoi(porta)) {
3159                 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
3160                 return -1;
3161         }
3162         reg = malloc(sizeof(struct sip_registry));
3163         if (!reg) {
3164                 ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
3165                 return -1;
3166         }
3167         memset(reg, 0, sizeof(struct sip_registry));
3168         regobjs++;
3169         ASTOBJ_INIT(reg);
3170         ast_copy_string(reg->contact, contact, sizeof(reg->contact));
3171         if (username)
3172                 ast_copy_string(reg->username, username, sizeof(reg->username));
3173         if (hostname)
3174                 ast_copy_string(reg->hostname, hostname, sizeof(reg->hostname));
3175         if (authuser)
3176                 ast_copy_string(reg->authuser, authuser, sizeof(reg->authuser));
3177         if (secret)
3178                 ast_copy_string(reg->secret, secret, sizeof(reg->secret));
3179         reg->expire = -1;
3180         reg->timeout =  -1;
3181         reg->refresh = default_expiry;
3182         reg->portno = porta ? atoi(porta) : 0;
3183         reg->callid_valid = 0;
3184         reg->ocseq = 101;
3185         ASTOBJ_CONTAINER_LINK(&regl, reg);
3186         ASTOBJ_UNREF(reg,sip_registry_destroy);
3187         return 0;
3188 }
3189
3190 /*--- lws2sws: Parse multiline SIP headers into one header */
3191 /* This is enabled if pedanticsipchecking is enabled */
3192 static int lws2sws(char *msgbuf, int len) 
3193
3194         int h = 0, t = 0; 
3195         int lws = 0; 
3196
3197         for (; h < len;) { 
3198                 /* Eliminate all CRs */ 
3199                 if (msgbuf[h] == '\r') { 
3200                         h++; 
3201                         continue; 
3202                 } 
3203                 /* Check for end-of-line */ 
3204                 if (msgbuf[h] == '\n') { 
3205                         /* Check for end-of-message */ 
3206                         if (h + 1 == len) 
3207                                 break; 
3208                         /* Check for a continuation line */ 
3209                         if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') { 
3210                                 /* Merge continuation line */ 
3211                                 h++; 
3212                                 continue; 
3213                         } 
3214                         /* Propagate LF and start new line */ 
3215                         msgbuf[t++] = msgbuf[h++]; 
3216                         lws = 0;
3217                         continue; 
3218                 } 
3219                 if (msgbuf[h] == ' ' || msgbuf[h] == '\t') { 
3220                         if (lws) { 
3221                                 h++; 
3222                                 continue; 
3223                         } 
3224                         msgbuf[t++] = msgbuf[h++]; 
3225                         lws = 1; 
3226                         continue; 
3227                 } 
3228                 msgbuf[t++] = msgbuf[h++]; 
3229                 if (lws) 
3230                         lws = 0; 
3231         } 
3232         msgbuf[t] = '\0'; 
3233         return t; 
3234 }
3235
3236 /*--- parse_request: Parse a SIP message ----*/
3237 static void parse_request(struct sip_request *req)
3238 {
3239         /* Divide fields by NULL's */
3240         char *c;
3241         int f = 0;
3242
3243         c = req->data;
3244
3245         /* First header starts immediately */
3246         req->header[f] = c;
3247         while(*c) {
3248                 if (*c == '\n') {
3249                         /* We've got a new header */
3250                         *c = 0;
3251
3252                         if (sipdebug && option_debug > 3)
3253                                 ast_log(LOG_DEBUG, "Header: %s (%d)\n", req->header[f], (int) strlen(req->header[f]));
3254                         if (ast_strlen_zero(req->header[f])) {
3255                                 /* Line by itself means we're now in content */
3256                                 c++;
3257                                 break;
3258                         }
3259                         if (f >= SIP_MAX_HEADERS - 1) {
3260                                 ast_log(LOG_WARNING, "Too many SIP headers. Ignoring.\n");
3261                         } else
3262                                 f++;
3263                         req->header[f] = c + 1;
3264                 } else if (*c == '\r') {
3265                         /* Ignore but eliminate \r's */
3266                         *c = 0;
3267                 }
3268                 c++;
3269         }
3270         /* Check for last header */
3271         if (!ast_strlen_zero(req->header[f])) 
3272                 f++;
3273         req->headers = f;
3274         /* Now we process any mime content */
3275         f = 0;
3276         req->line[f] = c;
3277         while(*c) {
3278                 if (*c == '\n') {
3279                         /* We've got a new line */
3280                         *c = 0;
3281                         if (sipdebug && option_debug > 3)
3282                                 ast_log(LOG_DEBUG, "Line: %s (%d)\n", req->line[f], (int) strlen(req->line[f]));
3283                         if (f >= SIP_MAX_LINES - 1) {
3284                                 ast_log(LOG_WARNING, "Too many SDP lines. Ignoring.\n");
3285                         } else
3286                                 f++;
3287                         req->line[f] = c + 1;
3288                 } else if (*c == '\r') {
3289                         /* Ignore and eliminate \r's */
3290                         *c = 0;
3291                 }
3292                 c++;
3293         }
3294         /* Check for last line */
3295         if (!ast_strlen_zero(req->line[f])) 
3296                 f++;
3297         req->lines = f;
3298         if (*c) 
3299                 ast_log(LOG_WARNING, "Odd content, extra stuff left over ('%s')\n", c);
3300         /* Split up the first line parts */
3301         determine_firstline_parts(req);
3302 }
3303
3304 /*--- process_sdp: Process SIP SDP and activate RTP channels---*/
3305 static int process_sdp(struct sip_pvt *p, struct sip_request *req)
3306 {
3307         char *m;
3308         char *c;
3309         char *a;
3310         char host[258];
3311         char iabuf[INET_ADDRSTRLEN];
3312         int len = -1;
3313         int portno = -1;
3314         int vportno = -1;
3315         int peercapability, peernoncodeccapability;
3316         int vpeercapability=0, vpeernoncodeccapability=0;
3317         struct sockaddr_in sin;
3318         char *codecs;
3319         struct hostent *hp;
3320         struct ast_hostent ahp;
3321         int codec;
3322         int destiterator = 0;
3323         int iterator;
3324         int sendonly = 0;
3325         int x,y;
3326         int debug=sip_debug_test_pvt(p);
3327         struct ast_channel *bridgepeer = NULL;
3328
3329         if (!p->rtp) {
3330                 ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
3331                 return -1;
3332         }
3333
3334         /* Update our last rtprx when we receive an SDP, too */
3335         time(&p->lastrtprx);
3336         time(&p->lastrtptx);
3337
3338         /* Get codec and RTP info from SDP */
3339         if (strcasecmp(get_header(req, "Content-Type"), "application/sdp")) {
3340                 ast_log(LOG_NOTICE, "Content is '%s', not 'application/sdp'\n", get_header(req, "Content-Type"));
3341                 return -1;
3342         }
3343         m = get_sdp(req, "m");
3344         sdpLineNum_iterator_init(&destiterator);
3345         c = get_sdp_iterate(&destiterator, req, "c");
3346         if (ast_strlen_zero(m) || ast_strlen_zero(c)) {
3347                 ast_log(LOG_WARNING, "Insufficient information for SDP (m = '%s', c = '%s')\n", m, c);
3348                 return -1;
3349         }
3350         if (sscanf(c, "IN IP4 %256s", host) != 1) {
3351                 ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
3352                 return -1;
3353         }
3354         /* XXX This could block for a long time, and block the main thread! XXX */
3355         hp = ast_gethostbyname(host, &ahp);
3356         if (!hp) {
3357                 ast_log(LOG_WARNING, "Unable to lookup host in c= line, '%s'\n", c);
3358                 return -1;
3359         }
3360         sdpLineNum_iterator_init(&iterator);
3361         ast_set_flag(p, SIP_NOVIDEO);   
3362         while ((m = get_sdp_iterate(&iterator, req, "m"))[0] != '\0') {
3363                 int found = 0;
3364                 if ((sscanf(m, "audio %d RTP/AVP %n", &x, &len) == 1) ||
3365                     (sscanf(m, "audio %d/%d RTP/AVP %n", &x, &y, &len) == 2)) {
3366                         found = 1;
3367                         portno = x;
3368                         /* Scan through the RTP payload types specified in a "m=" line: */
3369                         ast_rtp_pt_clear(p->rtp);
3370                         codecs = m + len;
3371                         while(!ast_strlen_zero(codecs)) {
3372                                 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
3373                                         ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
3374                                         return -1;
3375                                 }
3376                                 if (debug)
3377                                         ast_verbose("Found RTP audio format %d\n", codec);
3378                                 ast_rtp_set_m_type(p->rtp, codec);
3379                                 codecs = ast_skip_blanks(codecs + len);
3380                         }
3381                 }
3382                 if (p->vrtp)
3383                         ast_rtp_pt_clear(p->vrtp);  /* Must be cleared in case no m=video line exists */
3384
3385                 if (p->vrtp && (sscanf(m, "video %d RTP/AVP %n", &x, &len) == 1)) {
3386                         found = 1;
3387                         ast_clear_flag(p, SIP_NOVIDEO); 
3388                         vportno = x;
3389                         /* Scan through the RTP payload types specified in a "m=" line: */
3390                         codecs = m + len;
3391                         while(!ast_strlen_zero(codecs)) {
3392                                 if (sscanf(codecs, "%d%n", &codec, &len) != 1) {
3393                                         ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
3394                                         return -1;
3395                                 }
3396                                 if (debug)
3397                                         ast_verbose("Found video format %s\n", ast_getformatname(codec));
3398                                 ast_rtp_set_m_type(p->vrtp, codec);
3399                                 codecs = ast_skip_blanks(codecs + len);
3400                         }
3401                 }
3402                 if (!found )
3403                         ast_log(LOG_WARNING, "Unknown SDP media type in offer: %s\n", m);
3404         }
3405         if (portno == -1 && vportno == -1) {
3406                 /* No acceptable offer found in SDP */
3407                 return -2;
3408         }
3409         /* Check for Media-description-level-address for audio */
3410         if (pedanticsipchecking) {
3411                 c = get_sdp_iterate(&destiterator, req, "c");
3412                 if (!ast_strlen_zero(c)) {
3413                         if (sscanf(c, "IN IP4 %256s", host) != 1) {
3414                                 ast_log(LOG_WARNING, "Invalid secondary host in c= line, '%s'\n", c);
3415                         } else {
3416                                 /* XXX This could block for a long time, and block the main thread! XXX */
3417                                 hp = ast_gethostbyname(host, &ahp);
3418                                 if (!hp) {
3419                                         ast_log(LOG_WARNING, "Unable to lookup host in secondary c= line, '%s'\n", c);
3420                                 }
3421                         }
3422                 }
3423         }
3424         /* RTP addresses and ports for audio and video */
3425         sin.sin_family = AF_INET;
3426         memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
3427
3428         /* Setup audio port number */
3429         sin.sin_port = htons(portno);
3430         if (p->rtp && sin.sin_port) {
3431                 ast_rtp_set_peer(p->rtp, &sin);
3432                 if (debug) {
3433                         ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(iabuf,sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
3434                         ast_log(LOG_DEBUG,"Peer audio RTP is at port %s:%d\n",ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
3435                 }
3436         }
3437         /* Check for Media-description-level-address for video */
3438         if (pedanticsipchecking) {
3439                 c = get_sdp_iterate(&destiterator, req, "c");
3440                 if (!ast_strlen_zero(c)) {
3441                         if (sscanf(c, "IN IP4 %256s", host) != 1) {
3442                                 ast_log(LOG_WARNING, "Invalid secondary host in c= line, '%s'\n", c);
3443                         } else {
3444                                 /* XXX This could block for a long time, and block the main thread! XXX */
3445                                 hp = ast_gethostbyname(host, &ahp);
3446                                 if (!hp) {
3447                                         ast_log(LOG_WARNING, "Unable to lookup host in secondary c= line, '%s'\n", c);
3448                                 }
3449                         }
3450                 }
3451         }
3452         /* Setup video port number */
3453         sin.sin_port = htons(vportno);
3454         if (p->vrtp && sin.sin_port) {
3455                 ast_rtp_set_peer(p->vrtp, &sin);
3456                 if (debug) {
3457                         ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(iabuf,sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
3458                         ast_log(LOG_DEBUG,"Peer video RTP is at port %s:%d\n",ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
3459                 }
3460         }
3461
3462         /* Next, scan through each "a=rtpmap:" line, noting each
3463          * specified RTP payload type (with corresponding MIME subtype):
3464          */
3465         sdpLineNum_iterator_init(&iterator);
3466         while ((a = get_sdp_iterate(&iterator, req, "a"))[0] != '\0') {
3467                 char* mimeSubtype = ast_strdupa(a); /* ensures we have enough space */
3468                 if (!strcasecmp(a, "sendonly")) {
3469                         sendonly=1;
3470                         continue;
3471                 }
3472                 if (!strcasecmp(a, "sendrecv")) {
3473                         sendonly=0;
3474                 }
3475                 if (sscanf(a, "rtpmap: %u %[^/]/", &codec, mimeSubtype) != 2) continue;
3476                 if (debug)
3477                         ast_verbose("Found description format %s\n", mimeSubtype);
3478                 /* Note: should really look at the 'freq' and '#chans' params too */
3479                 ast_rtp_set_rtpmap_type(p->rtp, codec, "audio", mimeSubtype);
3480                 if (p->vrtp)
3481                         ast_rtp_set_rtpmap_type(p->vrtp, codec, "video", mimeSubtype);
3482         }
3483
3484         /* Now gather all of the codecs that were asked for: */
3485         ast_rtp_get_current_formats(p->rtp,
3486                                 &peercapability, &peernoncodeccapability);
3487         if (p->vrtp)
3488                 ast_rtp_get_current_formats(p->vrtp,
3489                                 &vpeercapability, &vpeernoncodeccapability);
3490         p->jointcapability = p->capability & (peercapability | vpeercapability);
3491         p->peercapability = (peercapability | vpeercapability);
3492         p->noncodeccapability = noncodeccapability & peernoncodeccapability;
3493         
3494         if (ast_test_flag(p, SIP_DTMF) == SIP_DTMF_AUTO) {
3495                 ast_clear_flag(p, SIP_DTMF);