52bca55bfa45ae2efd95a8437ba1eedcd6eef9c1
[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 Better support of forking
33  * \todo VIA branch tag transaction checking
34  * \todo Transaction support
35  * \todo We need to test TCP sessions with SIP proxies and in regards
36  *       to the SIP outbound specs.
37  *
38  * \ingroup channel_drivers
39  *
40  * \par Overview of the handling of SIP sessions
41  * The SIP channel handles several types of SIP sessions, or dialogs,
42  * not all of them being "telephone calls".
43  * - Incoming calls that will be sent to the PBX core
44  * - Outgoing calls, generated by the PBX
45  * - SIP subscriptions and notifications of states and voicemail messages
46  * - SIP registrations, both inbound and outbound
47  * - SIP peer management (peerpoke, OPTIONS)
48  * - SIP text messages
49  *
50  * In the SIP channel, there's a list of active SIP dialogs, which includes
51  * all of these when they are active. "sip show channels" in the CLI will
52  * show most of these, excluding subscriptions which are shown by
53  * "sip show subscriptions"
54  *
55  * \par incoming packets
56  * Incoming packets are received in the monitoring thread, then handled by
57  * sipsock_read(). This function parses the packet and matches an existing
58  * dialog or starts a new SIP dialog.
59  * 
60  * sipsock_read sends the packet to handle_incoming(), that parses a bit more.
61  * If it is a response to an outbound request, the packet is sent to handle_response().
62  * If it is a request, handle_incoming() sends it to one of a list of functions
63  * depending on the request type - INVITE, OPTIONS, REFER, BYE, CANCEL etc
64  * sipsock_read locks the ast_channel if it exists (an active call) and
65  * unlocks it after we have processed the SIP message.
66  *
67  * A new INVITE is sent to handle_request_invite(), that will end up
68  * starting a new channel in the PBX, the new channel after that executing
69  * in a separate channel thread. This is an incoming "call".
70  * When the call is answered, either by a bridged channel or the PBX itself
71  * the sip_answer() function is called.
72  *
73  * The actual media - Video or Audio - is mostly handled by the RTP subsystem
74  * in rtp.c 
75  * 
76  * \par Outbound calls
77  * Outbound calls are set up by the PBX through the sip_request_call()
78  * function. After that, they are activated by sip_call().
79  * 
80  * \par Hanging up
81  * The PBX issues a hangup on both incoming and outgoing calls through
82  * the sip_hangup() function
83  */
84
85 /*** MODULEINFO
86         <depend>chan_local</depend>
87  ***/
88
89 /*!  \page sip_session_timers SIP Session Timers in Asterisk Chan_sip
90
91         The SIP Session-Timers is an extension of the SIP protocol that allows end-points and proxies to
92         refresh a session periodically. The sessions are kept alive by sending a RE-INVITE or UPDATE
93         request at a negotiated interval. If a session refresh fails then all the entities that support Session-
94         Timers clear their internal session state. In addition, UAs generate a BYE request in order to clear
95         the state in the proxies and the remote UA (this is done for the benefit of SIP entities in the path
96         that do not support Session-Timers).
97
98         The Session-Timers can be configured on a system-wide, per-user, or per-peer basis. The peruser/
99         per-peer settings override the global settings. The following new parameters have been
100         added to the sip.conf file.
101                 session-timers=["accept", "originate", "refuse"]
102                 session-expires=[integer]
103                 session-minse=[integer]
104                 session-refresher=["uas", "uac"]
105
106         The session-timers parameter in sip.conf defines the mode of operation of SIP session-timers feature in
107         Asterisk. The Asterisk can be configured in one of the following three modes:
108
109         1. Accept :: In the "accept" mode, the Asterisk server honors session-timers requests
110                 made by remote end-points. A remote end-point can request Asterisk to engage
111                 session-timers by either sending it an INVITE request with a "Supported: timer"
112                 header in it or by responding to Asterisk's INVITE with a 200 OK that contains
113                 Session-Expires: header in it. In this mode, the Asterisk server does not 
114                 request session-timers from remote end-points. This is the default mode.
115         2. Originate :: In the "originate" mode, the Asterisk server requests the remote 
116                 end-points to activate session-timers in addition to honoring such requests
117                 made by the remote end-pints. In order to get as much protection as possible
118                 against hanging SIP channels due to network or end-point failures, Asterisk
119                 resends periodic re-INVITEs even if a remote end-point does not support
120                 the session-timers feature.
121         3. Refuse :: In the "refuse" mode, Asterisk acts as if it does not support session-
122                 timers for inbound or outbound requests. If a remote end-point requests
123                 session-timers in a dialog, then Asterisk ignores that request unless it's
124                 noted as a requirement (Require: header), in which case the INVITE is 
125                 rejected with a 420 Bad Extension response.
126
127 */
128
129 #include "asterisk.h"
130
131 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
132
133 #include <ctype.h>
134 #include <sys/ioctl.h>
135 #include <fcntl.h>
136 #include <signal.h>
137 #include <sys/signal.h>
138 #include <regex.h>
139
140 #include "asterisk/network.h"
141 #include "asterisk/paths.h"     /* need ast_config_AST_SYSTEM_NAME */
142
143 #include "asterisk/lock.h"
144 #include "asterisk/channel.h"
145 #include "asterisk/config.h"
146 #include "asterisk/module.h"
147 #include "asterisk/pbx.h"
148 #include "asterisk/sched.h"
149 #include "asterisk/io.h"
150 #include "asterisk/rtp.h"
151 #include "asterisk/udptl.h"
152 #include "asterisk/acl.h"
153 #include "asterisk/manager.h"
154 #include "asterisk/callerid.h"
155 #include "asterisk/cli.h"
156 #include "asterisk/app.h"
157 #include "asterisk/musiconhold.h"
158 #include "asterisk/dsp.h"
159 #include "asterisk/features.h"
160 #include "asterisk/srv.h"
161 #include "asterisk/astdb.h"
162 #include "asterisk/causes.h"
163 #include "asterisk/utils.h"
164 #include "asterisk/file.h"
165 #include "asterisk/astobj.h"
166 #include "asterisk/dnsmgr.h"
167 #include "asterisk/devicestate.h"
168 #include "asterisk/linkedlists.h"
169 #include "asterisk/stringfields.h"
170 #include "asterisk/monitor.h"
171 #include "asterisk/netsock.h"
172 #include "asterisk/localtime.h"
173 #include "asterisk/abstract_jb.h"
174 #include "asterisk/threadstorage.h"
175 #include "asterisk/translate.h"
176 #include "asterisk/ast_version.h"
177 #include "asterisk/event.h"
178 #include "asterisk/tcptls.h"
179
180 #ifndef FALSE
181 #define FALSE    0
182 #endif
183
184 #ifndef TRUE
185 #define TRUE     1
186 #endif
187
188 #define SIPBUFSIZE              512
189
190 #define XMIT_ERROR              -2
191
192 /* #define VOCAL_DATA_HACK */
193
194 #define DEFAULT_DEFAULT_EXPIRY  120
195 #define DEFAULT_MIN_EXPIRY      60
196 #define DEFAULT_MAX_EXPIRY      3600
197 #define DEFAULT_REGISTRATION_TIMEOUT 20
198 #define DEFAULT_MAX_FORWARDS    "70"
199
200 /* guard limit must be larger than guard secs */
201 /* guard min must be < 1000, and should be >= 250 */
202 #define EXPIRY_GUARD_SECS       15                /*!< How long before expiry do we reregister */
203 #define EXPIRY_GUARD_LIMIT      30                /*!< Below here, we use EXPIRY_GUARD_PCT instead of 
204                                                          EXPIRY_GUARD_SECS */
205 #define EXPIRY_GUARD_MIN        500                /*!< This is the minimum guard time applied. If 
206                                                    GUARD_PCT turns out to be lower than this, it 
207                                                    will use this time instead.
208                                                    This is in milliseconds. */
209 #define EXPIRY_GUARD_PCT        0.20                /*!< Percentage of expires timeout to use when 
210                                                     below EXPIRY_GUARD_LIMIT */
211 #define DEFAULT_EXPIRY 900                          /*!< Expire slowly */
212
213 static int min_expiry = DEFAULT_MIN_EXPIRY;        /*!< Minimum accepted registration time */
214 static int max_expiry = DEFAULT_MAX_EXPIRY;        /*!< Maximum accepted registration time */
215 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
216 static int expiry = DEFAULT_EXPIRY;
217
218 #ifndef MAX
219 #define MAX(a,b) ((a) > (b) ? (a) : (b))
220 #endif
221
222 #define CALLERID_UNKNOWN        "Unknown"
223
224 #define DEFAULT_MAXMS                2000             /*!< Qualification: Must be faster than 2 seconds by default */
225 #define DEFAULT_QUALIFYFREQ          60 * 1000        /*!< Qualification: How often to check for the host to be up */
226 #define DEFAULT_FREQ_NOTOK           10 * 1000        /*!< Qualification: How often to check, if the host is down... */
227
228 #define DEFAULT_RETRANS              1000             /*!< How frequently to retransmit Default: 2 * 500 ms in RFC 3261 */
229 #define MAX_RETRANS                  6                /*!< Try only 6 times for retransmissions, a total of 7 transmissions */
230 #define SIP_TIMER_T1                 500              /* SIP timer T1 (according to RFC 3261) */
231 #define SIP_TRANS_TIMEOUT            64 * SIP_TIMER_T1/*!< SIP request timeout (rfc 3261) 64*T1 
232                                                       \todo Use known T1 for timeout (peerpoke)
233                                                       */
234 #define DEFAULT_TRANS_TIMEOUT        -1               /* Use default SIP transaction timeout */
235 #define MAX_AUTHTRIES                3                /*!< Try authentication three times, then fail */
236
237 #define SIP_MAX_HEADERS              64               /*!< Max amount of SIP headers to read */
238 #define SIP_MAX_LINES                64               /*!< Max amount of lines in SIP attachment (like SDP) */
239 #define SIP_MAX_PACKET               4096             /*!< Also from RFC 3261 (2543), should sub headers tho */
240 #define SIP_MIN_PACKET               1024             /*!< Initialize size of memory to allocate for packets */
241
242 #define INITIAL_CSEQ                 101              /*!< our initial sip sequence number */
243
244 #define DEFAULT_MAX_SE               1800             /*!< Session-Timer Default Session-Expires period (RFC 4028) */
245 #define DEFAULT_MIN_SE               90               /*!< Session-Timer Default Min-SE period (RFC 4028) */
246
247 #define SDP_MAX_RTPMAP_CODECS        32               /*!< Maximum number of codecs allowed in received SDP */
248
249 /*! \brief Global jitterbuffer configuration - by default, jb is disabled */
250 static struct ast_jb_conf default_jbconf =
251 {
252         .flags = 0,
253         .max_size = -1,
254         .resync_threshold = -1,
255         .impl = ""
256 };
257 static struct ast_jb_conf global_jbconf;        /*!< Global jitterbuffer configuration */
258
259 static const char config[] = "sip.conf";        /*!< Main configuration file */
260 static const char notify_config[] = "sip_notify.conf";  /*!< Configuration file for sending Notify with CLI commands to reconfigure or reboot phones */
261
262 #define RTP     1
263 #define NO_RTP  0
264
265 /*! \brief Authorization scheme for call transfers 
266 \note Not a bitfield flag, since there are plans for other modes,
267         like "only allow transfers for authenticated devices" */
268 enum transfermodes {
269         TRANSFER_OPENFORALL,            /*!< Allow all SIP transfers */
270         TRANSFER_CLOSED,                /*!< Allow no SIP transfers */
271 };
272
273
274 enum sip_result {
275         AST_SUCCESS = 0,
276         AST_FAILURE = -1,
277 };
278
279 /*! \brief States for the INVITE transaction, not the dialog 
280         \note this is for the INVITE that sets up the dialog
281 */
282 enum invitestates {
283         INV_NONE = 0,           /*!< No state at all, maybe not an INVITE dialog */
284         INV_CALLING = 1,        /*!< Invite sent, no answer */
285         INV_PROCEEDING = 2,     /*!< We got/sent 1xx message */
286         INV_EARLY_MEDIA = 3,    /*!< We got 18x message with to-tag back */
287         INV_COMPLETED = 4,      /*!< Got final response with error. Wait for ACK, then CONFIRMED */
288         INV_CONFIRMED = 5,      /*!< Confirmed response - we've got an ack (Incoming calls only) */
289         INV_TERMINATED = 6,     /*!< Transaction done - either successful (AST_STATE_UP) or failed, but done 
290                                      The only way out of this is a BYE from one side */
291         INV_CANCELLED = 7,      /*!< Transaction cancelled by client or server in non-terminated state */
292 };
293
294 enum xmittype {
295         XMIT_CRITICAL = 2,              /*!< Transmit critical SIP message reliably, with re-transmits.
296                                               If it fails, it's critical and will cause a teardown of the session */
297         XMIT_RELIABLE = 1,              /*!< Transmit SIP message reliably, with re-transmits */
298         XMIT_UNRELIABLE = 0,            /*!< Transmit SIP message without bothering with re-transmits */
299 };
300
301 enum parse_register_result {
302         PARSE_REGISTER_FAILED,
303         PARSE_REGISTER_UPDATE,
304         PARSE_REGISTER_QUERY,
305 };
306
307 enum subscriptiontype { 
308         NONE = 0,
309         XPIDF_XML,
310         DIALOG_INFO_XML,
311         CPIM_PIDF_XML,
312         PIDF_XML,
313         MWI_NOTIFICATION
314 };
315
316 /*! \brief Subscription types that we support. We support
317    - dialoginfo updates (really device status, not dialog info as was the original intent of the standard)
318    - SIMPLE presence used for device status
319    - Voicemail notification subscriptions
320 */
321 static const struct cfsubscription_types {
322         enum subscriptiontype type;
323         const char * const event;
324         const char * const mediatype;
325         const char * const text;
326 } subscription_types[] = {
327         { NONE,            "-",        "unknown",                    "unknown" },
328         /* RFC 4235: SIP Dialog event package */
329         { DIALOG_INFO_XML, "dialog",   "application/dialog-info+xml", "dialog-info+xml" },
330         { CPIM_PIDF_XML,   "presence", "application/cpim-pidf+xml",   "cpim-pidf+xml" },  /* RFC 3863 */
331         { PIDF_XML,        "presence", "application/pidf+xml",        "pidf+xml" },       /* RFC 3863 */
332         { XPIDF_XML,       "presence", "application/xpidf+xml",       "xpidf+xml" },       /* Pre-RFC 3863 with MS additions */
333         { MWI_NOTIFICATION,     "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
334 };
335
336
337 /*! \brief Authentication types - proxy or www authentication 
338         \note Endpoints, like Asterisk, should always use WWW authentication to
339         allow multiple authentications in the same call - to the proxy and
340         to the end point.
341 */
342 enum sip_auth_type {
343         PROXY_AUTH = 407,
344         WWW_AUTH = 401,
345 };
346
347 /*! \brief Authentication result from check_auth* functions */
348 enum check_auth_result {
349         AUTH_DONT_KNOW = -100,  /*!< no result, need to check further */
350                 /* XXX maybe this is the same as AUTH_NOT_FOUND */
351
352         AUTH_SUCCESSFUL = 0,
353         AUTH_CHALLENGE_SENT = 1,
354         AUTH_SECRET_FAILED = -1,
355         AUTH_USERNAME_MISMATCH = -2,
356         AUTH_NOT_FOUND = -3,    /*!< returned by register_verify */
357         AUTH_FAKE_AUTH = -4,
358         AUTH_UNKNOWN_DOMAIN = -5,
359         AUTH_PEER_NOT_DYNAMIC = -6,
360         AUTH_ACL_FAILED = -7,
361 };
362
363 /*! \brief States for outbound registrations (with register= lines in sip.conf */
364 enum sipregistrystate {
365         REG_STATE_UNREGISTERED = 0,     /*!< We are not registred 
366                  *  \note Initial state. We should have a timeout scheduled for the initial
367                  * (or next) registration transmission, calling sip_reregister
368                  */
369
370         REG_STATE_REGSENT,      /*!< Registration request sent 
371                  * \note sent initial request, waiting for an ack or a timeout to
372                  * retransmit the initial request.
373                 */
374
375         REG_STATE_AUTHSENT,     /*!< We have tried to authenticate 
376                  * \note entered after transmit_register with auth info,
377                  * waiting for an ack.
378                  */
379
380         REG_STATE_REGISTERED,   /*!< Registered and done */
381
382         REG_STATE_REJECTED,     /*!< Registration rejected *
383                  * \note only used when the remote party has an expire larger than
384                  * our max-expire. This is a final state from which we do not
385                  * recover (not sure how correctly).
386                  */
387
388         REG_STATE_TIMEOUT,      /*!< Registration timed out *
389                 * \note XXX unused */
390
391         REG_STATE_NOAUTH,       /*!< We have no accepted credentials
392                  * \note fatal - no chance to proceed */
393
394         REG_STATE_FAILED,       /*!< Registration failed after several tries
395                  * \note fatal - no chance to proceed */
396 };
397
398 /*! \brief Modes in which Asterisk can be configured to run SIP Session-Timers */
399 enum st_mode {
400         SESSION_TIMER_MODE_INVALID = 0, /*!< Invalid value */ 
401         SESSION_TIMER_MODE_ACCEPT,      /*!< Honor inbound Session-Timer requests */
402         SESSION_TIMER_MODE_ORIGINATE,   /*!< Originate outbound and honor inbound requests */
403         SESSION_TIMER_MODE_REFUSE       /*!< Ignore inbound Session-Timers requests */
404 };
405
406 /*! \brief The entity playing the refresher role for Session-Timers */
407 enum st_refresher {
408         SESSION_TIMER_REFRESHER_AUTO,    /*!< Negotiated                      */
409         SESSION_TIMER_REFRESHER_UAC,     /*!< Session is refreshed by the UAC */
410         SESSION_TIMER_REFRESHER_UAS      /*!< Session is refreshed by the UAS */
411 };
412
413
414 /*! \brief definition of a sip proxy server
415  *
416  * For outbound proxies, this is allocated in the SIP peer dynamically or
417  * statically as the global_outboundproxy. The pointer in a SIP message is just
418  * a pointer and should *not* be de-allocated.
419  */
420 struct sip_proxy {
421         char name[MAXHOSTNAMELEN];      /*!< DNS name of domain/host or IP */
422         struct sockaddr_in ip;          /*!< Currently used IP address and port */
423         time_t last_dnsupdate;          /*!< When this was resolved */
424         int force;                      /*!< If it's an outbound proxy, Force use of this outbound proxy for all outbound requests */
425         /* Room for a SRV record chain based on the name */
426 };
427
428 /*! \brief States whether a SIP message can create a dialog in Asterisk. */
429 enum can_create_dialog {
430         CAN_NOT_CREATE_DIALOG,
431         CAN_CREATE_DIALOG,
432         CAN_CREATE_DIALOG_UNSUPPORTED_METHOD,
433 };
434
435 /*! \brief SIP Request methods known by Asterisk 
436
437    \note Do _NOT_ make any changes to this enum, or the array following it;
438    if you think you are doing the right thing, you are probably
439    not doing the right thing. If you think there are changes
440    needed, get someone else to review them first _before_
441    submitting a patch. If these two lists do not match properly
442    bad things will happen.
443 */
444
445 enum sipmethod {
446         SIP_UNKNOWN,            /*!< Unknown response */
447         SIP_RESPONSE,           /*!< Not request, response to outbound request */
448         SIP_REGISTER,           /*!< Registration to the mothership, tell us where you are located */
449         SIP_OPTIONS,            /*!< Check capabilities of a device, used for "ping" too */
450         SIP_NOTIFY,             /*!< Status update, Part of the event package standard, result of a SUBSCRIBE or a REFER */
451         SIP_INVITE,             /*!< Set up a session */
452         SIP_ACK,                /*!< End of a three-way handshake started with INVITE. */
453         SIP_PRACK,              /*!< Reliable pre-call signalling. Not supported in Asterisk. */
454         SIP_BYE,                /*!< End of a session */
455         SIP_REFER,              /*!< Refer to another URI (transfer) */
456         SIP_SUBSCRIBE,          /*!< Subscribe for updates (voicemail, session status, device status, presence) */
457         SIP_MESSAGE,            /*!< Text messaging */
458         SIP_UPDATE,             /*!< Update a dialog. We can send UPDATE; but not accept it */
459         SIP_INFO,               /*!< Information updates during a session */
460         SIP_CANCEL,             /*!< Cancel an INVITE */
461         SIP_PUBLISH,            /*!< Not supported in Asterisk */
462         SIP_PING,               /*!< Not supported at all, no standard but still implemented out there */
463 };
464
465 /*! \brief The core structure to setup dialogs. We parse incoming messages by using
466         structure and then route the messages according to the type.
467
468       \note Note that sip_methods[i].id == i must hold or the code breaks */
469 static const struct  cfsip_methods { 
470         enum sipmethod id;
471         int need_rtp;           /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
472         char * const text;
473         enum can_create_dialog can_create;
474 } sip_methods[] = {
475         { SIP_UNKNOWN,   RTP,    "-UNKNOWN-",   CAN_CREATE_DIALOG },
476         { SIP_RESPONSE,  NO_RTP, "SIP/2.0",     CAN_NOT_CREATE_DIALOG },
477         { SIP_REGISTER,  NO_RTP, "REGISTER",    CAN_CREATE_DIALOG },
478         { SIP_OPTIONS,   NO_RTP, "OPTIONS",     CAN_CREATE_DIALOG },
479         { SIP_NOTIFY,    NO_RTP, "NOTIFY",      CAN_CREATE_DIALOG },
480         { SIP_INVITE,    RTP,    "INVITE",      CAN_CREATE_DIALOG },
481         { SIP_ACK,       NO_RTP, "ACK",         CAN_NOT_CREATE_DIALOG },
482         { SIP_PRACK,     NO_RTP, "PRACK",       CAN_NOT_CREATE_DIALOG },
483         { SIP_BYE,       NO_RTP, "BYE",         CAN_NOT_CREATE_DIALOG },
484         { SIP_REFER,     NO_RTP, "REFER",       CAN_CREATE_DIALOG },
485         { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE",   CAN_CREATE_DIALOG },
486         { SIP_MESSAGE,   NO_RTP, "MESSAGE",     CAN_CREATE_DIALOG },
487         { SIP_UPDATE,    NO_RTP, "UPDATE",      CAN_NOT_CREATE_DIALOG },
488         { SIP_INFO,      NO_RTP, "INFO",        CAN_NOT_CREATE_DIALOG },
489         { SIP_CANCEL,    NO_RTP, "CANCEL",      CAN_NOT_CREATE_DIALOG },
490         { SIP_PUBLISH,   NO_RTP, "PUBLISH",     CAN_CREATE_DIALOG_UNSUPPORTED_METHOD },
491         { SIP_PING,      NO_RTP, "PING",        CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
492 };
493
494 /*!  Define SIP option tags, used in Require: and Supported: headers 
495         We need to be aware of these properties in the phones to use 
496         the replace: header. We should not do that without knowing
497         that the other end supports it... 
498         This is nothing we can configure, we learn by the dialog
499         Supported: header on the REGISTER (peer) or the INVITE
500         (other devices)
501         We are not using many of these today, but will in the future.
502         This is documented in RFC 3261
503 */
504 #define SUPPORTED               1
505 #define NOT_SUPPORTED           0
506
507 /* SIP options */
508 #define SIP_OPT_REPLACES        (1 << 0)
509 #define SIP_OPT_100REL          (1 << 1)
510 #define SIP_OPT_TIMER           (1 << 2)
511 #define SIP_OPT_EARLY_SESSION   (1 << 3)
512 #define SIP_OPT_JOIN            (1 << 4)
513 #define SIP_OPT_PATH            (1 << 5)
514 #define SIP_OPT_PREF            (1 << 6)
515 #define SIP_OPT_PRECONDITION    (1 << 7)
516 #define SIP_OPT_PRIVACY         (1 << 8)
517 #define SIP_OPT_SDP_ANAT        (1 << 9)
518 #define SIP_OPT_SEC_AGREE       (1 << 10)
519 #define SIP_OPT_EVENTLIST       (1 << 11)
520 #define SIP_OPT_GRUU            (1 << 12)
521 #define SIP_OPT_TARGET_DIALOG   (1 << 13)
522 #define SIP_OPT_NOREFERSUB      (1 << 14)
523 #define SIP_OPT_HISTINFO        (1 << 15)
524 #define SIP_OPT_RESPRIORITY     (1 << 16)
525 #define SIP_OPT_UNKNOWN         (1 << 17)
526
527
528 /*! \brief List of well-known SIP options. If we get this in a require,
529    we should check the list and answer accordingly. */
530 static const struct cfsip_options {
531         int id;                 /*!< Bitmap ID */
532         int supported;          /*!< Supported by Asterisk ? */
533         char * const text;      /*!< Text id, as in standard */
534 } sip_options[] = {     /* XXX used in 3 places */
535         /* RFC3891: Replaces: header for transfer */
536         { SIP_OPT_REPLACES,     SUPPORTED,      "replaces" },   
537         /* One version of Polycom firmware has the wrong label */
538         { SIP_OPT_REPLACES,     SUPPORTED,      "replace" },    
539         /* RFC3262: PRACK 100% reliability */
540         { SIP_OPT_100REL,       NOT_SUPPORTED,  "100rel" },     
541         /* RFC4028: SIP Session-Timers */
542         { SIP_OPT_TIMER,        SUPPORTED,      "timer" },
543         /* RFC3959: SIP Early session support */
544         { SIP_OPT_EARLY_SESSION, NOT_SUPPORTED, "early-session" },
545         /* RFC3911: SIP Join header support */
546         { SIP_OPT_JOIN,         NOT_SUPPORTED,  "join" },
547         /* RFC3327: Path support */
548         { SIP_OPT_PATH,         NOT_SUPPORTED,  "path" },
549         /* RFC3840: Callee preferences */
550         { SIP_OPT_PREF,         NOT_SUPPORTED,  "pref" },
551         /* RFC3312: Precondition support */
552         { SIP_OPT_PRECONDITION, NOT_SUPPORTED,  "precondition" },
553         /* RFC3323: Privacy with proxies*/
554         { SIP_OPT_PRIVACY,      NOT_SUPPORTED,  "privacy" },
555         /* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
556         { SIP_OPT_SDP_ANAT,     NOT_SUPPORTED,  "sdp-anat" },
557         /* RFC3329: Security agreement mechanism */
558         { SIP_OPT_SEC_AGREE,    NOT_SUPPORTED,  "sec_agree" },
559         /* SIMPLE events:  RFC4662 */
560         { SIP_OPT_EVENTLIST,    NOT_SUPPORTED,  "eventlist" },
561         /* GRUU: Globally Routable User Agent URI's */
562         { SIP_OPT_GRUU,         NOT_SUPPORTED,  "gruu" },
563         /* RFC4538: Target-dialog */
564         { SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED,  "tdialog" },
565         /* Disable the REFER subscription, RFC 4488 */
566         { SIP_OPT_NOREFERSUB,   NOT_SUPPORTED,  "norefersub" },
567         /* ietf-sip-history-info-06.txt */
568         { SIP_OPT_HISTINFO,     NOT_SUPPORTED,  "histinfo" },
569         /* ietf-sip-resource-priority-10.txt */
570         { SIP_OPT_RESPRIORITY,  NOT_SUPPORTED,  "resource-priority" },
571 };
572
573
574 /*! \brief SIP Methods we support 
575         \todo This string should be set dynamically. We only support REFER and SUBSCRIBE is we have
576         allowsubscribe and allowrefer on in sip.conf.
577 */
578 #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY"
579
580 /*! \brief SIP Extensions we support */
581 #define SUPPORTED_EXTENSIONS "replaces, timer" 
582
583 /*! \brief Standard SIP and TLS port from RFC 3261. DO NOT CHANGE THIS */
584 #define STANDARD_SIP_PORT       5060
585 #define STANDARD_TLS_PORT       5061
586 /*! \note in many SIP headers, absence of a port number implies port 5060,
587  * and this is why we cannot change the above constant.
588  * There is a limited number of places in asterisk where we could,
589  * in principle, use a different "default" port number, but
590  * we do not support this feature at the moment.
591  * You can run Asterisk with SIP on a different port with a configuration
592  * option. If you change this value, the signalling will be incorrect.
593  */
594
595 /*! \name DefaultValues Default values, set and reset in reload_config before reading configuration 
596
597    These are default values in the source. There are other recommended values in the
598    sip.conf.sample for new installations. These may differ to keep backwards compatibility,
599    yet encouraging new behaviour on new installations 
600  */
601 /*@{*/ 
602 #define DEFAULT_CONTEXT         "default"
603 #define DEFAULT_MOHINTERPRET    "default"
604 #define DEFAULT_MOHSUGGEST      ""
605 #define DEFAULT_VMEXTEN         "asterisk"
606 #define DEFAULT_CALLERID        "asterisk"
607 #define DEFAULT_NOTIFYMIME      "application/simple-message-summary"
608 #define DEFAULT_ALLOWGUEST      TRUE
609 #define DEFAULT_CALLCOUNTER     FALSE
610 #define DEFAULT_SRVLOOKUP       TRUE            /*!< Recommended setting is ON */
611 #define DEFAULT_COMPACTHEADERS  FALSE
612 #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. */
613 #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. */
614 #define DEFAULT_TOS_VIDEO       0               /*!< Video packets should be marked as DSCP AF41, but the default is 0 to be compatible with previous versions. */
615 #define DEFAULT_TOS_TEXT        0               /*!< Text packets should be marked as XXXX XXXX, but the default is 0 to be compatible with previous versions. */
616 #define DEFAULT_COS_SIP         4
617 #define DEFAULT_COS_AUDIO       5
618 #define DEFAULT_COS_VIDEO       6
619 #define DEFAULT_COS_TEXT        5
620 #define DEFAULT_ALLOW_EXT_DOM   TRUE
621 #define DEFAULT_REALM           "asterisk"
622 #define DEFAULT_NOTIFYRINGING   TRUE
623 #define DEFAULT_PEDANTIC        FALSE
624 #define DEFAULT_AUTOCREATEPEER  FALSE
625 #define DEFAULT_QUALIFY         FALSE
626 #define DEFAULT_REGEXTENONQUALIFY FALSE
627 #define DEFAULT_T1MIN           100             /*!< 100 MS for minimal roundtrip time */
628 #define DEFAULT_MAX_CALL_BITRATE (384)          /*!< Max bitrate for video */
629 #ifndef DEFAULT_USERAGENT
630 #define DEFAULT_USERAGENT "Asterisk PBX"        /*!< Default Useragent: header unless re-defined in sip.conf */
631 #define DEFAULT_SDPSESSION "Asterisk PBX"       /*!< Default SDP session name, (s=) header unless re-defined in sip.conf */
632 #define DEFAULT_SDPOWNER "root"         /*!< Default SDP username field in (o=) header unless re-defined in sip.conf */
633 #endif
634 /*@}*/ 
635
636 /*! \name DefaultSettings
637         Default setttings are used as a channel setting and as a default when
638         configuring devices 
639 */
640 /*@{*/ 
641 static char default_context[AST_MAX_CONTEXT];
642 static char default_subscribecontext[AST_MAX_CONTEXT];
643 static char default_language[MAX_LANGUAGE];
644 static char default_callerid[AST_MAX_EXTENSION];
645 static char default_fromdomain[AST_MAX_EXTENSION];
646 static char default_notifymime[AST_MAX_EXTENSION];
647 static int default_qualify;             /*!< Default Qualify= setting */
648 static char default_vmexten[AST_MAX_EXTENSION];
649 static char default_mohinterpret[MAX_MUSICCLASS];  /*!< Global setting for moh class to use when put on hold */
650 static char default_mohsuggest[MAX_MUSICCLASS];    /*!< Global setting for moh class to suggest when putting 
651                                                     *   a bridged channel on hold */
652 static int default_maxcallbitrate;      /*!< Maximum bitrate for call */
653 static struct ast_codec_pref default_prefs;             /*!< Default codec prefs */
654
655 /*! \brief a place to store all global settings for the sip channel driver */
656 struct sip_settings {
657         int peer_rtupdate;      /*!< G: Update database with registration data for peer? */
658         int rtsave_sysname;     /*!< G: Save system name at registration? */
659         int ignore_regexpire;   /*!< G: Ignore expiration of peer  */
660 };
661
662 static struct sip_settings sip_cfg;
663 /*@}*/ 
664
665 /*! \name GlobalSettings
666         Global settings apply to the channel (often settings you can change in the general section
667         of sip.conf
668 */
669 /*@{*/ 
670 static int global_directrtpsetup;       /*!< Enable support for Direct RTP setup (no re-invites) */
671 static int global_limitonpeers;         /*!< Match call limit on peers only */
672 static int global_rtautoclear;          /*!< Realtime ?? */
673 static int global_notifyringing;        /*!< Send notifications on ringing */
674 static int global_notifyhold;           /*!< Send notifications on hold */
675 static int global_alwaysauthreject;     /*!< Send 401 Unauthorized for all failing requests */
676 static int global_srvlookup;            /*!< SRV Lookup on or off. Default is on */
677 static int pedanticsipchecking;         /*!< Extra checking ?  Default off */
678 static int autocreatepeer;              /*!< Auto creation of peers at registration? Default off. */
679 static int global_match_auth_username;          /*!< Match auth username if available instead of From: Default off. */
680 static int global_relaxdtmf;            /*!< Relax DTMF */
681 static int global_rtptimeout;           /*!< Time out call if no RTP */
682 static int global_rtpholdtimeout;       /*!< Time out call if no RTP during hold */
683 static int global_rtpkeepalive;         /*!< Send RTP keepalives */
684 static int global_reg_timeout;  
685 static int global_regattempts_max;      /*!< Registration attempts before giving up */
686 static int global_allowguest;           /*!< allow unauthenticated users/peers to connect? */
687 static int global_callcounter;          /*!< Enable call counters for all devices. This is currently enabled by setting the peer
688                                                 call-limit to 999. When we remove the call-limit from the code, we can make it
689                                                 with just a boolean flag in the device structure */
690 static int global_allowsubscribe;       /*!< Flag for disabling ALL subscriptions, this is FALSE only if all peers are FALSE 
691                                             the global setting is in globals_flags[1] */
692 static unsigned int global_tos_sip;             /*!< IP type of service for SIP packets */
693 static unsigned int global_tos_audio;           /*!< IP type of service for audio RTP packets */
694 static unsigned int global_tos_video;           /*!< IP type of service for video RTP packets */
695 static unsigned int global_tos_text;            /*!< IP type of service for text RTP packets */
696 static unsigned int global_cos_sip;             /*!< 802.1p class of service for SIP packets */
697 static unsigned int global_cos_audio;           /*!< 802.1p class of service for audio RTP packets */
698 static unsigned int global_cos_video;           /*!< 802.1p class of service for video RTP packets */
699 static unsigned int global_cos_text;            /*!< 802.1p class of service for text RTP packets */
700 static int compactheaders;              /*!< send compact sip headers */
701 static int recordhistory;               /*!< Record SIP history. Off by default */
702 static int dumphistory;                 /*!< Dump history to verbose before destroying SIP dialog */
703 static char global_realm[MAXHOSTNAMELEN];               /*!< Default realm */
704 static char global_regcontext[AST_MAX_CONTEXT];         /*!< Context for auto-extensions */
705 static char global_useragent[AST_MAX_EXTENSION];        /*!< Useragent for the SIP channel */
706 static char global_sdpsession[AST_MAX_EXTENSION];       /*!< SDP session name for the SIP channel */
707 static char global_sdpowner[AST_MAX_EXTENSION]; /*!< SDP owner name for the SIP channel */
708 static int allow_external_domains;      /*!< Accept calls to external SIP domains? */
709 static int global_callevents;           /*!< Whether we send manager events or not */
710 static int global_authfailureevents;            /*!< Whether we send authentication failure manager events or not. Default no. */
711 static int global_t1;                   /*!< T1 time */
712 static int global_t1min;                /*!< T1 roundtrip time minimum */
713 static int global_timer_b;    /*!< Timer B - RFC 3261 Section 17.1.1.2 */
714 static int global_regextenonqualify;  /*!< Whether to add/remove regexten when qualifying peers */
715 static int global_autoframing;          /*!< Turn autoframing on or off. */
716 static enum transfermodes global_allowtransfer; /*!< SIP Refer restriction scheme */
717 static struct sip_proxy global_outboundproxy;   /*!< Outbound proxy */
718 static int global_matchexterniplocally; /*!< Match externip/externhost setting against localnet setting */
719 static int global_qualifyfreq; /*!< Qualify frequency */
720
721
722 /*! \brief Codecs that we support by default: */
723 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
724 static enum st_mode global_st_mode;           /*!< Mode of operation for Session-Timers           */
725 static enum st_refresher global_st_refresher; /*!< Session-Timer refresher                        */
726 static int global_min_se;                     /*!< Lowest threshold for session refresh interval  */
727 static int global_max_se;                     /*!< Highest threshold for session refresh interval */
728
729 /*@}*/ 
730
731 /*! \name Object counters @{
732  * \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
733  * should be used to modify these values. */
734 static int suserobjs = 0;                /*!< Static users */
735 static int ruserobjs = 0;                /*!< Realtime users */
736 static int speerobjs = 0;                /*!< Static peers */
737 static int rpeerobjs = 0;                /*!< Realtime peers */
738 static int apeerobjs = 0;                /*!< Autocreated peer objects */
739 static int regobjs = 0;                  /*!< Registry objects */
740 /* }@ */
741
742 static struct ast_flags global_flags[2] = {{0}};        /*!< global SIP_ flags */
743 static char used_context[AST_MAX_CONTEXT]; /*!< name of automatically created context for unloading */
744
745
746 AST_MUTEX_DEFINE_STATIC(netlock);
747
748 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
749    when it's doing something critical. */
750
751 AST_MUTEX_DEFINE_STATIC(monlock);
752
753 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
754
755 /*! \brief This is the thread for the monitor which checks for input on the channels
756    which are not currently in use.  */
757 static pthread_t monitor_thread = AST_PTHREADT_NULL;
758
759 static int sip_reloading = FALSE;                       /*!< Flag for avoiding multiple reloads at the same time */
760 static enum channelreloadreason sip_reloadreason;       /*!< Reason for last reload/load of configuration */
761
762 static struct sched_context *sched;     /*!< The scheduling context */
763 static struct io_context *io;           /*!< The IO context */
764 static int *sipsock_read_id;            /*!< ID of IO entry for sipsock FD */
765
766 #define DEC_CALL_LIMIT  0
767 #define INC_CALL_LIMIT  1
768 #define DEC_CALL_RINGING 2
769 #define INC_CALL_RINGING 3
770
771 /*!< Define some SIP transports */
772 enum sip_transport {
773         SIP_TRANSPORT_UDP = 1,
774         SIP_TRANSPORT_TCP = 1 << 1,
775         SIP_TRANSPORT_TLS = 1 << 2,
776 };
777
778 /*!< The SIP socket definition */
779 struct sip_socket {
780         ast_mutex_t *lock;
781         enum sip_transport type;
782         int fd;
783         uint16_t port;
784         struct ast_tcptls_session_instance *ser;
785 };
786
787 /*! \brief sip_request: The data grabbed from the UDP socket
788  *
789  * \verbatim
790  * Incoming messages: we first store the data from the socket in data[],
791  * adding a trailing \0 to make string parsing routines happy.
792  * Then call parse_request() and req.method = find_sip_method();
793  * to initialize the other fields. The \r\n at the end of each line is   
794  * replaced by \0, so that data[] is not a conforming SIP message anymore.
795  * After this processing, rlPart1 is set to non-NULL to remember
796  * that we can run get_header() on this kind of packet.
797  *
798  * parse_request() splits the first line as follows:
799  * Requests have in the first line      method uri SIP/2.0
800  *      rlPart1 = method; rlPart2 = uri;
801  * Responses have in the first line     SIP/2.0 NNN description
802  *      rlPart1 = SIP/2.0; rlPart2 = NNN + description;
803  *
804  * For outgoing packets, we initialize the fields with init_req() or init_resp()
805  * (which fills the first line to "METHOD uri SIP/2.0" or "SIP/2.0 code text"),
806  * and then fill the rest with add_header() and add_line().
807  * The \r\n at the end of the line are still there, so the get_header()
808  * and similar functions don't work on these packets. 
809  * \endverbatim
810  */
811 struct sip_request {
812         char *rlPart1;          /*!< SIP Method Name or "SIP/2.0" protocol version */
813         char *rlPart2;          /*!< The Request URI or Response Status */
814         int len;                /*!< bytes used in data[], excluding trailing null terminator. Rarely used. */
815         int headers;            /*!< # of SIP Headers */
816         int method;             /*!< Method of this request */
817         int lines;              /*!< Body Content */
818         unsigned int sdp_start; /*!< the line number where the SDP begins */
819         unsigned int sdp_end;   /*!< the line number where the SDP ends */
820         char debug;             /*!< print extra debugging if non zero */
821         char has_to_tag;        /*!< non-zero if packet has To: tag */
822         char ignore;            /*!< if non-zero This is a re-transmit, ignore it */
823         char *header[SIP_MAX_HEADERS];
824         char *line[SIP_MAX_LINES];
825         struct ast_str *data;   
826         struct sip_socket socket;       /*!< The socket used for this request */
827 };
828
829 /*! \brief structure used in transfers */
830 struct sip_dual {
831         struct ast_channel *chan1;      /*!< First channel involved */
832         struct ast_channel *chan2;      /*!< Second channel involved */
833         struct sip_request req;         /*!< Request that caused the transfer (REFER) */
834         int seqno;                      /*!< Sequence number */
835 };
836
837 struct sip_pkt;
838
839 /*! \brief Parameters to the transmit_invite function */
840 struct sip_invite_param {
841         int addsipheaders;              /*!< Add extra SIP headers */
842         const char *uri_options;        /*!< URI options to add to the URI */
843         const char *vxml_url;           /*!< VXML url for Cisco phones */
844         char *auth;                     /*!< Authentication */
845         char *authheader;               /*!< Auth header */
846         enum sip_auth_type auth_type;   /*!< Authentication type */
847         const char *replaces;           /*!< Replaces header for call transfers */
848         int transfer;                   /*!< Flag - is this Invite part of a SIP transfer? (invite/replaces) */
849 };
850
851 /*! \brief Structure to save routing information for a SIP session */
852 struct sip_route {
853         struct sip_route *next;
854         char hop[0];
855 };
856
857 /*! \brief Modes for SIP domain handling in the PBX */
858 enum domain_mode {
859         SIP_DOMAIN_AUTO,                /*!< This domain is auto-configured */
860         SIP_DOMAIN_CONFIG,              /*!< This domain is from configuration */
861 };
862
863 /*! \brief Domain data structure. 
864         \note In the future, we will connect this to a configuration tree specific
865         for this domain
866 */
867 struct domain {
868         char domain[MAXHOSTNAMELEN];            /*!< SIP domain we are responsible for */
869         char context[AST_MAX_EXTENSION];        /*!< Incoming context for this domain */
870         enum domain_mode mode;                  /*!< How did we find this domain? */
871         AST_LIST_ENTRY(domain) list;            /*!< List mechanics */
872 };
873
874 static AST_LIST_HEAD_STATIC(domain_list, domain);       /*!< The SIP domain list */
875
876
877 /*! \brief sip_history: Structure for saving transactions within a SIP dialog */
878 struct sip_history {
879         AST_LIST_ENTRY(sip_history) list;
880         char event[0];  /* actually more, depending on needs */
881 };
882
883 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
884
885 /*! \brief sip_auth: Credentials for authentication to other SIP services */
886 struct sip_auth {
887         char realm[AST_MAX_EXTENSION];  /*!< Realm in which these credentials are valid */
888         char username[256];             /*!< Username */
889         char secret[256];               /*!< Secret */
890         char md5secret[256];            /*!< MD5Secret */
891         struct sip_auth *next;          /*!< Next auth structure in list */
892 };
893
894 /*! \name SIPflags
895         Various flags for the flags field in the pvt structure 
896         Trying to sort these up (one or more of the following):
897         D: Dialog
898         P: Peer/user
899         G: Global flag
900         When flags are used by multiple structures, it is important that
901         they have a common layout so it is easy to copy them.
902 */
903 /*@{*/ 
904 #define SIP_OUTGOING            (1 << 0)        /*!< D: Direction of the last transaction in this dialog */
905 #define SIP_RINGING             (1 << 2)        /*!< D: Have sent 180 ringing */
906 #define SIP_PROGRESS_SENT       (1 << 3)        /*!< D: Have sent 183 message progress */
907 #define SIP_NEEDREINVITE        (1 << 4)        /*!< D: Do we need to send another reinvite? */
908 #define SIP_PENDINGBYE          (1 << 5)        /*!< D: Need to send bye after we ack? */
909 #define SIP_GOTREFER            (1 << 6)        /*!< D: Got a refer? */
910 #define SIP_CALL_LIMIT          (1 << 7)        /*!< D: Call limit enforced for this call */
911 #define SIP_INC_COUNT           (1 << 8)        /*!< D: Did this dialog increment the counter of in-use calls? */
912 #define SIP_INC_RINGING         (1 << 9)        /*!< D: Did this connection increment the counter of in-use calls? */
913 #define SIP_DEFER_BYE_ON_TRANSFER       (1 << 10)       /*!< D: Do not hangup at first ast_hangup */
914
915 #define SIP_PROMISCREDIR        (1 << 11)       /*!< DP: Promiscuous redirection */
916 #define SIP_TRUSTRPID           (1 << 12)       /*!< DP: Trust RPID headers? */
917 #define SIP_USEREQPHONE         (1 << 13)       /*!< DP: Add user=phone to numeric URI. Default off */
918 #define SIP_USECLIENTCODE       (1 << 14)       /*!< DP: Trust X-ClientCode info message */
919
920 /* DTMF flags - see str2dtmfmode() and dtmfmode2str() */
921 #define SIP_DTMF                (7 << 15)       /*!< DP: DTMF Support: five settings, uses three bits */
922 #define SIP_DTMF_RFC2833        (0 << 15)       /*!< DP: DTMF Support: RTP DTMF - "rfc2833" */
923 #define SIP_DTMF_INBAND         (1 << 15)       /*!< DP: DTMF Support: Inband audio, only for ULAW/ALAW - "inband" */
924 #define SIP_DTMF_INFO           (2 << 15)       /*!< DP: DTMF Support: SIP Info messages - "info" */
925 #define SIP_DTMF_AUTO           (3 << 15)       /*!< DP: DTMF Support: AUTO switch between rfc2833 and in-band DTMF */
926 #define SIP_DTMF_SHORTINFO      (4 << 15)       /*!< DP: DTMF Support: SIP Info messages - "info" - short variant */
927
928 /* NAT settings - see nat2str() */
929 #define SIP_NAT                 (3 << 18)       /*!< DP: four settings, uses two bits */
930 #define SIP_NAT_NEVER           (0 << 18)       /*!< DP: No nat support */
931 #define SIP_NAT_RFC3581         (1 << 18)       /*!< DP: NAT RFC3581 */
932 #define SIP_NAT_ROUTE           (2 << 18)       /*!< DP: NAT Only ROUTE */
933 #define SIP_NAT_ALWAYS          (3 << 18)       /*!< DP: NAT Both ROUTE and RFC3581 */
934
935 /* re-INVITE related settings */
936 #define SIP_REINVITE            (7 << 20)       /*!< DP: four settings, uses three bits */
937 #define SIP_REINVITE_NONE       (0 << 20)       /*!< DP: no reinvite allowed */
938 #define SIP_CAN_REINVITE        (1 << 20)       /*!< DP: allow peers to be reinvited to send media directly p2p */
939 #define SIP_CAN_REINVITE_NAT    (2 << 20)       /*!< DP: allow media reinvite when new peer is behind NAT */
940 #define SIP_REINVITE_UPDATE     (4 << 20)       /*!< DP: use UPDATE (RFC3311) when reinviting this peer */
941
942 /* "insecure" settings - see insecure2str() */
943 #define SIP_INSECURE            (3 << 23)       /*!< DP: three settings, uses two bits */
944 #define SIP_INSECURE_NONE       (0 << 23)       /*!< DP: secure mode */
945 #define SIP_INSECURE_PORT       (1 << 23)       /*!< DP: don't require matching port for incoming requests */
946 #define SIP_INSECURE_INVITE     (1 << 24)       /*!< DP: don't require authentication for incoming INVITEs */
947
948 /* Sending PROGRESS in-band settings */
949 #define SIP_PROG_INBAND         (3 << 25)       /*!< DP: three settings, uses two bits */
950 #define SIP_PROG_INBAND_NEVER   (0 << 25)
951 #define SIP_PROG_INBAND_NO      (1 << 25)
952 #define SIP_PROG_INBAND_YES     (2 << 25)
953
954 #define SIP_SENDRPID            (1 << 29)       /*!< DP: Remote Party-ID Support */
955 #define SIP_G726_NONSTANDARD    (1 << 31)       /*!< DP: Use non-standard packing for G726-32 data */
956
957 /*! \brief Flags to copy from peer/user to dialog */
958 #define SIP_FLAGS_TO_COPY \
959         (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
960          SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | SIP_G726_NONSTANDARD | \
961          SIP_USEREQPHONE | SIP_INSECURE)
962 /*@}*/ 
963
964 /*! \name SIPflags2
965         a second page of flags (for flags[1] */
966 /*@{*/ 
967 /* realtime flags */
968 #define SIP_PAGE2_RTCACHEFRIENDS        (1 << 0)        /*!< GP: Should we keep RT objects in memory for extended time? */
969 #define SIP_PAGE2_RTAUTOCLEAR           (1 << 2)        /*!< GP: Should we clean memory from peers after expiry? */
970 /* Space for addition of other realtime flags in the future */
971 #define SIP_PAGE2_STATECHANGEQUEUE      (1 << 9)        /*!< D: Unsent state pending change exists */
972
973 #define SIP_PAGE2_VIDEOSUPPORT          (1 << 14)       /*!< DP: Video supported if offered? */
974 #define SIP_PAGE2_TEXTSUPPORT           (1 << 15)       /*!< GDP: Global text enable */
975 #define SIP_PAGE2_ALLOWSUBSCRIBE        (1 << 16)       /*!< GP: Allow subscriptions from this peer? */
976 #define SIP_PAGE2_ALLOWOVERLAP          (1 << 17)       /*!< DP: Allow overlap dialing ? */
977 #define SIP_PAGE2_SUBSCRIBEMWIONLY      (1 << 18)       /*!< GP: Only issue MWI notification if subscribed to */
978
979 #define SIP_PAGE2_T38SUPPORT            (7 << 20)       /*!< GDP: T38 Fax Passthrough Support */
980 #define SIP_PAGE2_T38SUPPORT_UDPTL      (1 << 20)       /*!< GDP: T38 Fax Passthrough Support */
981 #define SIP_PAGE2_T38SUPPORT_RTP        (2 << 20)       /*!< GDP: T38 Fax Passthrough Support (not implemented) */
982 #define SIP_PAGE2_T38SUPPORT_TCP        (4 << 20)       /*!< GDP: T38 Fax Passthrough Support (not implemented) */
983
984 #define SIP_PAGE2_CALL_ONHOLD           (3 << 23)       /*!< D: Call hold states: */
985 #define SIP_PAGE2_CALL_ONHOLD_ACTIVE    (1 << 23)       /*!< D: Active hold */
986 #define SIP_PAGE2_CALL_ONHOLD_ONEDIR    (2 << 23)       /*!< D: One directional hold */
987 #define SIP_PAGE2_CALL_ONHOLD_INACTIVE  (3 << 23)       /*!< D: Inactive hold */
988
989 #define SIP_PAGE2_RFC2833_COMPENSATE    (1 << 25)       /*!< DP: Compensate for buggy RFC2833 implementations */
990 #define SIP_PAGE2_BUGGY_MWI             (1 << 26)       /*!< DP: Buggy CISCO MWI fix */
991 #define SIP_PAGE2_REGISTERTRYING        (1 << 29)       /*!< DP: Send 100 Trying on REGISTER attempts */
992
993 #define SIP_PAGE2_FLAGS_TO_COPY \
994         (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_VIDEOSUPPORT | \
995         SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE | SIP_PAGE2_BUGGY_MWI | \
996         SIP_PAGE2_TEXTSUPPORT )
997
998 /*@}*/ 
999
1000 /*! \name SIPflagsT38
1001         T.38 set of flags */
1002
1003 /*@{*/ 
1004 #define T38FAX_FILL_BIT_REMOVAL                 (1 << 0)        /*!< Default: 0 (unset)*/
1005 #define T38FAX_TRANSCODING_MMR                  (1 << 1)        /*!< Default: 0 (unset)*/
1006 #define T38FAX_TRANSCODING_JBIG                 (1 << 2)        /*!< Default: 0 (unset)*/
1007 /* Rate management */
1008 #define T38FAX_RATE_MANAGEMENT_TRANSFERED_TCF   (0 << 3)
1009 #define T38FAX_RATE_MANAGEMENT_LOCAL_TCF        (1 << 3)        /*!< Unset for transferredTCF (UDPTL), set for localTCF (TPKT) */
1010 /* UDP Error correction */
1011 #define T38FAX_UDP_EC_NONE                      (0 << 4)        /*!< two bits, if unset NO t38UDPEC field in T38 SDP*/
1012 #define T38FAX_UDP_EC_FEC                       (1 << 4)        /*!< Set for t38UDPFEC */
1013 #define T38FAX_UDP_EC_REDUNDANCY                (2 << 4)        /*!< Set for t38UDPRedundancy */
1014 /* T38 Spec version */
1015 #define T38FAX_VERSION                          (3 << 6)        /*!< two bits, 2 values so far, up to 4 values max */
1016 #define T38FAX_VERSION_0                        (0 << 6)        /*!< Version 0 */
1017 #define T38FAX_VERSION_1                        (1 << 6)        /*!< Version 1 */
1018 /* Maximum Fax Rate */
1019 #define T38FAX_RATE_2400                        (1 << 8)        /*!< 2400 bps t38FaxRate */
1020 #define T38FAX_RATE_4800                        (1 << 9)        /*!< 4800 bps t38FaxRate */
1021 #define T38FAX_RATE_7200                        (1 << 10)       /*!< 7200 bps t38FaxRate */
1022 #define T38FAX_RATE_9600                        (1 << 11)       /*!< 9600 bps t38FaxRate */
1023 #define T38FAX_RATE_12000                       (1 << 12)       /*!< 12000 bps t38FaxRate */
1024 #define T38FAX_RATE_14400                       (1 << 13)       /*!< 14400 bps t38FaxRate */
1025
1026 /*!< This is default: NO MMR and JBIG transcoding, NO fill bit removal, transferredTCF TCF, UDP FEC, Version 0 and 9600 max fax rate */
1027 static int global_t38_capability = T38FAX_VERSION_0 | T38FAX_RATE_2400 | T38FAX_RATE_4800 | T38FAX_RATE_7200 | T38FAX_RATE_9600;
1028 /*@}*/ 
1029
1030 /*! \brief debugging state
1031  * We store separately the debugging requests from the config file
1032  * and requests from the CLI. Debugging is enabled if either is set
1033  * (which means that if sipdebug is set in the config file, we can
1034  * only turn it off by reloading the config).
1035  */
1036 enum sip_debug_e {
1037         sip_debug_none = 0,
1038         sip_debug_config = 1,
1039         sip_debug_console = 2,
1040 };
1041
1042 static enum sip_debug_e sipdebug;
1043
1044 /*! \brief extra debugging for 'text' related events.
1045  * At thie moment this is set together with sip_debug_console.
1046  * It should either go away or be implemented properly.
1047  */
1048 static int sipdebug_text;
1049
1050 /*! \brief T38 States for a call */
1051 enum t38state {
1052         T38_DISABLED = 0,                /*!< Not enabled */
1053         T38_LOCAL_DIRECT,                /*!< Offered from local */
1054         T38_LOCAL_REINVITE,              /*!< Offered from local - REINVITE */
1055         T38_PEER_DIRECT,                 /*!< Offered from peer */
1056         T38_PEER_REINVITE,               /*!< Offered from peer - REINVITE */
1057         T38_ENABLED                      /*!< Negotiated (enabled) */
1058 };
1059
1060 /*! \brief T.38 channel settings (at some point we need to make this alloc'ed */
1061 struct t38properties {
1062         struct ast_flags t38support;    /*!< Flag for udptl, rtp or tcp support for this session */
1063         int capability;                 /*!< Our T38 capability */
1064         int peercapability;             /*!< Peers T38 capability */
1065         int jointcapability;            /*!< Supported T38 capability at both ends */
1066         enum t38state state;            /*!< T.38 state */
1067 };
1068
1069 /*! \brief Parameters to know status of transfer */
1070 enum referstatus {
1071         REFER_IDLE,                    /*!< No REFER is in progress */
1072         REFER_SENT,                    /*!< Sent REFER to transferee */
1073         REFER_RECEIVED,                /*!< Received REFER from transferrer */
1074         REFER_CONFIRMED,               /*!< Refer confirmed with a 100 TRYING (unused) */
1075         REFER_ACCEPTED,                /*!< Accepted by transferee */
1076         REFER_RINGING,                 /*!< Target Ringing */
1077         REFER_200OK,                   /*!< Answered by transfer target */
1078         REFER_FAILED,                  /*!< REFER declined - go on */
1079         REFER_NOAUTH                   /*!< We had no auth for REFER */
1080 };
1081
1082 /*! \brief generic struct to map between strings and integers.
1083  * Fill it with x-s pairs, terminate with an entry with s = NULL;
1084  * Then you can call map_x_s(...) to map an integer to a string,
1085  * and map_s_x() for the string -> integer mapping.
1086  */
1087 struct _map_x_s {
1088         int x;
1089         const char *s;
1090 };              
1091
1092 static const struct _map_x_s referstatusstrings[] = {
1093         { REFER_IDLE,           "<none>" },
1094         { REFER_SENT,           "Request sent" },
1095         { REFER_RECEIVED,       "Request received" },
1096         { REFER_CONFIRMED,      "Confirmed" },
1097         { REFER_ACCEPTED,       "Accepted" },
1098         { REFER_RINGING,        "Target ringing" },
1099         { REFER_200OK,          "Done" },
1100         { REFER_FAILED,         "Failed" },
1101         { REFER_NOAUTH,         "Failed - auth failure" },
1102         { -1,                   NULL} /* terminator */
1103 };
1104
1105 /*! \brief Structure to handle SIP transfers. Dynamically allocated when needed
1106         \note OEJ: Should be moved to string fields */
1107 struct sip_refer {
1108         char refer_to[AST_MAX_EXTENSION];               /*!< Place to store REFER-TO extension */
1109         char refer_to_domain[AST_MAX_EXTENSION];        /*!< Place to store REFER-TO domain */
1110         char refer_to_urioption[AST_MAX_EXTENSION];     /*!< Place to store REFER-TO uri options */
1111         char refer_to_context[AST_MAX_EXTENSION];       /*!< Place to store REFER-TO context */
1112         char referred_by[AST_MAX_EXTENSION];            /*!< Place to store REFERRED-BY extension */
1113         char referred_by_name[AST_MAX_EXTENSION];       /*!< Place to store REFERRED-BY extension */
1114         char refer_contact[AST_MAX_EXTENSION];          /*!< Place to store Contact info from a REFER extension */
1115         char replaces_callid[SIPBUFSIZE];                       /*!< Replace info: callid */
1116         char replaces_callid_totag[SIPBUFSIZE/2];               /*!< Replace info: to-tag */
1117         char replaces_callid_fromtag[SIPBUFSIZE/2];             /*!< Replace info: from-tag */
1118         struct sip_pvt *refer_call;                     /*!< Call we are referring. This is just a reference to a
1119                                                          * dialog owned by someone else, so we should not destroy
1120                                                          * it when the sip_refer object goes.
1121                                                          */
1122         int attendedtransfer;                           /*!< Attended or blind transfer? */
1123         int localtransfer;                              /*!< Transfer to local domain? */
1124         enum referstatus status;                        /*!< REFER status */
1125 };
1126
1127
1128 /*! \brief Structure that encapsulates all attributes related to running 
1129  *   SIP Session-Timers feature on a per dialog basis.
1130  */
1131 struct sip_st_dlg {
1132         int st_active;                          /*!< Session-Timers on/off */ 
1133         int st_interval;                        /*!< Session-Timers negotiated session refresh interval */
1134         int st_schedid;                         /*!< Session-Timers ast_sched scheduler id */
1135         enum st_refresher st_ref;               /*!< Session-Timers session refresher */
1136         int st_expirys;                         /*!< Session-Timers number of expirys */
1137         int st_active_peer_ua;                  /*!< Session-Timers on/off in peer UA */
1138         int st_cached_min_se;                   /*!< Session-Timers cached Min-SE */
1139         int st_cached_max_se;                   /*!< Session-Timers cached Session-Expires */
1140         enum st_mode st_cached_mode;            /*!< Session-Timers cached M.O. */
1141         enum st_refresher st_cached_ref;        /*!< Session-Timers cached refresher */
1142 };
1143
1144
1145 /*! \brief Structure that encapsulates all attributes related to configuration 
1146  *   of SIP Session-Timers feature on a per user/peer basis.
1147  */
1148 struct sip_st_cfg {
1149         enum st_mode st_mode_oper;      /*!< Mode of operation for Session-Timers           */
1150         enum st_refresher st_ref;       /*!< Session-Timer refresher                        */
1151         int st_min_se;                  /*!< Lowest threshold for session refresh interval  */
1152         int st_max_se;                  /*!< Highest threshold for session refresh interval */
1153 };
1154
1155
1156
1157
1158 /*! \brief sip_pvt: structures used for each SIP dialog, ie. a call, a registration, a subscribe.
1159  * Created and initialized by sip_alloc(), the descriptor goes into the list of
1160  * descriptors (dialoglist).
1161  */
1162 struct sip_pvt {
1163         struct sip_pvt *next;                   /*!< Next dialog in chain */
1164         ast_mutex_t pvt_lock;                   /*!< Dialog private lock */
1165         enum invitestates invitestate;          /*!< Track state of SIP_INVITEs */
1166         int method;                             /*!< SIP method that opened this dialog */
1167         AST_DECLARE_STRING_FIELDS(
1168                 AST_STRING_FIELD(callid);       /*!< Global CallID */
1169                 AST_STRING_FIELD(randdata);     /*!< Random data */
1170                 AST_STRING_FIELD(accountcode);  /*!< Account code */
1171                 AST_STRING_FIELD(realm);        /*!< Authorization realm */
1172                 AST_STRING_FIELD(nonce);        /*!< Authorization nonce */
1173                 AST_STRING_FIELD(opaque);       /*!< Opaque nonsense */
1174                 AST_STRING_FIELD(qop);          /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
1175                 AST_STRING_FIELD(domain);       /*!< Authorization domain */
1176                 AST_STRING_FIELD(from);         /*!< The From: header */
1177                 AST_STRING_FIELD(useragent);    /*!< User agent in SIP request */
1178                 AST_STRING_FIELD(exten);        /*!< Extension where to start */
1179                 AST_STRING_FIELD(context);      /*!< Context for this call */
1180                 AST_STRING_FIELD(subscribecontext); /*!< Subscribecontext */
1181                 AST_STRING_FIELD(subscribeuri); /*!< Subscribecontext */
1182                 AST_STRING_FIELD(fromdomain);   /*!< Domain to show in the from field */
1183                 AST_STRING_FIELD(fromuser);     /*!< User to show in the user field */
1184                 AST_STRING_FIELD(fromname);     /*!< Name to show in the user field */
1185                 AST_STRING_FIELD(tohost);       /*!< Host we should put in the "to" field */
1186                 AST_STRING_FIELD(todnid);       /*!< DNID of this call (overrides host) */
1187                 AST_STRING_FIELD(language);     /*!< Default language for this call */
1188                 AST_STRING_FIELD(mohinterpret); /*!< MOH class to use when put on hold */
1189                 AST_STRING_FIELD(mohsuggest);   /*!< MOH class to suggest when putting a peer on hold */
1190                 AST_STRING_FIELD(rdnis);        /*!< Referring DNIS */
1191                 AST_STRING_FIELD(redircause);   /*!< Referring cause */
1192                 AST_STRING_FIELD(theirtag);     /*!< Their tag */
1193                 AST_STRING_FIELD(username);     /*!< [user] name */
1194                 AST_STRING_FIELD(peername);     /*!< [peer] name, not set if [user] */
1195                 AST_STRING_FIELD(authname);     /*!< Who we use for authentication */
1196                 AST_STRING_FIELD(uri);          /*!< Original requested URI */
1197                 AST_STRING_FIELD(okcontacturi); /*!< URI from the 200 OK on INVITE */
1198                 AST_STRING_FIELD(peersecret);   /*!< Password */
1199                 AST_STRING_FIELD(peermd5secret);
1200                 AST_STRING_FIELD(cid_num);      /*!< Caller*ID number */
1201                 AST_STRING_FIELD(cid_name);     /*!< Caller*ID name */
1202                 AST_STRING_FIELD(via);          /*!< Via: header */
1203                 AST_STRING_FIELD(fullcontact);  /*!< The Contact: that the UA registers with us */
1204                         /* we only store the part in <brackets> in this field. */
1205                 AST_STRING_FIELD(our_contact);  /*!< Our contact header */
1206                 AST_STRING_FIELD(rpid);         /*!< Our RPID header */
1207                 AST_STRING_FIELD(rpid_from);    /*!< Our RPID From header */
1208                 AST_STRING_FIELD(url);          /*!< URL to be sent with next message to peer */
1209         );
1210         struct sip_socket socket;               /*!< The socket used for this dialog */
1211         unsigned int ocseq;                     /*!< Current outgoing seqno */
1212         unsigned int icseq;                     /*!< Current incoming seqno */
1213         ast_group_t callgroup;                  /*!< Call group */
1214         ast_group_t pickupgroup;                /*!< Pickup group */
1215         int lastinvite;                         /*!< Last Cseq of invite */
1216         int lastnoninvite;                      /*!< Last Cseq of non-invite */
1217         struct ast_flags flags[2];              /*!< SIP_ flags */
1218
1219         /* boolean or small integers that don't belong in flags */
1220         char do_history;                        /*!< Set if we want to record history */
1221         char alreadygone;                       /*!< already destroyed by our peer */
1222         char needdestroy;                       /*!< need to be destroyed by the monitor thread */
1223         char outgoing_call;                     /*!< this is an outgoing call */
1224         char answered_elsewhere;                /*!< This call is cancelled due to answer on another channel */
1225         char novideo;                           /*!< Didn't get video in invite, don't offer */
1226         char notext;                            /*!< Text not supported  (?) */
1227
1228         int timer_t1;                           /*!< SIP timer T1, ms rtt */
1229         int timer_b;                            /*!< SIP timer B, ms */
1230         unsigned int sipoptions;                /*!< Supported SIP options on the other end */
1231         unsigned int reqsipoptions;             /*!< Required SIP options on the other end */
1232         struct ast_codec_pref prefs;            /*!< codec prefs */
1233         int capability;                         /*!< Special capability (codec) */
1234         int jointcapability;                    /*!< Supported capability at both ends (codecs) */
1235         int peercapability;                     /*!< Supported peer capability */
1236         int prefcodec;                          /*!< Preferred codec (outbound only) */
1237         int noncodeccapability;                 /*!< DTMF RFC2833 telephony-event */
1238         int jointnoncodeccapability;            /*!< Joint Non codec capability */
1239         int redircodecs;                        /*!< Redirect codecs */
1240         int maxcallbitrate;                     /*!< Maximum Call Bitrate for Video Calls */    
1241         struct sip_proxy *outboundproxy;        /*!< Outbound proxy for this dialog */
1242         struct t38properties t38;               /*!< T38 settings */
1243         struct sockaddr_in udptlredirip;        /*!< Where our T.38 UDPTL should be going if not to us */
1244         struct ast_udptl *udptl;                /*!< T.38 UDPTL session */
1245         int callingpres;                        /*!< Calling presentation */
1246         int authtries;                          /*!< Times we've tried to authenticate */
1247         int expiry;                             /*!< How long we take to expire */
1248         long branch;                            /*!< The branch identifier of this session */
1249         char tag[11];                           /*!< Our tag for this session */
1250         int sessionid;                          /*!< SDP Session ID */
1251         int sessionversion;                     /*!< SDP Session Version */
1252         int sessionversion_remote;              /*!< Remote UA's SDP Session Version */
1253         int session_modify;                     /*!< Session modification request true/false  */
1254         struct sockaddr_in sa;                  /*!< Our peer */
1255         struct sockaddr_in redirip;             /*!< Where our RTP should be going if not to us */
1256         struct sockaddr_in vredirip;            /*!< Where our Video RTP should be going if not to us */
1257         struct sockaddr_in tredirip;            /*!< Where our Text RTP should be going if not to us */
1258         time_t lastrtprx;                       /*!< Last RTP received */
1259         time_t lastrtptx;                       /*!< Last RTP sent */
1260         int rtptimeout;                         /*!< RTP timeout time */
1261         struct sockaddr_in recv;                /*!< Received as */
1262         struct sockaddr_in ourip;               /*!< Our IP (as seen from the outside) */
1263         struct ast_channel *owner;              /*!< Who owns us (if we have an owner) */
1264         struct sip_route *route;                /*!< Head of linked list of routing steps (fm Record-Route) */
1265         int route_persistant;                   /*!< Is this the "real" route? */
1266         struct sip_auth *peerauth;              /*!< Realm authentication */
1267         int noncecount;                         /*!< Nonce-count */
1268         char lastmsg[256];                      /*!< Last Message sent/received */
1269         int amaflags;                           /*!< AMA Flags */
1270         int pendinginvite;                      /*!< Any pending INVITE or state NOTIFY (in subscribe pvt's) ? (seqno of this) */
1271         struct sip_request initreq;             /*!< Latest request that opened a new transaction
1272                                                         within this dialog.
1273                                                         NOT the request that opened the dialog
1274                                                 */
1275         
1276         int initid;                             /*!< Auto-congest ID if appropriate (scheduler) */
1277         int waitid;                             /*!< Wait ID for scheduler after 491 or other delays */
1278         int autokillid;                         /*!< Auto-kill ID (scheduler) */
1279         enum transfermodes allowtransfer;       /*!< REFER: restriction scheme */
1280         struct sip_refer *refer;                /*!< REFER: SIP transfer data structure */
1281         enum subscriptiontype subscribed;       /*!< SUBSCRIBE: Is this dialog a subscription?  */
1282         int stateid;                            /*!< SUBSCRIBE: ID for devicestate subscriptions */
1283         int laststate;                          /*!< SUBSCRIBE: Last known extension state */
1284         int dialogver;                          /*!< SUBSCRIBE: Version for subscription dialog-info */
1285         
1286         struct ast_dsp *vad;                    /*!< Inband DTMF Detection dsp */
1287         
1288         struct sip_peer *relatedpeer;           /*!< If this dialog is related to a peer, which one 
1289                                                         Used in peerpoke, mwi subscriptions */
1290         struct sip_registry *registry;          /*!< If this is a REGISTER dialog, to which registry */
1291         struct ast_rtp *rtp;                    /*!< RTP Session */
1292         struct ast_rtp *vrtp;                   /*!< Video RTP session */
1293         struct ast_rtp *trtp;                   /*!< Text RTP session */
1294         struct sip_pkt *packets;                /*!< Packets scheduled for re-transmission */
1295         struct sip_history_head *history;       /*!< History of this SIP dialog */
1296         size_t history_entries;                 /*!< Number of entires in the history */
1297         struct ast_variable *chanvars;          /*!< Channel variables to set for inbound call */
1298         struct sip_invite_param *options;       /*!< Options for INVITE */
1299         int autoframing;                        /*!< The number of Asters we group in a Pyroflax
1300                                                         before strolling to the GrokyzpÃ¥
1301                                                         (A bit unsure of this, please correct if
1302                                                         you know more) */
1303         struct sip_st_dlg *stimer;              /*!< SIP Session-Timers */              
1304 };
1305
1306 /*! Max entires in the history list for a sip_pvt */
1307 #define MAX_HISTORY_ENTRIES 50
1308
1309 /*!
1310  * Here we implement the container for dialogs (sip_pvt), defining
1311  * generic wrapper functions to ease the transition from the current
1312  * implementation (a single linked list) to a different container.
1313  * In addition to a reference to the container, we need functions to lock/unlock
1314  * the container and individual items, and functions to add/remove
1315  * references to the individual items.
1316  */
1317 static struct sip_pvt *dialoglist = NULL;
1318
1319 /*! \brief Protect the SIP dialog list (of sip_pvt's) */
1320 AST_MUTEX_DEFINE_STATIC(dialoglock);
1321
1322 #ifndef DETECT_DEADLOCKS
1323 /*! \brief hide the way the list is locked/unlocked */
1324 static void dialoglist_lock(void)
1325 {
1326         ast_mutex_lock(&dialoglock);
1327 }
1328
1329 static void dialoglist_unlock(void)
1330 {
1331         ast_mutex_unlock(&dialoglock);
1332 }
1333 #else
1334 /* we don't want to HIDE the information about where the lock was requested if trying to debug 
1335  * deadlocks!  So, just make these macros! */
1336 #define dialoglist_lock(x) ast_mutex_lock(&dialoglock)
1337 #define dialoglist_unlock(x) ast_mutex_unlock(&dialoglock)
1338 #endif
1339
1340 /*!
1341  * when we create or delete references, make sure to use these
1342  * functions so we keep track of the refcounts.
1343  * To simplify the code, we allow a NULL to be passed to dialog_unref().
1344  */
1345 static struct sip_pvt *dialog_ref(struct sip_pvt *p)
1346 {
1347         return p;
1348 }
1349
1350 static struct sip_pvt *dialog_unref(struct sip_pvt *p)
1351 {
1352         return NULL;
1353 }
1354
1355 /*! \brief sip packet - raw format for outbound packets that are sent or scheduled for transmission
1356  * Packets are linked in a list, whose head is in the struct sip_pvt they belong to.
1357  * Each packet holds a reference to the parent struct sip_pvt.
1358  * This structure is allocated in __sip_reliable_xmit() and only for packets that
1359  * require retransmissions.
1360  */
1361 struct sip_pkt {
1362         struct sip_pkt *next;                   /*!< Next packet in linked list */
1363         int retrans;                            /*!< Retransmission number */
1364         int method;                             /*!< SIP method for this packet */
1365         int seqno;                              /*!< Sequence number */
1366         char is_resp;                           /*!< 1 if this is a response packet (e.g. 200 OK), 0 if it is a request */
1367         char is_fatal;                          /*!< non-zero if there is a fatal error */
1368         struct sip_pvt *owner;                  /*!< Owner AST call */
1369         int retransid;                          /*!< Retransmission ID */
1370         int timer_a;                            /*!< SIP timer A, retransmission timer */
1371         int timer_t1;                           /*!< SIP Timer T1, estimated RTT or 500 ms */
1372         int packetlen;                          /*!< Length of packet */
1373         struct ast_str *data;
1374 };      
1375
1376 /*! \brief Structure for SIP user data. User's place calls to us */
1377 struct sip_user {
1378         /* Users who can access various contexts */
1379         ASTOBJ_COMPONENTS(struct sip_user);
1380         char secret[80];                /*!< Password */
1381         char md5secret[80];             /*!< Password in md5 */
1382         char context[AST_MAX_CONTEXT];  /*!< Default context for incoming calls */
1383         char subscribecontext[AST_MAX_CONTEXT]; /* Default context for subscriptions */
1384         char cid_num[80];               /*!< Caller ID num */
1385         char cid_name[80];              /*!< Caller ID name */
1386         char accountcode[AST_MAX_ACCOUNT_CODE]; /* Account code */
1387         char language[MAX_LANGUAGE];    /*!< Default language for this user */
1388         char mohinterpret[MAX_MUSICCLASS];/*!< Music on Hold class */
1389         char mohsuggest[MAX_MUSICCLASS];/*!< Music on Hold class */
1390         char useragent[256];            /*!< User agent in SIP request */
1391         struct ast_codec_pref prefs;    /*!< codec prefs */
1392         ast_group_t callgroup;          /*!< Call group */
1393         ast_group_t pickupgroup;        /*!< Pickup Group */
1394         unsigned int sipoptions;        /*!< Supported SIP options */
1395         struct ast_flags flags[2];      /*!< SIP_ flags */
1396
1397         /* things that don't belong in flags */
1398         char is_realtime;               /*!< this is a 'realtime' user */
1399
1400         int amaflags;                   /*!< AMA flags for billing */
1401         int callingpres;                /*!< Calling id presentation */
1402         int capability;                 /*!< Codec capability */
1403         int inUse;                      /*!< Number of calls in use */
1404         int call_limit;                 /*!< Limit of concurrent calls */
1405         enum transfermodes allowtransfer;       /*! SIP Refer restriction scheme */
1406         struct ast_ha *ha;              /*!< ACL setting */
1407         struct ast_variable *chanvars;  /*!< Variables to set for channel created by user */
1408         int maxcallbitrate;             /*!< Maximum Bitrate for a video call */
1409         int autoframing;
1410         struct sip_st_cfg stimer;       /*!< SIP Session-Timers */
1411 };
1412
1413 /*!
1414  * \brief A peer's mailbox
1415  *
1416  * We could use STRINGFIELDS here, but for only two strings, it seems like
1417  * too much effort ...
1418  */
1419 struct sip_mailbox {
1420         char *mailbox;
1421         char *context;
1422         /*! Associated MWI subscription */
1423         struct ast_event_sub *event_sub;
1424         AST_LIST_ENTRY(sip_mailbox) entry;
1425 };
1426
1427 /*! \brief Structure for SIP peer data, we place calls to peers if registered  or fixed IP address (host) */
1428 /* XXX field 'name' must be first otherwise sip_addrcmp() will fail */
1429 struct sip_peer {
1430         ASTOBJ_COMPONENTS(struct sip_peer);     /*!< name, refcount, objflags,  object pointers */
1431                                         /*!< peer->name is the unique name of this object */
1432         struct sip_socket socket;       /*!< Socket used for this peer */
1433         char secret[80];                /*!< Password */
1434         char md5secret[80];             /*!< Password in MD5 */
1435         struct sip_auth *auth;          /*!< Realm authentication list */
1436         char context[AST_MAX_CONTEXT];  /*!< Default context for incoming calls */
1437         char subscribecontext[AST_MAX_CONTEXT]; /*!< Default context for subscriptions */
1438         char username[80];              /*!< Temporary username until registration */ 
1439         char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */
1440         int amaflags;                   /*!< AMA Flags (for billing) */
1441         char tohost[MAXHOSTNAMELEN];    /*!< If not dynamic, IP address */
1442         char regexten[AST_MAX_EXTENSION]; /*!< Extension to register (if regcontext is used) */
1443         char fromuser[80];              /*!< From: user when calling this peer */
1444         char fromdomain[MAXHOSTNAMELEN];        /*!< From: domain when calling this peer */
1445         char fullcontact[256];          /*!< Contact registered with us (not in sip.conf) */
1446         char cid_num[80];               /*!< Caller ID num */
1447         char cid_name[80];              /*!< Caller ID name */
1448         int callingpres;                /*!< Calling id presentation */
1449         int inUse;                      /*!< Number of calls in use */
1450         int inRinging;                  /*!< Number of calls ringing */
1451         int onHold;                     /*!< Peer has someone on hold */
1452         int call_limit;                 /*!< Limit of concurrent calls */
1453         int busy_level;                 /*!< Level of active channels where we signal busy */
1454         enum transfermodes allowtransfer;       /*! SIP Refer restriction scheme */
1455         char vmexten[AST_MAX_EXTENSION]; /*!< Dialplan extension for MWI notify message*/
1456         char language[MAX_LANGUAGE];    /*!<  Default language for prompts */
1457         char mohinterpret[MAX_MUSICCLASS];/*!<  Music on Hold class */
1458         char mohsuggest[MAX_MUSICCLASS];/*!<  Music on Hold class */
1459         char useragent[256];            /*!<  User agent in SIP request (saved from registration) */
1460         struct ast_codec_pref prefs;    /*!<  codec prefs */
1461         int lastmsgssent;
1462         unsigned int sipoptions;        /*!<  Supported SIP options */
1463         struct ast_flags flags[2];      /*!<  SIP_ flags */
1464         
1465         /*! Mailboxes that this peer cares about */
1466         AST_LIST_HEAD_NOLOCK(, sip_mailbox) mailboxes;
1467
1468         /* things that don't belong in flags */
1469         char is_realtime;               /*!< this is a 'realtime' peer */
1470         char rt_fromcontact;            /*!< P: copy fromcontact from realtime */
1471         char host_dynamic;              /*!< P: Dynamic Peers register with Asterisk */
1472         char selfdestruct;              /*!< P: Automatic peers need to destruct themselves */
1473
1474         int expire;                     /*!<  When to expire this peer registration */
1475         int capability;                 /*!<  Codec capability */
1476         int rtptimeout;                 /*!<  RTP timeout */
1477         int rtpholdtimeout;             /*!<  RTP Hold Timeout */
1478         int rtpkeepalive;               /*!<  Send RTP packets for keepalive */
1479         ast_group_t callgroup;          /*!<  Call group */
1480         ast_group_t pickupgroup;        /*!<  Pickup group */
1481         struct sip_proxy *outboundproxy;        /*!< Outbound proxy for this peer */
1482         struct ast_dnsmgr_entry *dnsmgr;/*!<  DNS refresh manager for peer */
1483         struct sockaddr_in addr;        /*!<  IP address of peer */
1484         int maxcallbitrate;             /*!< Maximum Bitrate for a video call */
1485         
1486         /* Qualification */
1487         struct sip_pvt *call;           /*!<  Call pointer */
1488         int pokeexpire;                 /*!<  When to expire poke (qualify= checking) */
1489         int lastms;                     /*!<  How long last response took (in ms), or -1 for no response */
1490         int maxms;                      /*!<  Max ms we will accept for the host to be up, 0 to not monitor */
1491         int qualifyfreq;                /*!<  Qualification: How often to check for the host to be up */
1492         struct timeval ps;              /*!<  Time for sending SIP OPTION in sip_pke_peer() */
1493         struct sockaddr_in defaddr;     /*!<  Default IP address, used until registration */
1494         struct ast_ha *ha;              /*!<  Access control list */
1495         struct ast_variable *chanvars;  /*!<  Variables to set for channel created by user */
1496         struct sip_pvt *mwipvt;         /*!<  Subscription for MWI */
1497         int autoframing;
1498         struct sip_st_cfg stimer;       /*!<  SIP Session-Timers */
1499         int timer_t1;                   /*!<  The maximum T1 value for the peer */
1500         int timer_b;                    /*!<  The maximum timer B (transaction timeouts) */
1501         int deprecated_username; /*!< If it's a realtime peer, are they using the deprecated "username" instead of "defaultuser" */
1502 };
1503
1504
1505 /*! \brief Registrations with other SIP proxies
1506  * Created by sip_register(), the entry is linked in the 'regl' list,
1507  * and never deleted (other than at 'sip reload' or module unload times).
1508  * The entry always has a pending timeout, either waiting for an ACK to
1509  * the REGISTER message (in which case we have to retransmit the request),
1510  * or waiting for the next REGISTER message to be sent (either the initial one,
1511  * or once the previously completed registration one expires).
1512  * The registration can be in one of many states, though at the moment
1513  * the handling is a bit mixed.
1514  * Note that the entire evolution of sip_registry (transmissions,
1515  * incoming packets and timeouts) is driven by one single thread,
1516  * do_monitor(), so there is almost no synchronization issue.
1517  * The only exception  is the sip_pvt creation/lookup,
1518  * as the dialoglist is also manipulated by other threads.
1519  */
1520 struct sip_registry {
1521         ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
1522         AST_DECLARE_STRING_FIELDS(
1523                 AST_STRING_FIELD(callid);       /*!< Global Call-ID */
1524                 AST_STRING_FIELD(realm);        /*!< Authorization realm */
1525                 AST_STRING_FIELD(nonce);        /*!< Authorization nonce */
1526                 AST_STRING_FIELD(opaque);       /*!< Opaque nonsense */
1527                 AST_STRING_FIELD(qop);          /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
1528                 AST_STRING_FIELD(domain);       /*!< Authorization domain */
1529                 AST_STRING_FIELD(username);     /*!< Who we are registering as */
1530                 AST_STRING_FIELD(authuser);     /*!< Who we *authenticate* as */
1531                 AST_STRING_FIELD(hostname);     /*!< Domain or host we register to */
1532                 AST_STRING_FIELD(secret);       /*!< Password in clear text */  
1533                 AST_STRING_FIELD(md5secret);    /*!< Password in md5 */
1534                 AST_STRING_FIELD(callback);     /*!< Contact extension */
1535                 AST_STRING_FIELD(random);
1536         );
1537         enum sip_transport transport;
1538         int portno;                     /*!<  Optional port override */
1539         int expire;                     /*!< Sched ID of expiration */
1540         int expiry;                     /*!< Value to use for the Expires header */
1541         int regattempts;                /*!< Number of attempts (since the last success) */
1542         int timeout;                    /*!< sched id of sip_reg_timeout */
1543         int refresh;                    /*!< How often to refresh */
1544         struct sip_pvt *call;           /*!< create a sip_pvt structure for each outbound "registration dialog" in progress */
1545         enum sipregistrystate regstate; /*!< Registration state (see above) */
1546         struct timeval regtime;         /*!< Last successful registration time */
1547         int callid_valid;               /*!< 0 means we haven't chosen callid for this registry yet. */
1548         unsigned int ocseq;             /*!< Sequence number we got to for REGISTERs for this registry */
1549         struct ast_dnsmgr_entry *dnsmgr;        /*!<  DNS refresh manager for register */
1550         struct sockaddr_in us;          /*!< Who the server thinks we are */
1551         int noncecount;                 /*!< Nonce-count */
1552         char lastmsg[256];              /*!< Last Message sent/received */
1553 };
1554
1555 struct sip_threadinfo {
1556         int stop;
1557         pthread_t threadid;
1558         struct ast_tcptls_session_instance *ser;
1559         enum sip_transport type;        /* We keep a copy of the type here so we can display it in the connection list */
1560         AST_LIST_ENTRY(sip_threadinfo) list;
1561 };
1562
1563 /* --- Linked lists of various objects --------*/
1564
1565 /*! \brief  The thread list of TCP threads */
1566 static AST_LIST_HEAD_STATIC(threadl, sip_threadinfo);
1567
1568 /*! \brief  The user list: Users and friends */
1569 static struct ast_user_list {
1570         ASTOBJ_CONTAINER_COMPONENTS(struct sip_user);
1571 } userl;
1572
1573 /*! \brief  The peer list: Peers and Friends */
1574 static struct ast_peer_list {
1575         ASTOBJ_CONTAINER_COMPONENTS(struct sip_peer);
1576 } peerl;
1577
1578 /*! \brief  The register list: Other SIP proxies we register with and place calls to */
1579 static struct ast_register_list {
1580         ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
1581         int recheck;
1582 } regl;
1583
1584 static int temp_pvt_init(void *);
1585 static void temp_pvt_cleanup(void *);
1586
1587 /*! \brief A per-thread temporary pvt structure */
1588 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
1589
1590 /*! \brief Authentication list for realm authentication 
1591  * \todo Move the sip_auth list to AST_LIST */
1592 static struct sip_auth *authl = NULL;
1593
1594
1595 /* --- Sockets and networking --------------*/
1596
1597 /*! \brief Main socket for SIP communication.
1598  *
1599  * sipsock is shared between the SIP manager thread (which handles reload
1600  * requests), the io handler (sipsock_read()) and the user routines that
1601  * issue writes (using __sip_xmit()).
1602  * The socket is -1 only when opening fails (this is a permanent condition),
1603  * or when we are handling a reload() that changes its address (this is
1604  * a transient situation during which we might have a harmless race, see
1605  * below). Because the conditions for the race to be possible are extremely
1606  * rare, we don't want to pay the cost of locking on every I/O.
1607  * Rather, we remember that when the race may occur, communication is
1608  * bound to fail anyways, so we just live with this event and let
1609  * the protocol handle this above us.
1610  */
1611 static int sipsock  = -1;
1612
1613 static struct sockaddr_in bindaddr;     /*!< The address we bind to */
1614
1615 /*! \brief our (internal) default address/port to put in SIP/SDP messages
1616  *  internip is initialized picking a suitable address from one of the
1617  * interfaces, and the same port number we bind to. It is used as the
1618  * default address/port in SIP messages, and as the default address
1619  * (but not port) in SDP messages.
1620  */
1621 static struct sockaddr_in internip;
1622
1623 /*! \brief our external IP address/port for SIP sessions.
1624  * externip.sin_addr is only set when we know we might be behind
1625  * a NAT, and this is done using a variety of (mutually exclusive)
1626  * ways from the config file:
1627  *
1628  * + with "externip = host[:port]" we specify the address/port explicitly.
1629  *   The address is looked up only once when (re)loading the config file;
1630  * 
1631  * + with "externhost = host[:port]" we do a similar thing, but the
1632  *   hostname is stored in externhost, and the hostname->IP mapping
1633  *   is refreshed every 'externrefresh' seconds;
1634  * 
1635  * + with "stunaddr = host[:port]" we run queries every externrefresh seconds
1636  *   to the specified server, and store the result in externip.
1637  *
1638  * Other variables (externhost, externexpire, externrefresh) are used
1639  * to support the above functions.
1640  */
1641 static struct sockaddr_in externip;             /*!< External IP address if we are behind NAT */
1642
1643 static char externhost[MAXHOSTNAMELEN];         /*!< External host name */
1644 static time_t externexpire;                     /*!< Expiration counter for re-resolving external host name in dynamic DNS */
1645 static int externrefresh = 10;
1646 static struct sockaddr_in stunaddr;             /*!< stun server address */
1647
1648 /*! \brief  List of local networks
1649  * We store "localnet" addresses from the config file into an access list,
1650  * marked as 'DENY', so the call to ast_apply_ha() will return
1651  * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
1652  * (i.e. presumably public) addresses.
1653  */
1654 static struct ast_ha *localaddr;                /*!< List of local networks, on the same side of NAT as this Asterisk */
1655
1656 static int ourport_tcp;
1657 static int ourport_tls;
1658 static struct sockaddr_in debugaddr;
1659
1660 static struct ast_config *notify_types;         /*!< The list of manual NOTIFY types we know how to send */
1661
1662 /*! some list management macros. */
1663  
1664 #define UNLINK(element, head, prev) do {        \
1665         if (prev)                               \
1666                 (prev)->next = (element)->next; \
1667         else                                    \
1668                 (head) = (element)->next;       \
1669         } while (0)
1670
1671 enum t38_action_flag {
1672         SDP_T38_NONE = 0, /*!< Do not modify T38 information at all */
1673         SDP_T38_INITIATE, /*!< Remote side has requested T38 with us */
1674         SDP_T38_ACCEPT,   /*!< Remote side accepted our T38 request */
1675 };
1676
1677 /*---------------------------- Forward declarations of functions in chan_sip.c */
1678 /* Note: This is added to help splitting up chan_sip.c into several files
1679         in coming releases. */
1680
1681 /*--- PBX interface functions */
1682 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
1683 static int sip_devicestate(void *data);
1684 static int sip_sendtext(struct ast_channel *ast, const char *text);
1685 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
1686 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
1687 static int sip_hangup(struct ast_channel *ast);
1688 static int sip_answer(struct ast_channel *ast);
1689 static struct ast_frame *sip_read(struct ast_channel *ast);
1690 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
1691 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
1692 static int sip_transfer(struct ast_channel *ast, const char *dest);
1693 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1694 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
1695 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
1696 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
1697 static const char *sip_get_callid(struct ast_channel *chan);
1698
1699 static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin);
1700 static int sip_standard_port(struct sip_socket s);
1701 static int sip_prepare_socket(struct sip_pvt *p);
1702
1703 /*--- Transmitting responses and requests */
1704 static int sipsock_read(int *id, int fd, short events, void *ignore);
1705 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len);
1706 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod);
1707 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1708 static int retrans_pkt(const void *data);
1709 static int transmit_sip_request(struct sip_pvt *p, struct sip_request *req);
1710 static int transmit_response_using_temp(ast_string_field callid, struct sockaddr_in *sin, int useglobal_nat, const int intended_method, const struct sip_request *req, const char *msg);
1711 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1712 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1713 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1714 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp);
1715 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
1716 static int transmit_response_with_auth(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *rand, enum xmittype reliable, const char *header, int stale);
1717 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1718 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, int reliable);
1719 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
1720 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
1721 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init);
1722 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
1723 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
1724 static int transmit_info_with_vidupdate(struct sip_pvt *p);
1725 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
1726 static int transmit_refer(struct sip_pvt *p, const char *dest);
1727 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten);
1728 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
1729 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
1730 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1731 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1732 static void copy_request(struct sip_request *dst, const struct sip_request *src);
1733 static void receive_message(struct sip_pvt *p, struct sip_request *req);
1734 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req);
1735 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only);
1736
1737 /*--- Dialog management */
1738 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
1739                                  int useglobal_nat, const int intended_method);
1740 static int __sip_autodestruct(const void *data);
1741 static void sip_scheddestroy(struct sip_pvt *p, int ms);
1742 static int sip_cancel_destroy(struct sip_pvt *p);
1743 static struct sip_pvt *sip_destroy(struct sip_pvt *p);
1744 static int __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist);
1745 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
1746 static void __sip_pretend_ack(struct sip_pvt *p);
1747 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
1748 static int auto_congest(const void *arg);
1749 static int update_call_counter(struct sip_pvt *fup, int event);
1750 static int hangup_sip2cause(int cause);
1751 static const char *hangup_cause2sip(int cause);
1752 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
1753 static void free_old_route(struct sip_route *route);
1754 static void list_route(struct sip_route *route);
1755 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
1756 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
1757                                               struct sip_request *req, char *uri);
1758 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
1759 static void check_pendings(struct sip_pvt *p);
1760 static void *sip_park_thread(void *stuff);
1761 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
1762 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1763
1764 /*--- Codec handling / SDP */
1765 static void try_suggested_sip_codec(struct sip_pvt *p);
1766 static const char* get_sdp_iterate(int* start, struct sip_request *req, const char *name);
1767 static const char *get_sdp(struct sip_request *req, const char *name);
1768 static int find_sdp(struct sip_request *req);
1769 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
1770 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
1771                              struct ast_str **m_buf, struct ast_str **a_buf,
1772                              int debug, int *min_packet_size);
1773 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
1774                                 struct ast_str **m_buf, struct ast_str **a_buf,
1775                                 int debug);
1776 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp);
1777 static void do_setnat(struct sip_pvt *p, int natflags);
1778 static void stop_media_flows(struct sip_pvt *p);
1779
1780 /*--- Authentication stuff */
1781 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1782 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
1783 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1784                                          const char *secret, const char *md5secret, int sipmethod,
1785                                          char *uri, enum xmittype reliable, int ignore);
1786 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
1787                                               int sipmethod, char *uri, enum xmittype reliable,
1788                                               struct sockaddr_in *sin, struct sip_peer **authpeer);
1789 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin);
1790
1791 /*--- Domain handling */
1792 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1793 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
1794 static void clear_sip_domains(void);
1795
1796 /*--- SIP realm authentication */
1797 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno);
1798 static int clear_realm_authentication(struct sip_auth *authlist);       /* Clear realm authentication list (at reload) */
1799 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
1800
1801 /*--- Misc functions */
1802 static int sip_do_reload(enum channelreloadreason reason);
1803 static int reload_config(enum channelreloadreason reason);
1804 static int expire_register(const void *data);
1805 static void *do_monitor(void *data);
1806 static int restart_monitor(void);
1807 static int sip_addrcmp(char *name, struct sockaddr_in *sin);    /* Support for peer matching */
1808 static int sip_refer_allocate(struct sip_pvt *p);
1809 static void ast_quiet_chan(struct ast_channel *chan);
1810 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
1811
1812 /*--- Device monitoring and Device/extension state/event handling */
1813 static int cb_extensionstate(char *context, char* exten, int state, void *data);
1814 static int sip_devicestate(void *data);
1815 static int sip_poke_noanswer(const void *data);
1816 static int sip_poke_peer(struct sip_peer *peer);
1817 static void sip_poke_all_peers(void);
1818 static void sip_peer_hold(struct sip_pvt *p, int hold);
1819 static void mwi_event_cb(const struct ast_event *, void *);
1820
1821 /*--- Applications, functions, CLI and manager command helpers */
1822 static const char *sip_nat_mode(const struct sip_pvt *p);
1823 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1824 static char *transfermode2str(enum transfermodes mode) attribute_const;
1825 static const char *nat2str(int nat) attribute_const;
1826 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
1827 static char *sip_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1828 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1829 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1830 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1831 static void  print_group(int fd, ast_group_t group, int crlf);
1832 static const char *dtmfmode2str(int mode) attribute_const;
1833 static int str2dtmfmode(const char *str) attribute_unused;
1834 static const char *insecure2str(int mode) attribute_const;
1835 static void cleanup_stale_contexts(char *new, char *old);
1836 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
1837 static const char *domain_mode_to_text(const enum domain_mode mode);
1838 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1839 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1840 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1841 static char *sip_show_user(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1842 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1843 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1844 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1845 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
1846 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1847 static char *complete_sip_peer(const char *word, int state, int flags2);
1848 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
1849 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
1850 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
1851 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
1852 static char *complete_sip_user(const char *word, int state, int flags2);
1853 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state);
1854 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
1855 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1856 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1857 static char *sip_do_debug_ip(int fd, char *arg);
1858 static char *sip_do_debug_peer(int fd, char *arg);
1859 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1860 static char *sip_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1861 static char *sip_do_history_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1862 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1863 static int sip_dtmfmode(struct ast_channel *chan, void *data);
1864 static int sip_addheader(struct ast_channel *chan, void *data);
1865 static int sip_do_reload(enum channelreloadreason reason);
1866 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1867 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
1868
1869 /*--- Debugging 
1870         Functions for enabling debug per IP or fully, or enabling history logging for
1871         a SIP dialog
1872 */
1873 static void sip_dump_history(struct sip_pvt *dialog);   /* Dump history to debuglog at end of dialog, before destroying data */
1874 static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
1875 static inline int sip_debug_test_pvt(struct sip_pvt *p);
1876
1877
1878 /*! \brief Append to SIP dialog history 
1879         \return Always returns 0 */
1880 #define append_history(p, event, fmt , args... )        append_history_full(p, "%-15s " fmt, event, ## args)
1881 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
1882 static void sip_dump_history(struct sip_pvt *dialog);
1883
1884 /*--- Device object handling */
1885 static struct sip_peer *temp_peer(const char *name);
1886 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime);
1887 static struct sip_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime);
1888 static int update_call_counter(struct sip_pvt *fup, int event);
1889 static void sip_destroy_peer(struct sip_peer *peer);
1890 static void sip_destroy_user(struct sip_user *user);
1891 static int sip_poke_peer(struct sip_peer *peer);
1892 static void set_peer_defaults(struct sip_peer *peer);
1893 static struct sip_peer *temp_peer(const char *name);
1894 static void register_peer_exten(struct sip_peer *peer, int onoff);
1895 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime);
1896 static struct sip_user *find_user(const char *name, int realtime);
1897 static int sip_poke_peer_s(const void *data);
1898 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
1899 static void reg_source_db(struct sip_peer *peer);
1900 static void destroy_association(struct sip_peer *peer);
1901 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
1902 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
1903
1904 /* Realtime device support */
1905 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, int expirey, int deprecated_username);
1906 static struct sip_user *realtime_user(const char *username);
1907 static void update_peer(struct sip_peer *p, int expiry);
1908 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
1909 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername);
1910 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
1911 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1912
1913 /*--- Internal UA client handling (outbound registrations) */
1914 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us);
1915 static void sip_registry_destroy(struct sip_registry *reg);
1916 static int sip_register(const char *value, int lineno);
1917 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
1918 static int sip_reregister(const void *data);
1919 static int __sip_do_register(struct sip_registry *r);
1920 static int sip_reg_timeout(const void *data);
1921 static void sip_send_all_registers(void);
1922
1923 /*--- Parsing SIP requests and responses */
1924 static void append_date(struct sip_request *req);       /* Append date to SIP packet */
1925 static int determine_firstline_parts(struct sip_request *req);
1926 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1927 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
1928 static int find_sip_method(const char *msg);
1929 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
1930 static void parse_request(struct sip_request *req);
1931 static const char *get_header(const struct sip_request *req, const char *name);
1932 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
1933 static int method_match(enum sipmethod id, const char *name);
1934 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
1935 static char *get_in_brackets(char *tmp);
1936 static const char *find_alias(const char *name, const char *_default);
1937 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
1938 static int lws2sws(char *msgbuf, int len);
1939 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
1940 static char *remove_uri_parameters(char *uri);
1941 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
1942 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
1943 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
1944 static int set_address_from_contact(struct sip_pvt *pvt);
1945 static void check_via(struct sip_pvt *p, struct sip_request *req);
1946 static char *get_calleridname(const char *input, char *output, size_t outputsize);
1947 static int get_rpid_num(const char *input, char *output, int maxlen);
1948 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq);
1949 static int get_destination(struct sip_pvt *p, struct sip_request *oreq);
1950 static int get_msg_text(char *buf, int len, struct sip_request *req);
1951 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
1952
1953 /*--- Constructing requests and responses */
1954 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
1955 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
1956 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
1957 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod);
1958 static int init_resp(struct sip_request *resp, const char *msg);
1959 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
1960 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
1961 static void build_via(struct sip_pvt *p);
1962 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
1963 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin);
1964 static char *generate_random_string(char *buf, size_t size);
1965 static void build_callid_pvt(struct sip_pvt *pvt);
1966 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
1967 static void make_our_tag(char *tagbuf, size_t len);
1968 static int add_header(struct sip_request *req, const char *var, const char *value);
1969 static int add_header_contentLength(struct sip_request *req, int len);
1970 static int add_line(struct sip_request *req, const char *line);
1971 static int add_text(struct sip_request *req, const char *text);
1972 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
1973 static int add_vidupdate(struct sip_request *req);
1974 static void add_route(struct sip_request *req, struct sip_route *route);
1975 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1976 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1977 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
1978 static void set_destination(struct sip_pvt *p, char *uri);
1979 static void append_date(struct sip_request *req);
1980 static void build_contact(struct sip_pvt *p);
1981 static void build_rpid(struct sip_pvt *p);
1982
1983 /*------Request handling functions */
1984 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
1985 static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *recount, char *e, int *nounlock);
1986 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
1987 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
1988 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e);
1989 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
1990 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
1991 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
1992 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
1993 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
1994 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin);
1995 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
1996 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno);
1997
1998 /*------Response handling functions */
1999 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
2000 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
2001 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
2002 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
2003
2004 /*----- RTP interface functions */
2005 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp,  struct ast_rtp *trtp, int codecs, int nat_active);
2006 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
2007 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
2008 static enum ast_rtp_get_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
2009 static int sip_get_codec(struct ast_channel *chan);
2010 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect);
2011
2012 /*------ T38 Support --------- */
2013 static int sip_handle_t38_reinvite(struct ast_channel *chan, struct sip_pvt *pvt, int reinvite); 
2014 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
2015 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
2016 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
2017 static void change_t38_state(struct sip_pvt *p, int state);
2018
2019 /*------ Session-Timers functions --------- */
2020 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
2021 static int  proc_session_timer(const void *vp);
2022 static void stop_session_timer(struct sip_pvt *p);
2023 static void start_session_timer(struct sip_pvt *p);
2024 static void restart_session_timer(struct sip_pvt *p);
2025 static const char *strefresher2str(enum st_refresher r);
2026 static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref);
2027 static int parse_minse(const char *p_hdrval, int *const p_interval);
2028 static int st_get_se(struct sip_pvt *, int max);
2029 static enum st_refresher st_get_refresher(struct sip_pvt *);
2030 static enum st_mode st_get_mode(struct sip_pvt *);
2031 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
2032
2033
2034 /*! \brief Definition of this channel for PBX channel registration */
2035 static const struct ast_channel_tech sip_tech = {
2036         .type = "SIP",
2037         .description = "Session Initiation Protocol (SIP)",
2038         .capabilities = AST_FORMAT_AUDIO_MASK,  /* all audio formats */
2039         .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
2040         .requester = sip_request_call,                  /* called with chan unlocked */
2041         .devicestate = sip_devicestate,                 /* called with chan unlocked (not chan-specific) */
2042         .call = sip_call,                       /* called with chan locked */
2043         .send_html = sip_sendhtml,
2044         .hangup = sip_hangup,                   /* called with chan locked */
2045         .answer = sip_answer,                   /* called with chan locked */
2046         .read = sip_read,                       /* called with chan locked */
2047         .write = sip_write,                     /* called with chan locked */
2048         .write_video = sip_write,               /* called with chan locked */
2049         .write_text = sip_write,
2050         .indicate = sip_indicate,               /* called with chan locked */
2051         .transfer = sip_transfer,               /* called with chan locked */
2052         .fixup = sip_fixup,                     /* called with chan locked */
2053         .send_digit_begin = sip_senddigit_begin,        /* called with chan unlocked */
2054         .send_digit_end = sip_senddigit_end,
2055         .bridge = ast_rtp_bridge,                       /* XXX chan unlocked ? */
2056         .early_bridge = ast_rtp_early_bridge,
2057         .send_text = sip_sendtext,              /* called with chan locked */
2058         .func_channel_read = acf_channel_read,
2059         .queryoption = sip_queryoption,
2060         .get_pvt_uniqueid = sip_get_callid,
2061 };
2062
2063 /*! \brief This version of the sip channel tech has no send_digit_begin
2064  * callback so that the core knows that the channel does not want
2065  * DTMF BEGIN frames.
2066  * The struct is initialized just before registering the channel driver,
2067  * and is for use with channels using SIP INFO DTMF.
2068  */
2069 static struct ast_channel_tech sip_tech_info;
2070
2071 static void *sip_tcp_worker_fn(void *);
2072
2073 static struct ast_tls_config sip_tls_cfg;
2074 static struct ast_tls_config default_tls_cfg;
2075
2076 static struct server_args sip_tcp_desc = {
2077         .accept_fd = -1,
2078         .master = AST_PTHREADT_NULL,
2079         .tls_cfg = NULL,
2080         .poll_timeout = -1,
2081         .name = "sip tcp server",
2082         .accept_fn = ast_tcptls_server_root,
2083         .worker_fn = sip_tcp_worker_fn,
2084 };
2085
2086 static struct server_args sip_tls_desc = {
2087         .accept_fd = -1,
2088         .master = AST_PTHREADT_NULL,
2089         .tls_cfg = &sip_tls_cfg,
2090         .poll_timeout = -1,
2091         .name = "sip tls server",
2092         .accept_fn = ast_tcptls_server_root,
2093         .worker_fn = sip_tcp_worker_fn,
2094 };
2095
2096 /* wrapper macro to tell whether t points to one of the sip_tech descriptors */
2097 #define IS_SIP_TECH(t)  ((t) == &sip_tech || (t) == &sip_tech_info)
2098
2099 /*! \brief map from an integer value to a string.
2100  * If no match is found, return errorstring
2101  */
2102 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
2103 {
2104         const struct _map_x_s *cur;
2105
2106         for (cur = table; cur->s; cur++)
2107                 if (cur->x == x)
2108                         return cur->s;
2109         return errorstring;
2110 }
2111
2112 /*! \brief map from a string to an integer value, case insensitive.
2113  * If no match is found, return errorvalue.
2114  */
2115 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
2116 {
2117         const struct _map_x_s *cur;
2118
2119         for (cur = table; cur->s; cur++)
2120                 if (!strcasecmp(cur->s, s))
2121                         return cur->x;
2122         return errorvalue;
2123 }
2124
2125
2126 /*! \brief Interface structure with callbacks used to connect to RTP module */
2127 static struct ast_rtp_protocol sip_rtp = {
2128         .type = "SIP",
2129         .get_rtp_info = sip_get_rtp_peer,
2130         .get_vrtp_info = sip_get_vrtp_peer,
2131         .get_trtp_info = sip_get_trtp_peer,
2132         .set_rtp_peer = sip_set_rtp_peer,
2133         .get_codec = sip_get_codec,
2134 };
2135
2136 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *ser);
2137
2138 static void *sip_tcp_helper_thread(void *data)
2139 {
2140         struct sip_pvt *pvt = data;
2141         struct ast_tcptls_session_instance *ser = pvt->socket.ser;
2142
2143         return _sip_tcp_helper_thread(pvt, ser);
2144 }
2145
2146 static void *sip_tcp_worker_fn(void *data)
2147 {
2148         struct ast_tcptls_session_instance *ser = data;
2149
2150         return _sip_tcp_helper_thread(NULL, ser);
2151 }
2152
2153 /*! \brief SIP TCP helper function */
2154 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *ser) 
2155 {
2156         int res, cl;
2157         struct sip_request req = { 0, } , reqcpy = { 0, };
2158         struct sip_threadinfo *me;
2159         char buf[1024];
2160
2161         me = ast_calloc(1, sizeof(*me));
2162
2163         if (!me)
2164                 goto cleanup2;
2165
2166         me->threadid = pthread_self();
2167         me->ser = ser;
2168         if (ser->ssl)
2169                 me->type = SIP_TRANSPORT_TLS;
2170         else
2171                 me->type = SIP_TRANSPORT_TCP;
2172
2173         AST_LIST_LOCK(&threadl);
2174         AST_LIST_INSERT_TAIL(&threadl, me, list);
2175         AST_LIST_UNLOCK(&threadl);
2176
2177         req.socket.lock = ast_calloc(1, sizeof(*req.socket.lock));
2178
2179         if (!req.socket.lock)
2180                 goto cleanup;
2181
2182         ast_mutex_init(req.socket.lock);
2183         if (!(req.data = ast_str_create(SIP_MIN_PACKET)))
2184                 goto cleanup;
2185         if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET)))
2186                 goto cleanup;
2187
2188         for (;;) {
2189                 ast_str_reset(req.data);
2190                 ast_str_reset(reqcpy.data);
2191                 req.len = 0;
2192                 req.ignore = 0;
2193                 req.debug = 0;
2194
2195                 req.socket.fd = ser->fd;
2196                 if (ser->ssl) {
2197                         req.socket.type = SIP_TRANSPORT_TLS;
2198                         req.socket.port = htons(ourport_tls);
2199                 } else {
2200                         req.socket.type = SIP_TRANSPORT_TCP;
2201                         req.socket.port = htons(ourport_tcp);
2202                 }
2203                 res = ast_wait_for_input(ser->fd, -1);
2204                 if (res < 0) {
2205                         ast_debug(1, "ast_wait_for_input returned %d\n", res);
2206                         goto cleanup;
2207                 }
2208
2209                 /* Read in headers one line at a time */
2210                 while (req.len < 4 || strncmp((char *)&req.data->str + req.len - 4, "\r\n\r\n", 4)) {
2211                         if (req.socket.lock) 
2212                                 ast_mutex_lock(req.socket.lock);
2213                         if (!fgets(buf, sizeof(buf), ser->f)) {
2214                                 ast_mutex_unlock(req.socket.lock);
2215                                 goto cleanup;
2216                         }
2217                         if (req.socket.lock) 
2218                                 ast_mutex_unlock(req.socket.lock);
2219                         if (me->stop) 
2220                                  goto cleanup;
2221                         ast_str_append(&req.data, 0, "%s", buf);
2222                         req.len = req.data->used;
2223                 }
2224                 copy_request(&reqcpy, &req);
2225                 parse_request(&reqcpy);
2226                 if (sscanf(get_header(&reqcpy, "Content-Length"), "%d", &cl)) {
2227                         while (cl > 0) {
2228                                 if (req.socket.lock) 
2229                                         ast_mutex_lock(req.socket.lock);
2230                                 if (!fread(buf, (cl < sizeof(buf)) ? cl : sizeof(buf), 1, ser->f))
2231                                         goto cleanup;
2232                                 if (req.socket.lock) 
2233                                         ast_mutex_unlock(req.socket.lock);
2234                                 if (me->stop)
2235                                         goto cleanup;
2236                                 cl -= strlen(buf);
2237                                 ast_str_append(&req.data, 0, "%s", buf);
2238                                 req.len = req.data->used;
2239                         }
2240                 }
2241                 req.socket.ser = ser;
2242                 handle_request_do(&req, &ser->requestor);
2243         }
2244
2245 cleanup:
2246         AST_LIST_LOCK(&threadl);
2247         AST_LIST_REMOVE(&threadl, me, list);
2248         AST_LIST_UNLOCK(&threadl);
2249         ast_free(me);
2250 cleanup2:
2251         fclose(ser->f);
2252         ser = ast_tcptls_session_instance_destroy(ser);
2253         if (reqcpy.data)
2254                 ast_free(reqcpy.data);
2255         if (req.data) {
2256                 ast_free(req.data);
2257                 req.data = NULL;
2258         }
2259         
2260
2261         if (req.socket.lock) {
2262                 ast_mutex_destroy(req.socket.lock);
2263                 ast_free(req.socket.lock);
2264                 req.socket.lock = NULL;
2265         }
2266
2267         return NULL;
2268 }
2269
2270 #define sip_pvt_lock(x) ast_mutex_lock(&x->pvt_lock)
2271 #define sip_pvt_trylock(x) ast_mutex_trylock(&x->pvt_lock)
2272 #define sip_pvt_unlock(x) ast_mutex_unlock(&x->pvt_lock)
2273
2274 /*!
2275  * helper functions to unreference various types of objects.
2276  * By handling them this way, we don't have to declare the
2277  * destructor on each call, which removes the chance of errors.
2278  */
2279 static void unref_peer(struct sip_peer *peer)
2280 {
2281         ASTOBJ_UNREF(peer, sip_destroy_peer);
2282 }
2283
2284 static void unref_user(struct sip_user *user)
2285 {
2286         ASTOBJ_UNREF(user, sip_destroy_user);
2287 }
2288
2289 static void *registry_unref(struct sip_registry *reg)
2290 {
2291         ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
2292         ASTOBJ_UNREF(reg, sip_registry_destroy);
2293         return NULL;
2294 }
2295
2296 /*! \brief Add object reference to SIP registry */
2297 static struct sip_registry *registry_addref(struct sip_registry *reg)
2298 {
2299         ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
2300         return ASTOBJ_REF(reg); /* Add pointer to registry in packet */
2301 }
2302
2303 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
2304 static struct ast_udptl_protocol sip_udptl = {
2305         type: "SIP",
2306         get_udptl_info: sip_get_udptl_peer,
2307         set_udptl_peer: sip_set_udptl_peer,
2308 };
2309
2310 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
2311         __attribute__ ((format (printf, 2, 3)));
2312
2313
2314 /*! \brief Convert transfer status to string */
2315 static const char *referstatus2str(enum referstatus rstatus)
2316 {
2317         return map_x_s(referstatusstrings, rstatus, "");
2318 }
2319
2320 /*! \brief Initialize the initital request packet in the pvt structure.
2321         This packet is used for creating replies and future requests in
2322         a dialog */
2323 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
2324 {
2325         if (p->initreq.headers)
2326                 ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
2327         else
2328                 ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
2329         /* Use this as the basis */
2330         copy_request(&p->initreq, req);
2331         parse_request(&p->initreq);
2332         if (req->debug)
2333                 ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
2334 }
2335
2336 /*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
2337 static void sip_alreadygone(struct sip_pvt *dialog)
2338 {
2339         ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
2340         dialog->alreadygone = 1;
2341 }
2342
2343 /*! Resolve DNS srv name or host name in a sip_proxy structure */
2344 static int proxy_update(struct sip_proxy *proxy)
2345 {
2346         /* if it's actually an IP address and not a name,
2347            there's no need for a managed lookup */
2348         if (!inet_aton(proxy->name, &proxy->ip.sin_addr)) {
2349                 /* Ok, not an IP address, then let's check if it's a domain or host */
2350                 /* XXX Todo - if we have proxy port, don't do SRV */
2351                 if (ast_get_ip_or_srv(&proxy->ip, proxy->name, global_srvlookup ? "_sip._udp" : NULL) < 0) {
2352                         ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
2353                         return FALSE;
2354                 }
2355         }
2356         proxy->last_dnsupdate = time(NULL);
2357         return TRUE;
2358 }
2359
2360 /*! \brief Allocate and initialize sip proxy */
2361 static struct sip_proxy *proxy_allocate(char *name, char *port, int force)
2362 {
2363         struct sip_proxy *proxy;
2364         proxy = ast_calloc(1, sizeof(*proxy));
2365         if (!proxy)
2366                 return NULL;
2367         proxy->force = force;
2368         ast_copy_string(proxy->name, name, sizeof(proxy->name));
2369         proxy->ip.sin_port = htons((!ast_strlen_zero(port) ? atoi(port) : STANDARD_SIP_PORT));
2370         proxy_update(proxy);
2371         return proxy;
2372 }
2373
2374 /*! \brief Get default outbound proxy or global proxy */
2375 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
2376 {
2377         if (peer && peer->outboundproxy) {
2378                 if (sipdebug)
2379                         ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
2380                 append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
2381                 return peer->outboundproxy;
2382         }
2383         if (global_outboundproxy.name[0]) {
2384                 if (sipdebug)
2385                         ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
2386                 append_history(dialog, "OBproxy", "Using global obproxy %s", global_outboundproxy.name);
2387                 return &global_outboundproxy;
2388         }
2389         if (sipdebug)
2390                 ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
2391         return NULL;
2392 }
2393
2394 /*! \brief returns true if 'name' (with optional trailing whitespace)
2395  * matches the sip method 'id'.
2396  * Strictly speaking, SIP methods are case SENSITIVE, but we do
2397  * a case-insensitive comparison to be more tolerant.
2398  * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
2399  */
2400 static int method_match(enum sipmethod id, const char *name)
2401 {
2402         int len = strlen(sip_methods[id].text);
2403         int l_name = name ? strlen(name) : 0;
2404         /* true if the string is long enough, and ends with whitespace, and matches */
2405         return (l_name >= len && name[len] < 33 &&
2406                 !strncasecmp(sip_methods[id].text, name, len));
2407 }
2408
2409 /*! \brief  find_sip_method: Find SIP method from header */
2410 static int find_sip_method(const char *msg)
2411 {
2412         int i, res = 0;
2413         
2414         if (ast_strlen_zero(msg))
2415                 return 0;
2416         for (i = 1; i < (sizeof(sip_methods) / sizeof(sip_methods[0])) && !res; i++) {
2417                 if (method_match(i, msg))
2418                         res = sip_methods[i].id;
2419         }
2420         return res;
2421 }
2422
2423 /*! \brief Parse supported header in incoming packet */
2424 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
2425 {
2426         char *next, *sep;
2427         char *temp;
2428         unsigned int profile = 0;
2429         int i, found;
2430
2431         if (ast_strlen_zero(supported) )
2432                 return 0;
2433         temp = ast_strdupa(supported);
2434
2435         if (sipdebug)
2436                 ast_debug(3, "Begin: parsing SIP \"Supported: %s\"\n", supported);
2437
2438         for (next = temp; next; next = sep) {
2439                 found = FALSE;
2440                 if ( (sep = strchr(next, ',')) != NULL)
2441                         *sep++ = '\0';
2442                 next = ast_skip_blanks(next);
2443                 if (sipdebug)
2444                         ast_debug(3, "Found SIP option: -%s-\n", next);
2445                 for (i=0; i < (sizeof(sip_options) / sizeof(sip_options[0])); i++) {
2446                         if (!strcasecmp(next, sip_options[i].text)) {
2447                                 profile |= sip_options[i].id;
2448                                 found = TRUE;
2449                                 if (sipdebug)
2450                                         ast_debug(3, "Matched SIP option: %s\n", next);
2451                                 break;
2452                         }
2453                 }
2454
2455                 /* This function is used to parse both Suported: and Require: headers.
2456                 Let the caller of this function know that an unknown option tag was 
2457                 encountered, so that if the UAC requires it then the request can be 
2458                 rejected with a 420 response. */
2459                 if (!found)
2460                         profile |= SIP_OPT_UNKNOWN;
2461
2462                 if (!found && sipdebug) {
2463                         if (!strncasecmp(next, "x-", 2))
2464                                 ast_debug(3, "Found private SIP option, not supported: %s\n", next);
2465                         else
2466                                 ast_debug(3, "Found no match for SIP option: %s (Please file bug report!)\n", next);
2467                 }
2468         }
2469
2470         if (pvt)
2471                 pvt->sipoptions = profile;
2472         return profile;
2473 }
2474
2475 /*! \brief See if we pass debug IP filter */
2476 static inline int sip_debug_test_addr(const struct sockaddr_in *addr) 
2477 {
2478         if (!sipdebug)
2479                 return 0;
2480         if (debugaddr.sin_addr.s_addr) {
2481                 if (((ntohs(debugaddr.sin_port) != 0)
2482                         && (debugaddr.sin_port != addr->sin_port))
2483                         || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
2484                         return 0;
2485         }
2486         return 1;
2487 }
2488
2489 /*! \brief The real destination address for a write */
2490 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
2491 {
2492         if (p->outboundproxy)
2493                 return &p->outboundproxy->ip;
2494
2495         return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
2496 }
2497
2498 /*! \brief Display SIP nat mode */
2499 static const char *sip_nat_mode(const struct sip_pvt *p)
2500 {
2501         return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
2502 }
2503
2504 /*! \brief Test PVT for debugging output */
2505 static inline int sip_debug_test_pvt(struct sip_pvt *p) 
2506 {
2507         if (!sipdebug)
2508                 return 0;
2509         return sip_debug_test_addr(sip_real_dst(p));
2510 }
2511
2512 static inline const char *get_transport(enum sip_transport t)
2513 {
2514         switch (t) {
2515         case SIP_TRANSPORT_UDP:
2516                 return "UDP";
2517         case SIP_TRANSPORT_TCP:
2518                 return "TCP";
2519         case SIP_TRANSPORT_TLS:
2520                 return "TLS";
2521         }
2522
2523         return "UNKNOWN";
2524 }
2525
2526 /*! \brief Transmit SIP message 
2527         Sends a SIP request or response on a given socket (in the pvt)
2528         Called by retrans_pkt, send_request, send_response and 
2529         __sip_reliable_xmit
2530 */
2531 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len)
2532 {
2533         int res = 0;
2534         const struct sockaddr_in *dst = sip_real_dst(p);
2535
2536         ast_debug(1, "Trying to put '%.10s' onto %s socket destined for %s:%d\n", data->str, get_transport(p->socket.type), ast_inet_ntoa(dst->sin_addr), htons(dst->sin_port));
2537
2538         if (sip_prepare_socket(p) < 0)
2539                 return XMIT_ERROR;
2540
2541         if (p->socket.lock)
2542                 ast_mutex_lock(p->socket.lock);
2543
2544         if (p->socket.type & SIP_TRANSPORT_UDP) 
2545                 res = sendto(p->socket.fd, data->str, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
2546         else {
2547                 if (p->socket.ser->f) 
2548                         res = ast_tcptls_server_write(p->socket.ser, data->str, len);
2549                 else
2550                         ast_debug(1, "No p->socket.ser->f len=%d\n", len);
2551         } 
2552
2553         if (p->socket.lock)
2554                 ast_mutex_unlock(p->socket.lock);
2555
2556         if (res == -1) {
2557                 switch (errno) {
2558                         case EBADF:             /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
2559                         case EHOSTUNREACH:      /* Host can't be reached */
2560                         case ENETDOWN:          /* Interface down */
2561                         case ENETUNREACH:       /* Network failure */
2562                                 res = XMIT_ERROR;       /* Don't bother with trying to transmit again */
2563                 }
2564         }
2565         if (res != len)
2566                 ast_log(LOG_WARNING, "sip_xmit of %p (len %d) to %s:%d returned %d: %s\n", data, len, ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), res, strerror(errno));
2567
2568         return res;
2569 }
2570
2571 /*! \brief Build a Via header for a request */
2572 static void build_via(struct sip_pvt *p)
2573 {
2574         /* Work around buggy UNIDEN UIP200 firmware */
2575         const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
2576
2577         /* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
2578         ast_string_field_build(p, via, "SIP/2.0/%s %s:%d;branch=z9hG4bK%08x%s",
2579                         get_transport(p->socket.type),
2580                         ast_inet_ntoa(p->ourip.sin_addr),
2581                         ntohs(p->ourip.sin_port), p->branch, rport);
2582 }
2583
2584 /*! \brief NAT fix - decide which IP address to use for Asterisk server?
2585  *
2586  * Using the localaddr structure built up with localnet statements in sip.conf
2587  * apply it to their address to see if we need to substitute our
2588  * externip or can get away with our internal bindaddr
2589  * 'us' is always overwritten.
2590  */
2591 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us)
2592 {
2593         struct sockaddr_in theirs;
2594         /* Set want_remap to non-zero if we want to remap 'us' to an externally
2595          * reachable IP address and port. This is done if:
2596          * 1. we have a localaddr list (containing 'internal' addresses marked
2597          *    as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
2598          *    and AST_SENSE_ALLOW on 'external' ones);
2599          * 2. either stunaddr or externip is set, so we know what to use as the
2600          *    externally visible address;
2601          * 3. the remote address, 'them', is external;
2602          * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
2603          *    when passed to ast_apply_ha() so it does need to be remapped.
2604          *    This fourth condition is checked later.
2605          */
2606         int want_remap;
2607
2608         *us = internip;         /* starting guess for the internal address */
2609         /* now ask the system what would it use to talk to 'them' */
2610         ast_ouraddrfor(them, &us->sin_addr);
2611         theirs.sin_addr = *them;
2612
2613         want_remap = localaddr &&
2614                 (externip.sin_addr.s_addr || stunaddr.sin_addr.s_addr) &&
2615                 ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
2616
2617         if (want_remap &&
2618             (!global_matchexterniplocally || !ast_apply_ha(localaddr, us)) ) {
2619                 /* if we used externhost or stun, see if it is time to refresh the info */
2620                 if (externexpire && time(NULL) >= externexpire) {
2621                         if (stunaddr.sin_addr.s_addr) {
2622                                 ast_stun_request(sipsock, &stunaddr, NULL, &externip);
2623                         } else {
2624                                 if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
2625                                         ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
2626                         }
2627                         externexpire = time(NULL) + externrefresh;
2628                 }
2629                 if (externip.sin_addr.s_addr)
2630                         *us = externip;
2631                 else
2632                         ast_log(LOG_WARNING, "stun failed\n");
2633                 ast_debug(1, "Target address %s is not local, substituting externip\n", 
2634                         ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
2635         } else if (bindaddr.sin_addr.s_addr) {
2636                 /* no remapping, but we bind to a specific address, so use it. */
2637                 *us = bindaddr;
2638         }
2639 }
2640
2641 /*! \brief Append to SIP dialog history with arg list  */
2642 static __attribute__((format (printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
2643 {
2644         char buf[80], *c = buf; /* max history length */
2645         struct sip_history *hist;
2646         int l;
2647
2648         vsnprintf(buf, sizeof(buf), fmt, ap);
2649         strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
2650         l = strlen(buf) + 1;
2651         if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
2652                 return;
2653         if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
2654                 ast_free(hist);
2655                 return;
2656         }
2657         memcpy(hist->event, buf, l);
2658         if (p->history_entries == MAX_HISTORY_ENTRIES) {
2659                 struct sip_history *oldest;
2660                 oldest = AST_LIST_REMOVE_HEAD(p->history, list);
2661                 p->history_entries--;
2662                 ast_free(oldest);
2663         }
2664         AST_LIST_INSERT_TAIL(p->history, hist, list);
2665         p->history_entries++;
2666 }
2667
2668 /*! \brief Append to SIP dialog history with arg list  */
2669 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
2670 {
2671         va_list ap;
2672
2673         if (!p)
2674                 return;
2675
2676         if (!p->do_history && !recordhistory && !dumphistory)
2677                 return;
2678
2679         va_start(ap, fmt);
2680         append_history_va(p, fmt, ap);
2681         va_end(ap);
2682
2683         return;
2684 }
2685
2686 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
2687 static int retrans_pkt(const void *data)
2688 {
2689         struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
2690         int reschedule = DEFAULT_RETRANS;
2691         int xmitres = 0;
2692
2693         /* Lock channel PVT */
2694         sip_pvt_lock(pkt->owner);
2695
2696         if (pkt->retrans < MAX_RETRANS) {
2697                 pkt->retrans++;
2698                 if (!pkt->timer_t1) {   /* Re-schedule using timer_a and timer_t1 */
2699                         if (sipdebug)
2700                                 ast_debug(4, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n", pkt->retransid, sip_methods[pkt->method].text, pkt->method);
2701                 } else {
2702                         int siptimer_a;
2703
2704                         if (sipdebug)
2705                                 ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
2706                         if (!pkt->timer_a)
2707                                 pkt->timer_a = 2 ;
2708                         else
2709                                 pkt->timer_a = 2 * pkt->timer_a;
2710  
2711                         /* For non-invites, a maximum of 4 secs */
2712                         siptimer_a = pkt->timer_t1 * pkt->timer_a;      /* Double each time */
2713                         if (pkt->method != SIP_INVITE && siptimer_a > 4000)
2714                                 siptimer_a = 4000;
2715                 
2716                         /* Reschedule re-transmit */
2717                         reschedule = siptimer_a;
2718                         ast_debug(4, "** 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);
2719                 } 
2720
2721                 if (sip_debug_test_pvt(pkt->owner)) {
2722                         const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
2723                         ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
2724                                 pkt->retrans, sip_nat_mode(pkt->owner),
2725                                 ast_inet_ntoa(dst->sin_addr),
2726                                 ntohs(dst->sin_port), pkt->data->str);
2727                 }
2728
2729                 append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
2730                 xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
2731                 sip_pvt_unlock(pkt->owner);
2732                 if (xmitres == XMIT_ERROR)
2733                         ast_log(LOG_WARNING, "Network error on retransmit in dialog %s\n", pkt->owner->callid);
2734                 else 
2735                         return  reschedule;
2736         } 
2737         /* Too many retries */
2738         if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
2739                 if (pkt->is_fatal || sipdebug)  /* Tell us if it's critical or if we're debugging */
2740                         ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %s for seqno %d (%s %s)\n",
2741                                 pkt->owner->callid, pkt->seqno,
2742                                 pkt->is_fatal ? "Critical" : "Non-critical", pkt->is_resp ? "Response" : "Request");
2743         } else if (pkt->method == SIP_OPTIONS && sipdebug) {
2744                         ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) \n", pkt->owner->callid);
2745
2746         } 
2747         if (xmitres == XMIT_ERROR) {
2748                 ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
2749                 append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
2750         } else 
2751                 append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
2752                 
2753         pkt->retransid = -1;
2754
2755         if (pkt->is_fatal) {
2756                 while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
2757                         sip_pvt_unlock(pkt->owner);     /* SIP_PVT, not channel */
2758                         usleep(1);
2759                         sip_pvt_lock(pkt->owner);
2760                 }
2761
2762                 if (pkt->owner->owner && !pkt->owner->owner->hangupcause) 
2763                         pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
2764                 
2765                 if (pkt->owner->owner) {
2766                         sip_alreadygone(pkt->owner);
2767                         ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet.\n", pkt->owner->callid);
2768                         ast_queue_hangup(pkt->owner->owner);
2769                         ast_channel_unlock(pkt->owner->owner);
2770                 } else {
2771                         /* If no channel owner, destroy now */
2772
2773                         /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
2774                         if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
2775                                 pkt->owner->needdestroy = 1;
2776                                 sip_alreadygone(pkt->owner);
2777                                 append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
2778                         }
2779                 }
2780         }
2781
2782         if (pkt->method == SIP_BYE) {
2783                 /* We're not getting answers on SIP BYE's.  Tear down the call anyway. */
2784                 if (pkt->owner->owner) 
2785                         ast_channel_unlock(pkt->owner->owner);
2786                 append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
2787                 pkt->owner->needdestroy = 1;
2788         }
2789
2790         /* Remove the packet */
2791         for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
2792                 if (cur == pkt) {
2793                         UNLINK(cur, pkt->owner->packets, prev);
2794                         sip_pvt_unlock(pkt->owner);
2795                         if (pkt->data)
2796                                 ast_free(pkt->data);
2797                         ast_free(pkt);
2798                         return 0;
2799                 }
2800         }
2801         /* error case */
2802         ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
2803         sip_pvt_unlock(pkt->owner);
2804         return 0;
2805 }
2806
2807 /*! \brief Transmit packet with retransmits 
2808         \return 0 on success, -1 on failure to allocate packet 
2809 */
2810 static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod)
2811 {
2812         struct sip_pkt *pkt = NULL;
2813         int siptimer_a = DEFAULT_RETRANS;
2814         int xmitres = 0;
2815
2816         if (sipmethod == SIP_INVITE) {
2817                 /* Note this is a pending invite */
2818                 p->pendinginvite = seqno;
2819         }
2820
2821         /* If the transport is something reliable (TCP or TLS) then don't really send this reliably */
2822         /* I removed the code from retrans_pkt that does the same thing so it doesn't get loaded into the scheduler */
2823         /* According to the RFC some packets need to be retransmitted even if its TCP, so this needs to get revisited */
2824         if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
2825                 xmitres = __sip_xmit(dialog_ref(p), data, len); /* Send packet */
2826                 if (xmitres == XMIT_ERROR) {    /* Serious network trouble, no need to try again */
2827                         append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
2828                         return AST_FAILURE;
2829                 } else
2830                         return AST_SUCCESS;
2831         }
2832
2833         if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
2834                 return AST_FAILURE;
2835         /* copy data, add a terminator and save length */
2836         if (!(pkt->data = ast_str_create(len))) {
2837                 ast_free(pkt);
2838                 return AST_FAILURE;
2839         }
2840         ast_str_set(&pkt->data, 0, "%s%s", data->str, "\0");
2841         pkt->packetlen = len;
2842         /* copy other parameters from the caller */
2843         pkt->method = sipmethod;
2844         pkt->seqno = seqno;
2845         pkt->is_resp = resp;
2846         pkt->is_fatal = fatal;
2847         pkt->owner = dialog_ref(p);
2848         pkt->next = p->packets;
2849         p->packets = pkt;       /* Add it to the queue */
2850         pkt->timer_t1 = p->timer_t1;    /* Set SIP timer T1 */
2851         pkt->retransid = -1;
2852         if (pkt->timer_t1)
2853                 siptimer_a = pkt->timer_t1 * 2;
2854
2855         /* Schedule retransmission */
2856         AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
2857         if (sipdebug)
2858                 ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id  #%d\n", pkt->retransid);
2859
2860         xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);    /* Send packet */
2861
2862         if (xmitres == XMIT_ERROR) {    /* Serious network trouble, no need to try again */
2863                 append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
2864                 if (pkt->data)
2865                         ast_free(pkt->data);
2866                 return AST_FAILURE;
2867         } else {
2868                 return AST_SUCCESS;
2869         }
2870 }
2871
2872 /*! \brief Kill a SIP dialog (called only by the scheduler)
2873  * The scheduler has a reference to this dialog when p->autokillid != -1,
2874  * and we are called using that reference. So if the event is not
2875  * rescheduled, we need to call dialog_unref().
2876  */
2877 static int __sip_autodestruct(const void *data)
2878 {
2879         struct sip_pvt *p = (struct sip_pvt *)data;
2880
2881         /* If this is a subscription, tell the phone that we got a timeout */
2882         if (p->subscribed) {
2883                 transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);   /* Send last notification */
2884                 p->subscribed = NONE;
2885                 append_history(p, "Subscribestatus", "timeout");
2886                 ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
2887                 return 10000;   /* Reschedule this destruction so that we know that it's gone */
2888         }
2889
2890         /* If there are packets still waiting for delivery, delay the destruction */
2891         if (p->packets) {
2892                 ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
2893                 append_history(p, "ReliableXmit", "timeout");
2894                 return 10000;
2895         }
2896
2897         if (p->subscribed == MWI_NOTIFICATION)
2898                 if (p->relatedpeer)
2899                         unref_peer(p->relatedpeer);     /* Remove link to peer. If it's realtime, make sure it's gone from memory) */
2900
2901         /* Reset schedule ID */
2902         p->autokillid = -1;
2903
2904         if (p->owner) {
2905                 ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
2906                 ast_queue_hangup(p->owner);
2907                 dialog_unref(p);
2908         } else if (p->refer) {
2909                 ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
2910                 transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
2911                 append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
2912                 sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
2913                 dialog_unref(p);
2914         } else {
2915                 append_history(p, "AutoDestroy", "%s", p->callid);
2916                 ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
2917                 sip_destroy(p);         /* Go ahead and destroy dialog. All attempts to recover is done */
2918                 /* sip_destroy also absorbs the reference */
2919         }
2920         return 0;
2921 }
2922
2923 /*! \brief Schedule destruction of SIP dialog */
2924 static void sip_scheddestroy(struct sip_pvt *p, int ms)
2925 {
2926         if (ms < 0) {
2927                 if (p->timer_t1 == 0) {
2928                         p->timer_t1 = global_t1;        /* Set timer T1 if not set (RFC 3261) */
2929                         p->timer_b = global_timer_b;  /* Set timer B if not set (RFC 3261) */
2930                 }
2931                 ms = p->timer_t1 * 64;
2932         }
2933         if (sip_debug_test_pvt(p))
2934                 ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
2935         if (sip_cancel_destroy(p))
2936                 ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
2937
2938         if (p->do_history)
2939                 append_history(p, "SchedDestroy", "%d ms", ms);
2940         p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p));
2941
2942         if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0)
2943                 stop_session_timer(p);
2944 }
2945
2946 /*! \brief Cancel destruction of SIP dialog.
2947  * Be careful as this also absorbs the reference - if you call it
2948  * from within the scheduler, this might be the last reference.
2949  */
2950 static int sip_cancel_destroy(struct sip_pvt *p)
2951 {
2952         int res = 0;
2953         if (p->autokillid > -1) {
2954                 if (!(res = ast_sched_del(sched, p->autokillid))) {
2955                         append_history(p, "CancelDestroy", "");
2956                         p->autokillid = -1;
2957                 }
2958                 dialog_unref(p);
2959         }
2960         return res;
2961 }
2962
2963 /*! \brief Acknowledges receipt of a packet and stops retransmission 
2964  * called with p locked*/
2965 static void __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
2966 {
2967         struct sip_pkt *cur, *prev = NULL;
2968         const char *msg = "Not Found";  /* used only for debugging */
2969
2970         /* If we have an outbound proxy for this dialog, then delete it now since
2971           the rest of the requests in this dialog needs to follow the routing.
2972           If obforcing is set, we will keep the outbound proxy during the whole
2973           dialog, regardless of what the SIP rfc says
2974         */
2975         if (p->outboundproxy && !p->outboundproxy->force)
2976                 p->outboundproxy = NULL;
2977
2978         for (cur = p->packets; cur; prev = cur, cur = cur->next) {
2979                 if (cur->seqno != seqno || cur->is_resp != resp)
2980                         continue;
2981                 if (cur->is_resp || cur->method == sipmethod) {
2982                         msg = "Found";
2983                         if (!resp && (seqno == p->pendinginvite)) {
2984                                 ast_debug(1, "Acked pending invite %d\n", p->pendinginvite);
2985                                 p->pendinginvite = 0;
2986                         }
2987                         if (cur->retransid > -1) {
2988                                 if (sipdebug)
2989                                         ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
2990                         }
2991                         /* This odd section is designed to thwart a 
2992                          * race condition in the packet scheduler. There are
2993                          * two conditions under which deleting the packet from the
2994                          * scheduler can fail.
2995                          *
2996                          * 1. The packet has been removed from the scheduler because retransmission
2997                          * is being attempted. The problem is that if the packet is currently attempting
2998                          * retransmission and we are at this point in the code, then that MUST mean
2999                          * that retrans_pkt is waiting on p's lock. Therefore we will relinquish the
3000                          * lock temporarily to allow retransmission.
3001                          *
3002                          * 2. The packet has reached its maximum number of retransmissions and has
3003                          * been permanently removed from the packet scheduler. If this is the case, then
3004                          * the packet's retransid will be set to -1. The atomicity of the setting and checking
3005                          * of the retransid to -1 is ensured since in both cases p's lock is held.
3006                          */
3007                         while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
3008                                 sip_pvt_unlock(p);
3009                                 usleep(1);
3010                                 sip_pvt_lock(p);
3011                         }
3012                         UNLINK(cur, p->packets, prev);
3013                         dialog_unref(cur->owner);
3014                         if (cur->data)
3015                                 ast_free(cur->data);
3016                         ast_free(cur);
3017                         break;
3018                 }
3019         }
3020         ast_debug(1, "Stopping retransmission on '%s' of %s %d: Match %s\n",
3021                 p->callid, resp ? "Response" : "Request", seqno, msg);
3022 }
3023
3024 /*! \brief Pretend to ack all packets
3025  * called with p locked */
3026 static void __sip_pretend_ack(struct sip_pvt *p)
3027 {
3028         struct sip_pkt *cur = NULL;
3029
3030         while (p->packets) {
3031                 int method;
3032                 if (cur == p->packets) {
3033                         ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
3034                         return;
3035                 }
3036                 cur = p->packets;
3037                 method = (cur->method) ? cur->method : find_sip_method(cur->data->str);
3038                 __sip_ack(p, cur->seqno, cur->is_resp, method);
3039         }
3040 }
3041
3042 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
3043 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
3044 {
3045         struct sip_pkt *cur;
3046         int res = -1;
3047
3048         for (cur = p->packets; cur; cur = cur->next) {
3049                 if (cur->seqno == seqno && cur->is_resp == resp &&
3050                         (cur->is_resp || method_match(sipmethod, cur->data->str))) {
3051                         /* this is our baby */
3052                         if (cur->retransid > -1) {
3053                                 if (sipdebug)
3054                                         ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
3055                         }
3056                         AST_SCHED_DEL(sched, cur->retransid);
3057                         res = 0;
3058                         break;
3059                 }
3060         }
3061         ast_debug(1, "(Provisional) Stopping retransmission (but retaining packet) on '%s' %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res == -1 ? "Not Found" : "Found");
3062         return res;
3063 }
3064
3065
3066 /*! \brief Copy SIP request, parse it */
3067 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
3068 {
3069         copy_request(dst, src);
3070         parse_request(dst);
3071 }
3072
3073 /*! \brief add a blank line if no body */
3074 static void add_blank(struct sip_request *req)
3075 {
3076         if (!req->lines) {
3077                 /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
3078                 ast_str_append(&req->data, 0, "\r\n");
3079                 req->len = req->data->used;
3080         }
3081 }
3082
3083 /*! \brief Transmit response on SIP request*/
3084 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
3085 {
3086         int res;
3087
3088         add_blank(req);
3089         if (sip_debug_test_pvt(p)) {
3090                 const struct sockaddr_in *dst = sip_real_dst(p);
3091
3092                 ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
3093                         reliable ? "Reliably " : "", sip_nat_mode(p),
3094                         ast_inet_ntoa(dst->sin_addr),
3095                         ntohs(dst->sin_port), req->data->str);
3096         }
3097         if (p->do_history) {
3098                 struct sip_request tmp = { .rlPart1 = NULL, };
3099                 parse_copy(&tmp, req);
3100                 append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"), 
3101                         (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? tmp.rlPart2 : sip_methods[tmp.method].text);
3102                 ast_free(tmp.data);
3103         }
3104         res = (reliable) ?
3105                  __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
3106                 __sip_xmit(p, req->data, req->len);
3107         ast_free(req->data);
3108         req->data = NULL;
3109         if (res > 0)
3110                 return 0;
3111         return res;
3112 }
3113
3114 /*! \brief Send SIP Request to the other part of the dialogue */
3115 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
3116 {
3117         int res;
3118
3119         /* If we have an outbound proxy, reset peer address 
3120                 Only do this once.
3121         */
3122         if (p->outboundproxy) {
3123                 p->sa = p->outboundproxy->ip;
3124         }
3125
3126         add_blank(req);
3127         if (sip_debug_test_pvt(p)) {
3128                 if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
3129                         ast_verbose("%sTransmitting (NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port), req->data->str);
3130                 else
3131                         ast_verbose("%sTransmitting (no NAT) to %s:%d:\n%s\n---\n", reliable ? "Reliably " : "", ast_inet_ntoa(p->sa.sin_addr), ntohs(p->sa.sin_port), req->data->str);
3132         }
3133         if (p->do_history) {
3134                 struct sip_request tmp = { .rlPart1 = NULL, };
3135                 parse_copy(&tmp, req);
3136                 append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
3137                 ast_free(tmp.data);
3138         }
3139         res = (reliable) ?
3140                 __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
3141                 __sip_xmit(p, req->data, req->len);
3142         if (req->data) {
3143                 ast_free(req->data);
3144                 req->data = NULL;
3145         }
3146         return res;
3147 }
3148
3149 /*! \brief Query an option on a SIP dialog */
3150 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
3151 {
3152         int res = -1;
3153         enum ast_t38_state state = T38_STATE_UNAVAILABLE;
3154         struct sip_pvt *p = (struct sip_pvt *) chan->tech_pvt;
3155
3156         switch (option) {
3157         case AST_OPTION_T38_STATE:
3158                 /* Make sure we got an ast_t38_state enum passed in */
3159                 if (*datalen != sizeof(enum ast_t38_state)) {
3160                         ast_log(LOG_ERROR, "Invalid datalen for AST_OPTION_T38_STATE option. Expected %d, got %d\n", (int)sizeof(enum ast_t38_state), *datalen);
3161                         return -1;
3162                 }
3163
3164                 sip_pvt_lock(p);
3165
3166                 /* Now if T38 support is enabled we need to look and see what the current state is to get what we want to report back */
3167                 if (ast_test_flag(&p->t38.t38support, SIP_PAGE2_T38SUPPORT)) {
3168                         switch (p->t38.state) {
3169                         case T38_LOCAL_DIRECT:
3170                         case T38_LOCAL_REINVITE:
3171                         case T38_PEER_DIRECT:
3172                         case T38_PEER_REINVITE:
3173                                 state = T38_STATE_NEGOTIATING;
3174                                 break;
3175                         case T38_ENABLED:
3176                                 state = T38_STATE_NEGOTIATED;
3177                                 break;
3178                         default:
3179                                 state = T38_STATE_UNKNOWN;
3180                         }
3181                 }
3182
3183                 sip_pvt_unlock(p);
3184
3185                 *((enum ast_t38_state *) data) = state;
3186                 res = 0;
3187
3188                 break;
3189         default:
3190                 break;
3191         }
3192
3193         return res;
3194 }
3195
3196 /*! \brief Locate closing quote in a string, skipping escaped quotes.
3197  * optionally with a limit on the search.
3198  * start must be past the first quote.
3199  */
3200 static const char *find_closing_quote(const char *start, const char *lim)
3201 {
3202         char last_char = '\0';
3203         const char *s;
3204         for (s = start; *s && s != lim; last_char = *s++) {
3205                 if (*s == '"' && last_char != '\\')
3206                         break;
3207         }
3208         return s;
3209 }
3210
3211 /*! \brief Pick out text in brackets from character string
3212         \return pointer to terminated stripped string
3213         \param tmp input string that will be modified
3214         Examples:
3215 \verbatim
3216         "foo" <bar>     valid input, returns bar
3217         foo             returns the whole string
3218         < "foo ... >    returns the string between brackets
3219         < "foo...       bogus (missing closing bracket), returns the whole string
3220                         XXX maybe should still skip the opening bracket
3221 \endverbatim
3222  */
3223 static char *get_in_brackets(char *tmp)
3224 {
3225         const char *parse = tmp;
3226         char *first_bracket;
3227
3228         /*
3229          * Skip any quoted text until we find the part in brackets.
3230         * On any error give up and return the full string.
3231         */
3232         while ( (first_bracket = strchr(parse, '<')) ) {
3233                 char *first_quote = strchr(parse, '"');
3234
3235                 if (!first_quote || first_quote > first_bracket)
3236                         break; /* no need to look at quoted part */
3237                 /* the bracket is within quotes, so ignore it */
3238                 parse = find_closing_quote(first_quote + 1, NULL);
3239                 if (!*parse) { /* not found, return full string ? */
3240                         /* XXX or be robust and return in-bracket part ? */
3241                         ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
3242                         break;
3243                 }
3244                 parse++;
3245         }
3246         if (first_bracket) {
3247                 char *second_bracket = strchr(first_bracket + 1, '>');
3248                 if (second_bracket) {
3249                         *second_bracket = '\0';
3250                         tmp = first_bracket + 1;
3251                 } else {
3252                         ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
3253                 }
3254         }
3255         
3256         return tmp;
3257 }
3258
3259 /*! \brief * parses a URI in its components.
3260  *
3261  * \note 
3262  * - If scheme is specified, drop it from the top.
3263  * - If a component is not requested, do not split around it.
3264  *
3265  * This means that if we don't have domain, we cannot split
3266  * name:pass and domain:port.
3267  * It is safe to call with ret_name, pass, domain, port
3268  * pointing all to the same place.
3269  * Init pointers to empty string so we never get NULL dereferencing.
3270  * Overwrites the string.
3271  * return 0 on success, other values on error.
3272  * \verbatim 
3273  * general form we are expecting is sip[s]:username[:password][;parameter]@host[:port][;...] 
3274  * \endverbatim
3275  */
3276 static int parse_uri(char *uri, char *scheme,
3277         char **ret_name, char **pass, char **domain, char **port, char **options)
3278 {
3279         char *name = NULL;
3280         int error = 0;
3281
3282         /* init field as required */
3283         if (pass)
3284                 *pass = "";
3285         if (port)
3286                 *port = "";
3287         if (scheme) {
3288                 int l = strlen(scheme);
3289                 if (!strncasecmp(uri, scheme, l))
3290                         uri += l;
3291                 else {
3292                         ast_debug(1, "Missing scheme '%s' in '%s'\n", scheme, uri);
3293                         error = -1;
3294                 }
3295         }
3296         if (!domain) {
3297                 /* if we don't want to split around domain, keep everything as a name,
3298                  * so we need to do nothing here, except remember why.
3299                  */
3300         } else {
3301                 /* store the result in a temp. variable to avoid it being
3302                  * overwritten if arguments point to the same place.
3303                  */
3304                 char *c, *dom = "";
3305
3306                 if ((c = strchr(uri, '@')) == NULL) {
3307                         /* domain-only URI, according to the SIP RFC. */
3308                         dom = uri;
3309                         name = "";
3310                 } else {
3311                         *c++ = '\0';
3312                         dom = c;
3313                         name = uri;
3314                 }
3315
3316                 /* Remove options in domain and name */
3317                 dom = strsep(&dom, ";");
3318                 name = strsep(&name, ";");
3319
3320                 if (port && (c = strchr(dom, ':'))) { /* Remove :port */
3321                         *c++ = '\0';
3322                         *port = c;
3323                 }
3324                 if (pass && (c = strchr(name, ':'))) {  /* user:password */
3325                         *c++ = '\0';
3326                         *pass = c;
3327                 }
3328                 *domain = dom;
3329         }
3330         if (ret_name)   /* same as for domain, store the result only at the end */
3331                 *ret_name = name;
3332         if (options)
3333                 *options = uri ? uri : "";
3334
3335         return error;
3336 }
3337
3338 /*! \brief Send message with Access-URL header, if this is an HTML URL only! */
3339 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
3340 {
3341         struct sip_pvt *p = chan->tech_pvt;
3342
3343         if (subclass != AST_HTML_URL)
3344                 return -1;
3345
3346         ast_string_field_build(p, url, "<%s>;mode=active", data);
3347
3348         if (sip_debug_test_pvt(p))
3349                 ast_debug(1, "Send URL %s, state = %d!\n", data, chan->_state);
3350
3351         switch (chan->_state) {
3352         case AST_STATE_RING:
3353                 transmit_response(p, "100 Trying", &p->initreq);
3354                 break;
3355         case AST_STATE_RINGING:
3356                 transmit_response(p, "180 Ringing", &p->initreq);
3357                 break;
3358         case AST_STATE_UP:
3359                 if (!p->pendinginvite) {                /* We are up, and have no outstanding invite */
3360                         transmit_reinvite_with_sdp(p, FALSE, FALSE);
3361                 } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
3362                         ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);   
3363                 }       
3364                 break;
3365         default:
3366                 ast_log(LOG_WARNING, "Don't know how to send URI when state is %d!\n", chan->_state);
3367         }
3368
3369         return 0;
3370 }
3371
3372 /*! \brief Deliver SIP call ID for the call */
3373 static const char *sip_get_callid(struct ast_channel *chan)
3374 {
3375         return chan->tech_pvt ? ((struct sip_pvt *) chan->tech_pvt)->callid : "";
3376 }
3377
3378 /*! \brief Send SIP MESSAGE text within a call
3379         Called from PBX core sendtext() application */
3380 static int sip_sendtext(struct ast_channel *ast, const char *text)
3381 {
3382         struct sip_pvt *p = ast->tech_pvt;
3383         int debug = sip_debug_test_pvt(p);
3384
3385         if (debug)
3386                 ast_verbose("Sending text %s on %s\n", text, ast->name);
3387         if (!p)
3388                 return -1;
3389         if (ast_strlen_zero(text))
3390                 return 0;
3391         if (debug)
3392                 ast_verbose("Really sending text %s on %s\n", text, ast->name);
3393         transmit_message_with_text(p, text);
3394         return 0;       
3395 }
3396
3397 /*! \brief Update peer object in realtime storage 
3398         If the Asterisk system name is set in asterisk.conf, we will use
3399         that name and store that in the "regserver" field in the sippeers
3400         table to facilitate multi-server setups.
3401 */
3402 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *defaultuser, const char *fullcontact, int expirey, int deprecated_username)
3403 {
3404         char port[10];
3405         char ipaddr[INET_ADDRSTRLEN];
3406         char regseconds[20];
3407         char *tablename = NULL;
3408
3409         const char *sysname = ast_config_AST_SYSTEM_NAME;
3410         char *syslabel = NULL;
3411
3412         time_t nowtime = time(NULL) + expirey;
3413         const char *fc = fullcontact ? "fullcontact" : NULL;
3414
3415         int realtimeregs = ast_check_realtime("sipregs");
3416
3417         tablename = realtimeregs ? "sipregs" : "sippeers";
3418         
3419         snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);   /* Expiration time */
3420         ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
3421         snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
3422         
3423         if (ast_strlen_zero(sysname))   /* No system name, disable this */
3424                 sysname = NULL;
3425         else if (sip_cfg.rtsave_sysname)
3426                 syslabel = "regserver";
3427
3428         if (fc)
3429                 ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
3430                         "port", port, "regseconds", regseconds,
3431                         deprecated_username ? "username" : "defaultuser", defaultuser, fc, fullcontact, syslabel, sysname, NULL); /* note fc and syslabel _can_ be NULL */
3432         else
3433                 ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
3434                         "port", port, "regseconds", regseconds,
3435                         deprecated_username ? "username" : "defaultuser", defaultuser, syslabel, sysname, NULL); /* note syslabel _can_ be NULL */
3436 }
3437
3438 /*! \brief Automatically add peer extension to dial plan */
3439 static void register_peer_exten(struct sip_peer *peer, int onoff)
3440 {
3441         char multi[256];
3442         char *stringp, *ext, *context;
3443         struct pbx_find_info q = { .stacklen = 0 };
3444
3445         /* XXX note that global_regcontext is both a global 'enable' flag and
3446          * the name of the global regexten context, if not specified
3447          * individually.
3448          */
3449         if (ast_strlen_zero(global_regcontext))
3450                 return;
3451
3452         ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
3453         stringp = multi;
3454         while ((ext = strsep(&stringp, "&"))) {
3455                 if ((context = strchr(ext, '@'))) {
3456                         *context++ = '\0';      /* split ext@context */
3457                         if (!ast_context_find(context)) {
3458                                 ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
3459                                 continue;
3460                         }
3461                 } else {
3462                         context = global_regcontext;
3463                 }
3464                 if (onoff) {
3465                         ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
3466                                  ast_strdup(peer->name), ast_free_ptr, "SIP");
3467                 } else if (pbx_find_extension(NULL, NULL, &q, context, ext, 1, NULL, "", E_MATCH)) {
3468                         ast_context_remove_extension(context, ext, 1, NULL);
3469                 }
3470         }
3471 }
3472
3473 /*! Destroy mailbox subscriptions */
3474 static void destroy_mailbox(struct sip_mailbox *mailbox)
3475 {
3476         if (mailbox->mailbox)
3477                 ast_free(mailbox->mailbox);
3478         if (mailbox->context)
3479                 ast_free(mailbox->context);
3480 &nbs