Direct Media calls within private network sometimes get one way audio
[asterisk/asterisk.git] / channels / chan_sip.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2012, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*!
20  * \file
21  * \brief Implementation of Session Initiation Protocol
22  *
23  * \author Mark Spencer <markster@digium.com>
24  *
25  * See Also:
26  * \arg \ref AstCREDITS
27  *
28  * Implementation of RFC 3261 - without S/MIME, and experimental TCP and TLS support
29  * Configuration file \link Config_sip sip.conf \endlink
30  *
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
35  *
36  *
37  * ******** General TODO:s
38  * \todo Better support of forking
39  * \todo VIA branch tag transaction checking
40  * \todo Transaction support
41  *
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
46  *
47  * \ingroup channel_drivers
48  *
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)
57  * - SIP text messages
58  *
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"
63  *
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.
69  *
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.
76  *
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.
82  *
83  * The actual media - Video or Audio - is mostly handled by the RTP subsystem
84  * in rtp.c
85  *
86  * \par Outbound calls
87  * Outbound calls are set up by the PBX through the sip_request_call()
88  * function. After that, they are activated by sip_call().
89  *
90  * \par Hanging up
91  * The PBX issues a hangup on both incoming and outgoing calls through
92  * the sip_hangup() function
93  */
94
95 /*! \li \ref chan_sip.c uses configuration files \ref sip.conf and \ref sip_notify.conf
96  * \addtogroup configuration_file
97  */
98
99 /*! \page sip.conf sip.conf
100  * \verbinclude sip.conf.sample
101  */
102
103 /*! \page sip_notify.conf sip_notify.conf
104  * \verbinclude sip_notify.conf.sample
105  */
106
107 /*!
108  * \page sip_tcp_tls SIP TCP and TLS support
109  *
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 CHANNEL function
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
126  *
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.
130  *
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.
136  *
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.
151  *
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
164  *        a bad guess.
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.
174  */
175
176 /*** MODULEINFO
177         <use type="module">res_crypto</use>
178         <use type="module">res_http_websocket</use>
179         <support_level>extended</support_level>
180  ***/
181
182 /*!  \page sip_session_timers SIP Session Timers in Asterisk Chan_sip
183
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).
190
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"]
198
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:
201
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.
219
220 */
221
222 #include "asterisk.h"
223
224 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
225
226 #include <signal.h>
227 #include <sys/signal.h>
228 #include <regex.h>
229 #include <inttypes.h>
230
231 #include "asterisk/network.h"
232 #include "asterisk/paths.h"     /* need ast_config_AST_SYSTEM_NAME */
233 #include "asterisk/lock.h"
234 #include "asterisk/config.h"
235 #include "asterisk/module.h"
236 #include "asterisk/pbx.h"
237 #include "asterisk/sched.h"
238 #include "asterisk/io.h"
239 #include "asterisk/rtp_engine.h"
240 #include "asterisk/udptl.h"
241 #include "asterisk/acl.h"
242 #include "asterisk/manager.h"
243 #include "asterisk/callerid.h"
244 #include "asterisk/cli.h"
245 #include "asterisk/musiconhold.h"
246 #include "asterisk/dsp.h"
247 #include "asterisk/pickup.h"
248 #include "asterisk/parking.h"
249 #include "asterisk/srv.h"
250 #include "asterisk/astdb.h"
251 #include "asterisk/causes.h"
252 #include "asterisk/utils.h"
253 #include "asterisk/file.h"
254 #include "asterisk/astobj2.h"
255 #include "asterisk/dnsmgr.h"
256 #include "asterisk/devicestate.h"
257 #include "asterisk/monitor.h"
258 #include "asterisk/netsock2.h"
259 #include "asterisk/localtime.h"
260 #include "asterisk/abstract_jb.h"
261 #include "asterisk/threadstorage.h"
262 #include "asterisk/translate.h"
263 #include "asterisk/ast_version.h"
264 #include "asterisk/data.h"
265 #include "asterisk/aoc.h"
266 #include "asterisk/message.h"
267 #include "sip/include/sip.h"
268 #include "sip/include/globals.h"
269 #include "sip/include/config_parser.h"
270 #include "sip/include/reqresp_parser.h"
271 #include "sip/include/sip_utils.h"
272 #include "asterisk/sdp_srtp.h"
273 #include "asterisk/ccss.h"
274 #include "asterisk/xml.h"
275 #include "sip/include/dialog.h"
276 #include "sip/include/dialplan_functions.h"
277 #include "sip/include/security_events.h"
278 #include "sip/include/route.h"
279 #include "asterisk/sip_api.h"
280 #include "asterisk/app.h"
281 #include "asterisk/bridge.h"
282 #include "asterisk/stasis.h"
283 #include "asterisk/stasis_endpoints.h"
284 #include "asterisk/stasis_system.h"
285 #include "asterisk/stasis_channels.h"
286 #include "asterisk/features_config.h"
287 #include "asterisk/http_websocket.h"
288 #include "asterisk/format_cache.h"
289
290 /*** DOCUMENTATION
291         <application name="SIPDtmfMode" language="en_US">
292                 <synopsis>
293                         Change the dtmfmode for a SIP call.
294                 </synopsis>
295                 <syntax>
296                         <parameter name="mode" required="true">
297                                 <enumlist>
298                                         <enum name="inband" />
299                                         <enum name="info" />
300                                         <enum name="rfc2833" />
301                                 </enumlist>
302                         </parameter>
303                 </syntax>
304                 <description>
305                         <para>Changes the dtmfmode for a SIP call.</para>
306                 </description>
307         </application>
308         <application name="SIPAddHeader" language="en_US">
309                 <synopsis>
310                         Add a SIP header to the outbound call.
311                 </synopsis>
312                 <syntax argsep=":">
313                         <parameter name="Header" required="true" />
314                         <parameter name="Content" required="true" />
315                 </syntax>
316                 <description>
317                         <para>Adds a header to a SIP call placed with DIAL.</para>
318                         <para>Remember to use the X-header if you are adding non-standard SIP
319                         headers, like <literal>X-Asterisk-Accountcode:</literal>. Use this with care.
320                         Adding the wrong headers may jeopardize the SIP dialog.</para>
321                         <para>Always returns <literal>0</literal>.</para>
322                 </description>
323         </application>
324         <application name="SIPRemoveHeader" language="en_US">
325                 <synopsis>
326                         Remove SIP headers previously added with SIPAddHeader
327                 </synopsis>
328                 <syntax>
329                         <parameter name="Header" required="false" />
330                 </syntax>
331                 <description>
332                         <para>SIPRemoveHeader() allows you to remove headers which were previously
333                         added with SIPAddHeader(). If no parameter is supplied, all previously added
334                         headers will be removed. If a parameter is supplied, only the matching headers
335                         will be removed.</para>
336                         <para>For example you have added these 2 headers:</para>
337                         <para>SIPAddHeader(P-Asserted-Identity: sip:foo@bar);</para>
338                         <para>SIPAddHeader(P-Preferred-Identity: sip:bar@foo);</para>
339                         <para></para>
340                         <para>// remove all headers</para>
341                         <para>SIPRemoveHeader();</para>
342                         <para>// remove all P- headers</para>
343                         <para>SIPRemoveHeader(P-);</para>
344                         <para>// remove only the PAI header (note the : at the end)</para>
345                         <para>SIPRemoveHeader(P-Asserted-Identity:);</para>
346                         <para></para>
347                         <para>Always returns <literal>0</literal>.</para>
348                 </description>
349         </application>
350         <application name="SIPSendCustomINFO" language="en_US">
351                 <synopsis>
352                         Send a custom INFO frame on specified channels.
353                 </synopsis>
354                 <syntax>
355                         <parameter name="Data" required="true" />
356                         <parameter name="UserAgent" required="false" />
357                 </syntax>
358                 <description>
359                         <para>SIPSendCustomINFO() allows you to send a custom INFO message on all
360                         active SIP channels or on channels with the specified User Agent. This
361                         application is only available if TEST_FRAMEWORK is defined.</para>
362                 </description>
363         </application>
364         <function name="SIP_HEADER" language="en_US">
365                 <synopsis>
366                         Gets the specified SIP header from an incoming INVITE message.
367                 </synopsis>
368                 <syntax>
369                         <parameter name="name" required="true" />
370                         <parameter name="number">
371                                 <para>If not specified, defaults to <literal>1</literal>.</para>
372                         </parameter>
373                 </syntax>
374                 <description>
375                         <para>Since there are several headers (such as Via) which can occur multiple
376                         times, SIP_HEADER takes an optional second argument to specify which header with
377                         that name to retrieve. Headers start at offset <literal>1</literal>.</para>
378                         <para>Please observe that contents of the SDP (an attachment to the
379                         SIP request) can't be accessed with this function.</para>
380                 </description>
381         </function>
382         <function name="SIPPEER" language="en_US">
383                 <synopsis>
384                         Gets SIP peer information.
385                 </synopsis>
386                 <syntax>
387                         <parameter name="peername" required="true" />
388                         <parameter name="item">
389                                 <enumlist>
390                                         <enum name="ip">
391                                                 <para>(default) The IP address.</para>
392                                         </enum>
393                                         <enum name="port">
394                                                 <para>The port number.</para>
395                                         </enum>
396                                         <enum name="mailbox">
397                                                 <para>The configured mailbox.</para>
398                                         </enum>
399                                         <enum name="context">
400                                                 <para>The configured context.</para>
401                                         </enum>
402                                         <enum name="expire">
403                                                 <para>The epoch time of the next expire.</para>
404                                         </enum>
405                                         <enum name="dynamic">
406                                                 <para>Is it dynamic? (yes/no).</para>
407                                         </enum>
408                                         <enum name="callerid_name">
409                                                 <para>The configured Caller ID name.</para>
410                                         </enum>
411                                         <enum name="callerid_num">
412                                                 <para>The configured Caller ID number.</para>
413                                         </enum>
414                                         <enum name="callgroup">
415                                                 <para>The configured Callgroup.</para>
416                                         </enum>
417                                         <enum name="pickupgroup">
418                                                 <para>The configured Pickupgroup.</para>
419                                         </enum>
420                                         <enum name="namedcallgroup">
421                                                 <para>The configured Named Callgroup.</para>
422                                         </enum>
423                                         <enum name="namedpickupgroup">
424                                                 <para>The configured Named Pickupgroup.</para>
425                                         </enum>
426                                         <enum name="codecs">
427                                                 <para>The configured codecs.</para>
428                                         </enum>
429                                         <enum name="status">
430                                                 <para>Status (if qualify=yes).</para>
431                                         </enum>
432                                         <enum name="regexten">
433                                                 <para>Extension activated at registration.</para>
434                                         </enum>
435                                         <enum name="limit">
436                                                 <para>Call limit (call-limit).</para>
437                                         </enum>
438                                         <enum name="busylevel">
439                                                 <para>Configured call level for signalling busy.</para>
440                                         </enum>
441                                         <enum name="curcalls">
442                                                 <para>Current amount of calls. Only available if call-limit is set.</para>
443                                         </enum>
444                                         <enum name="language">
445                                                 <para>Default language for peer.</para>
446                                         </enum>
447                                         <enum name="accountcode">
448                                                 <para>Account code for this peer.</para>
449                                         </enum>
450                                         <enum name="useragent">
451                                                 <para>Current user agent header used by peer.</para>
452                                         </enum>
453                                         <enum name="maxforwards">
454                                                 <para>The value used for SIP loop prevention in outbound requests</para>
455                                         </enum>
456                                         <enum name="chanvar[name]">
457                                                 <para>A channel variable configured with setvar for this peer.</para>
458                                         </enum>
459                                         <enum name="codec[x]">
460                                                 <para>Preferred codec index number <replaceable>x</replaceable> (beginning with zero).</para>
461                                         </enum>
462                                 </enumlist>
463                         </parameter>
464                 </syntax>
465                 <description></description>
466         </function>
467         <function name="CHECKSIPDOMAIN" language="en_US">
468                 <synopsis>
469                         Checks if domain is a local domain.
470                 </synopsis>
471                 <syntax>
472                         <parameter name="domain" required="true" />
473                 </syntax>
474                 <description>
475                         <para>This function checks if the <replaceable>domain</replaceable> in the argument is configured
476                         as a local SIP domain that this Asterisk server is configured to handle.
477                         Returns the domain name if it is locally handled, otherwise an empty string.
478                         Check the <literal>domain=</literal> configuration in <filename>sip.conf</filename>.</para>
479                 </description>
480         </function>
481         <manager name="SIPpeers" language="en_US">
482                 <synopsis>
483                         List SIP peers (text format).
484                 </synopsis>
485                 <syntax>
486                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
487                 </syntax>
488                 <description>
489                         <para>Lists SIP peers in text format with details on current status.
490                         <literal>Peerlist</literal> will follow as separate events, followed by a final event called
491                         <literal>PeerlistComplete</literal>.</para>
492                 </description>
493         </manager>
494         <manager name="SIPshowpeer" language="en_US">
495                 <synopsis>
496                         show SIP peer (text format).
497                 </synopsis>
498                 <syntax>
499                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
500                         <parameter name="Peer" required="true">
501                                 <para>The peer name you want to check.</para>
502                         </parameter>
503                 </syntax>
504                 <description>
505                         <para>Show one SIP peer with details on current status.</para>
506                 </description>
507         </manager>
508         <manager name="SIPqualifypeer" language="en_US">
509                 <synopsis>
510                         Qualify SIP peers.
511                 </synopsis>
512                 <syntax>
513                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
514                         <parameter name="Peer" required="true">
515                                 <para>The peer name you want to qualify.</para>
516                         </parameter>
517                 </syntax>
518                 <description>
519                         <para>Qualify a SIP peer.</para>
520                 </description>
521                 <see-also>
522                         <ref type="managerEvent">SIPQualifyPeerDone</ref>
523                 </see-also>
524         </manager>
525         <manager name="SIPshowregistry" language="en_US">
526                 <synopsis>
527                         Show SIP registrations (text format).
528                 </synopsis>
529                 <syntax>
530                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
531                 </syntax>
532                 <description>
533                         <para>Lists all registration requests and status. Registrations will follow as separate
534                         events followed by a final event called <literal>RegistrationsComplete</literal>.</para>
535                 </description>
536         </manager>
537         <manager name="SIPnotify" language="en_US">
538                 <synopsis>
539                         Send a SIP notify.
540                 </synopsis>
541                 <syntax>
542                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
543                         <parameter name="Channel" required="true">
544                                 <para>Peer to receive the notify.</para>
545                         </parameter>
546                         <parameter name="Variable" required="true">
547                                 <para>At least one variable pair must be specified.
548                                 <replaceable>name</replaceable>=<replaceable>value</replaceable></para>
549                         </parameter>
550                 </syntax>
551                 <description>
552                         <para>Sends a SIP Notify event.</para>
553                         <para>All parameters for this event must be specified in the body of this request
554                         via multiple <literal>Variable: name=value</literal> sequences.</para>
555                 </description>
556         </manager>
557         <manager name="SIPpeerstatus" language="en_US">
558                 <synopsis>
559                         Show the status of one or all of the sip peers.
560                 </synopsis>
561                 <syntax>
562                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
563                         <parameter name="Peer" required="false">
564                                 <para>The peer name you want to check.</para>
565                         </parameter>
566                 </syntax>
567                 <description>
568                         <para>Retrieves the status of one or all of the sip peers.  If no peer name is specified, status
569                         for all of the sip peers will be retrieved.</para>
570                 </description>
571         </manager>
572         <info name="SIPMessageFromInfo" language="en_US" tech="SIP">
573                 <para>The <literal>from</literal> parameter can be a configured peer name
574                 or in the form of "display-name" &lt;URI&gt;.</para>
575         </info>
576         <info name="SIPMessageToInfo" language="en_US" tech="SIP">
577                 <para>Specifying a prefix of <literal>sip:</literal> will send the
578                 message as a SIP MESSAGE request.</para>
579         </info>
580         <managerEvent language="en_US" name="SIPQualifyPeerDone">
581                 <managerEventInstance class="EVENT_FLAG_CALL">
582                         <synopsis>Raised when SIPQualifyPeer has finished qualifying the specified peer.</synopsis>
583                         <syntax>
584                                 <parameter name="Peer">
585                                         <para>The name of the peer.</para>
586                                 </parameter>
587                                 <parameter name="ActionID">
588                                         <para>This is only included if an ActionID Header was sent with the action request, in which case it will be that ActionID.</para>
589                                 </parameter>
590                         </syntax>
591                         <see-also>
592                                 <ref type="manager">SIPqualifypeer</ref>
593                         </see-also>
594                 </managerEventInstance>
595         </managerEvent>
596         <managerEvent language="en_US" name="SessionTimeout">
597                 <managerEventInstance class="EVENT_FLAG_CALL">
598                         <synopsis>Raised when a SIP session times out.</synopsis>
599                         <syntax>
600                                 <channel_snapshot/>
601                                 <parameter name="Source">
602                                         <para>The source of the session timeout.</para>
603                                         <enumlist>
604                                                 <enum name="RTPTimeout" />
605                                                 <enum name="SIPSessionTimer" />
606                                         </enumlist>
607                                 </parameter>
608                         </syntax>
609                 </managerEventInstance>
610         </managerEvent>
611  ***/
612
613 static int min_expiry = DEFAULT_MIN_EXPIRY;        /*!< Minimum accepted registration time */
614 static int max_expiry = DEFAULT_MAX_EXPIRY;        /*!< Maximum accepted registration time */
615 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
616 static int min_subexpiry = DEFAULT_MIN_EXPIRY;     /*!< Minimum accepted subscription time */
617 static int max_subexpiry = DEFAULT_MAX_EXPIRY;     /*!< Maximum accepted subscription time */
618 static int mwi_expiry = DEFAULT_MWI_EXPIRY;
619
620 static int unauth_sessions = 0;
621 static int authlimit = DEFAULT_AUTHLIMIT;
622 static int authtimeout = DEFAULT_AUTHTIMEOUT;
623
624 /*! \brief Global jitterbuffer configuration - by default, jb is disabled
625  *  \note Values shown here match the defaults shown in sip.conf.sample */
626 static struct ast_jb_conf default_jbconf =
627 {
628         .flags = 0,
629         .max_size = 200,
630         .resync_threshold = 1000,
631         .impl = "fixed",
632         .target_extra = 40,
633 };
634 static struct ast_jb_conf global_jbconf;                /*!< Global jitterbuffer configuration */
635
636 static const char config[] = "sip.conf";                /*!< Main configuration file */
637 static const char notify_config[] = "sip_notify.conf";  /*!< Configuration file for sending Notify with CLI commands to reconfigure or reboot phones */
638
639 /*! \brief Readable descriptions of device states.
640  *  \note Should be aligned to above table as index */
641 static const struct invstate2stringtable {
642         const enum invitestates state;
643         const char *desc;
644 } invitestate2string[] = {
645         {INV_NONE,              "None"  },
646         {INV_CALLING,           "Calling (Trying)"},
647         {INV_PROCEEDING,        "Proceeding "},
648         {INV_EARLY_MEDIA,       "Early media"},
649         {INV_COMPLETED,         "Completed (done)"},
650         {INV_CONFIRMED,         "Confirmed (up)"},
651         {INV_TERMINATED,        "Done"},
652         {INV_CANCELLED,         "Cancelled"}
653 };
654
655 /*! \brief Subscription types that we support. We support
656  * - dialoginfo updates (really device status, not dialog info as was the original intent of the standard)
657  * - SIMPLE presence used for device status
658  * - Voicemail notification subscriptions
659  */
660 static const struct cfsubscription_types {
661         enum subscriptiontype type;
662         const char * const event;
663         const char * const mediatype;
664         const char * const text;
665 } subscription_types[] = {
666         { NONE,            "-",        "unknown",                    "unknown" },
667         /* RFC 4235: SIP Dialog event package */
668         { DIALOG_INFO_XML, "dialog",   "application/dialog-info+xml", "dialog-info+xml" },
669         { CPIM_PIDF_XML,   "presence", "application/cpim-pidf+xml",   "cpim-pidf+xml" },  /* RFC 3863 */
670         { PIDF_XML,        "presence", "application/pidf+xml",        "pidf+xml" },       /* RFC 3863 */
671         { XPIDF_XML,       "presence", "application/xpidf+xml",       "xpidf+xml" },       /* Pre-RFC 3863 with MS additions */
672         { MWI_NOTIFICATION,     "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
673 };
674
675 /*! \brief The core structure to setup dialogs. We parse incoming messages by using
676  *  structure and then route the messages according to the type.
677  *
678  *  \note Note that sip_methods[i].id == i must hold or the code breaks
679  */
680 static const struct  cfsip_methods {
681         enum sipmethod id;
682         int need_rtp;           /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
683         char * const text;
684         enum can_create_dialog can_create;
685 } sip_methods[] = {
686         { SIP_UNKNOWN,   RTP,    "-UNKNOWN-",CAN_CREATE_DIALOG },
687         { SIP_RESPONSE,  NO_RTP, "SIP/2.0",  CAN_NOT_CREATE_DIALOG },
688         { SIP_REGISTER,  NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
689         { SIP_OPTIONS,   NO_RTP, "OPTIONS",  CAN_CREATE_DIALOG },
690         { SIP_NOTIFY,    NO_RTP, "NOTIFY",   CAN_CREATE_DIALOG },
691         { SIP_INVITE,    RTP,    "INVITE",   CAN_CREATE_DIALOG },
692         { SIP_ACK,       NO_RTP, "ACK",      CAN_NOT_CREATE_DIALOG },
693         { SIP_PRACK,     NO_RTP, "PRACK",    CAN_NOT_CREATE_DIALOG },
694         { SIP_BYE,       NO_RTP, "BYE",      CAN_NOT_CREATE_DIALOG },
695         { SIP_REFER,     NO_RTP, "REFER",    CAN_CREATE_DIALOG },
696         { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE",CAN_CREATE_DIALOG },
697         { SIP_MESSAGE,   NO_RTP, "MESSAGE",  CAN_CREATE_DIALOG },
698         { SIP_UPDATE,    NO_RTP, "UPDATE",   CAN_NOT_CREATE_DIALOG },
699         { SIP_INFO,      NO_RTP, "INFO",     CAN_NOT_CREATE_DIALOG },
700         { SIP_CANCEL,    NO_RTP, "CANCEL",   CAN_NOT_CREATE_DIALOG },
701         { SIP_PUBLISH,   NO_RTP, "PUBLISH",  CAN_CREATE_DIALOG },
702         { SIP_PING,      NO_RTP, "PING",     CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
703 };
704
705 /*! \brief Diversion header reasons
706  *
707  * The core defines a bunch of constants used to define
708  * redirecting reasons. This provides a translation table
709  * between those and the strings which may be present in
710  * a SIP Diversion header
711  */
712 static const struct sip_reasons {
713         enum AST_REDIRECTING_REASON code;
714         char * const text;
715 } sip_reason_table[] = {
716         { AST_REDIRECTING_REASON_UNKNOWN, "unknown" },
717         { AST_REDIRECTING_REASON_USER_BUSY, "user-busy" },
718         { AST_REDIRECTING_REASON_NO_ANSWER, "no-answer" },
719         { AST_REDIRECTING_REASON_UNAVAILABLE, "unavailable" },
720         { AST_REDIRECTING_REASON_UNCONDITIONAL, "unconditional" },
721         { AST_REDIRECTING_REASON_TIME_OF_DAY, "time-of-day" },
722         { AST_REDIRECTING_REASON_DO_NOT_DISTURB, "do-not-disturb" },
723         { AST_REDIRECTING_REASON_DEFLECTION, "deflection" },
724         { AST_REDIRECTING_REASON_FOLLOW_ME, "follow-me" },
725         { AST_REDIRECTING_REASON_OUT_OF_ORDER, "out-of-service" },
726         { AST_REDIRECTING_REASON_AWAY, "away" },
727         { AST_REDIRECTING_REASON_CALL_FWD_DTE, "unknown"},
728         { AST_REDIRECTING_REASON_SEND_TO_VM, "send_to_vm"},
729 };
730
731
732 /*! \name DefaultSettings
733         Default setttings are used as a channel setting and as a default when
734         configuring devices
735 */
736 static char default_language[MAX_LANGUAGE];      /*!< Default language setting for new channels */
737 static char default_callerid[AST_MAX_EXTENSION]; /*!< Default caller ID for sip messages */
738 static char default_mwi_from[80];                /*!< Default caller ID for MWI updates */
739 static char default_fromdomain[AST_MAX_EXTENSION]; /*!< Default domain on outound messages */
740 static int default_fromdomainport;                 /*!< Default domain port on outbound messages */
741 static char default_notifymime[AST_MAX_EXTENSION]; /*!< Default MIME media type for MWI notify messages */
742 static char default_vmexten[AST_MAX_EXTENSION];    /*!< Default From Username on MWI updates */
743 static int default_qualify;                        /*!< Default Qualify= setting */
744 static int default_keepalive;                      /*!< Default keepalive= setting */
745 static char default_mohinterpret[MAX_MUSICCLASS];  /*!< Global setting for moh class to use when put on hold */
746 static char default_mohsuggest[MAX_MUSICCLASS];    /*!< Global setting for moh class to suggest when putting
747                                                     *   a bridged channel on hold */
748 static char default_parkinglot[AST_MAX_CONTEXT];   /*!< Parkinglot */
749 static char default_engine[256];                   /*!< Default RTP engine */
750 static int default_maxcallbitrate;                 /*!< Maximum bitrate for call */
751 static char default_zone[MAX_TONEZONE_COUNTRY];        /*!< Default tone zone for channels created from the SIP driver */
752 static unsigned int default_transports;            /*!< Default Transports (enum ast_transport) that are acceptable */
753 static unsigned int default_primary_transport;     /*!< Default primary Transport (enum ast_transport) for outbound connections to devices */
754
755 static struct sip_settings sip_cfg;             /*!< SIP configuration data.
756                                         \note in the future we could have multiple of these (per domain, per device group etc) */
757
758 /*!< use this macro when ast_uri_decode is dependent on pedantic checking to be on. */
759 #define SIP_PEDANTIC_DECODE(str)        \
760         if (sip_cfg.pedanticsipchecking && !ast_strlen_zero(str)) {     \
761                 ast_uri_decode(str, ast_uri_sip_user);  \
762         }       \
763
764 static unsigned int chan_idx;       /*!< used in naming sip channel */
765 static int global_match_auth_username;    /*!< Match auth username if available instead of From: Default off. */
766
767 static int global_relaxdtmf;        /*!< Relax DTMF */
768 static int global_prematuremediafilter;   /*!< Enable/disable premature frames in a call (causing 183 early media) */
769 static int global_rtptimeout;       /*!< Time out call if no RTP */
770 static int global_rtpholdtimeout;   /*!< Time out call if no RTP during hold */
771 static int global_rtpkeepalive;     /*!< Send RTP keepalives */
772 static int global_reg_timeout;      /*!< Global time between attempts for outbound registrations */
773 static int global_regattempts_max;  /*!< Registration attempts before giving up */
774 static int global_reg_retry_403;    /*!< Treat 403 responses to registrations as 401 responses */
775 static int global_shrinkcallerid;   /*!< enable or disable shrinking of caller id  */
776 static int global_callcounter;      /*!< Enable call counters for all devices. This is currently enabled by setting the peer
777                                      *   call-limit to INT_MAX. When we remove the call-limit from the code, we can make it
778                                      *   with just a boolean flag in the device structure */
779 static unsigned int global_tos_sip;      /*!< IP type of service for SIP packets */
780 static unsigned int global_tos_audio;    /*!< IP type of service for audio RTP packets */
781 static unsigned int global_tos_video;    /*!< IP type of service for video RTP packets */
782 static unsigned int global_tos_text;     /*!< IP type of service for text RTP packets */
783 static unsigned int global_cos_sip;      /*!< 802.1p class of service for SIP packets */
784 static unsigned int global_cos_audio;    /*!< 802.1p class of service for audio RTP packets */
785 static unsigned int global_cos_video;    /*!< 802.1p class of service for video RTP packets */
786 static unsigned int global_cos_text;     /*!< 802.1p class of service for text RTP packets */
787 static unsigned int recordhistory;       /*!< Record SIP history. Off by default */
788 static unsigned int dumphistory;         /*!< Dump history to verbose before destroying SIP dialog */
789 static char global_useragent[AST_MAX_EXTENSION];    /*!< Useragent for the SIP channel */
790 static char global_sdpsession[AST_MAX_EXTENSION];   /*!< SDP session name for the SIP channel */
791 static char global_sdpowner[AST_MAX_EXTENSION];     /*!< SDP owner name for the SIP channel */
792 static int global_authfailureevents;     /*!< Whether we send authentication failure manager events or not. Default no. */
793 static int global_t1;           /*!< T1 time */
794 static int global_t1min;        /*!< T1 roundtrip time minimum */
795 static int global_timer_b;      /*!< Timer B - RFC 3261 Section 17.1.1.2 */
796 static unsigned int global_autoframing; /*!< Turn autoframing on or off. */
797 static int global_qualifyfreq;          /*!< Qualify frequency */
798 static int global_qualify_gap;          /*!< Time between our group of peer pokes */
799 static int global_qualify_peers;        /*!< Number of peers to poke at a given time */
800
801 static enum st_mode global_st_mode;           /*!< Mode of operation for Session-Timers           */
802 static enum st_refresher_param global_st_refresher; /*!< Session-Timer refresher                        */
803 static int global_min_se;                     /*!< Lowest threshold for session refresh interval  */
804 static int global_max_se;                     /*!< Highest threshold for session refresh interval */
805
806 static int global_store_sip_cause;    /*!< Whether the MASTER_CHANNEL(HASH(SIP_CAUSE,[chan_name])) var should be set */
807
808 static int global_dynamic_exclude_static = 0; /*!< Exclude static peers from contact registrations */
809 static unsigned char global_refer_addheaders; /*!< Add extra headers to outgoing REFER */
810 /*@}*/
811
812 /*!
813  * We use libxml2 in order to parse XML that may appear in the body of a SIP message. Currently,
814  * the only usage is for parsing PIDF bodies of incoming PUBLISH requests in the call-completion
815  * event package. This variable is set at module load time and may be checked at runtime to determine
816  * if XML parsing support was found.
817  */
818 static int can_parse_xml;
819
820 /*! \name Object counters @{
821  *
822  * \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
823  * should be used to modify these values.
824  */
825 static int speerobjs = 0;     /*!< Static peers */
826 static int rpeerobjs = 0;     /*!< Realtime peers */
827 static int apeerobjs = 0;     /*!< Autocreated peer objects */
828 /*! @} */
829
830 static struct ast_flags global_flags[3] = {{0}};  /*!< global SIP_ flags */
831 static unsigned int global_t38_maxdatagram;                /*!< global T.38 FaxMaxDatagram override */
832
833 static struct stasis_subscription *network_change_sub; /*!< subscription id for network change events */
834 static struct stasis_subscription *acl_change_sub; /*!< subscription id for named ACL system change events */
835 static int network_change_sched_id = -1;
836
837 static char used_context[AST_MAX_CONTEXT];        /*!< name of automatically created context for unloading */
838
839 AST_MUTEX_DEFINE_STATIC(netlock);
840
841 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
842    when it's doing something critical. */
843 AST_MUTEX_DEFINE_STATIC(monlock);
844
845 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
846
847 /*! \brief This is the thread for the monitor which checks for input on the channels
848    which are not currently in use.  */
849 static pthread_t monitor_thread = AST_PTHREADT_NULL;
850
851 static int sip_reloading = FALSE;                       /*!< Flag for avoiding multiple reloads at the same time */
852 static enum channelreloadreason sip_reloadreason;       /*!< Reason for last reload/load of configuration */
853
854 struct ast_sched_context *sched;     /*!< The scheduling context */
855 static struct io_context *io;           /*!< The IO context */
856 static int *sipsock_read_id;            /*!< ID of IO entry for sipsock FD */
857 struct sip_pkt;
858 static AST_LIST_HEAD_STATIC(domain_list, domain);    /*!< The SIP domain list */
859
860 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
861
862 static enum sip_debug_e sipdebug;
863
864 /*! \brief extra debugging for 'text' related events.
865  *  At the moment this is set together with sip_debug_console.
866  *  \note It should either go away or be implemented properly.
867  */
868 static int sipdebug_text;
869
870 static const struct _map_x_s referstatusstrings[] = {
871         { REFER_IDLE,      "<none>" },
872         { REFER_SENT,      "Request sent" },
873         { REFER_RECEIVED,  "Request received" },
874         { REFER_CONFIRMED, "Confirmed" },
875         { REFER_ACCEPTED,  "Accepted" },
876         { REFER_RINGING,   "Target ringing" },
877         { REFER_200OK,     "Done" },
878         { REFER_FAILED,    "Failed" },
879         { REFER_NOAUTH,    "Failed - auth failure" },
880         { -1,               NULL} /* terminator */
881 };
882
883 /* --- Hash tables of various objects --------*/
884 #ifdef LOW_MEMORY
885 static const int HASH_PEER_SIZE = 17;
886 static const int HASH_DIALOG_SIZE = 17;
887 static const int HASH_REGISTRY_SIZE = 17;
888 #else
889 static const int HASH_PEER_SIZE = 563;  /*!< Size of peer hash table, prime number preferred! */
890 static const int HASH_DIALOG_SIZE = 563;
891 static const int HASH_REGISTRY_SIZE = 563;
892 #endif
893
894 static const struct {
895         enum ast_cc_service_type service;
896         const char *service_string;
897 } sip_cc_service_map [] = {
898         [AST_CC_NONE] = { AST_CC_NONE, "" },
899         [AST_CC_CCBS] = { AST_CC_CCBS, "BS" },
900         [AST_CC_CCNR] = { AST_CC_CCNR, "NR" },
901         [AST_CC_CCNL] = { AST_CC_CCNL, "NL" },
902 };
903
904 static const struct {
905         enum sip_cc_notify_state state;
906         const char *state_string;
907 } sip_cc_notify_state_map [] = {
908         [CC_QUEUED] = {CC_QUEUED, "cc-state: queued"},
909         [CC_READY] = {CC_READY, "cc-state: ready"},
910 };
911
912 AST_LIST_HEAD_STATIC(epa_static_data_list, epa_backend);
913
914
915 /*!
916  * Used to create new entity IDs by ESCs.
917  */
918 static int esc_etag_counter;
919 static const int DEFAULT_PUBLISH_EXPIRES = 3600;
920
921 #ifdef HAVE_LIBXML2
922 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);
923
924 static const struct sip_esc_publish_callbacks cc_esc_publish_callbacks = {
925         .initial_handler = cc_esc_publish_handler,
926         .modify_handler = cc_esc_publish_handler,
927 };
928 #endif
929
930 /*!
931  * \brief The Event State Compositors
932  *
933  * An Event State Compositor is an entity which
934  * accepts PUBLISH requests and acts appropriately
935  * based on these requests.
936  *
937  * The actual event_state_compositor structure is simply
938  * an ao2_container of sip_esc_entrys. When an incoming
939  * PUBLISH is received, we can match the appropriate sip_esc_entry
940  * using the entity ID of the incoming PUBLISH.
941  */
942 static struct event_state_compositor {
943         enum subscriptiontype event;
944         const char * name;
945         const struct sip_esc_publish_callbacks *callbacks;
946         struct ao2_container *compositor;
947 } event_state_compositors [] = {
948 #ifdef HAVE_LIBXML2
949         {CALL_COMPLETION, "call-completion", &cc_esc_publish_callbacks},
950 #endif
951 };
952
953 struct state_notify_data {
954         int state;
955         struct ao2_container *device_state_info;
956         int presence_state;
957         const char *presence_subtype;
958         const char *presence_message;
959 };
960
961
962 static const int ESC_MAX_BUCKETS = 37;
963
964 /*!
965  * \details
966  * Here we implement the container for dialogs which are in the
967  * dialog_needdestroy state to iterate only through the dialogs
968  * unlink them instead of iterate through all dialogs
969  */
970 struct ao2_container *dialogs_needdestroy;
971
972 /*!
973  * \details
974  * Here we implement the container for dialogs which have rtp
975  * traffic and rtptimeout, rtpholdtimeout or rtpkeepalive
976  * set. We use this container instead the whole dialog list.
977  */
978 struct ao2_container *dialogs_rtpcheck;
979
980 /*!
981  * \details
982  * Here we implement the container for dialogs (sip_pvt), defining
983  * generic wrapper functions to ease the transition from the current
984  * implementation (a single linked list) to a different container.
985  * In addition to a reference to the container, we need functions to lock/unlock
986  * the container and individual items, and functions to add/remove
987  * references to the individual items.
988  */
989 static struct ao2_container *dialogs;
990 #define sip_pvt_lock(x) ao2_lock(x)
991 #define sip_pvt_trylock(x) ao2_trylock(x)
992 #define sip_pvt_unlock(x) ao2_unlock(x)
993
994 /*! \brief  The table of TCP threads */
995 static struct ao2_container *threadt;
996
997 /*! \brief  The peer list: Users, Peers and Friends */
998 static struct ao2_container *peers;
999 static struct ao2_container *peers_by_ip;
1000
1001 /*! \brief  A bogus peer, to be used when authentication should fail */
1002 static struct sip_peer *bogus_peer;
1003 /*! \brief  We can recognise the bogus peer by this invalid MD5 hash */
1004 #define BOGUS_PEER_MD5SECRET "intentionally_invalid_md5_string"
1005
1006 /*! \brief  The register list: Other SIP proxies we register with and receive calls from */
1007 static struct ao2_container *registry_list;
1008
1009 /*! \brief  The MWI subscription list */
1010 static struct ao2_container *subscription_mwi_list;
1011
1012 static int temp_pvt_init(void *);
1013 static void temp_pvt_cleanup(void *);
1014
1015 /*! \brief A per-thread temporary pvt structure */
1016 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
1017
1018 /*! \brief A per-thread buffer for transport to string conversion */
1019 AST_THREADSTORAGE(sip_transport_str_buf);
1020
1021 /*! \brief Size of the SIP transport buffer */
1022 #define SIP_TRANSPORT_STR_BUFSIZE 128
1023
1024 /*! \brief Authentication container for realm authentication */
1025 static struct sip_auth_container *authl = NULL;
1026 /*! \brief Global authentication container protection while adjusting the references. */
1027 AST_MUTEX_DEFINE_STATIC(authl_lock);
1028
1029 static struct ast_manager_event_blob *session_timeout_to_ami(struct stasis_message *msg);
1030 STASIS_MESSAGE_TYPE_DEFN_LOCAL(session_timeout_type,
1031         .to_ami = session_timeout_to_ami,
1032         );
1033
1034 /* --- Sockets and networking --------------*/
1035
1036 /*! \brief Main socket for UDP SIP communication.
1037  *
1038  * sipsock is shared between the SIP manager thread (which handles reload
1039  * requests), the udp io handler (sipsock_read()) and the user routines that
1040  * issue udp writes (using __sip_xmit()).
1041  * The socket is -1 only when opening fails (this is a permanent condition),
1042  * or when we are handling a reload() that changes its address (this is
1043  * a transient situation during which we might have a harmless race, see
1044  * below). Because the conditions for the race to be possible are extremely
1045  * rare, we don't want to pay the cost of locking on every I/O.
1046  * Rather, we remember that when the race may occur, communication is
1047  * bound to fail anyways, so we just live with this event and let
1048  * the protocol handle this above us.
1049  */
1050 static int sipsock  = -1;
1051
1052 struct ast_sockaddr bindaddr;   /*!< UDP: The address we bind to */
1053
1054 /*! \brief our (internal) default address/port to put in SIP/SDP messages
1055  *  internip is initialized picking a suitable address from one of the
1056  * interfaces, and the same port number we bind to. It is used as the
1057  * default address/port in SIP messages, and as the default address
1058  * (but not port) in SDP messages.
1059  */
1060 static struct ast_sockaddr internip;
1061
1062 /*! \brief our external IP address/port for SIP sessions.
1063  * externaddr.sin_addr is only set when we know we might be behind
1064  * a NAT, and this is done using a variety of (mutually exclusive)
1065  * ways from the config file:
1066  *
1067  * + with "externaddr = host[:port]" we specify the address/port explicitly.
1068  *   The address is looked up only once when (re)loading the config file;
1069  *
1070  * + with "externhost = host[:port]" we do a similar thing, but the
1071  *   hostname is stored in externhost, and the hostname->IP mapping
1072  *   is refreshed every 'externrefresh' seconds;
1073  *
1074  * Other variables (externhost, externexpire, externrefresh) are used
1075  * to support the above functions.
1076  */
1077 static struct ast_sockaddr externaddr;      /*!< External IP address if we are behind NAT */
1078 static struct ast_sockaddr media_address; /*!< External RTP IP address if we are behind NAT */
1079 static struct ast_sockaddr rtpbindaddr;   /*!< RTP: The address we bind to */
1080
1081 static char externhost[MAXHOSTNAMELEN];   /*!< External host name */
1082 static time_t externexpire;             /*!< Expiration counter for re-resolving external host name in dynamic DNS */
1083 static int externrefresh = 10;          /*!< Refresh timer for DNS-based external address (dyndns) */
1084 static uint16_t externtcpport;          /*!< external tcp port */
1085 static uint16_t externtlsport;          /*!< external tls port */
1086
1087 /*! \brief  List of local networks
1088  * We store "localnet" addresses from the config file into an access list,
1089  * marked as 'DENY', so the call to ast_apply_ha() will return
1090  * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
1091  * (i.e. presumably public) addresses.
1092  */
1093 static struct ast_ha *localaddr;    /*!< List of local networks, on the same side of NAT as this Asterisk */
1094
1095 static int ourport_tcp;             /*!< The port used for TCP connections */
1096 static int ourport_tls;             /*!< The port used for TCP/TLS connections */
1097 static struct ast_sockaddr debugaddr;
1098
1099 static struct ast_config *notify_types = NULL;    /*!< The list of manual NOTIFY types we know how to send */
1100
1101 /*! some list management macros. */
1102
1103 #define UNLINK(element, head, prev) do {        \
1104         if (prev)                               \
1105                 (prev)->next = (element)->next; \
1106         else                                    \
1107                 (head) = (element)->next;       \
1108         } while (0)
1109
1110 struct ao2_container *sip_monitor_instances;
1111
1112 struct show_peers_context;
1113
1114 /*---------------------------- Forward declarations of functions in chan_sip.c */
1115 /* Note: This is added to help splitting up chan_sip.c into several files
1116         in coming releases. */
1117
1118 /*--- PBX interface functions */
1119 static struct ast_channel *sip_request_call(const char *type, struct ast_format_cap *cap, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *dest, int *cause);
1120 static int sip_devicestate(const char *data);
1121 static int sip_sendtext(struct ast_channel *ast, const char *text);
1122 static int sip_call(struct ast_channel *ast, const char *dest, int timeout);
1123 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
1124 static int sip_hangup(struct ast_channel *ast);
1125 static int sip_answer(struct ast_channel *ast);
1126 static struct ast_frame *sip_read(struct ast_channel *ast);
1127 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
1128 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
1129 static int sip_transfer(struct ast_channel *ast, const char *dest);
1130 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1131 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
1132 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
1133 static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen);
1134 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
1135 static const char *sip_get_callid(struct ast_channel *chan);
1136
1137 static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr);
1138 static int sip_standard_port(enum ast_transport type, int port);
1139 static int sip_prepare_socket(struct sip_pvt *p);
1140 static int get_address_family_filter(unsigned int transport);
1141
1142 /*--- Transmitting responses and requests */
1143 static int sipsock_read(int *id, int fd, short events, void *ignore);
1144 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data);
1145 static int __sip_reliable_xmit(struct sip_pvt *p, uint32_t seqno, int resp, struct ast_str *data, int fatal, int sipmethod);
1146 static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp);
1147 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1148 static int retrans_pkt(const void *data);
1149 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);
1150 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1151 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1152 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1153 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);
1154 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
1155 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);
1156 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
1157 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1158 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable);
1159 static int transmit_request(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch);
1160 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch);
1161 static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri);
1162 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri);
1163 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
1164 static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded);
1165 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
1166 static int transmit_info_with_vidupdate(struct sip_pvt *p);
1167 static int transmit_message(struct sip_pvt *p, int init, int auth);
1168 static int transmit_refer(struct sip_pvt *p, const char *dest);
1169 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
1170 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
1171 static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state);
1172 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
1173 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno);
1174 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno);
1175 static void copy_request(struct sip_request *dst, const struct sip_request *src);
1176 static void receive_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
1177 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward);
1178 static int sip_send_mwi_to_peer(struct sip_peer *peer, int cache_only);
1179
1180 /* Misc dialog routines */
1181 static int __sip_autodestruct(const void *data);
1182 static int update_call_counter(struct sip_pvt *fup, int event);
1183 static int auto_congest(const void *arg);
1184 static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method);
1185 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards, int resp);
1186 static int build_path(struct sip_pvt *p, struct sip_peer *peer, struct sip_request *req, const char *pathbuf);
1187 static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
1188                                               struct sip_request *req, const char *uri);
1189 static int get_sip_pvt_from_replaces(const char *callid, const char *totag, const char *fromtag,
1190                 struct sip_pvt **out_pvt, struct ast_channel **out_chan);
1191 static void check_pendings(struct sip_pvt *p);
1192 static void sip_set_owner(struct sip_pvt *p, struct ast_channel *chan);
1193
1194 static void *sip_pickup_thread(void *stuff);
1195 static int sip_pickup(struct ast_channel *chan);
1196
1197 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1198 static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method);
1199
1200 /*--- Codec handling / SDP */
1201 static void try_suggested_sip_codec(struct sip_pvt *p);
1202 static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
1203 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
1204 static int find_sdp(struct sip_request *req);
1205 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
1206 static int process_sdp_o(const char *o, struct sip_pvt *p);
1207 static int process_sdp_c(const char *c, struct ast_sockaddr *addr);
1208 static int process_sdp_a_sendonly(const char *a, int *sendonly);
1209 static int process_sdp_a_ice(const char *a, struct sip_pvt *p, struct ast_rtp_instance *instance);
1210 static int process_sdp_a_dtls(const char *a, struct sip_pvt *p, struct ast_rtp_instance *instance);
1211 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec);
1212 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec);
1213 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);
1214 static int process_sdp_a_image(const char *a, struct sip_pvt *p);
1215 static void add_ice_to_sdp(struct ast_rtp_instance *instance, struct ast_str **a_buf);
1216 static void add_dtls_to_sdp(struct ast_rtp_instance *instance, struct ast_str **a_buf);
1217 static void start_ice(struct ast_rtp_instance *instance, int offer);
1218 static void add_codec_to_sdp(const struct sip_pvt *p, struct ast_format *codec,
1219                              struct ast_str **m_buf, struct ast_str **a_buf,
1220                              int debug, int *min_packet_size, int *max_packet_size);
1221 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
1222                                 struct ast_str **m_buf, struct ast_str **a_buf,
1223                                 int debug);
1224 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
1225 static void do_setnat(struct sip_pvt *p);
1226 static void stop_media_flows(struct sip_pvt *p);
1227
1228 /*--- Authentication stuff */
1229 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1230 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
1231 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1232                                          const char *secret, const char *md5secret, int sipmethod,
1233                                          const char *uri, enum xmittype reliable);
1234 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
1235                                               int sipmethod, const char *uri, enum xmittype reliable,
1236                                               struct ast_sockaddr *addr, struct sip_peer **authpeer);
1237 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr);
1238
1239 /*--- Domain handling */
1240 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1241 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
1242 static void clear_sip_domains(void);
1243
1244 /*--- SIP realm authentication */
1245 static void add_realm_authentication(struct sip_auth_container **credentials, const char *configuration, int lineno);
1246 static struct sip_auth *find_realm_authentication(struct sip_auth_container *credentials, const char *realm);
1247
1248 /*--- Misc functions */
1249 static int check_rtp_timeout(struct sip_pvt *dialog, time_t t);
1250 static int reload_config(enum channelreloadreason reason);
1251 static void add_diversion(struct sip_request *req, struct sip_pvt *pvt);
1252 static int expire_register(const void *data);
1253 static void *do_monitor(void *data);
1254 static int restart_monitor(void);
1255 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
1256 static struct ast_variable *copy_vars(struct ast_variable *src);
1257 static int dialog_find_multiple(void *obj, void *arg, int flags);
1258 static struct ast_channel *sip_pvt_lock_full(struct sip_pvt *pvt);
1259 /* static int sip_addrcmp(char *name, struct sockaddr_in *sin); Support for peer matching */
1260 static int sip_refer_alloc(struct sip_pvt *p);
1261 static void sip_refer_destroy(struct sip_pvt *p);
1262 static int sip_notify_alloc(struct sip_pvt *p);
1263 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
1264 static void set_peer_nat(const struct sip_pvt *p, struct sip_peer *peer);
1265 static void check_for_nat(const struct ast_sockaddr *them, struct sip_pvt *p);
1266
1267 /*--- Device monitoring and Device/extension state/event handling */
1268 static int extensionstate_update(const char *context, const char *exten, struct state_notify_data *data, struct sip_pvt *p, int force);
1269 static int cb_extensionstate(char *context, char *exten, struct ast_state_cb_info *info, void *data);
1270 static int sip_poke_noanswer(const void *data);
1271 static int sip_poke_peer(struct sip_peer *peer, int force);
1272 static void sip_poke_all_peers(void);
1273 static void sip_peer_hold(struct sip_pvt *p, int hold);
1274 static void mwi_event_cb(void *, struct stasis_subscription *, struct stasis_message *);
1275 static void network_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
1276 static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
1277 static void sip_keepalive_all_peers(void);
1278
1279 /*--- Applications, functions, CLI and manager command helpers */
1280 static const char *sip_nat_mode(const struct sip_pvt *p);
1281 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1282 static char *transfermode2str(enum transfermodes mode) attribute_const;
1283 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
1284 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1285 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1286 static struct sip_peer *_sip_show_peers_one(int fd, struct mansession *s, struct show_peers_context *cont, struct sip_peer *peer);
1287 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1288 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1289 static void  print_group(int fd, ast_group_t group, int crlf);
1290 static void  print_named_groups(int fd, struct ast_namedgroups *groups, int crlf);
1291 static const char *dtmfmode2str(int mode) attribute_const;
1292 static int str2dtmfmode(const char *str) attribute_unused;
1293 static const char *insecure2str(int mode) attribute_const;
1294 static const char *allowoverlap2str(int mode) attribute_const;
1295 static void cleanup_stale_contexts(char *new, char *old);
1296 static const char *domain_mode_to_text(const enum domain_mode mode);
1297 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1298 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1299 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1300 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1301 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1302 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1303 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1304 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1305 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1306 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
1307 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1308 static char *complete_sip_peer(const char *word, int state, int flags2);
1309 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
1310 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
1311 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
1312 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
1313 static char *complete_sip_notify(const char *line, const char *word, int pos, int state);
1314 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1315 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1316 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1317 static char *sip_do_debug_ip(int fd, const char *arg);
1318 static char *sip_do_debug_peer(int fd, const char *arg);
1319 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1320 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1321 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1322 static int sip_dtmfmode(struct ast_channel *chan, const char *data);
1323 static int sip_addheader(struct ast_channel *chan, const char *data);
1324 static int sip_do_reload(enum channelreloadreason reason);
1325 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1326 static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
1327                                       const char *name, int flag, int family);
1328 static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
1329                                       const char *name, int flag);
1330 static int ast_sockaddr_resolve_first_transport(struct ast_sockaddr *addr,
1331                                                 const char *name, int flag, unsigned int transport);
1332
1333 /*--- Debugging
1334         Functions for enabling debug per IP or fully, or enabling history logging for
1335         a SIP dialog
1336 */
1337 static void sip_dump_history(struct sip_pvt *dialog);   /* Dump history to debuglog at end of dialog, before destroying data */
1338 static inline int sip_debug_test_addr(const struct ast_sockaddr *addr);
1339 static inline int sip_debug_test_pvt(struct sip_pvt *p);
1340 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
1341 static void sip_dump_history(struct sip_pvt *dialog);
1342
1343 /*--- Device object handling */
1344 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
1345 static int update_call_counter(struct sip_pvt *fup, int event);
1346 static void sip_destroy_peer(struct sip_peer *peer);
1347 static void sip_destroy_peer_fn(void *peer);
1348 static void set_peer_defaults(struct sip_peer *peer);
1349 static struct sip_peer *temp_peer(const char *name);
1350 static void register_peer_exten(struct sip_peer *peer, int onoff);
1351 static int sip_poke_peer_s(const void *data);
1352 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
1353 static void reg_source_db(struct sip_peer *peer);
1354 static void destroy_association(struct sip_peer *peer);
1355 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
1356 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
1357 static void set_socket_transport(struct sip_socket *socket, int transport);
1358 static int peer_ipcmp_cb_full(void *obj, void *arg, void *data, int flags);
1359
1360 /* Realtime device support */
1361 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);
1362 static void update_peer(struct sip_peer *p, int expire);
1363 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
1364 static const char *get_name_from_variable(const struct ast_variable *var);
1365 static struct sip_peer *realtime_peer(const char *peername, struct ast_sockaddr *sin, char *callbackexten, int devstate_only, int which_objects);
1366 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1367
1368 /*--- Internal UA client handling (outbound registrations) */
1369 static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p);
1370 static void sip_registry_destroy(void *reg);
1371 static int sip_register(const char *value, int lineno);
1372 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
1373 static int sip_reregister(const void *data);
1374 static int __sip_do_register(struct sip_registry *r);
1375 static int sip_reg_timeout(const void *data);
1376 static void sip_send_all_registers(void);
1377 static int sip_reinvite_retry(const void *data);
1378
1379 /*--- Parsing SIP requests and responses */
1380 static int determine_firstline_parts(struct sip_request *req);
1381 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1382 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
1383 static int find_sip_method(const char *msg);
1384 static unsigned int parse_allowed_methods(struct sip_request *req);
1385 static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req);
1386 static int parse_request(struct sip_request *req);
1387 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
1388 static int method_match(enum sipmethod id, const char *name);
1389 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
1390 static void parse_oli(struct sip_request *req, struct ast_channel *chan);
1391 static const char *find_alias(const char *name, const char *_default);
1392 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
1393 static void lws2sws(struct ast_str *msgbuf);
1394 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
1395 static char *remove_uri_parameters(char *uri);
1396 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
1397 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
1398 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
1399 static int set_address_from_contact(struct sip_pvt *pvt);
1400 static void check_via(struct sip_pvt *p, const struct sip_request *req);
1401 static int get_rpid(struct sip_pvt *p, struct sip_request *oreq);
1402 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason, char **reason_str);
1403 static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id);
1404 static int transmit_state_notify(struct sip_pvt *p, struct state_notify_data *data, int full, int timeout);
1405 static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen);
1406 static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen);
1407 static int get_domain(const char *str, char *domain, int len);
1408 static void get_realm(struct sip_pvt *p, const struct sip_request *req);
1409 static char *get_content(struct sip_request *req);
1410
1411 /*-- TCP connection handling ---*/
1412 static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session);
1413 static void *sip_tcp_worker_fn(void *);
1414
1415 /*--- Constructing requests and responses */
1416 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
1417 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
1418 static void deinit_req(struct sip_request *req);
1419 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, uint32_t seqno, int newbranch);
1420 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri);
1421 static int init_resp(struct sip_request *resp, const char *msg);
1422 static inline int resp_needs_contact(const char *msg, enum sipmethod method);
1423 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
1424 static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p);
1425 static void build_via(struct sip_pvt *p);
1426 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
1427 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog);
1428 static char *generate_random_string(char *buf, size_t size);
1429 static void build_callid_pvt(struct sip_pvt *pvt);
1430 static void change_callid_pvt(struct sip_pvt *pvt, const char *callid);
1431 static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain);
1432 static void build_localtag_registry(struct sip_registry *reg);
1433 static void make_our_tag(struct sip_pvt *pvt);
1434 static int add_header(struct sip_request *req, const char *var, const char *value);
1435 static int add_max_forwards(struct sip_pvt *dialog, struct sip_request *req);
1436 static int add_content(struct sip_request *req, const char *line);
1437 static int finalize_content(struct sip_request *req);
1438 static void destroy_msg_headers(struct sip_pvt *pvt);
1439 static int add_text(struct sip_request *req, struct sip_pvt *p);
1440 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
1441 static int add_rpid(struct sip_request *req, struct sip_pvt *p);
1442 static int add_vidupdate(struct sip_request *req);
1443 static void add_route(struct sip_request *req, struct sip_route *route, int skip);
1444 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1445 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1446 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
1447 static void set_destination(struct sip_pvt *p, const char *uri);
1448 static void add_date(struct sip_request *req);
1449 static void add_expires(struct sip_request *req, int expires);
1450 static void build_contact(struct sip_pvt *p);
1451
1452 /*------Request handling functions */
1453 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock);
1454 static int handle_request_update(struct sip_pvt *p, struct sip_request *req);
1455 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);
1456 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, uint32_t seqno, int *nounlock);
1457 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
1458 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *sin, const char *e);
1459 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
1460 static int handle_request_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
1461 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
1462 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
1463 static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
1464 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req,
1465                 int *nounlock, struct sip_pvt *replaces_pvt, struct ast_channel *replaces_chan);
1466 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
1467 static int local_attended_transfer(struct sip_pvt *transferer, struct ast_channel *transferer_chan, uint32_t seqno, int *nounlock);
1468
1469 /*------Response handling functions */
1470 static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1471 static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1472 static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1473 static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1474 static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1475 static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1476 static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1477
1478 /*------ SRTP Support -------- */
1479 static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct ast_sdp_srtp **srtp, const char *a);
1480
1481 /*------ T38 Support --------- */
1482 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
1483 static void change_t38_state(struct sip_pvt *p, int state);
1484
1485 /*------ Session-Timers functions --------- */
1486 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
1487 static int  proc_session_timer(const void *vp);
1488 static void stop_session_timer(struct sip_pvt *p);
1489 static void start_session_timer(struct sip_pvt *p);
1490 static void restart_session_timer(struct sip_pvt *p);
1491 static const char *strefresherparam2str(enum st_refresher r);
1492 static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher_param *const p_ref);
1493 static int parse_minse(const char *p_hdrval, int *const p_interval);
1494 static int st_get_se(struct sip_pvt *, int max);
1495 static enum st_refresher st_get_refresher(struct sip_pvt *);
1496 static enum st_mode st_get_mode(struct sip_pvt *, int no_cached);
1497 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
1498
1499 /*------- RTP Glue functions -------- */
1500 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);
1501
1502 /*!--- SIP MWI Subscription support */
1503 static int sip_subscribe_mwi(const char *value, int lineno);
1504 static void sip_subscribe_mwi_destroy(void *data);
1505 static void sip_send_all_mwi_subscriptions(void);
1506 static int sip_subscribe_mwi_do(const void *data);
1507 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
1508
1509 /*! \brief Definition of this channel for PBX channel registration */
1510 struct ast_channel_tech sip_tech = {
1511         .type = "SIP",
1512         .description = "Session Initiation Protocol (SIP)",
1513         .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1514         .requester = sip_request_call,                  /* called with chan unlocked */
1515         .devicestate = sip_devicestate,                 /* called with chan unlocked (not chan-specific) */
1516         .call = sip_call,                       /* called with chan locked */
1517         .send_html = sip_sendhtml,
1518         .hangup = sip_hangup,                   /* called with chan locked */
1519         .answer = sip_answer,                   /* called with chan locked */
1520         .read = sip_read,                       /* called with chan locked */
1521         .write = sip_write,                     /* called with chan locked */
1522         .write_video = sip_write,               /* called with chan locked */
1523         .write_text = sip_write,
1524         .indicate = sip_indicate,               /* called with chan locked */
1525         .transfer = sip_transfer,               /* called with chan locked */
1526         .fixup = sip_fixup,                     /* called with chan locked */
1527         .send_digit_begin = sip_senddigit_begin,        /* called with chan unlocked */
1528         .send_digit_end = sip_senddigit_end,
1529         .early_bridge = ast_rtp_instance_early_bridge,
1530         .send_text = sip_sendtext,              /* called with chan locked */
1531         .func_channel_read = sip_acf_channel_read,
1532         .setoption = sip_setoption,
1533         .queryoption = sip_queryoption,
1534         .get_pvt_uniqueid = sip_get_callid,
1535 };
1536
1537 /*! \brief This version of the sip channel tech has no send_digit_begin
1538  * callback so that the core knows that the channel does not want
1539  * DTMF BEGIN frames.
1540  * The struct is initialized just before registering the channel driver,
1541  * and is for use with channels using SIP INFO DTMF.
1542  */
1543 struct ast_channel_tech sip_tech_info;
1544
1545 /*------- CC Support -------- */
1546 static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan);
1547 static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent);
1548 static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent);
1549 static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason);
1550 static int sip_cc_agent_status_request(struct ast_cc_agent *agent);
1551 static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent);
1552 static int sip_cc_agent_recall(struct ast_cc_agent *agent);
1553 static void sip_cc_agent_destructor(struct ast_cc_agent *agent);
1554
1555 static struct ast_cc_agent_callbacks sip_cc_agent_callbacks = {
1556         .type = "SIP",
1557         .init = sip_cc_agent_init,
1558         .start_offer_timer = sip_cc_agent_start_offer_timer,
1559         .stop_offer_timer = sip_cc_agent_stop_offer_timer,
1560         .respond = sip_cc_agent_respond,
1561         .status_request = sip_cc_agent_status_request,
1562         .start_monitoring = sip_cc_agent_start_monitoring,
1563         .callee_available = sip_cc_agent_recall,
1564         .destructor = sip_cc_agent_destructor,
1565 };
1566
1567 /* -------- End of declarations of structures, constants and forward declarations of functions
1568    Below starts actual code
1569    ------------------------
1570 */
1571
1572 static int sip_epa_register(const struct epa_static_data *static_data)
1573 {
1574         struct epa_backend *backend = ast_calloc(1, sizeof(*backend));
1575
1576         if (!backend) {
1577                 return -1;
1578         }
1579
1580         backend->static_data = static_data;
1581
1582         AST_LIST_LOCK(&epa_static_data_list);
1583         AST_LIST_INSERT_TAIL(&epa_static_data_list, backend, next);
1584         AST_LIST_UNLOCK(&epa_static_data_list);
1585         return 0;
1586 }
1587
1588 static void sip_epa_unregister_all(void)
1589 {
1590         struct epa_backend *backend;
1591
1592         AST_LIST_LOCK(&epa_static_data_list);
1593         while ((backend = AST_LIST_REMOVE_HEAD(&epa_static_data_list, next))) {
1594                 ast_free(backend);
1595         }
1596         AST_LIST_UNLOCK(&epa_static_data_list);
1597 }
1598
1599 static void cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry);
1600
1601 static void cc_epa_destructor(void *data)
1602 {
1603         struct sip_epa_entry *epa_entry = data;
1604         struct cc_epa_entry *cc_entry = epa_entry->instance_data;
1605         ast_free(cc_entry);
1606 }
1607
1608 static const struct epa_static_data cc_epa_static_data  = {
1609         .event = CALL_COMPLETION,
1610         .name = "call-completion",
1611         .handle_error = cc_handle_publish_error,
1612         .destructor = cc_epa_destructor,
1613 };
1614
1615 static const struct epa_static_data *find_static_data(const char * const event_package)
1616 {
1617         const struct epa_backend *backend = NULL;
1618
1619         AST_LIST_LOCK(&epa_static_data_list);
1620         AST_LIST_TRAVERSE(&epa_static_data_list, backend, next) {
1621                 if (!strcmp(backend->static_data->name, event_package)) {
1622                         break;
1623                 }
1624         }
1625         AST_LIST_UNLOCK(&epa_static_data_list);
1626         return backend ? backend->static_data : NULL;
1627 }
1628
1629 static struct sip_epa_entry *create_epa_entry (const char * const event_package, const char * const destination)
1630 {
1631         struct sip_epa_entry *epa_entry;
1632         const struct epa_static_data *static_data;
1633
1634         if (!(static_data = find_static_data(event_package))) {
1635                 return NULL;
1636         }
1637
1638         if (!(epa_entry = ao2_t_alloc(sizeof(*epa_entry), static_data->destructor, "Allocate new EPA entry"))) {
1639                 return NULL;
1640         }
1641
1642         epa_entry->static_data = static_data;
1643         ast_copy_string(epa_entry->destination, destination, sizeof(epa_entry->destination));
1644         return epa_entry;
1645 }
1646 static enum ast_cc_service_type service_string_to_service_type(const char * const service_string)
1647 {
1648         enum ast_cc_service_type service;
1649         for (service = AST_CC_CCBS; service <= AST_CC_CCNL; ++service) {
1650                 if (!strcasecmp(service_string, sip_cc_service_map[service].service_string)) {
1651                         return service;
1652                 }
1653         }
1654         return AST_CC_NONE;
1655 }
1656
1657 /* Even state compositors code */
1658 static void esc_entry_destructor(void *obj)
1659 {
1660         struct sip_esc_entry *esc_entry = obj;
1661         if (esc_entry->sched_id > -1) {
1662                 AST_SCHED_DEL(sched, esc_entry->sched_id);
1663         }
1664 }
1665
1666 static int esc_hash_fn(const void *obj, const int flags)
1667 {
1668         const struct sip_esc_entry *entry = obj;
1669         return ast_str_hash(entry->entity_tag);
1670 }
1671
1672 static int esc_cmp_fn(void *obj, void *arg, int flags)
1673 {
1674         struct sip_esc_entry *entry1 = obj;
1675         struct sip_esc_entry *entry2 = arg;
1676
1677         return (!strcmp(entry1->entity_tag, entry2->entity_tag)) ? (CMP_MATCH | CMP_STOP) : 0;
1678 }
1679
1680 static struct event_state_compositor *get_esc(const char * const event_package) {
1681         int i;
1682         for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1683                 if (!strcasecmp(event_package, event_state_compositors[i].name)) {
1684                         return &event_state_compositors[i];
1685                 }
1686         }
1687         return NULL;
1688 }
1689
1690 static struct sip_esc_entry *get_esc_entry(const char * entity_tag, struct event_state_compositor *esc) {
1691         struct sip_esc_entry *entry;
1692         struct sip_esc_entry finder;
1693
1694         ast_copy_string(finder.entity_tag, entity_tag, sizeof(finder.entity_tag));
1695
1696         entry = ao2_find(esc->compositor, &finder, OBJ_POINTER);
1697
1698         return entry;
1699 }
1700
1701 static int publish_expire(const void *data)
1702 {
1703         struct sip_esc_entry *esc_entry = (struct sip_esc_entry *) data;
1704         struct event_state_compositor *esc = get_esc(esc_entry->event);
1705
1706         ast_assert(esc != NULL);
1707
1708         ao2_unlink(esc->compositor, esc_entry);
1709         ao2_ref(esc_entry, -1);
1710         return 0;
1711 }
1712
1713 static void create_new_sip_etag(struct sip_esc_entry *esc_entry, int is_linked)
1714 {
1715         int new_etag = ast_atomic_fetchadd_int(&esc_etag_counter, +1);
1716         struct event_state_compositor *esc = get_esc(esc_entry->event);
1717
1718         ast_assert(esc != NULL);
1719         if (is_linked) {
1720                 ao2_unlink(esc->compositor, esc_entry);
1721         }
1722         snprintf(esc_entry->entity_tag, sizeof(esc_entry->entity_tag), "%d", new_etag);
1723         ao2_link(esc->compositor, esc_entry);
1724 }
1725
1726 static struct sip_esc_entry *create_esc_entry(struct event_state_compositor *esc, struct sip_request *req, const int expires)
1727 {
1728         struct sip_esc_entry *esc_entry;
1729         int expires_ms;
1730
1731         if (!(esc_entry = ao2_alloc(sizeof(*esc_entry), esc_entry_destructor))) {
1732                 return NULL;
1733         }
1734
1735         esc_entry->event = esc->name;
1736
1737         expires_ms = expires * 1000;
1738         /* Bump refcount for scheduler */
1739         ao2_ref(esc_entry, +1);
1740         esc_entry->sched_id = ast_sched_add(sched, expires_ms, publish_expire, esc_entry);
1741
1742         /* Note: This links the esc_entry into the ESC properly */
1743         create_new_sip_etag(esc_entry, 0);
1744
1745         return esc_entry;
1746 }
1747
1748 static int initialize_escs(void)
1749 {
1750         int i, res = 0;
1751         for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1752                 if (!((event_state_compositors[i].compositor) =
1753                                         ao2_container_alloc(ESC_MAX_BUCKETS, esc_hash_fn, esc_cmp_fn))) {
1754                         res = -1;
1755                 }
1756         }
1757         return res;
1758 }
1759
1760 static void destroy_escs(void)
1761 {
1762         int i;
1763         for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1764                 ao2_cleanup(event_state_compositors[i].compositor);
1765         }
1766 }
1767
1768
1769 static int find_by_notify_uri_helper(void *obj, void *arg, int flags)
1770 {
1771         struct ast_cc_agent *agent = obj;
1772         struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1773         const char *uri = arg;
1774
1775         return !sip_uri_cmp(agent_pvt->notify_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
1776 }
1777
1778 static struct ast_cc_agent *find_sip_cc_agent_by_notify_uri(const char * const uri)
1779 {
1780         struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_notify_uri_helper, (char *)uri, "SIP");
1781         return agent;
1782 }
1783
1784 static int find_by_subscribe_uri_helper(void *obj, void *arg, int flags)
1785 {
1786         struct ast_cc_agent *agent = obj;
1787         struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1788         const char *uri = arg;
1789
1790         return !sip_uri_cmp(agent_pvt->subscribe_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
1791 }
1792
1793 static struct ast_cc_agent *find_sip_cc_agent_by_subscribe_uri(const char * const uri)
1794 {
1795         struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_subscribe_uri_helper, (char *)uri, "SIP");
1796         return agent;
1797 }
1798
1799 static int find_by_callid_helper(void *obj, void *arg, int flags)
1800 {
1801         struct ast_cc_agent *agent = obj;
1802         struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1803         struct sip_pvt *call_pvt = arg;
1804
1805         return !strcmp(agent_pvt->original_callid, call_pvt->callid) ? CMP_MATCH | CMP_STOP : 0;
1806 }
1807
1808 static struct ast_cc_agent *find_sip_cc_agent_by_original_callid(struct sip_pvt *pvt)
1809 {
1810         struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_callid_helper, pvt, "SIP");
1811         return agent;
1812 }
1813
1814 static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan)
1815 {
1816         struct sip_cc_agent_pvt *agent_pvt = ast_calloc(1, sizeof(*agent_pvt));
1817         struct sip_pvt *call_pvt = ast_channel_tech_pvt(chan);
1818
1819         if (!agent_pvt) {
1820                 return -1;
1821         }
1822
1823         ast_assert(!strcmp(ast_channel_tech(chan)->type, "SIP"));
1824
1825         ast_copy_string(agent_pvt->original_callid, call_pvt->callid, sizeof(agent_pvt->original_callid));
1826         ast_copy_string(agent_pvt->original_exten, call_pvt->exten, sizeof(agent_pvt->original_exten));
1827         agent_pvt->offer_timer_id = -1;
1828         agent->private_data = agent_pvt;
1829         sip_pvt_lock(call_pvt);
1830         ast_set_flag(&call_pvt->flags[0], SIP_OFFER_CC);
1831         sip_pvt_unlock(call_pvt);
1832         return 0;
1833 }
1834
1835 static int sip_offer_timer_expire(const void *data)
1836 {
1837         struct ast_cc_agent *agent = (struct ast_cc_agent *) data;
1838         struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1839
1840         agent_pvt->offer_timer_id = -1;
1841
1842         return ast_cc_failed(agent->core_id, "SIP agent %s's offer timer expired", agent->device_name);
1843 }
1844
1845 static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent)
1846 {
1847         struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1848         int when;
1849
1850         when = ast_get_cc_offer_timer(agent->cc_params) * 1000;
1851         agent_pvt->offer_timer_id = ast_sched_add(sched, when, sip_offer_timer_expire, agent);
1852         return 0;
1853 }
1854
1855 static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent)
1856 {
1857         struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1858
1859         AST_SCHED_DEL(sched, agent_pvt->offer_timer_id);
1860         return 0;
1861 }
1862
1863 static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason)
1864 {
1865         struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1866
1867         sip_pvt_lock(agent_pvt->subscribe_pvt);
1868         ast_set_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
1869         if (reason == AST_CC_AGENT_RESPONSE_SUCCESS || !ast_strlen_zero(agent_pvt->notify_uri)) {
1870                 /* The second half of this if statement may be a bit hard to grasp,
1871                  * so here's an explanation. When a subscription comes into
1872                  * chan_sip, as long as it is not malformed, it will be passed
1873                  * to the CC core. If the core senses an out-of-order state transition,
1874                  * then the core will call this callback with the "reason" set to a
1875                  * failure condition.
1876                  * However, an out-of-order state transition will occur during a resubscription
1877                  * for CC. In such a case, we can see that we have already generated a notify_uri
1878                  * and so we can detect that this isn't a *real* failure. Rather, it is just
1879                  * something the core doesn't recognize as a legitimate SIP state transition.
1880                  * Thus we respond with happiness and flowers.
1881                  */
1882                 transmit_response(agent_pvt->subscribe_pvt, "200 OK", &agent_pvt->subscribe_pvt->initreq);
1883                 transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_QUEUED);
1884         } else {
1885                 transmit_response(agent_pvt->subscribe_pvt, "500 Internal Error", &agent_pvt->subscribe_pvt->initreq);
1886         }
1887         sip_pvt_unlock(agent_pvt->subscribe_pvt);
1888         agent_pvt->is_available = TRUE;
1889 }
1890
1891 static int sip_cc_agent_status_request(struct ast_cc_agent *agent)
1892 {
1893         struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1894         enum ast_device_state state = agent_pvt->is_available ? AST_DEVICE_NOT_INUSE : AST_DEVICE_INUSE;
1895         return ast_cc_agent_status_response(agent->core_id, state);
1896 }
1897
1898 static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent)
1899 {
1900         /* To start monitoring just means to wait for an incoming PUBLISH
1901          * to tell us that the caller has become available again. No special
1902          * action is needed
1903          */
1904         return 0;
1905 }
1906
1907 static int sip_cc_agent_recall(struct ast_cc_agent *agent)
1908 {
1909         struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1910         /* If we have received a PUBLISH beforehand stating that the caller in question
1911          * is not available, we can save ourself a bit of effort here and just report
1912          * the caller as busy
1913          */
1914         if (!agent_pvt->is_available) {
1915                 return ast_cc_agent_caller_busy(agent->core_id, "Caller %s is busy, reporting to the core",
1916                                 agent->device_name);
1917         }
1918         /* Otherwise, we transmit a NOTIFY to the caller and await either
1919          * a PUBLISH or an INVITE
1920          */
1921         sip_pvt_lock(agent_pvt->subscribe_pvt);
1922         transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_READY);
1923         sip_pvt_unlock(agent_pvt->subscribe_pvt);
1924         return 0;
1925 }
1926
1927 static void sip_cc_agent_destructor(struct ast_cc_agent *agent)
1928 {
1929         struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1930
1931         if (!agent_pvt) {
1932                 /* The agent constructor probably failed. */
1933                 return;
1934         }
1935
1936         sip_cc_agent_stop_offer_timer(agent);
1937         if (agent_pvt->subscribe_pvt) {
1938                 sip_pvt_lock(agent_pvt->subscribe_pvt);
1939                 if (!ast_test_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
1940                         /* If we haven't sent a 200 OK for the SUBSCRIBE dialog yet, then we need to send a response letting
1941                          * the subscriber know something went wrong
1942                          */
1943                         transmit_response(agent_pvt->subscribe_pvt, "500 Internal Server Error", &agent_pvt->subscribe_pvt->initreq);
1944                 }
1945                 sip_pvt_unlock(agent_pvt->subscribe_pvt);
1946                 agent_pvt->subscribe_pvt = dialog_unref(agent_pvt->subscribe_pvt, "SIP CC agent destructor: Remove ref to subscription");
1947         }
1948         ast_free(agent_pvt);
1949 }
1950
1951
1952 static int sip_monitor_instance_hash_fn(const void *obj, const int flags)
1953 {
1954         const struct sip_monitor_instance *monitor_instance = obj;
1955         return monitor_instance->core_id;
1956 }
1957
1958 static int sip_monitor_instance_cmp_fn(void *obj, void *arg, int flags)
1959 {
1960         struct sip_monitor_instance *monitor_instance1 = obj;
1961         struct sip_monitor_instance *monitor_instance2 = arg;
1962
1963         return monitor_instance1->core_id == monitor_instance2->core_id ? CMP_MATCH | CMP_STOP : 0;
1964 }
1965
1966 static void sip_monitor_instance_destructor(void *data)
1967 {
1968         struct sip_monitor_instance *monitor_instance = data;
1969         if (monitor_instance->subscription_pvt) {
1970                 sip_pvt_lock(monitor_instance->subscription_pvt);
1971                 monitor_instance->subscription_pvt->expiry = 0;
1972                 transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 0, monitor_instance->subscribe_uri);
1973                 sip_pvt_unlock(monitor_instance->subscription_pvt);
1974                 dialog_unref(monitor_instance->subscription_pvt, "Unref monitor instance ref of subscription pvt");
1975         }
1976         if (monitor_instance->suspension_entry) {
1977                 monitor_instance->suspension_entry->body[0] = '\0';
1978                 transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_REMOVE ,monitor_instance->notify_uri);
1979                 ao2_t_ref(monitor_instance->suspension_entry, -1, "Decrementing suspension entry refcount in sip_monitor_instance_destructor");
1980         }
1981         ast_string_field_free_memory(monitor_instance);
1982 }
1983
1984 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)
1985 {
1986         struct sip_monitor_instance *monitor_instance = ao2_alloc(sizeof(*monitor_instance), sip_monitor_instance_destructor);
1987
1988         if (!monitor_instance) {
1989                 return NULL;
1990         }
1991
1992         if (ast_string_field_init(monitor_instance, 256)) {
1993                 ao2_ref(monitor_instance, -1);
1994                 return NULL;
1995         }
1996
1997         ast_string_field_set(monitor_instance, subscribe_uri, subscribe_uri);
1998         ast_string_field_set(monitor_instance, peername, peername);
1999         ast_string_field_set(monitor_instance, device_name, device_name);
2000         monitor_instance->core_id = core_id;
2001         ao2_link(sip_monitor_instances, monitor_instance);
2002         return monitor_instance;
2003 }
2004
2005 static int find_sip_monitor_instance_by_subscription_pvt(void *obj, void *arg, int flags)
2006 {
2007         struct sip_monitor_instance *monitor_instance = obj;
2008         return monitor_instance->subscription_pvt == arg ? CMP_MATCH | CMP_STOP : 0;
2009 }
2010
2011 static int find_sip_monitor_instance_by_suspension_entry(void *obj, void *arg, int flags)
2012 {
2013         struct sip_monitor_instance *monitor_instance = obj;
2014         return monitor_instance->suspension_entry == arg ? CMP_MATCH | CMP_STOP : 0;
2015 }
2016
2017 static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id);
2018 static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor);
2019 static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor);
2020 static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id);
2021 static void sip_cc_monitor_destructor(void *private_data);
2022
2023 static struct ast_cc_monitor_callbacks sip_cc_monitor_callbacks = {
2024         .type = "SIP",
2025         .request_cc = sip_cc_monitor_request_cc,
2026         .suspend = sip_cc_monitor_suspend,
2027         .unsuspend = sip_cc_monitor_unsuspend,
2028         .cancel_available_timer = sip_cc_monitor_cancel_available_timer,
2029         .destructor = sip_cc_monitor_destructor,
2030 };
2031
2032 static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id)
2033 {
2034         struct sip_monitor_instance *monitor_instance = monitor->private_data;
2035         enum ast_cc_service_type service = monitor->service_offered;
2036         int when;
2037
2038         if (!monitor_instance) {
2039                 return -1;
2040         }
2041
2042         if (!(monitor_instance->subscription_pvt = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL, NULL))) {
2043                 return -1;
2044         }
2045
2046         when = service == AST_CC_CCBS ? ast_get_ccbs_available_timer(monitor->interface->config_params) :
2047                 ast_get_ccnr_available_timer(monitor->interface->config_params);
2048
2049         sip_pvt_lock(monitor_instance->subscription_pvt);
2050         ast_set_flag(&monitor_instance->subscription_pvt->flags[0], SIP_OUTGOING);
2051         create_addr(monitor_instance->subscription_pvt, monitor_instance->peername, 0, 1);
2052         ast_sip_ouraddrfor(&monitor_instance->subscription_pvt->sa, &monitor_instance->subscription_pvt->ourip, monitor_instance->subscription_pvt);
2053         monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
2054         monitor_instance->subscription_pvt->expiry = when;
2055
2056         transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 2, monitor_instance->subscribe_uri);
2057         sip_pvt_unlock(monitor_instance->subscription_pvt);
2058
2059         ao2_t_ref(monitor, +1, "Adding a ref to the monitor for the scheduler");
2060         *available_timer_id = ast_sched_add(sched, when * 1000, ast_cc_available_timer_expire, monitor);
2061         return 0;
2062 }
2063
2064 static int construct_pidf_body(enum sip_cc_publish_state state, char *pidf_body, size_t size, const char *presentity)
2065 {
2066         struct ast_str *body = ast_str_alloca(size);
2067         char tuple_id[32];
2068
2069         generate_random_string(tuple_id, sizeof(tuple_id));
2070
2071         /* We'll make this a bare-bones pidf body. In state_notify_build_xml, the PIDF
2072          * body gets a lot more extra junk that isn't necessary, so we'll leave it out here.
2073          */
2074         ast_str_append(&body, 0, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
2075         /* XXX The entity attribute is currently set to the peer name associated with the
2076          * dialog. This is because we currently only call this function for call-completion
2077          * PUBLISH bodies. In such cases, the entity is completely disregarded. For other
2078          * event packages, it may be crucial to have a proper URI as the presentity so this
2079          * should be revisited as support is expanded.
2080          */
2081         ast_str_append(&body, 0, "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" entity=\"%s\">\n", presentity);
2082         ast_str_append(&body, 0, "<tuple id=\"%s\">\n", tuple_id);
2083         ast_str_append(&body, 0, "<status><basic>%s</basic></status>\n", state == CC_OPEN ? "open" : "closed");
2084         ast_str_append(&body, 0, "</tuple>\n");
2085         ast_str_append(&body, 0, "</presence>\n");
2086         ast_copy_string(pidf_body, ast_str_buffer(body), size);
2087         return 0;
2088 }
2089
2090 static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor)
2091 {
2092         struct sip_monitor_instance *monitor_instance = monitor->private_data;
2093         enum sip_publish_type publish_type;
2094         struct cc_epa_entry *cc_entry;
2095
2096         if (!monitor_instance) {
2097                 return -1;
2098         }
2099
2100         if (!monitor_instance->suspension_entry) {
2101                 /* We haven't yet allocated the suspension entry, so let's give it a shot */
2102                 if (!(monitor_instance->suspension_entry = create_epa_entry("call-completion", monitor_instance->peername))) {
2103                         ast_log(LOG_WARNING, "Unable to allocate sip EPA entry for call-completion\n");
2104                         ao2_ref(monitor_instance, -1);
2105                         return -1;
2106                 }
2107                 if (!(cc_entry = ast_calloc(1, sizeof(*cc_entry)))) {
2108                         ast_log(LOG_WARNING, "Unable to allocate space for instance data of EPA entry for call-completion\n");
2109                         ao2_ref(monitor_instance, -1);
2110                         return -1;
2111                 }
2112                 cc_entry->core_id = monitor->core_id;
2113                 monitor_instance->suspension_entry->instance_data = cc_entry;
2114                 publish_type = SIP_PUBLISH_INITIAL;
2115         } else {
2116                 publish_type = SIP_PUBLISH_MODIFY;
2117                 cc_entry = monitor_instance->suspension_entry->instance_data;
2118         }
2119
2120         cc_entry->current_state = CC_CLOSED;
2121
2122         if (ast_strlen_zero(monitor_instance->notify_uri)) {
2123                 /* If we have no set notify_uri, then what this means is that we have
2124                  * not received a NOTIFY from this destination stating that he is
2125                  * currently available.
2126                  *
2127                  * This situation can arise when the core calls the suspend callbacks
2128                  * of multiple destinations. If one of the other destinations aside
2129                  * from this one notified Asterisk that he is available, then there
2130                  * is no reason to take any suspension action on this device. Rather,
2131                  * we should return now and if we receive a NOTIFY while monitoring
2132                  * is still "suspended" then we can immediately respond with the
2133                  * proper PUBLISH to let this endpoint know what is going on.
2134                  */
2135                 return 0;
2136         }
2137         construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
2138         return transmit_publish(monitor_instance->suspension_entry, publish_type, monitor_instance->notify_uri);
2139 }
2140
2141 static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor)
2142 {
2143         struct sip_monitor_instance *monitor_instance = monitor->private_data;
2144         struct cc_epa_entry *cc_entry;
2145
2146         if (!monitor_instance) {
2147                 return -1;
2148         }
2149
2150         ast_assert(monitor_instance->suspension_entry != NULL);
2151
2152         cc_entry = monitor_instance->suspension_entry->instance_data;
2153         cc_entry->current_state = CC_OPEN;
2154         if (ast_strlen_zero(monitor_instance->notify_uri)) {
2155                 /* This means we are being asked to unsuspend a call leg we never
2156                  * sent a PUBLISH on. As such, there is no reason to send another
2157                  * PUBLISH at this point either. We can just return instead.
2158                  */
2159                 return 0;
2160         }
2161         construct_pidf_body(CC_OPEN, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
2162         return transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_MODIFY, monitor_instance->notify_uri);
2163 }
2164
2165 static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id)
2166 {
2167         if (*sched_id != -1) {
2168                 AST_SCHED_DEL(sched, *sched_id);
2169                 ao2_t_ref(monitor, -1, "Removing scheduler's reference to the monitor");
2170         }
2171         return 0;
2172 }
2173
2174 static void sip_cc_monitor_destructor(void *private_data)
2175 {
2176         struct sip_monitor_instance *monitor_instance = private_data;
2177         ao2_unlink(sip_monitor_instances, monitor_instance);
2178         ast_module_unref(ast_module_info->self);
2179 }
2180
2181 static int sip_get_cc_information(struct sip_request *req, char *subscribe_uri, size_t size, enum ast_cc_service_type *service)
2182 {
2183         char *call_info = ast_strdupa(sip_get_header(req, "Call-Info"));
2184         char *uri;
2185         char *purpose;
2186         char *service_str;
2187         static const char cc_purpose[] = "purpose=call-completion";
2188         static const int cc_purpose_len = sizeof(cc_purpose) - 1;
2189
2190         if (ast_strlen_zero(call_info)) {
2191                 /* No Call-Info present. Definitely no CC offer */
2192                 return -1;
2193         }
2194
2195         uri = strsep(&call_info, ";");
2196
2197         while ((purpose = strsep(&call_info, ";"))) {
2198                 if (!strncmp(purpose, cc_purpose, cc_purpose_len)) {
2199                         break;
2200                 }
2201         }
2202         if (!purpose) {
2203                 /* We didn't find the appropriate purpose= parameter. Oh well */
2204                 return -1;
2205         }
2206
2207         /* Okay, call-completion has been offered. Let's figure out what type of service this is */
2208         while ((service_str = strsep(&call_info, ";"))) {
2209                 if (!strncmp(service_str, "m=", 2)) {
2210                         break;
2211                 }
2212         }
2213         if (!service_str) {
2214                 /* So they didn't offer a particular service, We'll just go with CCBS since it really
2215                  * doesn't matter anyway
2216                  */
2217                 service_str = "BS";
2218         } else {
2219                 /* We already determined that there is an "m=" so no need to check
2220                  * the result of this strsep
2221                  */
2222                 strsep(&service_str, "=");
2223         }
2224
2225         if ((*service = service_string_to_service_type(service_str)) == AST_CC_NONE) {
2226                 /* Invalid service offered */
2227                 return -1;
2228         }
2229
2230         ast_copy_string(subscribe_uri, get_in_brackets(uri), size);
2231
2232         return 0;
2233 }
2234
2235 /*
2236  * \brief Determine what, if any, CC has been offered and queue a CC frame if possible
2237  *
2238  * After taking care of some formalities to be sure that this call is eligible for CC,
2239  * we first try to see if we can make use of native CC. We grab the information from
2240  * the passed-in sip_request (which is always a response to an INVITE). If we can
2241  * use native CC monitoring for the call, then so be it.
2242  *
2243  * If native cc monitoring is not possible or not supported, then we will instead attempt
2244  * to use generic monitoring. Falling back to generic from a failed attempt at using native
2245  * monitoring will only work if the monitor policy of the endpoint is "always"
2246  *
2247  * \param pvt The current dialog. Contains CC parameters for the endpoint
2248  * \param req The response to the INVITE we want to inspect
2249  * \param service The service to use if generic monitoring is to be used. For native
2250  * monitoring, we get the service from the SIP response itself
2251  */
2252 static void sip_handle_cc(struct sip_pvt *pvt, struct sip_request *req, enum ast_cc_service_type service)
2253 {
2254         enum ast_cc_monitor_policies monitor_policy = ast_get_cc_monitor_policy(pvt->cc_params);
2255         int core_id;
2256         char interface_name[AST_CHANNEL_NAME];
2257
2258         if (monitor_policy == AST_CC_MONITOR_NEVER) {
2259                 /* Don't bother, just return */
2260                 return;
2261         }
2262
2263         if ((core_id = ast_cc_get_current_core_id(pvt->owner)) == -1) {
2264                 /* For some reason, CC is invalid, so don't try it! */
2265                 return;
2266         }
2267
2268         ast_channel_get_device_name(pvt->owner, interface_name, sizeof(interface_name));
2269
2270         if (monitor_policy == AST_CC_MONITOR_ALWAYS || monitor_policy == AST_CC_MONITOR_NATIVE) {
2271                 char subscribe_uri[SIPBUFSIZE];
2272                 char device_name[AST_CHANNEL_NAME];
2273                 enum ast_cc_service_type offered_service;
2274                 struct sip_monitor_instance *monitor_instance;
2275                 if (sip_get_cc_information(req, subscribe_uri, sizeof(subscribe_uri), &offered_service)) {
2276                         /* If CC isn't being offered to us, or for some reason the CC offer is
2277                          * not formatted correctly, then it may still be possible to use generic
2278                          * call completion since the monitor policy may be "always"
2279                          */
2280                         goto generic;
2281                 }
2282                 ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
2283                 if (!(monitor_instance = sip_monitor_instance_init(core_id, subscribe_uri, pvt->peername, device_name))) {
2284                         /* Same deal. We can try using generic still */
2285                         goto generic;
2286                 }
2287                 /* We bump the refcount of chan_sip because once we queue this frame, the CC core
2288                  * will have a reference to callbacks in this module. We decrement the module
2289                  * refcount once the monitor destructor is called
2290                  */
2291                 ast_module_ref(ast_module_info->self);
2292                 ast_queue_cc_frame(pvt->owner, "SIP", pvt->dialstring, offered_service, monitor_instance);
2293                 ao2_ref(monitor_instance, -1);
2294                 return;
2295         }
2296
2297 generic:
2298         if (monitor_policy == AST_CC_MONITOR_GENERIC || monitor_policy == AST_CC_MONITOR_ALWAYS) {
2299                 ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE, interface_name, service, NULL);
2300         }
2301 }
2302
2303 /*! \brief Working TLS connection configuration */
2304 static struct ast_tls_config sip_tls_cfg;
2305
2306 /*! \brief Default TLS connection configuration */
2307 static struct ast_tls_config default_tls_cfg;
2308
2309 /*! \brief Default DTLS connection configuration */
2310 static struct ast_rtp_dtls_cfg default_dtls_cfg;
2311
2312 /*! \brief The TCP server definition */
2313 static struct ast_tcptls_session_args sip_tcp_desc = {
2314         .accept_fd = -1,
2315         .master = AST_PTHREADT_NULL,
2316         .tls_cfg = NULL,
2317         .poll_timeout = -1,
2318         .name = "SIP TCP server",
2319         .accept_fn = ast_tcptls_server_root,
2320         .worker_fn = sip_tcp_worker_fn,
2321 };
2322
2323 /*! \brief The TCP/TLS server definition */
2324 static struct ast_tcptls_session_args sip_tls_desc = {
2325         .accept_fd = -1,
2326         .master = AST_PTHREADT_NULL,
2327         .tls_cfg = &sip_tls_cfg,
2328         .poll_timeout = -1,
2329         .name = "SIP TLS server",
2330         .accept_fn = ast_tcptls_server_root,
2331         .worker_fn = sip_tcp_worker_fn,
2332 };
2333
2334 /*! \brief Append to SIP dialog history
2335         \return Always returns 0 */
2336 #define append_history(p, event, fmt , args... )        append_history_full(p, "%-15s " fmt, event, ## args)
2337
2338 struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, const char *tag, char *file, int line, const char *func)
2339 {
2340         if (p)
2341 #ifdef REF_DEBUG
2342                 __ao2_ref_debug(p, 1, tag, file, line, func);
2343 #else
2344                 ao2_ref(p, 1);
2345 #endif
2346         else
2347                 ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
2348         return p;
2349 }
2350
2351 struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, const char *tag, char *file, int line, const char *func)
2352 {
2353         if (p)
2354 #ifdef REF_DEBUG
2355                 __ao2_ref_debug(p, -1, tag, file, line, func);
2356 #else
2357                 ao2_ref(p, -1);
2358 #endif
2359         return NULL;
2360 }
2361
2362 /*! \brief map from an integer value to a string.
2363  * If no match is found, return errorstring
2364  */
2365 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
2366 {
2367         const struct _map_x_s *cur;
2368
2369         for (cur = table; cur->s; cur++) {
2370                 if (cur->x == x) {
2371                         return cur->s;
2372                 }
2373         }
2374         return errorstring;
2375 }
2376
2377 /*! \brief map from a string to an integer value, case insensitive.
2378  * If no match is found, return errorvalue.
2379  */
2380 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
2381 {
2382         const struct _map_x_s *cur;
2383
2384         for (cur = table; cur->s; cur++) {
2385                 if (!strcasecmp(cur->s, s)) {
2386                         return cur->x;
2387                 }
2388         }
2389         return errorvalue;
2390 }
2391
2392 static enum AST_REDIRECTING_REASON sip_reason_str_to_code(const char *text)
2393 {
2394         enum AST_REDIRECTING_REASON ast = AST_REDIRECTING_REASON_UNKNOWN;
2395         int i;
2396
2397         for (i = 0; i < ARRAY_LEN(sip_reason_table); ++i) {
2398                 if (!strcasecmp(text, sip_reason_table[i].text)) {
2399                         ast = sip_reason_table[i].code;
2400                         break;
2401                 }
2402         }
2403
2404         return ast;
2405 }
2406
2407 static const char *sip_reason_code_to_str(struct ast_party_redirecting_reason *reason, int *table_lookup)
2408 {
2409         int code = reason->code;
2410
2411         /* If there's a specific string set, then we just
2412          * use it.
2413          */
2414         if (!ast_strlen_zero(reason->str)) {
2415                 /* If we care about whether this can be found in
2416                  * the table, then we need to check about that.
2417                  */
2418                 if (table_lookup) {
2419                         /* If the string is literally "unknown" then don't bother with the lookup
2420                          * because it can lead to a false negative.
2421                          */
2422                         if (!strcasecmp(reason->str, "unknown") ||
2423                                         sip_reason_str_to_code(reason->str) != AST_REDIRECTING_REASON_UNKNOWN) {
2424                                 *table_lookup = TRUE;
2425                         } else {
2426                                 *table_lookup = FALSE;
2427                         }
2428                 }
2429                 return reason->str;
2430         }
2431
2432         if (table_lookup) {
2433                 *table_lookup = TRUE;
2434         }
2435
2436         if (code >= 0 && code < ARRAY_LEN(sip_reason_table)) {
2437                 return sip_reason_table[code].text;
2438         }
2439
2440         return "unknown";
2441 }
2442
2443 /*!
2444  * \brief generic function for determining if a correct transport is being
2445  * used to contact a peer
2446  *
2447  * this is done as a macro so that the "tmpl" var can be passed either a
2448  * sip_request or a sip_peer
2449  */
2450 #define check_request_transport(peer, tmpl) ({ \
2451         int ret = 0; \
2452         if (peer->socket.type == tmpl->socket.type) \
2453                 ; \
2454         else if (!(peer->transports & tmpl->socket.type)) {\
2455                 ast_log(LOG_ERROR, \
2456                         "'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
2457                         sip_get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
2458                         ); \
2459                 ret = 1; \
2460         } else if (peer->socket.type & AST_TRANSPORT_TLS) { \
2461                 ast_log(LOG_WARNING, \
2462                         "peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
2463                         peer->name, sip_get_transport(tmpl->socket.type) \
2464                 ); \
2465         } else { \
2466                 ast_debug(1, \
2467                         "peer '%s' has contacted us over %s even though we prefer %s.\n", \
2468                         peer->name, sip_get_transport(tmpl->socket.type), sip_get_transport(peer->socket.type) \
2469                 ); \
2470         }\
2471         (ret); \
2472 })
2473
2474 /*! \brief
2475  * duplicate a list of channel variables, \return the copy.
2476  */
2477 static struct ast_variable *copy_vars(struct ast_variable *src)
2478 {
2479         struct ast_variable *res = NULL, *tmp, *v = NULL;
2480
2481         for (v = src ; v ; v = v->next) {
2482                 if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
2483                         tmp->next = res;
2484                         res = tmp;
2485                 }
2486         }
2487         return res;
2488 }
2489
2490 static void tcptls_packet_destructor(void *obj)
2491 {
2492         struct tcptls_packet *packet = obj;
2493
2494         ast_free(packet->data);
2495 }
2496
2497 static void sip_tcptls_client_args_destructor(void *obj)
2498 {
2499         struct ast_tcptls_session_args *args = obj;
2500         if (args->tls_cfg) {
2501                 ast_free(args->tls_cfg->certfile);
2502                 ast_free(args->tls_cfg->pvtfile);
2503                 ast_free(args->tls_cfg->cipher);
2504                 ast_free(args->tls_cfg->cafile);
2505                 ast_free(args->tls_cfg->capath);
2506
2507                 ast_ssl_teardown(args->tls_cfg);
2508         }
2509         ast_free(args->tls_cfg);
2510         ast_free((char *) args->name);
2511 }
2512
2513 static void sip_threadinfo_destructor(void *obj)
2514 {
2515         struct sip_threadinfo *th = obj;
2516         struct tcptls_packet *packet;
2517
2518         if (th->alert_pipe[1] > -1) {
2519                 close(th->alert_pipe[0]);
2520         }
2521         if (th->alert_pipe[1] > -1) {
2522                 close(th->alert_pipe[1]);
2523         }
2524         th->alert_pipe[0] = th->alert_pipe[1] = -1;
2525
2526         while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
2527                 ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
2528         }
2529
2530         if (th->tcptls_session) {
2531                 ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
2532         }
2533 }
2534
2535 /*! \brief creates a sip_threadinfo object and links it into the threadt table. */
2536 static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
2537 {
2538         struct sip_threadinfo *th;
2539
2540         if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
2541                 return NULL;
2542         }
2543
2544         th->alert_pipe[0] = th->alert_pipe[1] = -1;
2545
2546         if (pipe(th->alert_pipe) == -1) {
2547                 ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
2548                 ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
2549                 return NULL;
2550         }
2551         ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
2552         th->tcptls_session = tcptls_session;
2553         th->type = transport ? transport : (tcptls_session->ssl ? AST_TRANSPORT_TLS: AST_TRANSPORT_TCP);
2554         ao2_t_link(threadt, th, "Adding new tcptls helper thread");
2555         ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
2556         return th;
2557 }
2558
2559 /*! \brief used to indicate to a tcptls thread that data is ready to be written */
2560 static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
2561 {
2562         int res = len;
2563         struct sip_threadinfo *th = NULL;
2564         struct tcptls_packet *packet = NULL;
2565         struct sip_threadinfo tmp = {
2566                 .tcptls_session = tcptls_session,
2567         };
2568         enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
2569
2570         if (!tcptls_session) {
2571                 return XMIT_ERROR;
2572         }
2573
2574         ao2_lock(tcptls_session);
2575
2576         if ((tcptls_session->fd == -1) ||
2577                 !(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
2578                 !(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
2579                 !(packet->data = ast_str_create(len))) {
2580                 goto tcptls_write_setup_error;
2581         }
2582
2583         /* goto tcptls_write_error should _NOT_ be used beyond this point */
2584         ast_str_set(&packet->data, 0, "%s", (char *) buf);
2585         packet->len = len;
2586
2587         /* alert tcptls thread handler that there is a packet to be sent.
2588          * must lock the thread info object to guarantee control of the
2589          * packet queue */
2590         ao2_lock(th);
2591         if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
2592                 ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
2593                 ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
2594                 packet = NULL;
2595                 res = XMIT_ERROR;
2596         } else { /* it is safe to queue the frame after issuing the alert when we hold the threadinfo lock */
2597                 AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
2598         }
2599         ao2_unlock(th);
2600
2601         ao2_unlock(tcptls_session);
2602         ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
2603         return res;
2604
2605 tcptls_write_setup_error:
2606         if (th) {
2607                 ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
2608         }
2609         if (packet) {
2610                 ao2_t_ref(packet, -1, "could not allocate packet's data");
2611         }
2612         ao2_unlock(tcptls_session);
2613
2614         return XMIT_ERROR;
2615 }
2616
2617 /*! \brief SIP TCP connection handler */
2618 static void *sip_tcp_worker_fn(void *data)
2619 {
2620         struct ast_tcptls_session_instance *tcptls_session = data;
2621
2622         return _sip_tcp_helper_thread(tcptls_session);
2623 }
2624
2625 /*! \brief SIP WebSocket connection handler */
2626 static void sip_websocket_callback(struct ast_websocket *session, struct ast_variable *parameters, struct ast_variable *headers)
2627 {
2628         int res;
2629
2630         if (ast_websocket_set_nonblock(session)) {
2631                 goto end;
2632         }
2633
2634         if (ast_websocket_set_timeout(session, sip_cfg.websocket_write_timeout)) {
2635                 goto end;
2636         }
2637
2638         while ((res = ast_wait_for_input(ast_websocket_fd(session), -1)) > 0) {
2639                 char *payload;
2640                 uint64_t payload_len;
2641                 enum ast_websocket_opcode opcode;
2642                 int fragmented;
2643
2644                 if (ast_websocket_read(session, &payload, &payload_len, &opcode, &fragmented)) {
2645                         /* We err on the side of caution and terminate the session if any error occurs */
2646                         break;
2647                 }
2648
2649                 if (opcode == AST_WEBSOCKET_OPCODE_TEXT || opcode == AST_WEBSOCKET_OPCODE_BINARY) {
2650                         struct sip_request req = { 0, };
2651
2652                         if (!(req.data = ast_str_create(payload_len + 1))) {
2653                                 goto end;
2654                         }
2655
2656                         if (ast_str_set(&req.data, -1, "%s", payload) == AST_DYNSTR_BUILD_FAILED) {
2657                                 deinit_req(&req);
2658                                 goto end;
2659                         }
2660
2661                         req.socket.fd = ast_websocket_fd(session);
2662                         set_socket_transport(&req.socket, ast_websocket_is_secure(session) ? AST_TRANSPORT_WSS : AST_TRANSPORT_WS);
2663                         req.socket.ws_session = session;
2664
2665                         handle_request_do(&req, ast_websocket_remote_address(session));
2666                         deinit_req(&req);
2667
2668                 } else if (opcode == AST_WEBSOCKET_OPCODE_CLOSE) {
2669                         break;
2670                 }
2671         }
2672
2673 end:
2674         ast_websocket_unref(session);
2675 }
2676
2677 /*! \brief Check if the authtimeout has expired.
2678  * \param start the time when the session started
2679  *
2680  * \retval 0 the timeout has expired
2681  * \retval -1 error
2682  * \return the number of milliseconds until the timeout will expire
2683  */
2684 static int sip_check_authtimeout(time_t start)
2685 {
2686         int timeout;
2687         time_t now;
2688         if(time(&now) == -1) {
2689                 ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
2690                 return -1;
2691         }
2692
2693         timeout = (authtimeout - (now - start)) * 1000;
2694         if (timeout < 0) {
2695                 /* we have timed out */
2696                 return 0;
2697         }
2698
2699         return timeout;
2700 }
2701
2702 /*!
2703  * \brief Indication of a TCP message's integrity
2704  */
2705 enum message_integrity {
2706         /*!
2707          * The message has an error in it with
2708          * regards to its Content-Length header
2709          */
2710         MESSAGE_INVALID,
2711         /*!
2712          * The message is incomplete
2713          */
2714         MESSAGE_FRAGMENT,
2715         /*!
2716          * The data contains a complete message
2717          * plus a fragment of another.
2718          */
2719         MESSAGE_FRAGMENT_COMPLETE,
2720         /*!
2721          * The message is complete
2722          */
2723         MESSAGE_COMPLETE,
2724 };
2725
2726 /*!
2727  * \brief
2728  * Get the content length from an unparsed SIP message
2729  *
2730  * \param message The unparsed SIP message headers
2731  * \return The value of the Content-Length header or -1 if message is invalid
2732  */
2733 static int read_raw_content_length(const char *message)
2734 {
2735         char *content_length_str;
2736         int content_length = -1;
2737
2738         struct ast_str *msg_copy;
2739         char *msg;
2740
2741         /* Using a ast_str because lws2sws takes one of those */
2742         if (!(msg_copy = ast_str_create(strlen(message) + 1))) {
2743                 return -1;
2744         }
2745         ast_str_set(&msg_copy, 0, "%s", message);
2746
2747         if (sip_cfg.pedanticsipchecking) {
2748                 lws2sws(msg_copy);
2749         }
2750
2751         msg = ast_str_buffer(msg_copy);
2752
2753         /* Let's find a Content-Length header */
2754         if ((content_length_str = strcasestr(msg, "\nContent-Length:"))) {
2755                 content_length_str += sizeof("\nContent-Length:") - 1;
2756         } else if ((content_length_str = strcasestr(msg, "\nl:"))) {
2757                 content_length_str += sizeof("\nl:") - 1;
2758         } else {
2759                 /* RFC 3261 18.3
2760                  * "In the case of stream-oriented transports such as TCP, the Content-
2761                  *  Length header field indicates the size of the body.  The Content-
2762                  *  Length header field MUST be used with stream oriented transports."
2763                  */
2764                 goto done;
2765         }
2766
2767         /* Double-check that this is a complete header */
2768         if (!strchr(content_length_str, '\n')) {
2769                 goto done;
2770         }
2771
2772         if (sscanf(content_length_str, "%30d", &content_length) != 1) {
2773                 content_length = -1;
2774         }
2775
2776 done:
2777         ast_free(msg_copy);
2778         return content_length;
2779 }
2780
2781 /*!
2782  * \brief Check that a message received over TCP is a full message
2783  *
2784  * This will take the information read in and then determine if
2785  * 1) The message is a full SIP request
2786  * 2) The message is a partial SIP request
2787  * 3) The message contains a full SIP request along with another partial request
2788  * \param data The unparsed incoming SIP message.
2789  * \param request The resulting request with extra fragments removed.
2790  * \param overflow If the message contains more than a full request, this is the remainder of the message
2791  * \return The resulting integrity of the message
2792  */
2793 static enum message_integrity check_message_integrity(struct ast_str **request, struct ast_str **overflow)
2794 {
2795         char *message = ast_str_buffer(*request);
2796         char *body;
2797         int content_length;
2798         int message_len = ast_str_strlen(*request);
2799         int body_len;
2800
2801         /* Important pieces to search for in a SIP request are \r\n\r\n. This
2802          * marks either
2803          * 1) The division between the headers and body
2804          * 2) The end of the SIP request
2805          */
2806         body = strstr(message, "\r\n\r\n");
2807         if (!body) {
2808                 /* This is clearly a partial message since we haven't reached an end
2809                  * yet.
2810                  */
2811                 return MESSAGE_FRAGMENT;
2812         }
2813         body += sizeof("\r\n\r\n") - 1;
2814         body_len = message_len - (body - message);
2815
2816         body[-1] = '\0';
2817         content_length = read_raw_content_length(message);
2818         body[-1] = '\n';
2819
2820         if (content_length < 0) {
2821                 return MESSAGE_INVALID;
2822         } else if (content_length == 0) {
2823                 /* We've definitely received an entire message. We need
2824                  * to check if there's also a fragment of another message
2825                  * in addition.
2826                  */
2827                 if (body_len == 0) {
2828                         return MESSAGE_COMPLETE;
2829                 } else {
2830                         ast_str_append(overflow, 0, "%s", body);
2831                         ast_str_truncate(*request, message_len - body_len);
2832                         return MESSAGE_FRAGMENT_COMPLETE;
2833                 }
2834         }
2835         /* Positive content length. Let's see what sort of
2836          * message body we're dealing with.
2837          */
2838         if (body_len < content_length) {
2839                 /* We don't have the full message body yet */
2840                 return MESSAGE_FRAGMENT;
2841         } else if (body_len > content_length) {
2842                 /* We have the full message plus a fragment of a further
2843                  * message
2844                  */
2845                 ast_str_append(overflow, 0, "%s", body + content_length);
2846                 ast_str_truncate(*request, message_len - (body_len - content_length));
2847                 return MESSAGE_FRAGMENT_COMPLETE;
2848         } else {
2849                 /* Yay! Full message with no extra content */
2850                 return MESSAGE_COMPLETE;
2851         }
2852 }
2853
2854 /*!
2855  * \brief Read SIP request or response from a TCP/TLS connection
2856  *
2857  * \param req The request structure to be filled in
2858  * \param tcptls_session The TCP/TLS connection from which to read
2859  * \retval -1 Failed to read data
2860  * \retval 0 Successfully read data
2861  */
2862 static int sip_tcptls_read(struct sip_request *req, struct ast_tcptls_session_instance *tcptls_session,
2863                 int authenticated, time_t start)
2864 {
2865         enum message_integrity message_integrity = MESSAGE_FRAGMENT;
2866
2867         while (message_integrity == MESSAGE_FRAGMENT) {
2868                 size_t datalen;
2869
2870                 if (ast_str_strlen(tcptls_session->overflow_buf) == 0) {
2871                         char readbuf[4097];
2872                         int timeout;
2873                         int res;
2874                         if (!tcptls_session->client && !authenticated) {
2875                                 if ((timeout = sip_check_authtimeout(start)) < 0) {
2876                                         return -1;
2877                                 }
2878
2879                                 if (timeout == 0) {
2880                                         ast_debug(2, "SIP TCP/TLS server timed out\n");
2881                                         return -1;
2882                                 }
2883                         } else {
2884                                 timeout = -1;
2885                         }
2886                         res = ast_wait_for_input(tcptls_session->fd, timeout);
2887                         if (res < 0) {
2888                                 ast_debug(2, "SIP TCP/TLS server :: ast_wait_for_input returned %d\n", res);
2889                                 return -1;
2890                         } else if (res == 0) {
2891                                 ast_debug(2, "SIP TCP/TLS server timed out\n");
2892                                 return -1;
2893                         }
2894
2895                         res = ast_tcptls_server_read(tcptls_session, readbuf, sizeof(readbuf) - 1);
2896                         if (res < 0) {
2897                                 if (errno == EAGAIN || errno == EINTR) {
2898                                         continue;
2899                                 }
2900                                 ast_debug(2, "SIP TCP/TLS server error when receiving data\n");
2901                                 return -1;
2902                         } else if (res == 0) {
2903                                 ast_debug(2, "SIP TCP/TLS server has shut down\n");
2904                                 return -1;
2905                         }
2906                         readbuf[res] = '\0';
2907                         ast_str_append(&req->data, 0, "%s", readbuf);
2908                 } else {
2909                         ast_str_append(&req->data, 0, "%s", ast_str_buffer(tcptls_session->overflow_buf));
2910                         ast_str_reset(tcptls_session->overflow_buf);
2911                 }
2912
2913                 datalen = ast_str_strlen(req->data);
2914                 if (datalen > SIP_MAX_PACKET_SIZE) {
2915                         ast_log(LOG_WARNING, "Rejecting TCP/TLS packet from '%s' because way too large: %zu\n",
2916                                 ast_sockaddr_stringify(&tcptls_session->remote_address), datalen);
2917                         return -1;
2918                 }
2919
2920                 message_integrity = check_message_integrity(&req->data, &tcptls_session->overflow_buf);
2921         }
2922
2923         return 0;
2924 }
2925
2926 /*! \brief SIP TCP thread management function
2927         This function reads from the socket, parses the packet into a request
2928 */
2929 static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session)
2930 {
2931         int res, timeout = -1, authenticated = 0, flags;
2932         time_t start;
2933         struct sip_request req = { 0, } , reqcpy = { 0, };
2934         struct sip_threadinfo *me = NULL;
2935         char buf[1024] = "";
2936         struct pollfd fds[2] = { { 0 }, { 0 }, };
2937         struct ast_tcptls_session_args *ca = NULL;
2938
2939         /* If this is a server session, then the connection has already been
2940          * setup. Check if the authlimit has been reached and if not create the
2941          * threadinfo object so we can access this thread for writing.
2942          *
2943          * if this is a client connection more work must be done.
2944          * 1. We own the parent session args for a client connection.  This pointer needs
2945          *    to be held on to so we can decrement it's ref count on thread destruction.
2946          * 2. The threadinfo object was created before this thread was launched, however
2947          *    it must be found within the threadt table.
2948          * 3. Last, the tcptls_session must be started.
2949          */
2950         if (!tcptls_session->client) {
2951                 if (ast_atomic_fetchadd_int(&unauth_sessions, +1) >= authlimit) {
2952                         /* unauth_sessions is decremented in the cleanup code */
2953                         goto cleanup;
2954                 }
2955
2956                 if ((flags = fcntl(tcptls_session->fd, F_GETFL)) == -1) {
2957                         ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
2958                         goto cleanup;
2959                 }
2960
2961                 flags |= O_NONBLOCK;
2962                 if (fcntl(tcptls_session->fd, F_SETFL, flags) == -1) {
2963                         ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
2964                         goto cleanup;
2965                 }
2966
2967                 if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? AST_TRANSPORT_TLS : AST_TRANSPORT_TCP))) {
2968                         goto cleanup;
2969                 }
2970                 ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
2971         } else {
2972                 struct sip_threadinfo tmp = {
2973                         .tcptls_session = tcptls_session,
2974                 };
2975
2976                 if ((!(ca = tcptls_session->parent)) ||
2977                         (!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
2978                         (!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
2979                         goto cleanup;
2980                 }
2981         }
2982
2983         flags = 1;
2984         if (setsockopt(tcptls_session->fd, SOL_SOCKET, SO_KEEPALIVE, &flags, sizeof(flags))) {
2985                 ast_log(LOG_ERROR, "error enabling TCP keep-alives on sip socket: %s\n", strerror(errno));
2986                 goto cleanup;
2987         }
2988
2989         me->threadid = pthread_self();
2990         ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "TLS" : "TCP");
2991
2992         /* set up pollfd to watch for reads on both the socket and the alert_pipe */
2993         fds[0].fd = tcptls_session->fd;
2994         fds[1].fd = me->alert_pipe[0];
2995         fds[0].events = fds[1].events = POLLIN | POLLPRI;
2996
2997         if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
2998                 goto cleanup;
2999         }
3000         if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET))) {
3001                 goto cleanup;
3002         }
3003
3004         if(time(&start) == -1) {
3005                 ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
3006                 goto cleanup;
3007         }
3008
3009         /*
3010          * We cannot let the stream exclusively wait for data to arrive.
3011          * We have to wake up the task to send outgoing messages.
3012          */
3013         ast_tcptls_stream_set_exclusive_input(tcptls_session->stream_cookie, 0);
3014
3015         ast_tcptls_stream_set_timeout_sequence(tcptls_session->stream_cookie, ast_tvnow(),
3016                 tcptls_session->client ? -1 : (authtimeout * 1000));
3017
3018         for (;;) {
3019                 struct ast_str *str_save;
3020
3021                 if (!tcptls_session->client && req.authenticated && !authenticated) {
3022                         authenticated = 1;
3023                         ast_tcptls_stream_set_timeout_disable(tcptls_session->stream_cookie);
3024                         ast_atomic_fetchadd_int(&unauth_sessions, -1);
3025                 }
3026
3027                 /* calculate the timeout for unauthenticated server sessions */
3028                 if (!tcptls_session->client && !authenticated ) {
3029                         if ((timeout = sip_check_authtimeout(start)) < 0) {
3030                                 goto cleanup;
3031                         }
3032
3033                         if (timeout == 0) {
3034                                 ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "TLS": "TCP");
3035                                 goto cleanup;
3036                         }
3037                 } else {
3038                         timeout = -1;
3039                 }
3040
3041                 if (ast_str_strlen(tcptls_session->overflow_buf) == 0) {
3042                         res = ast_poll(fds, 2, timeout); /* polls for both socket and alert_pipe */
3043                         if (res < 0) {
3044                                 ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "TLS": "TCP", res);
3045                                 goto cleanup;
3046                         } else if (res == 0) {
3047                                 /* timeout */
3048                                 ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "TLS": "TCP");
3049                                 goto cleanup;
3050                         }
3051                 }
3052
3053                 /*
3054                  * handle the socket event, check for both reads from the socket fd or TCP overflow buffer,
3055                  * and writes from alert_pipe fd.
3056                  */
3057                 if (fds[0].revents || (ast_str_strlen(tcptls_session->overflow_buf) > 0)) { /* there is data on the socket to be read */
3058                         fds[0].revents = 0;
3059
3060                         /* clear request structure */
3061                         str_save = req.data;
3062                         memset(&req, 0, sizeof(req));
3063                         req.data = str_save;
3064                         ast_str_reset(req.data);
3065
3066                         str_save = reqcpy.data;
3067                         memset(&reqcpy, 0, sizeof(reqcpy));
3068                         reqcpy.data = str_save;
3069                         ast_str_reset(reqcpy.data);
3070
3071                         memset(buf, 0, sizeof(buf));
3072
3073                         if (tcptls_session->ssl) {
3074                                 set_socket_transport(&req.socket, AST_TRANSPORT_TLS);
3075                                 req.socket.port = htons(ourport_tls);
3076                         } else {
3077                                 set_socket_transport(&req.socket, AST_TRANSPORT_TCP);
3078                                 req.socket.port = htons(ourport_tcp);
3079                         }
3080                         req.socket.fd = tcptls_session->fd;
3081
3082                         res = sip_tcptls_read(&req, tcptls_session, authenticated, start);
3083                         if (res < 0) {
3084                                 goto cleanup;
3085                         }
3086
3087                         req.socket.tcptls_session = tcptls_session;
3088                         req.socket.ws_session = NULL;
3089                         handle_request_do(&req, &tcptls_session->remote_address);
3090                 }
3091
3092                 if (fds[1].revents) { /* alert_pipe indicates there is data in the send queue to be sent */
3093                         enum sip_tcptls_alert alert;
3094                         struct tcptls_packet *packet;
3095
3096                         fds[1].revents = 0;
3097
3098                         if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
3099                                 ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
3100                                 continue;
3101                         }
3102
3103                         switch (alert) {
3104                         case TCPTLS_ALERT_STOP:
3105                                 goto cleanup;
3106                         case TCPTLS_ALERT_DATA:
3107                                 ao2_lock(me);
3108                                 if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
3109                                         ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty\n");
3110                                 }
3111                                 ao2_unlock(me);
3112
3113                                 if (packet) {
3114                                         if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {