2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2012, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
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.
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.
21 * \brief Implementation of Session Initiation Protocol
23 * \author Mark Spencer <markster@digium.com>
26 * \arg \ref AstCREDITS
28 * Implementation of RFC 3261 - without S/MIME, and experimental TCP and TLS support
29 * Configuration file \link Config_sip sip.conf \endlink
31 * ********** IMPORTANT *
32 * \note TCP/TLS support is EXPERIMENTAL and WILL CHANGE. This applies to configuration
33 * settings, dialplan commands and dialplans apps/functions
34 * See \ref sip_tcp_tls
37 * ******** General TODO:s
38 * \todo Better support of forking
39 * \todo VIA branch tag transaction checking
40 * \todo Transaction support
42 * ******** Wishlist: Improvements
43 * - Support of SIP domains for devices, so that we match on username\@domain in the From: header
44 * - Connect registrations with a specific device on the incoming call. It's not done
45 * automatically in Asterisk
47 * \ingroup channel_drivers
49 * \par Overview of the handling of SIP sessions
50 * The SIP channel handles several types of SIP sessions, or dialogs,
51 * not all of them being "telephone calls".
52 * - Incoming calls that will be sent to the PBX core
53 * - Outgoing calls, generated by the PBX
54 * - SIP subscriptions and notifications of states and voicemail messages
55 * - SIP registrations, both inbound and outbound
56 * - SIP peer management (peerpoke, OPTIONS)
59 * In the SIP channel, there's a list of active SIP dialogs, which includes
60 * all of these when they are active. "sip show channels" in the CLI will
61 * show most of these, excluding subscriptions which are shown by
62 * "sip show subscriptions"
64 * \par incoming packets
65 * Incoming packets are received in the monitoring thread, then handled by
66 * sipsock_read() for udp only. In tcp, packets are read by the tcp_helper thread.
67 * sipsock_read() function parses the packet and matches an existing
68 * dialog or starts a new SIP dialog.
70 * sipsock_read sends the packet to handle_incoming(), that parses a bit more.
71 * If it is a response to an outbound request, the packet is sent to handle_response().
72 * If it is a request, handle_incoming() sends it to one of a list of functions
73 * depending on the request type - INVITE, OPTIONS, REFER, BYE, CANCEL etc
74 * sipsock_read locks the ast_channel if it exists (an active call) and
75 * unlocks it after we have processed the SIP message.
77 * A new INVITE is sent to handle_request_invite(), that will end up
78 * starting a new channel in the PBX, the new channel after that executing
79 * in a separate channel thread. This is an incoming "call".
80 * When the call is answered, either by a bridged channel or the PBX itself
81 * the sip_answer() function is called.
83 * The actual media - Video or Audio - is mostly handled by the RTP subsystem
87 * Outbound calls are set up by the PBX through the sip_request_call()
88 * function. After that, they are activated by sip_call().
91 * The PBX issues a hangup on both incoming and outgoing calls through
92 * the sip_hangup() function
95 /*! \li \ref chan_sip.c uses configuration files \ref sip.conf and \ref sip_notify.conf
96 * \addtogroup configuration_file
99 /*! \page sip.conf sip.conf
100 * \verbinclude sip.conf.sample
103 /*! \page sip_notify.conf sip_notify.conf
104 * \verbinclude sip_notify.conf.sample
108 * \page sip_tcp_tls SIP TCP and TLS support
110 * \par tcpfixes TCP implementation changes needed
111 * \todo Fix TCP/TLS handling in dialplan, SRV records, transfers and much more
112 * \todo Save TCP/TLS sessions in registry
113 * If someone registers a SIPS uri, this forces us to set up a TLS connection back.
114 * \todo Add TCP/TLS information to function SIPPEER and SIPCHANINFO
115 * \todo If tcpenable=yes, we must open a TCP socket on the same address as the IP for UDP.
116 * The tcpbindaddr config option should only be used to open ADDITIONAL ports
117 * So we should propably go back to
118 * bindaddr= the default address to bind to. If tcpenable=yes, then bind this to both udp and TCP
119 * if tlsenable=yes, open TLS port (provided we also have cert)
120 * tcpbindaddr = extra address for additional TCP connections
121 * tlsbindaddr = extra address for additional TCP/TLS connections
122 * udpbindaddr = extra address for additional UDP connections
123 * These three options should take multiple IP/port pairs
124 * Note: Since opening additional listen sockets is a *new* feature we do not have today
125 * the XXXbindaddr options needs to be disabled until we have support for it
127 * \todo re-evaluate the transport= setting in sip.conf. This is right now not well
128 * thought of. If a device in sip.conf contacts us via TCP, we should not switch transport,
129 * even if udp is the configured first transport.
131 * \todo Be prepared for one outbound and another incoming socket per pvt. This applies
132 * specially to communication with other peers (proxies).
133 * \todo We need to test TCP sessions with SIP proxies and in regards
134 * to the SIP outbound specs.
135 * \todo ;transport=tls was deprecated in RFC3261 and should not be used at all. See section 26.2.2.
137 * \todo If the message is smaller than the given Content-length, the request should get a 400 Bad request
138 * message. If it's a response, it should be dropped. (RFC 3261, Section 18.3)
139 * \todo Since we have had multidomain support in Asterisk for quite a while, we need to support
140 * multiple domains in our TLS implementation, meaning one socket and one cert per domain
141 * \todo Selection of transport for a request needs to be done after we've parsed all route headers,
142 * also considering outbound proxy options.
143 * First request: Outboundproxy, routes, (reg contact or URI. If URI doesn't have port: DNS naptr, srv, AAA)
144 * Intermediate requests: Outboundproxy(only when forced), routes, contact/uri
145 * DNS naptr support is crucial. A SIP uri might lead to a TLS connection.
146 * Also note that due to outbound proxy settings, a SIPS uri might have to be sent on UDP (not to recommend though)
147 * \todo Default transports are set to UDP, which cause the wrong behaviour when contacting remote
148 * devices directly from the dialplan. UDP is only a fallback if no other method works,
149 * in order to be compatible with RFC2543 (SIP/1.0) devices. For transactions that exceed the
150 * MTU (like INIVTE with video, audio and RTT) TCP should be preferred.
152 * When dialling unconfigured peers (with no port number) or devices in external domains
153 * NAPTR records MUST be consulted to find configured transport. If they are not found,
154 * SRV records for both TCP and UDP should be checked. If there's a record for TCP, use that.
155 * If there's no record for TCP, then use UDP as a last resort. If there's no SRV records,
156 * \note this only applies if there's no outbound proxy configured for the session. If an outbound
157 * proxy is configured, these procedures might apply for locating the proxy and determining
158 * the transport to use for communication with the proxy.
159 * \par Other bugs to fix ----
160 * __set_address_from_contact(const char *fullcontact, struct sockaddr_in *sin, int tcp)
161 * - sets TLS port as default for all TCP connections, unless other port is given in contact.
162 * parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
163 * - assumes that the contact the UA registers is using the same transport as the REGISTER request, which is
165 * - Does not save any information about TCP/TLS connected devices, which is a severe BUG, as discussed on the mailing list.
166 * get_destination(struct sip_pvt *p, struct sip_request *oreq)
167 * - Doesn't store the information that we got an incoming SIPS request in the channel, so that
168 * we can require a secure signalling path OUT of Asterisk (on SIP or IAX2). Possibly, the call should
169 * fail on in-secure signalling paths if there's no override in our configuration. At least, provide a
170 * channel variable in the dialplan.
171 * get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
172 * - As above, if we have a SIPS: uri in the refer-to header
173 * - Does not check transport in refer_to uri.
177 <use type="module">res_crypto</use>
178 <use type="module">res_http_websocket</use>
179 <support_level>core</support_level>
182 /*! \page sip_session_timers SIP Session Timers in Asterisk Chan_sip
184 The SIP Session-Timers is an extension of the SIP protocol that allows end-points and proxies to
185 refresh a session periodically. The sessions are kept alive by sending a RE-INVITE or UPDATE
186 request at a negotiated interval. If a session refresh fails then all the entities that support Session-
187 Timers clear their internal session state. In addition, UAs generate a BYE request in order to clear
188 the state in the proxies and the remote UA (this is done for the benefit of SIP entities in the path
189 that do not support Session-Timers).
191 The Session-Timers can be configured on a system-wide, per-user, or per-peer basis. The peruser/
192 per-peer settings override the global settings. The following new parameters have been
193 added to the sip.conf file.
194 session-timers=["accept", "originate", "refuse"]
195 session-expires=[integer]
196 session-minse=[integer]
197 session-refresher=["uas", "uac"]
199 The session-timers parameter in sip.conf defines the mode of operation of SIP session-timers feature in
200 Asterisk. The Asterisk can be configured in one of the following three modes:
202 1. Accept :: In the "accept" mode, the Asterisk server honors session-timers requests
203 made by remote end-points. A remote end-point can request Asterisk to engage
204 session-timers by either sending it an INVITE request with a "Supported: timer"
205 header in it or by responding to Asterisk's INVITE with a 200 OK that contains
206 Session-Expires: header in it. In this mode, the Asterisk server does not
207 request session-timers from remote end-points. This is the default mode.
208 2. Originate :: In the "originate" mode, the Asterisk server requests the remote
209 end-points to activate session-timers in addition to honoring such requests
210 made by the remote end-pints. In order to get as much protection as possible
211 against hanging SIP channels due to network or end-point failures, Asterisk
212 resends periodic re-INVITEs even if a remote end-point does not support
213 the session-timers feature.
214 3. Refuse :: In the "refuse" mode, Asterisk acts as if it does not support session-
215 timers for inbound or outbound requests. If a remote end-point requests
216 session-timers in a dialog, then Asterisk ignores that request unless it's
217 noted as a requirement (Require: header), in which case the INVITE is
218 rejected with a 420 Bad Extension response.
222 #include "asterisk.h"
224 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
227 #include <sys/signal.h>
229 #include <inttypes.h>
231 #include "asterisk/network.h"
232 #include "asterisk/paths.h" /* need ast_config_AST_SYSTEM_NAME */
234 Uncomment the define below, if you are having refcount related memory leaks.
235 With this uncommented, this module will generate a file, /tmp/refs, which contains
236 a history of the ao2_ref() calls. To be useful, all calls to ao2_* functions should
237 be modified to ao2_t_* calls, and include a tag describing what is happening with
238 enough detail, to make pairing up a reference count increment with its corresponding decrement.
239 The refcounter program in utils/ can be invaluable in highlighting objects that are not
240 balanced, along with the complete history for that object.
241 In normal operation, the macros defined will throw away the tags, so they do not
242 affect the speed of the program at all. They can be considered to be documentation.
244 Note: This must also be enabled in channels/sip/security_events.c
246 /* #define REF_DEBUG 1 */
248 #include "asterisk/lock.h"
249 #include "asterisk/config.h"
250 #include "asterisk/module.h"
251 #include "asterisk/pbx.h"
252 #include "asterisk/sched.h"
253 #include "asterisk/io.h"
254 #include "asterisk/rtp_engine.h"
255 #include "asterisk/udptl.h"
256 #include "asterisk/acl.h"
257 #include "asterisk/manager.h"
258 #include "asterisk/callerid.h"
259 #include "asterisk/cli.h"
260 #include "asterisk/musiconhold.h"
261 #include "asterisk/dsp.h"
262 #include "asterisk/pickup.h"
263 #include "asterisk/parking.h"
264 #include "asterisk/srv.h"
265 #include "asterisk/astdb.h"
266 #include "asterisk/causes.h"
267 #include "asterisk/utils.h"
268 #include "asterisk/file.h"
269 #include "asterisk/astobj2.h"
270 #include "asterisk/dnsmgr.h"
271 #include "asterisk/devicestate.h"
272 #include "asterisk/monitor.h"
273 #include "asterisk/netsock2.h"
274 #include "asterisk/localtime.h"
275 #include "asterisk/abstract_jb.h"
276 #include "asterisk/threadstorage.h"
277 #include "asterisk/translate.h"
278 #include "asterisk/ast_version.h"
279 #include "asterisk/data.h"
280 #include "asterisk/aoc.h"
281 #include "asterisk/message.h"
282 #include "sip/include/sip.h"
283 #include "sip/include/globals.h"
284 #include "sip/include/config_parser.h"
285 #include "sip/include/reqresp_parser.h"
286 #include "sip/include/sip_utils.h"
287 #include "asterisk/sdp_srtp.h"
288 #include "asterisk/ccss.h"
289 #include "asterisk/xml.h"
290 #include "sip/include/dialog.h"
291 #include "sip/include/dialplan_functions.h"
292 #include "sip/include/security_events.h"
293 #include "asterisk/sip_api.h"
294 #include "asterisk/app.h"
295 #include "asterisk/bridge.h"
296 #include "asterisk/stasis.h"
297 #include "asterisk/stasis_endpoints.h"
298 #include "asterisk/stasis_system.h"
299 #include "asterisk/stasis_channels.h"
300 #include "asterisk/features_config.h"
301 #include "asterisk/http_websocket.h"
304 <application name="SIPDtmfMode" language="en_US">
306 Change the dtmfmode for a SIP call.
309 <parameter name="mode" required="true">
311 <enum name="inband" />
313 <enum name="rfc2833" />
318 <para>Changes the dtmfmode for a SIP call.</para>
321 <application name="SIPAddHeader" language="en_US">
323 Add a SIP header to the outbound call.
326 <parameter name="Header" required="true" />
327 <parameter name="Content" required="true" />
330 <para>Adds a header to a SIP call placed with DIAL.</para>
331 <para>Remember to use the X-header if you are adding non-standard SIP
332 headers, like <literal>X-Asterisk-Accountcode:</literal>. Use this with care.
333 Adding the wrong headers may jeopardize the SIP dialog.</para>
334 <para>Always returns <literal>0</literal>.</para>
337 <application name="SIPRemoveHeader" language="en_US">
339 Remove SIP headers previously added with SIPAddHeader
342 <parameter name="Header" required="false" />
345 <para>SIPRemoveHeader() allows you to remove headers which were previously
346 added with SIPAddHeader(). If no parameter is supplied, all previously added
347 headers will be removed. If a parameter is supplied, only the matching headers
348 will be removed.</para>
349 <para>For example you have added these 2 headers:</para>
350 <para>SIPAddHeader(P-Asserted-Identity: sip:foo@bar);</para>
351 <para>SIPAddHeader(P-Preferred-Identity: sip:bar@foo);</para>
353 <para>// remove all headers</para>
354 <para>SIPRemoveHeader();</para>
355 <para>// remove all P- headers</para>
356 <para>SIPRemoveHeader(P-);</para>
357 <para>// remove only the PAI header (note the : at the end)</para>
358 <para>SIPRemoveHeader(P-Asserted-Identity:);</para>
360 <para>Always returns <literal>0</literal>.</para>
363 <application name="SIPSendCustomINFO" language="en_US">
365 Send a custom INFO frame on specified channels.
368 <parameter name="Data" required="true" />
369 <parameter name="UserAgent" required="false" />
372 <para>SIPSendCustomINFO() allows you to send a custom INFO message on all
373 active SIP channels or on channels with the specified User Agent. This
374 application is only available if TEST_FRAMEWORK is defined.</para>
377 <function name="SIP_HEADER" language="en_US">
379 Gets the specified SIP header from an incoming INVITE message.
382 <parameter name="name" required="true" />
383 <parameter name="number">
384 <para>If not specified, defaults to <literal>1</literal>.</para>
388 <para>Since there are several headers (such as Via) which can occur multiple
389 times, SIP_HEADER takes an optional second argument to specify which header with
390 that name to retrieve. Headers start at offset <literal>1</literal>.</para>
391 <para>Please observe that contents of the SDP (an attachment to the
392 SIP request) can't be accessed with this function.</para>
395 <function name="SIPPEER" language="en_US">
397 Gets SIP peer information.
400 <parameter name="peername" required="true" />
401 <parameter name="item">
404 <para>(default) The IP address.</para>
407 <para>The port number.</para>
409 <enum name="mailbox">
410 <para>The configured mailbox.</para>
412 <enum name="context">
413 <para>The configured context.</para>
416 <para>The epoch time of the next expire.</para>
418 <enum name="dynamic">
419 <para>Is it dynamic? (yes/no).</para>
421 <enum name="callerid_name">
422 <para>The configured Caller ID name.</para>
424 <enum name="callerid_num">
425 <para>The configured Caller ID number.</para>
427 <enum name="callgroup">
428 <para>The configured Callgroup.</para>
430 <enum name="pickupgroup">
431 <para>The configured Pickupgroup.</para>
433 <enum name="namedcallgroup">
434 <para>The configured Named Callgroup.</para>
436 <enum name="namedpickupgroup">
437 <para>The configured Named Pickupgroup.</para>
440 <para>The configured codecs.</para>
443 <para>Status (if qualify=yes).</para>
445 <enum name="regexten">
446 <para>Extension activated at registration.</para>
449 <para>Call limit (call-limit).</para>
451 <enum name="busylevel">
452 <para>Configured call level for signalling busy.</para>
454 <enum name="curcalls">
455 <para>Current amount of calls. Only available if call-limit is set.</para>
457 <enum name="language">
458 <para>Default language for peer.</para>
460 <enum name="accountcode">
461 <para>Account code for this peer.</para>
463 <enum name="useragent">
464 <para>Current user agent header used by peer.</para>
466 <enum name="maxforwards">
467 <para>The value used for SIP loop prevention in outbound requests</para>
469 <enum name="chanvar[name]">
470 <para>A channel variable configured with setvar for this peer.</para>
472 <enum name="codec[x]">
473 <para>Preferred codec index number <replaceable>x</replaceable> (beginning with zero).</para>
478 <description></description>
480 <function name="SIPCHANINFO" language="en_US">
482 Gets the specified SIP parameter from the current channel.
485 <parameter name="item" required="true">
488 <para>The IP address of the peer.</para>
491 <para>The source IP address of the peer.</para>
494 <para>The SIP URI from the <literal>From:</literal> header.</para>
497 <para>The SIP URI from the <literal>Contact:</literal> header.</para>
499 <enum name="useragent">
500 <para>The Useragent header used by the peer.</para>
502 <enum name="peername">
503 <para>The name of the peer.</para>
505 <enum name="t38passthrough">
506 <para><literal>1</literal> if T38 is offered or enabled in this channel,
507 otherwise <literal>0</literal>.</para>
512 <description></description>
514 <function name="CHECKSIPDOMAIN" language="en_US">
516 Checks if domain is a local domain.
519 <parameter name="domain" required="true" />
522 <para>This function checks if the <replaceable>domain</replaceable> in the argument is configured
523 as a local SIP domain that this Asterisk server is configured to handle.
524 Returns the domain name if it is locally handled, otherwise an empty string.
525 Check the <literal>domain=</literal> configuration in <filename>sip.conf</filename>.</para>
528 <manager name="SIPpeers" language="en_US">
530 List SIP peers (text format).
533 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
536 <para>Lists SIP peers in text format with details on current status.
537 <literal>Peerlist</literal> will follow as separate events, followed by a final event called
538 <literal>PeerlistComplete</literal>.</para>
541 <manager name="SIPshowpeer" language="en_US">
543 show SIP peer (text format).
546 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
547 <parameter name="Peer" required="true">
548 <para>The peer name you want to check.</para>
552 <para>Show one SIP peer with details on current status.</para>
555 <manager name="SIPqualifypeer" language="en_US">
560 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
561 <parameter name="Peer" required="true">
562 <para>The peer name you want to qualify.</para>
566 <para>Qualify a SIP peer.</para>
569 <ref type="managerEvent">SIPQualifyPeerDone</ref>
572 <manager name="SIPshowregistry" language="en_US">
574 Show SIP registrations (text format).
577 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
580 <para>Lists all registration requests and status. Registrations will follow as separate
581 events followed by a final event called <literal>RegistrationsComplete</literal>.</para>
584 <manager name="SIPnotify" language="en_US">
589 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
590 <parameter name="Channel" required="true">
591 <para>Peer to receive the notify.</para>
593 <parameter name="Variable" required="true">
594 <para>At least one variable pair must be specified.
595 <replaceable>name</replaceable>=<replaceable>value</replaceable></para>
599 <para>Sends a SIP Notify event.</para>
600 <para>All parameters for this event must be specified in the body of this request
601 via multiple <literal>Variable: name=value</literal> sequences.</para>
604 <manager name="SIPpeerstatus" language="en_US">
606 Show the status of one or all of the sip peers.
609 <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
610 <parameter name="Peer" required="false">
611 <para>The peer name you want to check.</para>
615 <para>Retrieves the status of one or all of the sip peers. If no peer name is specified, status
616 for all of the sip peers will be retrieved.</para>
619 <info name="SIPMessageFromInfo" language="en_US" tech="SIP">
620 <para>The <literal>from</literal> parameter can be a configured peer name
621 or in the form of "display-name" <URI>.</para>
623 <info name="SIPMessageToInfo" language="en_US" tech="SIP">
624 <para>Specifying a prefix of <literal>sip:</literal> will send the
625 message as a SIP MESSAGE request.</para>
627 <managerEvent language="en_US" name="SIPQualifyPeerDone">
628 <managerEventInstance class="EVENT_FLAG_CALL">
629 <synopsis>Raised when SIPQualifyPeer has finished qualifying the specified peer.</synopsis>
631 <parameter name="Peer">
632 <para>The name of the peer.</para>
634 <parameter name="ActionID">
635 <para>This is only included if an ActionID Header was sent with the action request, in which case it will be that ActionID.</para>
639 <ref type="manager">SIPqualifypeer</ref>
641 </managerEventInstance>
643 <managerEvent language="en_US" name="SessionTimeout">
644 <managerEventInstance class="EVENT_FLAG_CALL">
645 <synopsis>Raised when a SIP session times out.</synopsis>
648 <parameter name="Source">
649 <para>The source of the session timeout.</para>
651 <enum name="RTPTimeout" />
652 <enum name="SIPSessionTimer" />
656 </managerEventInstance>
660 static int min_expiry = DEFAULT_MIN_EXPIRY; /*!< Minimum accepted registration time */
661 static int max_expiry = DEFAULT_MAX_EXPIRY; /*!< Maximum accepted registration time */
662 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
663 static int min_subexpiry = DEFAULT_MIN_EXPIRY; /*!< Minimum accepted subscription time */
664 static int max_subexpiry = DEFAULT_MAX_EXPIRY; /*!< Maximum accepted subscription time */
665 static int mwi_expiry = DEFAULT_MWI_EXPIRY;
667 static int unauth_sessions = 0;
668 static int authlimit = DEFAULT_AUTHLIMIT;
669 static int authtimeout = DEFAULT_AUTHTIMEOUT;
671 /*! \brief Global jitterbuffer configuration - by default, jb is disabled
672 * \note Values shown here match the defaults shown in sip.conf.sample */
673 static struct ast_jb_conf default_jbconf =
677 .resync_threshold = 1000,
681 static struct ast_jb_conf global_jbconf; /*!< Global jitterbuffer configuration */
683 static const char config[] = "sip.conf"; /*!< Main configuration file */
684 static const char notify_config[] = "sip_notify.conf"; /*!< Configuration file for sending Notify with CLI commands to reconfigure or reboot phones */
686 /*! \brief Readable descriptions of device states.
687 * \note Should be aligned to above table as index */
688 static const struct invstate2stringtable {
689 const enum invitestates state;
691 } invitestate2string[] = {
693 {INV_CALLING, "Calling (Trying)"},
694 {INV_PROCEEDING, "Proceeding "},
695 {INV_EARLY_MEDIA, "Early media"},
696 {INV_COMPLETED, "Completed (done)"},
697 {INV_CONFIRMED, "Confirmed (up)"},
698 {INV_TERMINATED, "Done"},
699 {INV_CANCELLED, "Cancelled"}
702 /*! \brief Subscription types that we support. We support
703 * - dialoginfo updates (really device status, not dialog info as was the original intent of the standard)
704 * - SIMPLE presence used for device status
705 * - Voicemail notification subscriptions
707 static const struct cfsubscription_types {
708 enum subscriptiontype type;
709 const char * const event;
710 const char * const mediatype;
711 const char * const text;
712 } subscription_types[] = {
713 { NONE, "-", "unknown", "unknown" },
714 /* RFC 4235: SIP Dialog event package */
715 { DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
716 { CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" }, /* RFC 3863 */
717 { PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" }, /* RFC 3863 */
718 { XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" }, /* Pre-RFC 3863 with MS additions */
719 { MWI_NOTIFICATION, "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
722 /*! \brief The core structure to setup dialogs. We parse incoming messages by using
723 * structure and then route the messages according to the type.
725 * \note Note that sip_methods[i].id == i must hold or the code breaks
727 static const struct cfsip_methods {
729 int need_rtp; /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
731 enum can_create_dialog can_create;
733 { SIP_UNKNOWN, RTP, "-UNKNOWN-",CAN_CREATE_DIALOG },
734 { SIP_RESPONSE, NO_RTP, "SIP/2.0", CAN_NOT_CREATE_DIALOG },
735 { SIP_REGISTER, NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
736 { SIP_OPTIONS, NO_RTP, "OPTIONS", CAN_CREATE_DIALOG },
737 { SIP_NOTIFY, NO_RTP, "NOTIFY", CAN_CREATE_DIALOG },
738 { SIP_INVITE, RTP, "INVITE", CAN_CREATE_DIALOG },
739 { SIP_ACK, NO_RTP, "ACK", CAN_NOT_CREATE_DIALOG },
740 { SIP_PRACK, NO_RTP, "PRACK", CAN_NOT_CREATE_DIALOG },
741 { SIP_BYE, NO_RTP, "BYE", CAN_NOT_CREATE_DIALOG },
742 { SIP_REFER, NO_RTP, "REFER", CAN_CREATE_DIALOG },
743 { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE",CAN_CREATE_DIALOG },
744 { SIP_MESSAGE, NO_RTP, "MESSAGE", CAN_CREATE_DIALOG },
745 { SIP_UPDATE, NO_RTP, "UPDATE", CAN_NOT_CREATE_DIALOG },
746 { SIP_INFO, NO_RTP, "INFO", CAN_NOT_CREATE_DIALOG },
747 { SIP_CANCEL, NO_RTP, "CANCEL", CAN_NOT_CREATE_DIALOG },
748 { SIP_PUBLISH, NO_RTP, "PUBLISH", CAN_CREATE_DIALOG },
749 { SIP_PING, NO_RTP, "PING", CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
752 /*! \brief Diversion header reasons
754 * The core defines a bunch of constants used to define
755 * redirecting reasons. This provides a translation table
756 * between those and the strings which may be present in
757 * a SIP Diversion header
759 static const struct sip_reasons {
760 enum AST_REDIRECTING_REASON code;
762 } sip_reason_table[] = {
763 { AST_REDIRECTING_REASON_UNKNOWN, "unknown" },
764 { AST_REDIRECTING_REASON_USER_BUSY, "user-busy" },
765 { AST_REDIRECTING_REASON_NO_ANSWER, "no-answer" },
766 { AST_REDIRECTING_REASON_UNAVAILABLE, "unavailable" },
767 { AST_REDIRECTING_REASON_UNCONDITIONAL, "unconditional" },
768 { AST_REDIRECTING_REASON_TIME_OF_DAY, "time-of-day" },
769 { AST_REDIRECTING_REASON_DO_NOT_DISTURB, "do-not-disturb" },
770 { AST_REDIRECTING_REASON_DEFLECTION, "deflection" },
771 { AST_REDIRECTING_REASON_FOLLOW_ME, "follow-me" },
772 { AST_REDIRECTING_REASON_OUT_OF_ORDER, "out-of-service" },
773 { AST_REDIRECTING_REASON_AWAY, "away" },
774 { AST_REDIRECTING_REASON_CALL_FWD_DTE, "unknown"},
775 { AST_REDIRECTING_REASON_SEND_TO_VM, "send_to_vm"},
779 /*! \name DefaultSettings
780 Default setttings are used as a channel setting and as a default when
783 static char default_language[MAX_LANGUAGE]; /*!< Default language setting for new channels */
784 static char default_callerid[AST_MAX_EXTENSION]; /*!< Default caller ID for sip messages */
785 static char default_mwi_from[80]; /*!< Default caller ID for MWI updates */
786 static char default_fromdomain[AST_MAX_EXTENSION]; /*!< Default domain on outound messages */
787 static int default_fromdomainport; /*!< Default domain port on outbound messages */
788 static char default_notifymime[AST_MAX_EXTENSION]; /*!< Default MIME media type for MWI notify messages */
789 static char default_vmexten[AST_MAX_EXTENSION]; /*!< Default From Username on MWI updates */
790 static int default_qualify; /*!< Default Qualify= setting */
791 static int default_keepalive; /*!< Default keepalive= setting */
792 static char default_mohinterpret[MAX_MUSICCLASS]; /*!< Global setting for moh class to use when put on hold */
793 static char default_mohsuggest[MAX_MUSICCLASS]; /*!< Global setting for moh class to suggest when putting
794 * a bridged channel on hold */
795 static char default_parkinglot[AST_MAX_CONTEXT]; /*!< Parkinglot */
796 static char default_engine[256]; /*!< Default RTP engine */
797 static int default_maxcallbitrate; /*!< Maximum bitrate for call */
798 static struct ast_codec_pref default_prefs; /*!< Default codec prefs */
799 static char default_zone[MAX_TONEZONE_COUNTRY]; /*!< Default tone zone for channels created from the SIP driver */
800 static unsigned int default_transports; /*!< Default Transports (enum ast_transport) that are acceptable */
801 static unsigned int default_primary_transport; /*!< Default primary Transport (enum ast_transport) for outbound connections to devices */
803 static struct sip_settings sip_cfg; /*!< SIP configuration data.
804 \note in the future we could have multiple of these (per domain, per device group etc) */
806 /*!< use this macro when ast_uri_decode is dependent on pedantic checking to be on. */
807 #define SIP_PEDANTIC_DECODE(str) \
808 if (sip_cfg.pedanticsipchecking && !ast_strlen_zero(str)) { \
809 ast_uri_decode(str, ast_uri_sip_user); \
812 static unsigned int chan_idx; /*!< used in naming sip channel */
813 static int global_match_auth_username; /*!< Match auth username if available instead of From: Default off. */
815 static int global_relaxdtmf; /*!< Relax DTMF */
816 static int global_prematuremediafilter; /*!< Enable/disable premature frames in a call (causing 183 early media) */
817 static int global_rtptimeout; /*!< Time out call if no RTP */
818 static int global_rtpholdtimeout; /*!< Time out call if no RTP during hold */
819 static int global_rtpkeepalive; /*!< Send RTP keepalives */
820 static int global_reg_timeout; /*!< Global time between attempts for outbound registrations */
821 static int global_regattempts_max; /*!< Registration attempts before giving up */
822 static int global_reg_retry_403; /*!< Treat 403 responses to registrations as 401 responses */
823 static int global_shrinkcallerid; /*!< enable or disable shrinking of caller id */
824 static int global_callcounter; /*!< Enable call counters for all devices. This is currently enabled by setting the peer
825 * call-limit to INT_MAX. When we remove the call-limit from the code, we can make it
826 * with just a boolean flag in the device structure */
827 static unsigned int global_tos_sip; /*!< IP type of service for SIP packets */
828 static unsigned int global_tos_audio; /*!< IP type of service for audio RTP packets */
829 static unsigned int global_tos_video; /*!< IP type of service for video RTP packets */
830 static unsigned int global_tos_text; /*!< IP type of service for text RTP packets */
831 static unsigned int global_cos_sip; /*!< 802.1p class of service for SIP packets */
832 static unsigned int global_cos_audio; /*!< 802.1p class of service for audio RTP packets */
833 static unsigned int global_cos_video; /*!< 802.1p class of service for video RTP packets */
834 static unsigned int global_cos_text; /*!< 802.1p class of service for text RTP packets */
835 static unsigned int recordhistory; /*!< Record SIP history. Off by default */
836 static unsigned int dumphistory; /*!< Dump history to verbose before destroying SIP dialog */
837 static char global_useragent[AST_MAX_EXTENSION]; /*!< Useragent for the SIP channel */
838 static char global_sdpsession[AST_MAX_EXTENSION]; /*!< SDP session name for the SIP channel */
839 static char global_sdpowner[AST_MAX_EXTENSION]; /*!< SDP owner name for the SIP channel */
840 static int global_authfailureevents; /*!< Whether we send authentication failure manager events or not. Default no. */
841 static int global_t1; /*!< T1 time */
842 static int global_t1min; /*!< T1 roundtrip time minimum */
843 static int global_timer_b; /*!< Timer B - RFC 3261 Section 17.1.1.2 */
844 static unsigned int global_autoframing; /*!< Turn autoframing on or off. */
845 static int global_qualifyfreq; /*!< Qualify frequency */
846 static int global_qualify_gap; /*!< Time between our group of peer pokes */
847 static int global_qualify_peers; /*!< Number of peers to poke at a given time */
849 static enum st_mode global_st_mode; /*!< Mode of operation for Session-Timers */
850 static enum st_refresher_param global_st_refresher; /*!< Session-Timer refresher */
851 static int global_min_se; /*!< Lowest threshold for session refresh interval */
852 static int global_max_se; /*!< Highest threshold for session refresh interval */
854 static int global_store_sip_cause; /*!< Whether the MASTER_CHANNEL(HASH(SIP_CAUSE,[chan_name])) var should be set */
856 static int global_dynamic_exclude_static = 0; /*!< Exclude static peers from contact registrations */
857 static unsigned char global_refer_addheaders; /*!< Add extra headers to outgoing REFER */
861 * We use libxml2 in order to parse XML that may appear in the body of a SIP message. Currently,
862 * the only usage is for parsing PIDF bodies of incoming PUBLISH requests in the call-completion
863 * event package. This variable is set at module load time and may be checked at runtime to determine
864 * if XML parsing support was found.
866 static int can_parse_xml;
868 /*! \name Object counters @{
870 * \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
871 * should be used to modify these values.
873 static int speerobjs = 0; /*!< Static peers */
874 static int rpeerobjs = 0; /*!< Realtime peers */
875 static int apeerobjs = 0; /*!< Autocreated peer objects */
876 static int regobjs = 0; /*!< Registry objects */
879 static struct ast_flags global_flags[3] = {{0}}; /*!< global SIP_ flags */
880 static int global_t38_maxdatagram; /*!< global T.38 FaxMaxDatagram override */
882 static struct stasis_subscription *network_change_sub; /*!< subscription id for network change events */
883 static struct stasis_subscription *acl_change_sub; /*!< subscription id for named ACL system change events */
884 static int network_change_sched_id = -1;
886 static char used_context[AST_MAX_CONTEXT]; /*!< name of automatically created context for unloading */
888 AST_MUTEX_DEFINE_STATIC(netlock);
890 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
891 when it's doing something critical. */
892 AST_MUTEX_DEFINE_STATIC(monlock);
894 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
896 /*! \brief This is the thread for the monitor which checks for input on the channels
897 which are not currently in use. */
898 static pthread_t monitor_thread = AST_PTHREADT_NULL;
900 static int sip_reloading = FALSE; /*!< Flag for avoiding multiple reloads at the same time */
901 static enum channelreloadreason sip_reloadreason; /*!< Reason for last reload/load of configuration */
903 struct ast_sched_context *sched; /*!< The scheduling context */
904 static struct io_context *io; /*!< The IO context */
905 static int *sipsock_read_id; /*!< ID of IO entry for sipsock FD */
907 static AST_LIST_HEAD_STATIC(domain_list, domain); /*!< The SIP domain list */
909 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
911 static enum sip_debug_e sipdebug;
913 /*! \brief extra debugging for 'text' related events.
914 * At the moment this is set together with sip_debug_console.
915 * \note It should either go away or be implemented properly.
917 static int sipdebug_text;
919 static const struct _map_x_s referstatusstrings[] = {
920 { REFER_IDLE, "<none>" },
921 { REFER_SENT, "Request sent" },
922 { REFER_RECEIVED, "Request received" },
923 { REFER_CONFIRMED, "Confirmed" },
924 { REFER_ACCEPTED, "Accepted" },
925 { REFER_RINGING, "Target ringing" },
926 { REFER_200OK, "Done" },
927 { REFER_FAILED, "Failed" },
928 { REFER_NOAUTH, "Failed - auth failure" },
929 { -1, NULL} /* terminator */
932 /* --- Hash tables of various objects --------*/
934 static const int HASH_PEER_SIZE = 17;
935 static const int HASH_DIALOG_SIZE = 17;
937 static const int HASH_PEER_SIZE = 563; /*!< Size of peer hash table, prime number preferred! */
938 static const int HASH_DIALOG_SIZE = 563;
941 static const struct {
942 enum ast_cc_service_type service;
943 const char *service_string;
944 } sip_cc_service_map [] = {
945 [AST_CC_NONE] = { AST_CC_NONE, "" },
946 [AST_CC_CCBS] = { AST_CC_CCBS, "BS" },
947 [AST_CC_CCNR] = { AST_CC_CCNR, "NR" },
948 [AST_CC_CCNL] = { AST_CC_CCNL, "NL" },
951 static const struct {
952 enum sip_cc_notify_state state;
953 const char *state_string;
954 } sip_cc_notify_state_map [] = {
955 [CC_QUEUED] = {CC_QUEUED, "cc-state: queued"},
956 [CC_READY] = {CC_READY, "cc-state: ready"},
959 AST_LIST_HEAD_STATIC(epa_static_data_list, epa_backend);
963 * Used to create new entity IDs by ESCs.
965 static int esc_etag_counter;
966 static const int DEFAULT_PUBLISH_EXPIRES = 3600;
969 static int cc_esc_publish_handler(struct sip_pvt *pvt, struct sip_request *req, struct event_state_compositor *esc, struct sip_esc_entry *esc_entry);
971 static const struct sip_esc_publish_callbacks cc_esc_publish_callbacks = {
972 .initial_handler = cc_esc_publish_handler,
973 .modify_handler = cc_esc_publish_handler,
978 * \brief The Event State Compositors
980 * An Event State Compositor is an entity which
981 * accepts PUBLISH requests and acts appropriately
982 * based on these requests.
984 * The actual event_state_compositor structure is simply
985 * an ao2_container of sip_esc_entrys. When an incoming
986 * PUBLISH is received, we can match the appropriate sip_esc_entry
987 * using the entity ID of the incoming PUBLISH.
989 static struct event_state_compositor {
990 enum subscriptiontype event;
992 const struct sip_esc_publish_callbacks *callbacks;
993 struct ao2_container *compositor;
994 } event_state_compositors [] = {
996 {CALL_COMPLETION, "call-completion", &cc_esc_publish_callbacks},
1000 struct state_notify_data {
1002 struct ao2_container *device_state_info;
1004 const char *presence_subtype;
1005 const char *presence_message;
1009 static const int ESC_MAX_BUCKETS = 37;
1013 * Here we implement the container for dialogs which are in the
1014 * dialog_needdestroy state to iterate only through the dialogs
1015 * unlink them instead of iterate through all dialogs
1017 struct ao2_container *dialogs_needdestroy;
1021 * Here we implement the container for dialogs which have rtp
1022 * traffic and rtptimeout, rtpholdtimeout or rtpkeepalive
1023 * set. We use this container instead the whole dialog list.
1025 struct ao2_container *dialogs_rtpcheck;
1029 * Here we implement the container for dialogs (sip_pvt), defining
1030 * generic wrapper functions to ease the transition from the current
1031 * implementation (a single linked list) to a different container.
1032 * In addition to a reference to the container, we need functions to lock/unlock
1033 * the container and individual items, and functions to add/remove
1034 * references to the individual items.
1036 static struct ao2_container *dialogs;
1037 #define sip_pvt_lock(x) ao2_lock(x)
1038 #define sip_pvt_trylock(x) ao2_trylock(x)
1039 #define sip_pvt_unlock(x) ao2_unlock(x)
1041 /*! \brief The table of TCP threads */
1042 static struct ao2_container *threadt;
1044 /*! \brief The peer list: Users, Peers and Friends */
1045 static struct ao2_container *peers;
1046 static struct ao2_container *peers_by_ip;
1048 /*! \brief A bogus peer, to be used when authentication should fail */
1049 static struct sip_peer *bogus_peer;
1050 /*! \brief We can recognise the bogus peer by this invalid MD5 hash */
1051 #define BOGUS_PEER_MD5SECRET "intentionally_invalid_md5_string"
1053 /*! \brief The register list: Other SIP proxies we register with and receive calls from */
1054 static struct ast_register_list {
1055 ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
1059 /*! \brief The MWI subscription list */
1060 static struct ast_subscription_mwi_list {
1061 ASTOBJ_CONTAINER_COMPONENTS(struct sip_subscription_mwi);
1063 static int temp_pvt_init(void *);
1064 static void temp_pvt_cleanup(void *);
1066 /*! \brief A per-thread temporary pvt structure */
1067 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
1069 /*! \brief A per-thread buffer for transport to string conversion */
1070 AST_THREADSTORAGE(sip_transport_str_buf);
1072 /*! \brief Size of the SIP transport buffer */
1073 #define SIP_TRANSPORT_STR_BUFSIZE 128
1075 /*! \brief Authentication container for realm authentication */
1076 static struct sip_auth_container *authl = NULL;
1077 /*! \brief Global authentication container protection while adjusting the references. */
1078 AST_MUTEX_DEFINE_STATIC(authl_lock);
1080 static struct ast_manager_event_blob *session_timeout_to_ami(struct stasis_message *msg);
1081 STASIS_MESSAGE_TYPE_DEFN_LOCAL(session_timeout_type,
1082 .to_ami = session_timeout_to_ami,
1085 /* --- Sockets and networking --------------*/
1087 /*! \brief Main socket for UDP SIP communication.
1089 * sipsock is shared between the SIP manager thread (which handles reload
1090 * requests), the udp io handler (sipsock_read()) and the user routines that
1091 * issue udp writes (using __sip_xmit()).
1092 * The socket is -1 only when opening fails (this is a permanent condition),
1093 * or when we are handling a reload() that changes its address (this is
1094 * a transient situation during which we might have a harmless race, see
1095 * below). Because the conditions for the race to be possible are extremely
1096 * rare, we don't want to pay the cost of locking on every I/O.
1097 * Rather, we remember that when the race may occur, communication is
1098 * bound to fail anyways, so we just live with this event and let
1099 * the protocol handle this above us.
1101 static int sipsock = -1;
1103 struct ast_sockaddr bindaddr; /*!< UDP: The address we bind to */
1105 /*! \brief our (internal) default address/port to put in SIP/SDP messages
1106 * internip is initialized picking a suitable address from one of the
1107 * interfaces, and the same port number we bind to. It is used as the
1108 * default address/port in SIP messages, and as the default address
1109 * (but not port) in SDP messages.
1111 static struct ast_sockaddr internip;
1113 /*! \brief our external IP address/port for SIP sessions.
1114 * externaddr.sin_addr is only set when we know we might be behind
1115 * a NAT, and this is done using a variety of (mutually exclusive)
1116 * ways from the config file:
1118 * + with "externaddr = host[:port]" we specify the address/port explicitly.
1119 * The address is looked up only once when (re)loading the config file;
1121 * + with "externhost = host[:port]" we do a similar thing, but the
1122 * hostname is stored in externhost, and the hostname->IP mapping
1123 * is refreshed every 'externrefresh' seconds;
1125 * Other variables (externhost, externexpire, externrefresh) are used
1126 * to support the above functions.
1128 static struct ast_sockaddr externaddr; /*!< External IP address if we are behind NAT */
1129 static struct ast_sockaddr media_address; /*!< External RTP IP address if we are behind NAT */
1131 static char externhost[MAXHOSTNAMELEN]; /*!< External host name */
1132 static time_t externexpire; /*!< Expiration counter for re-resolving external host name in dynamic DNS */
1133 static int externrefresh = 10; /*!< Refresh timer for DNS-based external address (dyndns) */
1134 static uint16_t externtcpport; /*!< external tcp port */
1135 static uint16_t externtlsport; /*!< external tls port */
1137 /*! \brief List of local networks
1138 * We store "localnet" addresses from the config file into an access list,
1139 * marked as 'DENY', so the call to ast_apply_ha() will return
1140 * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
1141 * (i.e. presumably public) addresses.
1143 static struct ast_ha *localaddr; /*!< List of local networks, on the same side of NAT as this Asterisk */
1145 static int ourport_tcp; /*!< The port used for TCP connections */
1146 static int ourport_tls; /*!< The port used for TCP/TLS connections */
1147 static struct ast_sockaddr debugaddr;
1149 static struct ast_config *notify_types = NULL; /*!< The list of manual NOTIFY types we know how to send */
1151 /*! some list management macros. */
1153 #define UNLINK(element, head, prev) do { \
1155 (prev)->next = (element)->next; \
1157 (head) = (element)->next; \
1160 struct ao2_container *sip_monitor_instances;
1162 struct show_peers_context;
1164 /*---------------------------- Forward declarations of functions in chan_sip.c */
1165 /* Note: This is added to help splitting up chan_sip.c into several files
1166 in coming releases. */
1168 /*--- PBX interface functions */
1169 static struct ast_channel *sip_request_call(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, const char *dest, int *cause);
1170 static int sip_devicestate(const char *data);
1171 static int sip_sendtext(struct ast_channel *ast, const char *text);
1172 static int sip_call(struct ast_channel *ast, const char *dest, int timeout);
1173 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
1174 static int sip_hangup(struct ast_channel *ast);
1175 static int sip_answer(struct ast_channel *ast);
1176 static struct ast_frame *sip_read(struct ast_channel *ast);
1177 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
1178 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
1179 static int sip_transfer(struct ast_channel *ast, const char *dest);
1180 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1181 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
1182 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
1183 static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen);
1184 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
1185 static const char *sip_get_callid(struct ast_channel *chan);
1187 static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr);
1188 static int sip_standard_port(enum ast_transport type, int port);
1189 static int sip_prepare_socket(struct sip_pvt *p);
1190 static int get_address_family_filter(unsigned int transport);
1192 /*--- Transmitting responses and requests */
1193 static int sipsock_read(int *id, int fd, short events, void *ignore);
1194 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data);
1195 static int __sip_reliable_xmit(struct sip_pvt *p, uint32_t seqno, int resp, struct ast_str *data, int fatal, int sipmethod);
1196 static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp);
1197 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1198 static int retrans_pkt(const void *data);
1199 static int transmit_response_using_temp(ast_string_field callid, struct ast_sockaddr *addr, int useglobal_nat, const int intended_method, const struct sip_request *req, const char *msg);
1200 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1201 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1202 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1203 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp, int rpid);
1204 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
1205 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);
1206 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
1207 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1208 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable);
1209 static int transmit_request(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch);
1210 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch);
1211 static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri);
1212 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri);
1213 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
1214 static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded);
1215 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
1216 static int transmit_info_with_vidupdate(struct sip_pvt *p);
1217 static int transmit_message(struct sip_pvt *p, int init, int auth);
1218 static int transmit_refer(struct sip_pvt *p, const char *dest);
1219 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
1220 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
1221 static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state);
1222 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
1223 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno);
1224 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno);
1225 static void copy_request(struct sip_request *dst, const struct sip_request *src);
1226 static void receive_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
1227 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward);
1228 static int sip_send_mwi_to_peer(struct sip_peer *peer, int cache_only);
1230 /* Misc dialog routines */
1231 static int __sip_autodestruct(const void *data);
1232 static void *registry_unref(struct sip_registry *reg, char *tag);
1233 static int update_call_counter(struct sip_pvt *fup, int event);
1234 static int auto_congest(const void *arg);
1235 static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method);
1236 static void free_old_route(struct sip_route *route);
1237 static void list_route(struct sip_route *route);
1238 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards, int resp);
1239 static int build_path(struct sip_pvt *p, struct sip_peer *peer, struct sip_request *req, char *pathbuf);
1240 static int copy_route(struct sip_route **dst, const struct sip_route *src);
1241 static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
1242 struct sip_request *req, const char *uri);
1243 static int get_sip_pvt_from_replaces(const char *callid, const char *totag, const char *fromtag,
1244 struct sip_pvt **out_pvt, struct ast_channel **out_chan);
1245 static void check_pendings(struct sip_pvt *p);
1246 static void sip_set_owner(struct sip_pvt *p, struct ast_channel *chan);
1248 static void *sip_pickup_thread(void *stuff);
1249 static int sip_pickup(struct ast_channel *chan);
1251 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1252 static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method);
1254 /*--- Codec handling / SDP */
1255 static void try_suggested_sip_codec(struct sip_pvt *p);
1256 static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
1257 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
1258 static int find_sdp(struct sip_request *req);
1259 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
1260 static int process_sdp_o(const char *o, struct sip_pvt *p);
1261 static int process_sdp_c(const char *c, struct ast_sockaddr *addr);
1262 static int process_sdp_a_sendonly(const char *a, int *sendonly);
1263 static int process_sdp_a_ice(const char *a, struct sip_pvt *p, struct ast_rtp_instance *instance);
1264 static int process_sdp_a_dtls(const char *a, struct sip_pvt *p, struct ast_rtp_instance *instance);
1265 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec);
1266 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec);
1267 static int process_sdp_a_text(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newtextrtp, char *red_fmtp, int *red_num_gen, int *red_data_pt, int *last_rtpmap_codec);
1268 static int process_sdp_a_image(const char *a, struct sip_pvt *p);
1269 static void add_ice_to_sdp(struct ast_rtp_instance *instance, struct ast_str **a_buf);
1270 static void add_dtls_to_sdp(struct ast_rtp_instance *instance, struct ast_str **a_buf);
1271 static void start_ice(struct ast_rtp_instance *instance);
1272 static void add_codec_to_sdp(const struct sip_pvt *p, struct ast_format *codec,
1273 struct ast_str **m_buf, struct ast_str **a_buf,
1274 int debug, int *min_packet_size, int *max_packet_size);
1275 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
1276 struct ast_str **m_buf, struct ast_str **a_buf,
1278 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
1279 static void do_setnat(struct sip_pvt *p);
1280 static void stop_media_flows(struct sip_pvt *p);
1282 /*--- Authentication stuff */
1283 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1284 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
1285 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1286 const char *secret, const char *md5secret, int sipmethod,
1287 const char *uri, enum xmittype reliable);
1288 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
1289 int sipmethod, const char *uri, enum xmittype reliable,
1290 struct ast_sockaddr *addr, struct sip_peer **authpeer);
1291 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr);
1293 /*--- Domain handling */
1294 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1295 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
1296 static void clear_sip_domains(void);
1298 /*--- SIP realm authentication */
1299 static void add_realm_authentication(struct sip_auth_container **credentials, const char *configuration, int lineno);
1300 static struct sip_auth *find_realm_authentication(struct sip_auth_container *credentials, const char *realm);
1302 /*--- Misc functions */
1303 static int check_rtp_timeout(struct sip_pvt *dialog, time_t t);
1304 static int reload_config(enum channelreloadreason reason);
1305 static void add_diversion(struct sip_request *req, struct sip_pvt *pvt);
1306 static int expire_register(const void *data);
1307 static void *do_monitor(void *data);
1308 static int restart_monitor(void);
1309 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
1310 static struct ast_variable *copy_vars(struct ast_variable *src);
1311 static int dialog_find_multiple(void *obj, void *arg, int flags);
1312 static struct ast_channel *sip_pvt_lock_full(struct sip_pvt *pvt);
1313 /* static int sip_addrcmp(char *name, struct sockaddr_in *sin); Support for peer matching */
1314 static int sip_refer_alloc(struct sip_pvt *p);
1315 static int sip_notify_alloc(struct sip_pvt *p);
1316 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
1317 static void set_peer_nat(const struct sip_pvt *p, struct sip_peer *peer);
1318 static void check_for_nat(const struct ast_sockaddr *them, struct sip_pvt *p);
1320 /*--- Device monitoring and Device/extension state/event handling */
1321 static int extensionstate_update(const char *context, const char *exten, struct state_notify_data *data, struct sip_pvt *p, int force);
1322 static int cb_extensionstate(char *context, char *exten, struct ast_state_cb_info *info, void *data);
1323 static int sip_poke_noanswer(const void *data);
1324 static int sip_poke_peer(struct sip_peer *peer, int force);
1325 static void sip_poke_all_peers(void);
1326 static void sip_peer_hold(struct sip_pvt *p, int hold);
1327 static void mwi_event_cb(void *, struct stasis_subscription *, struct stasis_message *);
1328 static void network_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
1329 static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
1330 static void sip_keepalive_all_peers(void);
1332 /*--- Applications, functions, CLI and manager command helpers */
1333 static const char *sip_nat_mode(const struct sip_pvt *p);
1334 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1335 static char *transfermode2str(enum transfermodes mode) attribute_const;
1336 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
1337 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1338 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1339 static struct sip_peer *_sip_show_peers_one(int fd, struct mansession *s, struct show_peers_context *cont, struct sip_peer *peer);
1340 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1341 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1342 static void print_group(int fd, ast_group_t group, int crlf);
1343 static void print_named_groups(int fd, struct ast_namedgroups *groups, int crlf);
1344 static const char *dtmfmode2str(int mode) attribute_const;
1345 static int str2dtmfmode(const char *str) attribute_unused;
1346 static const char *insecure2str(int mode) attribute_const;
1347 static const char *allowoverlap2str(int mode) attribute_const;
1348 static void cleanup_stale_contexts(char *new, char *old);
1349 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
1350 static const char *domain_mode_to_text(const enum domain_mode mode);
1351 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1352 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1353 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1354 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1355 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1356 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1357 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1358 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1359 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1360 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
1361 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1362 static char *complete_sip_peer(const char *word, int state, int flags2);
1363 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
1364 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
1365 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
1366 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
1367 static char *complete_sip_notify(const char *line, const char *word, int pos, int state);
1368 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1369 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1370 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1371 static char *sip_do_debug_ip(int fd, const char *arg);
1372 static char *sip_do_debug_peer(int fd, const char *arg);
1373 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1374 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1375 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1376 static int sip_dtmfmode(struct ast_channel *chan, const char *data);
1377 static int sip_addheader(struct ast_channel *chan, const char *data);
1378 static int sip_do_reload(enum channelreloadreason reason);
1379 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1380 static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
1381 const char *name, int flag, int family);
1382 static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
1383 const char *name, int flag);
1384 static int ast_sockaddr_resolve_first_transport(struct ast_sockaddr *addr,
1385 const char *name, int flag, unsigned int transport);
1388 Functions for enabling debug per IP or fully, or enabling history logging for
1391 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to debuglog at end of dialog, before destroying data */
1392 static inline int sip_debug_test_addr(const struct ast_sockaddr *addr);
1393 static inline int sip_debug_test_pvt(struct sip_pvt *p);
1394 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
1395 static void sip_dump_history(struct sip_pvt *dialog);
1397 /*--- Device object handling */
1398 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
1399 static int update_call_counter(struct sip_pvt *fup, int event);
1400 static void sip_destroy_peer(struct sip_peer *peer);
1401 static void sip_destroy_peer_fn(void *peer);
1402 static void set_peer_defaults(struct sip_peer *peer);
1403 static struct sip_peer *temp_peer(const char *name);
1404 static void register_peer_exten(struct sip_peer *peer, int onoff);
1405 static int sip_poke_peer_s(const void *data);
1406 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
1407 static void reg_source_db(struct sip_peer *peer);
1408 static void destroy_association(struct sip_peer *peer);
1409 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
1410 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
1411 static void set_socket_transport(struct sip_socket *socket, int transport);
1412 static int peer_ipcmp_cb_full(void *obj, void *arg, void *data, int flags);
1414 /* Realtime device support */
1415 static void realtime_update_peer(const char *peername, struct ast_sockaddr *addr, const char *username, const char *fullcontact, const char *useragent, int expirey, unsigned short deprecated_username, int lastms, const char *path);
1416 static void update_peer(struct sip_peer *p, int expire);
1417 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
1418 static const char *get_name_from_variable(const struct ast_variable *var);
1419 static struct sip_peer *realtime_peer(const char *peername, struct ast_sockaddr *sin, char *callbackexten, int devstate_only, int which_objects);
1420 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1422 /*--- Internal UA client handling (outbound registrations) */
1423 static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p);
1424 static void sip_registry_destroy(struct sip_registry *reg);
1425 static int sip_register(const char *value, int lineno);
1426 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
1427 static int sip_reregister(const void *data);
1428 static int __sip_do_register(struct sip_registry *r);
1429 static int sip_reg_timeout(const void *data);
1430 static void sip_send_all_registers(void);
1431 static int sip_reinvite_retry(const void *data);
1433 /*--- Parsing SIP requests and responses */
1434 static int determine_firstline_parts(struct sip_request *req);
1435 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1436 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
1437 static int find_sip_method(const char *msg);
1438 static unsigned int parse_allowed_methods(struct sip_request *req);
1439 static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req);
1440 static int parse_request(struct sip_request *req);
1441 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
1442 static int method_match(enum sipmethod id, const char *name);
1443 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
1444 static void parse_oli(struct sip_request *req, struct ast_channel *chan);
1445 static const char *find_alias(const char *name, const char *_default);
1446 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
1447 static void lws2sws(struct ast_str *msgbuf);
1448 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
1449 static char *remove_uri_parameters(char *uri);
1450 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
1451 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
1452 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
1453 static int set_address_from_contact(struct sip_pvt *pvt);
1454 static void check_via(struct sip_pvt *p, const struct sip_request *req);
1455 static int get_rpid(struct sip_pvt *p, struct sip_request *oreq);
1456 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason, char **reason_str);
1457 static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id);
1458 static int transmit_state_notify(struct sip_pvt *p, struct state_notify_data *data, int full, int timeout);
1459 static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen);
1460 static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen);
1461 static int get_domain(const char *str, char *domain, int len);
1462 static void get_realm(struct sip_pvt *p, const struct sip_request *req);
1463 static char *get_content(struct sip_request *req);
1465 /*-- TCP connection handling ---*/
1466 static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session);
1467 static void *sip_tcp_worker_fn(void *);
1469 /*--- Constructing requests and responses */
1470 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
1471 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
1472 static void deinit_req(struct sip_request *req);
1473 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, uint32_t seqno, int newbranch);
1474 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri);
1475 static int init_resp(struct sip_request *resp, const char *msg);
1476 static inline int resp_needs_contact(const char *msg, enum sipmethod method);
1477 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
1478 static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p);
1479 static void build_via(struct sip_pvt *p);
1480 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
1481 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog);
1482 static char *generate_random_string(char *buf, size_t size);
1483 static void build_callid_pvt(struct sip_pvt *pvt);
1484 static void change_callid_pvt(struct sip_pvt *pvt, const char *callid);
1485 static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain);
1486 static void build_localtag_registry(struct sip_registry *reg);
1487 static void make_our_tag(struct sip_pvt *pvt);
1488 static int add_header(struct sip_request *req, const char *var, const char *value);
1489 static int add_max_forwards(struct sip_pvt *dialog, struct sip_request *req);
1490 static int add_content(struct sip_request *req, const char *line);
1491 static int finalize_content(struct sip_request *req);
1492 static void destroy_msg_headers(struct sip_pvt *pvt);
1493 static int add_text(struct sip_request *req, struct sip_pvt *p);
1494 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
1495 static int add_rpid(struct sip_request *req, struct sip_pvt *p);
1496 static int add_vidupdate(struct sip_request *req);
1497 static void add_route(struct sip_request *req, struct sip_route *route);
1498 static void make_route_list(struct sip_route *route, char *r, int rem);
1499 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1500 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1501 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
1502 static void set_destination(struct sip_pvt *p, char *uri);
1503 static void add_date(struct sip_request *req);
1504 static void add_expires(struct sip_request *req, int expires);
1505 static void build_contact(struct sip_pvt *p);
1507 /*------Request handling functions */
1508 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock);
1509 static int handle_request_update(struct sip_pvt *p, struct sip_request *req);
1510 static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, int *recount, const char *e, int *nounlock);
1511 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, uint32_t seqno, int *nounlock);
1512 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
1513 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *sin, const char *e);
1514 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
1515 static int handle_request_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
1516 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
1517 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
1518 static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
1519 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req,
1520 int *nounlock, struct sip_pvt *replaces_pvt, struct ast_channel *replaces_chan);
1521 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
1522 static int local_attended_transfer(struct sip_pvt *transferer, struct ast_channel *transferer_chan, uint32_t seqno, int *nounlock);
1524 /*------Response handling functions */
1525 static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1526 static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1527 static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1528 static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1529 static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1530 static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1531 static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1533 /*------ SRTP Support -------- */
1534 static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct ast_sdp_srtp **srtp, const char *a);
1536 /*------ T38 Support --------- */
1537 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
1538 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
1539 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
1540 static void change_t38_state(struct sip_pvt *p, int state);
1542 /*------ Session-Timers functions --------- */
1543 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
1544 static int proc_session_timer(const void *vp);
1545 static void stop_session_timer(struct sip_pvt *p);
1546 static void start_session_timer(struct sip_pvt *p);
1547 static void restart_session_timer(struct sip_pvt *p);
1548 static const char *strefresherparam2str(enum st_refresher r);
1549 static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher_param *const p_ref);
1550 static int parse_minse(const char *p_hdrval, int *const p_interval);
1551 static int st_get_se(struct sip_pvt *, int max);
1552 static enum st_refresher st_get_refresher(struct sip_pvt *);
1553 static enum st_mode st_get_mode(struct sip_pvt *, int no_cached);
1554 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
1556 /*------- RTP Glue functions -------- */
1557 static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance *instance, struct ast_rtp_instance *vinstance, struct ast_rtp_instance *tinstance, const struct ast_format_cap *cap, int nat_active);
1559 /*!--- SIP MWI Subscription support */
1560 static int sip_subscribe_mwi(const char *value, int lineno);
1561 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi);
1562 static void sip_send_all_mwi_subscriptions(void);
1563 static int sip_subscribe_mwi_do(const void *data);
1564 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
1566 /*! \brief Definition of this channel for PBX channel registration */
1567 struct ast_channel_tech sip_tech = {
1569 .description = "Session Initiation Protocol (SIP)",
1570 .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1571 .requester = sip_request_call, /* called with chan unlocked */
1572 .devicestate = sip_devicestate, /* called with chan unlocked (not chan-specific) */
1573 .call = sip_call, /* called with chan locked */
1574 .send_html = sip_sendhtml,
1575 .hangup = sip_hangup, /* called with chan locked */
1576 .answer = sip_answer, /* called with chan locked */
1577 .read = sip_read, /* called with chan locked */
1578 .write = sip_write, /* called with chan locked */
1579 .write_video = sip_write, /* called with chan locked */
1580 .write_text = sip_write,
1581 .indicate = sip_indicate, /* called with chan locked */
1582 .transfer = sip_transfer, /* called with chan locked */
1583 .fixup = sip_fixup, /* called with chan locked */
1584 .send_digit_begin = sip_senddigit_begin, /* called with chan unlocked */
1585 .send_digit_end = sip_senddigit_end,
1586 .early_bridge = ast_rtp_instance_early_bridge,
1587 .send_text = sip_sendtext, /* called with chan locked */
1588 .func_channel_read = sip_acf_channel_read,
1589 .setoption = sip_setoption,
1590 .queryoption = sip_queryoption,
1591 .get_pvt_uniqueid = sip_get_callid,
1594 /*! \brief This version of the sip channel tech has no send_digit_begin
1595 * callback so that the core knows that the channel does not want
1596 * DTMF BEGIN frames.
1597 * The struct is initialized just before registering the channel driver,
1598 * and is for use with channels using SIP INFO DTMF.
1600 struct ast_channel_tech sip_tech_info;
1602 /*------- CC Support -------- */
1603 static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan);
1604 static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent);
1605 static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent);
1606 static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason);
1607 static int sip_cc_agent_status_request(struct ast_cc_agent *agent);
1608 static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent);
1609 static int sip_cc_agent_recall(struct ast_cc_agent *agent);
1610 static void sip_cc_agent_destructor(struct ast_cc_agent *agent);
1612 static struct ast_cc_agent_callbacks sip_cc_agent_callbacks = {
1614 .init = sip_cc_agent_init,
1615 .start_offer_timer = sip_cc_agent_start_offer_timer,
1616 .stop_offer_timer = sip_cc_agent_stop_offer_timer,
1617 .respond = sip_cc_agent_respond,
1618 .status_request = sip_cc_agent_status_request,
1619 .start_monitoring = sip_cc_agent_start_monitoring,
1620 .callee_available = sip_cc_agent_recall,
1621 .destructor = sip_cc_agent_destructor,
1624 /* -------- End of declarations of structures, constants and forward declarations of functions
1625 Below starts actual code
1626 ------------------------
1629 static int sip_epa_register(const struct epa_static_data *static_data)
1631 struct epa_backend *backend = ast_calloc(1, sizeof(*backend));
1637 backend->static_data = static_data;
1639 AST_LIST_LOCK(&epa_static_data_list);
1640 AST_LIST_INSERT_TAIL(&epa_static_data_list, backend, next);
1641 AST_LIST_UNLOCK(&epa_static_data_list);
1645 static void sip_epa_unregister_all(void)
1647 struct epa_backend *backend;
1649 AST_LIST_LOCK(&epa_static_data_list);
1650 while ((backend = AST_LIST_REMOVE_HEAD(&epa_static_data_list, next))) {
1653 AST_LIST_UNLOCK(&epa_static_data_list);
1656 static void cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry);
1658 static void cc_epa_destructor(void *data)
1660 struct sip_epa_entry *epa_entry = data;
1661 struct cc_epa_entry *cc_entry = epa_entry->instance_data;
1665 static const struct epa_static_data cc_epa_static_data = {
1666 .event = CALL_COMPLETION,
1667 .name = "call-completion",
1668 .handle_error = cc_handle_publish_error,
1669 .destructor = cc_epa_destructor,
1672 static const struct epa_static_data *find_static_data(const char * const event_package)
1674 const struct epa_backend *backend = NULL;
1676 AST_LIST_LOCK(&epa_static_data_list);
1677 AST_LIST_TRAVERSE(&epa_static_data_list, backend, next) {
1678 if (!strcmp(backend->static_data->name, event_package)) {
1682 AST_LIST_UNLOCK(&epa_static_data_list);
1683 return backend ? backend->static_data : NULL;
1686 static struct sip_epa_entry *create_epa_entry (const char * const event_package, const char * const destination)
1688 struct sip_epa_entry *epa_entry;
1689 const struct epa_static_data *static_data;
1691 if (!(static_data = find_static_data(event_package))) {
1695 if (!(epa_entry = ao2_t_alloc(sizeof(*epa_entry), static_data->destructor, "Allocate new EPA entry"))) {
1699 epa_entry->static_data = static_data;
1700 ast_copy_string(epa_entry->destination, destination, sizeof(epa_entry->destination));
1703 static enum ast_cc_service_type service_string_to_service_type(const char * const service_string)
1705 enum ast_cc_service_type service;
1706 for (service = AST_CC_CCBS; service <= AST_CC_CCNL; ++service) {
1707 if (!strcasecmp(service_string, sip_cc_service_map[service].service_string)) {
1714 /* Even state compositors code */
1715 static void esc_entry_destructor(void *obj)
1717 struct sip_esc_entry *esc_entry = obj;
1718 if (esc_entry->sched_id > -1) {
1719 AST_SCHED_DEL(sched, esc_entry->sched_id);
1723 static int esc_hash_fn(const void *obj, const int flags)
1725 const struct sip_esc_entry *entry = obj;
1726 return ast_str_hash(entry->entity_tag);
1729 static int esc_cmp_fn(void *obj, void *arg, int flags)
1731 struct sip_esc_entry *entry1 = obj;
1732 struct sip_esc_entry *entry2 = arg;
1734 return (!strcmp(entry1->entity_tag, entry2->entity_tag)) ? (CMP_MATCH | CMP_STOP) : 0;
1737 static struct event_state_compositor *get_esc(const char * const event_package) {
1739 for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1740 if (!strcasecmp(event_package, event_state_compositors[i].name)) {
1741 return &event_state_compositors[i];
1747 static struct sip_esc_entry *get_esc_entry(const char * entity_tag, struct event_state_compositor *esc) {
1748 struct sip_esc_entry *entry;
1749 struct sip_esc_entry finder;
1751 ast_copy_string(finder.entity_tag, entity_tag, sizeof(finder.entity_tag));
1753 entry = ao2_find(esc->compositor, &finder, OBJ_POINTER);
1758 static int publish_expire(const void *data)
1760 struct sip_esc_entry *esc_entry = (struct sip_esc_entry *) data;
1761 struct event_state_compositor *esc = get_esc(esc_entry->event);
1763 ast_assert(esc != NULL);
1765 ao2_unlink(esc->compositor, esc_entry);
1766 ao2_ref(esc_entry, -1);
1770 static void create_new_sip_etag(struct sip_esc_entry *esc_entry, int is_linked)
1772 int new_etag = ast_atomic_fetchadd_int(&esc_etag_counter, +1);
1773 struct event_state_compositor *esc = get_esc(esc_entry->event);
1775 ast_assert(esc != NULL);
1777 ao2_unlink(esc->compositor, esc_entry);
1779 snprintf(esc_entry->entity_tag, sizeof(esc_entry->entity_tag), "%d", new_etag);
1780 ao2_link(esc->compositor, esc_entry);
1783 static struct sip_esc_entry *create_esc_entry(struct event_state_compositor *esc, struct sip_request *req, const int expires)
1785 struct sip_esc_entry *esc_entry;
1788 if (!(esc_entry = ao2_alloc(sizeof(*esc_entry), esc_entry_destructor))) {
1792 esc_entry->event = esc->name;
1794 expires_ms = expires * 1000;
1795 /* Bump refcount for scheduler */
1796 ao2_ref(esc_entry, +1);
1797 esc_entry->sched_id = ast_sched_add(sched, expires_ms, publish_expire, esc_entry);
1799 /* Note: This links the esc_entry into the ESC properly */
1800 create_new_sip_etag(esc_entry, 0);
1805 static int initialize_escs(void)
1808 for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1809 if (!((event_state_compositors[i].compositor) =
1810 ao2_container_alloc(ESC_MAX_BUCKETS, esc_hash_fn, esc_cmp_fn))) {
1817 static void destroy_escs(void)
1820 for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1821 ao2_ref(event_state_compositors[i].compositor, -1);
1826 static int find_by_notify_uri_helper(void *obj, void *arg, int flags)
1828 struct ast_cc_agent *agent = obj;
1829 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1830 const char *uri = arg;
1832 return !sip_uri_cmp(agent_pvt->notify_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
1835 static struct ast_cc_agent *find_sip_cc_agent_by_notify_uri(const char * const uri)
1837 struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_notify_uri_helper, (char *)uri, "SIP");
1841 static int find_by_subscribe_uri_helper(void *obj, void *arg, int flags)
1843 struct ast_cc_agent *agent = obj;
1844 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1845 const char *uri = arg;
1847 return !sip_uri_cmp(agent_pvt->subscribe_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
1850 static struct ast_cc_agent *find_sip_cc_agent_by_subscribe_uri(const char * const uri)
1852 struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_subscribe_uri_helper, (char *)uri, "SIP");
1856 static int find_by_callid_helper(void *obj, void *arg, int flags)
1858 struct ast_cc_agent *agent = obj;
1859 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1860 struct sip_pvt *call_pvt = arg;
1862 return !strcmp(agent_pvt->original_callid, call_pvt->callid) ? CMP_MATCH | CMP_STOP : 0;
1865 static struct ast_cc_agent *find_sip_cc_agent_by_original_callid(struct sip_pvt *pvt)
1867 struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_callid_helper, pvt, "SIP");
1871 static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan)
1873 struct sip_cc_agent_pvt *agent_pvt = ast_calloc(1, sizeof(*agent_pvt));
1874 struct sip_pvt *call_pvt = ast_channel_tech_pvt(chan);
1880 ast_assert(!strcmp(ast_channel_tech(chan)->type, "SIP"));
1882 ast_copy_string(agent_pvt->original_callid, call_pvt->callid, sizeof(agent_pvt->original_callid));
1883 ast_copy_string(agent_pvt->original_exten, call_pvt->exten, sizeof(agent_pvt->original_exten));
1884 agent_pvt->offer_timer_id = -1;
1885 agent->private_data = agent_pvt;
1886 sip_pvt_lock(call_pvt);
1887 ast_set_flag(&call_pvt->flags[0], SIP_OFFER_CC);
1888 sip_pvt_unlock(call_pvt);
1892 static int sip_offer_timer_expire(const void *data)
1894 struct ast_cc_agent *agent = (struct ast_cc_agent *) data;
1895 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1897 agent_pvt->offer_timer_id = -1;
1899 return ast_cc_failed(agent->core_id, "SIP agent %s's offer timer expired", agent->device_name);
1902 static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent)
1904 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1907 when = ast_get_cc_offer_timer(agent->cc_params) * 1000;
1908 agent_pvt->offer_timer_id = ast_sched_add(sched, when, sip_offer_timer_expire, agent);
1912 static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent)
1914 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1916 AST_SCHED_DEL(sched, agent_pvt->offer_timer_id);
1920 static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason)
1922 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1924 sip_pvt_lock(agent_pvt->subscribe_pvt);
1925 ast_set_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
1926 if (reason == AST_CC_AGENT_RESPONSE_SUCCESS || !ast_strlen_zero(agent_pvt->notify_uri)) {
1927 /* The second half of this if statement may be a bit hard to grasp,
1928 * so here's an explanation. When a subscription comes into
1929 * chan_sip, as long as it is not malformed, it will be passed
1930 * to the CC core. If the core senses an out-of-order state transition,
1931 * then the core will call this callback with the "reason" set to a
1932 * failure condition.
1933 * However, an out-of-order state transition will occur during a resubscription
1934 * for CC. In such a case, we can see that we have already generated a notify_uri
1935 * and so we can detect that this isn't a *real* failure. Rather, it is just
1936 * something the core doesn't recognize as a legitimate SIP state transition.
1937 * Thus we respond with happiness and flowers.
1939 transmit_response(agent_pvt->subscribe_pvt, "200 OK", &agent_pvt->subscribe_pvt->initreq);
1940 transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_QUEUED);
1942 transmit_response(agent_pvt->subscribe_pvt, "500 Internal Error", &agent_pvt->subscribe_pvt->initreq);
1944 sip_pvt_unlock(agent_pvt->subscribe_pvt);
1945 agent_pvt->is_available = TRUE;
1948 static int sip_cc_agent_status_request(struct ast_cc_agent *agent)
1950 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1951 enum ast_device_state state = agent_pvt->is_available ? AST_DEVICE_NOT_INUSE : AST_DEVICE_INUSE;
1952 return ast_cc_agent_status_response(agent->core_id, state);
1955 static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent)
1957 /* To start monitoring just means to wait for an incoming PUBLISH
1958 * to tell us that the caller has become available again. No special
1964 static int sip_cc_agent_recall(struct ast_cc_agent *agent)
1966 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1967 /* If we have received a PUBLISH beforehand stating that the caller in question
1968 * is not available, we can save ourself a bit of effort here and just report
1969 * the caller as busy
1971 if (!agent_pvt->is_available) {
1972 return ast_cc_agent_caller_busy(agent->core_id, "Caller %s is busy, reporting to the core",
1973 agent->device_name);
1975 /* Otherwise, we transmit a NOTIFY to the caller and await either
1976 * a PUBLISH or an INVITE
1978 sip_pvt_lock(agent_pvt->subscribe_pvt);
1979 transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_READY);
1980 sip_pvt_unlock(agent_pvt->subscribe_pvt);
1984 static void sip_cc_agent_destructor(struct ast_cc_agent *agent)
1986 struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1989 /* The agent constructor probably failed. */
1993 sip_cc_agent_stop_offer_timer(agent);
1994 if (agent_pvt->subscribe_pvt) {
1995 sip_pvt_lock(agent_pvt->subscribe_pvt);
1996 if (!ast_test_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
1997 /* If we haven't sent a 200 OK for the SUBSCRIBE dialog yet, then we need to send a response letting
1998 * the subscriber know something went wrong
2000 transmit_response(agent_pvt->subscribe_pvt, "500 Internal Server Error", &agent_pvt->subscribe_pvt->initreq);
2002 sip_pvt_unlock(agent_pvt->subscribe_pvt);
2003 agent_pvt->subscribe_pvt = dialog_unref(agent_pvt->subscribe_pvt, "SIP CC agent destructor: Remove ref to subscription");
2005 ast_free(agent_pvt);
2009 static int sip_monitor_instance_hash_fn(const void *obj, const int flags)
2011 const struct sip_monitor_instance *monitor_instance = obj;
2012 return monitor_instance->core_id;
2015 static int sip_monitor_instance_cmp_fn(void *obj, void *arg, int flags)
2017 struct sip_monitor_instance *monitor_instance1 = obj;
2018 struct sip_monitor_instance *monitor_instance2 = arg;
2020 return monitor_instance1->core_id == monitor_instance2->core_id ? CMP_MATCH | CMP_STOP : 0;
2023 static void sip_monitor_instance_destructor(void *data)
2025 struct sip_monitor_instance *monitor_instance = data;
2026 if (monitor_instance->subscription_pvt) {
2027 sip_pvt_lock(monitor_instance->subscription_pvt);
2028 monitor_instance->subscription_pvt->expiry = 0;
2029 transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 0, monitor_instance->subscribe_uri);
2030 sip_pvt_unlock(monitor_instance->subscription_pvt);
2031 dialog_unref(monitor_instance->subscription_pvt, "Unref monitor instance ref of subscription pvt");
2033 if (monitor_instance->suspension_entry) {
2034 monitor_instance->suspension_entry->body[0] = '\0';
2035 transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_REMOVE ,monitor_instance->notify_uri);
2036 ao2_t_ref(monitor_instance->suspension_entry, -1, "Decrementing suspension entry refcount in sip_monitor_instance_destructor");
2038 ast_string_field_free_memory(monitor_instance);
2041 static struct sip_monitor_instance *sip_monitor_instance_init(int core_id, const char * const subscribe_uri, const char * const peername, const char * const device_name)
2043 struct sip_monitor_instance *monitor_instance = ao2_alloc(sizeof(*monitor_instance), sip_monitor_instance_destructor);
2045 if (!monitor_instance) {
2049 if (ast_string_field_init(monitor_instance, 256)) {
2050 ao2_ref(monitor_instance, -1);
2054 ast_string_field_set(monitor_instance, subscribe_uri, subscribe_uri);
2055 ast_string_field_set(monitor_instance, peername, peername);
2056 ast_string_field_set(monitor_instance, device_name, device_name);
2057 monitor_instance->core_id = core_id;
2058 ao2_link(sip_monitor_instances, monitor_instance);
2059 return monitor_instance;
2062 static int find_sip_monitor_instance_by_subscription_pvt(void *obj, void *arg, int flags)
2064 struct sip_monitor_instance *monitor_instance = obj;
2065 return monitor_instance->subscription_pvt == arg ? CMP_MATCH | CMP_STOP : 0;
2068 static int find_sip_monitor_instance_by_suspension_entry(void *obj, void *arg, int flags)
2070 struct sip_monitor_instance *monitor_instance = obj;
2071 return monitor_instance->suspension_entry == arg ? CMP_MATCH | CMP_STOP : 0;
2074 static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id);
2075 static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor);
2076 static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor);
2077 static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id);
2078 static void sip_cc_monitor_destructor(void *private_data);
2080 static struct ast_cc_monitor_callbacks sip_cc_monitor_callbacks = {
2082 .request_cc = sip_cc_monitor_request_cc,
2083 .suspend = sip_cc_monitor_suspend,
2084 .unsuspend = sip_cc_monitor_unsuspend,
2085 .cancel_available_timer = sip_cc_monitor_cancel_available_timer,
2086 .destructor = sip_cc_monitor_destructor,
2089 static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id)
2091 struct sip_monitor_instance *monitor_instance = monitor->private_data;
2092 enum ast_cc_service_type service = monitor->service_offered;
2095 if (!monitor_instance) {
2099 if (!(monitor_instance->subscription_pvt = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL, NULL))) {
2103 when = service == AST_CC_CCBS ? ast_get_ccbs_available_timer(monitor->interface->config_params) :
2104 ast_get_ccnr_available_timer(monitor->interface->config_params);
2106 sip_pvt_lock(monitor_instance->subscription_pvt);
2107 ast_set_flag(&monitor_instance->subscription_pvt->flags[0], SIP_OUTGOING);
2108 create_addr(monitor_instance->subscription_pvt, monitor_instance->peername, 0, 1);
2109 ast_sip_ouraddrfor(&monitor_instance->subscription_pvt->sa, &monitor_instance->subscription_pvt->ourip, monitor_instance->subscription_pvt);
2110 monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
2111 monitor_instance->subscription_pvt->expiry = when;
2113 transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 2, monitor_instance->subscribe_uri);
2114 sip_pvt_unlock(monitor_instance->subscription_pvt);
2116 ao2_t_ref(monitor, +1, "Adding a ref to the monitor for the scheduler");
2117 *available_timer_id = ast_sched_add(sched, when * 1000, ast_cc_available_timer_expire, monitor);
2121 static int construct_pidf_body(enum sip_cc_publish_state state, char *pidf_body, size_t size, const char *presentity)
2123 struct ast_str *body = ast_str_alloca(size);
2126 generate_random_string(tuple_id, sizeof(tuple_id));
2128 /* We'll make this a bare-bones pidf body. In state_notify_build_xml, the PIDF
2129 * body gets a lot more extra junk that isn't necessary, so we'll leave it out here.
2131 ast_str_append(&body, 0, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
2132 /* XXX The entity attribute is currently set to the peer name associated with the
2133 * dialog. This is because we currently only call this function for call-completion
2134 * PUBLISH bodies. In such cases, the entity is completely disregarded. For other
2135 * event packages, it may be crucial to have a proper URI as the presentity so this
2136 * should be revisited as support is expanded.
2138 ast_str_append(&body, 0, "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" entity=\"%s\">\n", presentity);
2139 ast_str_append(&body, 0, "<tuple id=\"%s\">\n", tuple_id);
2140 ast_str_append(&body, 0, "<status><basic>%s</basic></status>\n", state == CC_OPEN ? "open" : "closed");
2141 ast_str_append(&body, 0, "</tuple>\n");
2142 ast_str_append(&body, 0, "</presence>\n");
2143 ast_copy_string(pidf_body, ast_str_buffer(body), size);
2147 static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor)
2149 struct sip_monitor_instance *monitor_instance = monitor->private_data;
2150 enum sip_publish_type publish_type;
2151 struct cc_epa_entry *cc_entry;
2153 if (!monitor_instance) {
2157 if (!monitor_instance->suspension_entry) {
2158 /* We haven't yet allocated the suspension entry, so let's give it a shot */
2159 if (!(monitor_instance->suspension_entry = create_epa_entry("call-completion", monitor_instance->peername))) {
2160 ast_log(LOG_WARNING, "Unable to allocate sip EPA entry for call-completion\n");
2161 ao2_ref(monitor_instance, -1);
2164 if (!(cc_entry = ast_calloc(1, sizeof(*cc_entry)))) {
2165 ast_log(LOG_WARNING, "Unable to allocate space for instance data of EPA entry for call-completion\n");
2166 ao2_ref(monitor_instance, -1);
2169 cc_entry->core_id = monitor->core_id;
2170 monitor_instance->suspension_entry->instance_data = cc_entry;
2171 publish_type = SIP_PUBLISH_INITIAL;
2173 publish_type = SIP_PUBLISH_MODIFY;
2174 cc_entry = monitor_instance->suspension_entry->instance_data;
2177 cc_entry->current_state = CC_CLOSED;
2179 if (ast_strlen_zero(monitor_instance->notify_uri)) {
2180 /* If we have no set notify_uri, then what this means is that we have
2181 * not received a NOTIFY from this destination stating that he is
2182 * currently available.
2184 * This situation can arise when the core calls the suspend callbacks
2185 * of multiple destinations. If one of the other destinations aside
2186 * from this one notified Asterisk that he is available, then there
2187 * is no reason to take any suspension action on this device. Rather,
2188 * we should return now and if we receive a NOTIFY while monitoring
2189 * is still "suspended" then we can immediately respond with the
2190 * proper PUBLISH to let this endpoint know what is going on.
2194 construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
2195 return transmit_publish(monitor_instance->suspension_entry, publish_type, monitor_instance->notify_uri);
2198 static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor)
2200 struct sip_monitor_instance *monitor_instance = monitor->private_data;
2201 struct cc_epa_entry *cc_entry;
2203 if (!monitor_instance) {
2207 ast_assert(monitor_instance->suspension_entry != NULL);
2209 cc_entry = monitor_instance->suspension_entry->instance_data;
2210 cc_entry->current_state = CC_OPEN;
2211 if (ast_strlen_zero(monitor_instance->notify_uri)) {
2212 /* This means we are being asked to unsuspend a call leg we never
2213 * sent a PUBLISH on. As such, there is no reason to send another
2214 * PUBLISH at this point either. We can just return instead.
2218 construct_pidf_body(CC_OPEN, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
2219 return transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_MODIFY, monitor_instance->notify_uri);
2222 static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id)
2224 if (*sched_id != -1) {
2225 AST_SCHED_DEL(sched, *sched_id);
2226 ao2_t_ref(monitor, -1, "Removing scheduler's reference to the monitor");
2231 static void sip_cc_monitor_destructor(void *private_data)
2233 struct sip_monitor_instance *monitor_instance = private_data;
2234 ao2_unlink(sip_monitor_instances, monitor_instance);
2235 ast_module_unref(ast_module_info->self);
2238 static int sip_get_cc_information(struct sip_request *req, char *subscribe_uri, size_t size, enum ast_cc_service_type *service)
2240 char *call_info = ast_strdupa(sip_get_header(req, "Call-Info"));
2244 static const char cc_purpose[] = "purpose=call-completion";
2245 static const int cc_purpose_len = sizeof(cc_purpose) - 1;
2247 if (ast_strlen_zero(call_info)) {
2248 /* No Call-Info present. Definitely no CC offer */
2252 uri = strsep(&call_info, ";");
2254 while ((purpose = strsep(&call_info, ";"))) {
2255 if (!strncmp(purpose, cc_purpose, cc_purpose_len)) {
2260 /* We didn't find the appropriate purpose= parameter. Oh well */
2264 /* Okay, call-completion has been offered. Let's figure out what type of service this is */
2265 while ((service_str = strsep(&call_info, ";"))) {
2266 if (!strncmp(service_str, "m=", 2)) {
2271 /* So they didn't offer a particular service, We'll just go with CCBS since it really
2272 * doesn't matter anyway
2276 /* We already determined that there is an "m=" so no need to check
2277 * the result of this strsep
2279 strsep(&service_str, "=");
2282 if ((*service = service_string_to_service_type(service_str)) == AST_CC_NONE) {
2283 /* Invalid service offered */
2287 ast_copy_string(subscribe_uri, get_in_brackets(uri), size);
2293 * \brief Determine what, if any, CC has been offered and queue a CC frame if possible
2295 * After taking care of some formalities to be sure that this call is eligible for CC,
2296 * we first try to see if we can make use of native CC. We grab the information from
2297 * the passed-in sip_request (which is always a response to an INVITE). If we can
2298 * use native CC monitoring for the call, then so be it.
2300 * If native cc monitoring is not possible or not supported, then we will instead attempt
2301 * to use generic monitoring. Falling back to generic from a failed attempt at using native
2302 * monitoring will only work if the monitor policy of the endpoint is "always"
2304 * \param pvt The current dialog. Contains CC parameters for the endpoint
2305 * \param req The response to the INVITE we want to inspect
2306 * \param service The service to use if generic monitoring is to be used. For native
2307 * monitoring, we get the service from the SIP response itself
2309 static void sip_handle_cc(struct sip_pvt *pvt, struct sip_request *req, enum ast_cc_service_type service)
2311 enum ast_cc_monitor_policies monitor_policy = ast_get_cc_monitor_policy(pvt->cc_params);
2313 char interface_name[AST_CHANNEL_NAME];
2315 if (monitor_policy == AST_CC_MONITOR_NEVER) {
2316 /* Don't bother, just return */
2320 if ((core_id = ast_cc_get_current_core_id(pvt->owner)) == -1) {
2321 /* For some reason, CC is invalid, so don't try it! */
2325 ast_channel_get_device_name(pvt->owner, interface_name, sizeof(interface_name));
2327 if (monitor_policy == AST_CC_MONITOR_ALWAYS || monitor_policy == AST_CC_MONITOR_NATIVE) {
2328 char subscribe_uri[SIPBUFSIZE];
2329 char device_name[AST_CHANNEL_NAME];
2330 enum ast_cc_service_type offered_service;
2331 struct sip_monitor_instance *monitor_instance;
2332 if (sip_get_cc_information(req, subscribe_uri, sizeof(subscribe_uri), &offered_service)) {
2333 /* If CC isn't being offered to us, or for some reason the CC offer is
2334 * not formatted correctly, then it may still be possible to use generic
2335 * call completion since the monitor policy may be "always"
2339 ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
2340 if (!(monitor_instance = sip_monitor_instance_init(core_id, subscribe_uri, pvt->peername, device_name))) {
2341 /* Same deal. We can try using generic still */
2344 /* We bump the refcount of chan_sip because once we queue this frame, the CC core
2345 * will have a reference to callbacks in this module. We decrement the module
2346 * refcount once the monitor destructor is called
2348 ast_module_ref(ast_module_info->self);
2349 ast_queue_cc_frame(pvt->owner, "SIP", pvt->dialstring, offered_service, monitor_instance);
2350 ao2_ref(monitor_instance, -1);
2355 if (monitor_policy == AST_CC_MONITOR_GENERIC || monitor_policy == AST_CC_MONITOR_ALWAYS) {
2356 ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE, interface_name, service, NULL);
2360 /*! \brief Working TLS connection configuration */
2361 static struct ast_tls_config sip_tls_cfg;
2363 /*! \brief Default TLS connection configuration */
2364 static struct ast_tls_config default_tls_cfg;
2366 /*! \brief The TCP server definition */
2367 static struct ast_tcptls_session_args sip_tcp_desc = {
2369 .master = AST_PTHREADT_NULL,
2372 .name = "SIP TCP server",
2373 .accept_fn = ast_tcptls_server_root,
2374 .worker_fn = sip_tcp_worker_fn,
2377 /*! \brief The TCP/TLS server definition */
2378 static struct ast_tcptls_session_args sip_tls_desc = {
2380 .master = AST_PTHREADT_NULL,
2381 .tls_cfg = &sip_tls_cfg,
2383 .name = "SIP TLS server",
2384 .accept_fn = ast_tcptls_server_root,
2385 .worker_fn = sip_tcp_worker_fn,
2388 /*! \brief Append to SIP dialog history
2389 \return Always returns 0 */
2390 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
2392 struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, const char *tag, char *file, int line, const char *func)
2396 __ao2_ref_debug(p, 1, tag, file, line, func);
2401 ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
2405 struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, const char *tag, char *file, int line, const char *func)
2409 __ao2_ref_debug(p, -1, tag, file, line, func);
2416 /*! \brief map from an integer value to a string.
2417 * If no match is found, return errorstring
2419 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
2421 const struct _map_x_s *cur;
2423 for (cur = table; cur->s; cur++) {
2431 /*! \brief map from a string to an integer value, case insensitive.
2432 * If no match is found, return errorvalue.
2434 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
2436 const struct _map_x_s *cur;
2438 for (cur = table; cur->s; cur++) {
2439 if (!strcasecmp(cur->s, s)) {
2446 static enum AST_REDIRECTING_REASON sip_reason_str_to_code(const char *text)
2448 enum AST_REDIRECTING_REASON ast = AST_REDIRECTING_REASON_UNKNOWN;
2451 for (i = 0; i < ARRAY_LEN(sip_reason_table); ++i) {
2452 if (!strcasecmp(text, sip_reason_table[i].text)) {
2453 ast = sip_reason_table[i].code;
2461 static const char *sip_reason_code_to_str(struct ast_party_redirecting_reason *reason, int *table_lookup)
2463 int code = reason->code;
2465 /* If there's a specific string set, then we just
2468 if (!ast_strlen_zero(reason->str)) {
2469 /* If we care about whether this can be found in
2470 * the table, then we need to check about that.
2473 /* If the string is literally "unknown" then don't bother with the lookup
2474 * because it can lead to a false negative.
2476 if (!strcasecmp(reason->str, "unknown") ||
2477 sip_reason_str_to_code(reason->str) != AST_REDIRECTING_REASON_UNKNOWN) {
2478 *table_lookup = TRUE;
2480 *table_lookup = FALSE;
2487 *table_lookup = TRUE;
2490 if (code >= 0 && code < ARRAY_LEN(sip_reason_table)) {
2491 return sip_reason_table[code].text;
2498 * \brief generic function for determining if a correct transport is being
2499 * used to contact a peer
2501 * this is done as a macro so that the "tmpl" var can be passed either a
2502 * sip_request or a sip_peer
2504 #define check_request_transport(peer, tmpl) ({ \
2506 if (peer->socket.type == tmpl->socket.type) \
2508 else if (!(peer->transports & tmpl->socket.type)) {\
2509 ast_log(LOG_ERROR, \
2510 "'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
2511 sip_get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
2514 } else if (peer->socket.type & AST_TRANSPORT_TLS) { \
2515 ast_log(LOG_WARNING, \
2516 "peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
2517 peer->name, sip_get_transport(tmpl->socket.type) \
2521 "peer '%s' has contacted us over %s even though we prefer %s.\n", \
2522 peer->name, sip_get_transport(tmpl->socket.type), sip_get_transport(peer->socket.type) \
2529 * duplicate a list of channel variables, \return the copy.
2531 static struct ast_variable *copy_vars(struct ast_variable *src)
2533 struct ast_variable *res = NULL, *tmp, *v = NULL;
2535 for (v = src ; v ; v = v->next) {
2536 if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
2544 static void tcptls_packet_destructor(void *obj)
2546 struct tcptls_packet *packet = obj;
2548 ast_free(packet->data);
2551 static void sip_tcptls_client_args_destructor(void *obj)
2553 struct ast_tcptls_session_args *args = obj;
2554 if (args->tls_cfg) {
2555 ast_free(args->tls_cfg->certfile);
2556 ast_free(args->tls_cfg->pvtfile);
2557 ast_free(args->tls_cfg->cipher);
2558 ast_free(args->tls_cfg->cafile);
2559 ast_free(args->tls_cfg->capath);
2561 ast_ssl_teardown(args->tls_cfg);
2563 ast_free(args->tls_cfg);
2564 ast_free((char *) args->name);
2567 static void sip_threadinfo_destructor(void *obj)
2569 struct sip_threadinfo *th = obj;
2570 struct tcptls_packet *packet;
2572 if (th->alert_pipe[1] > -1) {
2573 close(th->alert_pipe[0]);
2575 if (th->alert_pipe[1] > -1) {
2576 close(th->alert_pipe[1]);
2578 th->alert_pipe[0] = th->alert_pipe[1] = -1;
2580 while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
2581 ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
2584 if (th->tcptls_session) {
2585 ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
2589 /*! \brief creates a sip_threadinfo object and links it into the threadt table. */
2590 static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
2592 struct sip_threadinfo *th;
2594 if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
2598 th->alert_pipe[0] = th->alert_pipe[1] = -1;
2600 if (pipe(th->alert_pipe) == -1) {
2601 ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
2602 ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
2605 ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
2606 th->tcptls_session = tcptls_session;
2607 th->type = transport ? transport : (tcptls_session->ssl ? AST_TRANSPORT_TLS: AST_TRANSPORT_TCP);
2608 ao2_t_link(threadt, th, "Adding new tcptls helper thread");
2609 ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
2613 /*! \brief used to indicate to a tcptls thread that data is ready to be written */
2614 static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
2617 struct sip_threadinfo *th = NULL;
2618 struct tcptls_packet *packet = NULL;
2619 struct sip_threadinfo tmp = {
2620 .tcptls_session = tcptls_session,
2622 enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
2624 if (!tcptls_session) {
2628 ao2_lock(tcptls_session);
2630 if ((tcptls_session->fd == -1) ||
2631 !(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
2632 !(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
2633 !(packet->data = ast_str_create(len))) {
2634 goto tcptls_write_setup_error;
2637 /* goto tcptls_write_error should _NOT_ be used beyond this point */
2638 ast_str_set(&packet->data, 0, "%s", (char *) buf);
2641 /* alert tcptls thread handler that there is a packet to be sent.
2642 * must lock the thread info object to guarantee control of the
2645 if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
2646 ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
2647 ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
2650 } else { /* it is safe to queue the frame after issuing the alert when we hold the threadinfo lock */
2651 AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
2655 ao2_unlock(tcptls_session);
2656 ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
2659 tcptls_write_setup_error:
2661 ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
2664 ao2_t_ref(packet, -1, "could not allocate packet's data");
2666 ao2_unlock(tcptls_session);
2671 /*! \brief SIP TCP connection handler */
2672 static void *sip_tcp_worker_fn(void *data)
2674 struct ast_tcptls_session_instance *tcptls_session = data;
2676 return _sip_tcp_helper_thread(tcptls_session);
2679 /*! \brief SIP WebSocket connection handler */
2680 static void sip_websocket_callback(struct ast_websocket *session, struct ast_variable *parameters, struct ast_variable *headers)
2684 if (ast_websocket_set_nonblock(session)) {
2688 while ((res = ast_wait_for_input(ast_websocket_fd(session), -1)) > 0) {
2690 uint64_t payload_len;
2691 enum ast_websocket_opcode opcode;
2694 if (ast_websocket_read(session, &payload, &payload_len, &opcode, &fragmented)) {
2695 /* We err on the side of caution and terminate the session if any error occurs */
2699 if (opcode == AST_WEBSOCKET_OPCODE_TEXT || opcode == AST_WEBSOCKET_OPCODE_BINARY) {
2700 struct sip_request req = { 0, };
2702 if (!(req.data = ast_str_create(payload_len + 1))) {
2706 if (ast_str_set(&req.data, -1, "%s", payload) == AST_DYNSTR_BUILD_FAILED) {
2711 req.socket.fd = ast_websocket_fd(session);
2712 set_socket_transport(&req.socket, ast_websocket_is_secure(session) ? AST_TRANSPORT_WSS : AST_TRANSPORT_WS);
2713 req.socket.ws_session = session;
2715 handle_request_do(&req, ast_websocket_remote_address(session));
2718 } else if (opcode == AST_WEBSOCKET_OPCODE_CLOSE) {
2724 ast_websocket_unref(session);
2727 /*! \brief Check if the authtimeout has expired.
2728 * \param start the time when the session started
2730 * \retval 0 the timeout has expired
2732 * \return the number of milliseconds until the timeout will expire
2734 static int sip_check_authtimeout(time_t start)
2738 if(time(&now) == -1) {
2739 ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
2743 timeout = (authtimeout - (now - start)) * 1000;
2745 /* we have timed out */
2753 * \brief Read a SIP request or response from a TLS connection
2755 * Because TLS operations are hidden from view via a FILE handle, the
2756 * logic for reading data is a bit complex, and we have to make periodic
2757 * checks to be sure we aren't taking too long to perform the necessary
2760 * \todo XXX This should be altered in the future not to use a FILE pointer
2762 * \param req The request structure to fill in
2763 * \param tcptls_session The TLS connection on which the data is being received
2764 * \param authenticated A flag indicating whether authentication has occurred yet.
2765 * This is only relevant in a server role.
2766 * \param start The time at which we started attempting to read data. Used in
2767 * determining if there has been a timeout.
2768 * \param me Thread info. Used as a means of determining if the session needs to be stoppped.
2769 * \retval -1 Failed to read data
2770 * \retval 0 Succeeded in reading data
2772 static int sip_tls_read(struct sip_request *req, struct sip_request *reqcpy, struct ast_tcptls_session_instance *tcptls_session,
2773 int authenticated, time_t start, struct sip_threadinfo *me)
2775 int res, content_length, after_poll = 1, need_poll = 1;
2776 size_t datalen = ast_str_strlen(req->data);
2777 char buf[1024] = "";
2780 /* Read in headers one line at a time */
2781 while (datalen < 4 || strncmp(REQ_OFFSET_TO_STR(req, data->used - 4), "\r\n\r\n", 4)) {
2782 if (!tcptls_session->client && !authenticated) {
2783 if ((timeout = sip_check_authtimeout(start)) < 0) {
2784 ast_debug(2, "SIP TLS server failed to determine authentication timeout\n");
2789 ast_debug(2, "SIP TLS server timed out\n");
2796 /* special polling behavior is required for TLS
2797 * sockets because of the buffering done in the
2802 res = ast_wait_for_input(tcptls_session->fd, timeout);
2804 ast_debug(2, "SIP TLS server :: ast_wait_for_input returned %d\n", res);
2806 } else if (res == 0) {
2808 ast_debug(2, "SIP TLS server timed out\n");
2813 ao2_lock(tcptls_session);
2814 if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
2815 ao2_unlock(tcptls_session);
2823 ao2_unlock(tcptls_session);
2828 ast_str_append(&req->data, 0, "%s", buf);
2830 datalen = ast_str_strlen(req->data);
2831 if (datalen > SIP_MAX_PACKET_SIZE) {
2832 ast_log(LOG_WARNING, "Rejecting TLS packet from '%s' because way too large: %zu\n",
2833 ast_sockaddr_stringify(&tcptls_session->remote_address), datalen);
2837 copy_request(reqcpy, req);
2838 parse_request(reqcpy);
2839 /* In order to know how much to read, we need the content-length header */
2840 if (sscanf(sip_get_header(reqcpy, "Content-Length"), "%30d", &content_length)) {
2841 while (content_length > 0) {
2843 if (!tcptls_session->client && !authenticated) {
2844 if ((timeout = sip_check_authtimeout(start)) < 0) {
2849 ast_debug(2, "SIP TLS server timed out\n");
2859 res = ast_wait_for_input(tcptls_session->fd, timeout);
2861 ast_debug(2, "SIP TLS server :: ast_wait_for_input returned %d\n", res);
2863 } else if (res == 0) {
2865 ast_debug(2, "SIP TLS server timed out\n");
2870 ao2_lock(tcptls_session);
2871 if (!(bytes_read = fread(buf, 1, MIN(sizeof(buf) - 1, content_length), tcptls_session->f))) {
2872 ao2_unlock(tcptls_session);
2880 buf[bytes_read] = '\0';
2881 ao2_unlock(tcptls_session);
2886 content_length -= strlen(buf);
2887 ast_str_append(&req->data, 0, "%s", buf);
2889 datalen = ast_str_strlen(req->data);
2890 if (datalen > SIP_MAX_PACKET_SIZE) {
2891 ast_log(LOG_WARNING, "Rejecting TLS packet from '%s' because way too large: %zu\n",
2892 ast_sockaddr_stringify(&tcptls_session->remote_address), datalen);
2897 /*! \todo XXX If there's no Content-Length or if the content-length and what
2898 we receive is not the same - we should generate an error */
2903 * \brief Indication of a TCP message's integrity
2905 enum message_integrity {
2907 * The message has an error in it with
2908 * regards to its Content-Length header
2912 * The message is incomplete
2916 * The data contains a complete message
2917 * plus a fragment of another.
2919 MESSAGE_FRAGMENT_COMPLETE,
2921 * The message is complete
2928 * Get the content length from an unparsed SIP message
2930 * \param message The unparsed SIP message headers
2931 * \return The value of the Content-Length header or -1 if message is invalid
2933 static int read_raw_content_length(const char *message)
2935 char *content_length_str;
2936 int content_length = -1;
2938 struct ast_str *msg_copy;
2941 /* Using a ast_str because lws2sws takes one of those */
2942 if (!(msg_copy = ast_str_create(strlen(message) + 1))) {
2945 ast_str_set(&msg_copy, 0, "%s", message);
2947 if (sip_cfg.pedanticsipchecking) {
2951 msg = ast_str_buffer(msg_copy);
2953 /* Let's find a Content-Length header */
2954 if ((content_length_str = strcasestr(msg, "\nContent-Length:"))) {
2955 content_length_str += sizeof("\nContent-Length:") - 1;
2956 } else if ((content_length_str = strcasestr(msg, "\nl:"))) {
2957 content_length_str += sizeof("\nl:") - 1;
2960 * "In the case of stream-oriented transports such as TCP, the Content-
2961 * Length header field indicates the size of the body. The Content-
2962 * Length header field MUST be used with stream oriented transports."
2967 /* Double-check that this is a complete header */
2968 if (!strchr(content_length_str, '\n')) {
2972 if (sscanf(content_length_str, "%30d", &content_length) != 1) {
2973 content_length = -1;
2978 return content_length;
2982 * \brief Check that a message received over TCP is a full message
2984 * This will take the information read in and then determine if
2985 * 1) The message is a full SIP request
2986 * 2) The message is a partial SIP request
2987 * 3) The message contains a full SIP request along with another partial request
2988 * \param data The unparsed incoming SIP message.
2989 * \param request The resulting request with extra fragments removed.
2990 * \param overflow If the message contains more than a full request, this is the remainder of the message
2991 * \return The resulting integrity of the message
2993 static enum message_integrity check_message_integrity(struct ast_str **request, struct ast_str **overflow)
2995 char *message = ast_str_buffer(*request);
2998 int message_len = ast_str_strlen(*request);
3001 /* Important pieces to search for in a SIP request are \r\n\r\n. This
3003 * 1) The division between the headers and body
3004 * 2) The end of the SIP request
3006 body = strstr(message, "\r\n\r\n");
3008 /* This is clearly a partial message since we haven't reached an end
3011 return MESSAGE_FRAGMENT;
3013 body += sizeof("\r\n\r\n") - 1;
3014 body_len = message_len - (body - message);
3017 content_length = read_raw_content_length(message);
3020 if (content_length < 0) {
3021 return MESSAGE_INVALID;
3022 } else if (content_length == 0) {
3023 /* We've definitely received an entire message. We need
3024 * to check if there's also a fragment of another message
3027 if (body_len == 0) {
3028 return MESSAGE_COMPLETE;
3030 ast_str_append(overflow, 0, "%s", body);
3031 ast_str_truncate(*request, message_len - body_len);
3032 return MESSAGE_FRAGMENT_COMPLETE;
3035 /* Positive content length. Let's see what sort of
3036 * message body we're dealing with.
3038 if (body_len < content_length) {
3039 /* We don't have the full message body yet */
3040 return MESSAGE_FRAGMENT;
3041 } else if (body_len > content_length) {
3042 /* We have the full message plus a fragment of a further
3045 ast_str_append(overflow, 0, "%s", body + content_length);
3046 ast_str_truncate(*request, message_len - (body_len - content_length));
3047 return MESSAGE_FRAGMENT_COMPLETE;
3049 /* Yay! Full message with no extra content */
3050 return MESSAGE_COMPLETE;
3055 * \brief Read SIP request or response from a TCP connection
3057 * \param req The request structure to be filled in
3058 * \param tcptls_session The TCP connection from which to read
3059 * \retval -1 Failed to read data
3060 * \retval 0 Successfully read data
3062 static int sip_tcp_read(struct sip_request *req, struct ast_tcptls_session_instance *tcptls_session,
3063 int authenticated, time_t start)
3065 enum message_integrity message_integrity = MESSAGE_FRAGMENT;
3067 while (message_integrity == MESSAGE_FRAGMENT) {
3070 if (ast_str_strlen(tcptls_session->overflow_buf) == 0) {
3074 if (!tcptls_session->client && !authenticated) {
3075 if ((timeout = sip_check_authtimeout(start)) < 0) {
3080 ast_debug(2, "SIP TCP server timed out\n");
3086 res = ast_wait_for_input(tcptls_session->fd, timeout);
3088 ast_debug(2, "SIP TCP server :: ast_wait_for_input returned %d\n", res);
3090 } else if (res == 0) {
3091 ast_debug(2, "SIP TCP server timed out\n");
3095 res = recv(tcptls_session->fd, readbuf, sizeof(readbuf) - 1, 0);
3097 ast_debug(2, "SIP TCP server error when receiving data\n");