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