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