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