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