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