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