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