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