Asterisk - The Open Source Telephony Project  GIT-master-a1fa8df
chan_sip.c
Go to the documentation of this file.
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2012, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18 
19 /*!
20  * \file
21  * \brief Implementation of Session Initiation Protocol
22  *
23  * \author Mark Spencer <markster@digium.com>
24  *
25  * See Also:
26  * \arg \ref AstCREDITS
27  *
28  * Implementation of RFC 3261 - without S/MIME, and experimental TCP and TLS support
29  * Configuration file \link Config_sip sip.conf \endlink
30  *
31  * ********** IMPORTANT *
32  * \note TCP/TLS support is EXPERIMENTAL and WILL CHANGE. This applies to configuration
33  * settings, dialplan commands and dialplans apps/functions
34  * See \ref sip_tcp_tls
35  *
36  *
37  * ******** General TODO:s
38  * \todo Better support of forking
39  * \todo VIA branch tag transaction checking
40  * \todo Transaction support
41  *
42  * ******** Wishlist: Improvements
43  * - Support of SIP domains for devices, so that we match on username\@domain in the From: header
44  * - Connect registrations with a specific device on the incoming call. It's not done
45  * automatically in Asterisk
46  *
47  * \ingroup channel_drivers
48  *
49  * \par Overview of the handling of SIP sessions
50  * The SIP channel handles several types of SIP sessions, or dialogs,
51  * not all of them being "telephone calls".
52  * - Incoming calls that will be sent to the PBX core
53  * - Outgoing calls, generated by the PBX
54  * - SIP subscriptions and notifications of states and voicemail messages
55  * - SIP registrations, both inbound and outbound
56  * - SIP peer management (peerpoke, OPTIONS)
57  * - SIP text messages
58  *
59  * In the SIP channel, there's a list of active SIP dialogs, which includes
60  * all of these when they are active. "sip show channels" in the CLI will
61  * show most of these, excluding subscriptions which are shown by
62  * "sip show subscriptions"
63  *
64  * \par incoming packets
65  * Incoming packets are received in the monitoring thread, then handled by
66  * sipsock_read() for udp only. In tcp, packets are read by the tcp_helper thread.
67  * sipsock_read() function parses the packet and matches an existing
68  * dialog or starts a new SIP dialog.
69  *
70  * sipsock_read sends the packet to handle_incoming(), that parses a bit more.
71  * If it is a response to an outbound request, the packet is sent to handle_response().
72  * If it is a request, handle_incoming() sends it to one of a list of functions
73  * depending on the request type - INVITE, OPTIONS, REFER, BYE, CANCEL etc
74  * sipsock_read locks the ast_channel if it exists (an active call) and
75  * unlocks it after we have processed the SIP message.
76  *
77  * A new INVITE is sent to handle_request_invite(), that will end up
78  * starting a new channel in the PBX, the new channel after that executing
79  * in a separate channel thread. This is an incoming "call".
80  * When the call is answered, either by a bridged channel or the PBX itself
81  * the sip_answer() function is called.
82  *
83  * The actual media - Video or Audio - is mostly handled by the RTP subsystem
84  * in rtp.c
85  *
86  * \par Outbound calls
87  * Outbound calls are set up by the PBX through the sip_request_call()
88  * function. After that, they are activated by sip_call().
89  *
90  * \par Hanging up
91  * The PBX issues a hangup on both incoming and outgoing calls through
92  * the sip_hangup() function
93  */
94 
95 /*! \li \ref chan_sip.c uses configuration files \ref sip.conf and \ref sip_notify.conf
96  * \addtogroup configuration_file
97  */
98 
99 /*! \page sip.conf sip.conf
100  * \verbinclude sip.conf.sample
101  */
102 
103 /*! \page sip_notify.conf sip_notify.conf
104  * \verbinclude sip_notify.conf.sample
105  */
106 
107 /*!
108  * \page sip_tcp_tls SIP TCP and TLS support
109  *
110  * \par tcpfixes TCP implementation changes needed
111  * \todo Fix TCP/TLS handling in dialplan, SRV records, transfers and much more
112  * \todo Save TCP/TLS sessions in registry
113  * If someone registers a SIPS uri, this forces us to set up a TLS connection back.
114  * \todo Add TCP/TLS information to function SIPPEER and CHANNEL function
115  * \todo If tcpenable=yes, we must open a TCP socket on the same address as the IP for UDP.
116  * The tcpbindaddr config option should only be used to open ADDITIONAL ports
117  * So we should propably go back to
118  * bindaddr= the default address to bind to. If tcpenable=yes, then bind this to both udp and TCP
119  * if tlsenable=yes, open TLS port (provided we also have cert)
120  * tcpbindaddr = extra address for additional TCP connections
121  * tlsbindaddr = extra address for additional TCP/TLS connections
122  * udpbindaddr = extra address for additional UDP connections
123  * These three options should take multiple IP/port pairs
124  * Note: Since opening additional listen sockets is a *new* feature we do not have today
125  * the XXXbindaddr options needs to be disabled until we have support for it
126  *
127  * \todo re-evaluate the transport= setting in sip.conf. This is right now not well
128  * thought of. If a device in sip.conf contacts us via TCP, we should not switch transport,
129  * even if udp is the configured first transport.
130  *
131  * \todo Be prepared for one outbound and another incoming socket per pvt. This applies
132  * specially to communication with other peers (proxies).
133  * \todo We need to test TCP sessions with SIP proxies and in regards
134  * to the SIP outbound specs.
135  * \todo ;transport=tls was deprecated in RFC3261 and should not be used at all. See section 26.2.2.
136  *
137  * \todo If the message is smaller than the given Content-length, the request should get a 400 Bad request
138  * message. If it's a response, it should be dropped. (RFC 3261, Section 18.3)
139  * \todo Since we have had multidomain support in Asterisk for quite a while, we need to support
140  * multiple domains in our TLS implementation, meaning one socket and one cert per domain
141  * \todo Selection of transport for a request needs to be done after we've parsed all route headers,
142  * also considering outbound proxy options.
143  * First request: Outboundproxy, routes, (reg contact or URI. If URI doesn't have port: DNS naptr, srv, AAA)
144  * Intermediate requests: Outboundproxy(only when forced), routes, contact/uri
145  * DNS naptr support is crucial. A SIP uri might lead to a TLS connection.
146  * Also note that due to outbound proxy settings, a SIPS uri might have to be sent on UDP (not to recommend though)
147  * \todo Default transports are set to UDP, which cause the wrong behaviour when contacting remote
148  * devices directly from the dialplan. UDP is only a fallback if no other method works,
149  * in order to be compatible with RFC2543 (SIP/1.0) devices. For transactions that exceed the
150  * MTU (like INIVTE with video, audio and RTT) TCP should be preferred.
151  *
152  * When dialling unconfigured peers (with no port number) or devices in external domains
153  * NAPTR records MUST be consulted to find configured transport. If they are not found,
154  * SRV records for both TCP and UDP should be checked. If there's a record for TCP, use that.
155  * If there's no record for TCP, then use UDP as a last resort. If there's no SRV records,
156  * \note this only applies if there's no outbound proxy configured for the session. If an outbound
157  * proxy is configured, these procedures might apply for locating the proxy and determining
158  * the transport to use for communication with the proxy.
159  * \par Other bugs to fix ----
160  * __set_address_from_contact(const char *fullcontact, struct sockaddr_in *sin, int tcp)
161  * - sets TLS port as default for all TCP connections, unless other port is given in contact.
162  * parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
163  * - assumes that the contact the UA registers is using the same transport as the REGISTER request, which is
164  * a bad guess.
165  * - Does not save any information about TCP/TLS connected devices, which is a severe BUG, as discussed on the mailing list.
166  * get_destination(struct sip_pvt *p, struct sip_request *oreq)
167  * - Doesn't store the information that we got an incoming SIPS request in the channel, so that
168  * we can require a secure signalling path OUT of Asterisk (on SIP or IAX2). Possibly, the call should
169  * fail on in-secure signalling paths if there's no override in our configuration. At least, provide a
170  * channel variable in the dialplan.
171  * get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
172  * - As above, if we have a SIPS: uri in the refer-to header
173  * - Does not check transport in refer_to uri.
174  */
175 
176 /*** MODULEINFO
177  <use type="module">res_crypto</use>
178  <use type="module">res_http_websocket</use>
179  <defaultenabled>no</defaultenabled>
180  <support_level>deprecated</support_level>
181  <replacement>chan_pjsip</replacement>
182  <deprecated_in>17</deprecated_in>
183  <removed_in>21</removed_in>
184  ***/
185 
186 /*! \page sip_session_timers SIP Session Timers in Asterisk Chan_sip
187 
188  The SIP Session-Timers is an extension of the SIP protocol that allows end-points and proxies to
189  refresh a session periodically. The sessions are kept alive by sending a RE-INVITE or UPDATE
190  request at a negotiated interval. If a session refresh fails then all the entities that support Session-
191  Timers clear their internal session state. In addition, UAs generate a BYE request in order to clear
192  the state in the proxies and the remote UA (this is done for the benefit of SIP entities in the path
193  that do not support Session-Timers).
194 
195  The Session-Timers can be configured on a system-wide, per-user, or per-peer basis. The peruser/
196  per-peer settings override the global settings. The following new parameters have been
197  added to the sip.conf file.
198  session-timers=["accept", "originate", "refuse"]
199  session-expires=[integer]
200  session-minse=[integer]
201  session-refresher=["uas", "uac"]
202 
203  The session-timers parameter in sip.conf defines the mode of operation of SIP session-timers feature in
204  Asterisk. The Asterisk can be configured in one of the following three modes:
205 
206  1. Accept :: In the "accept" mode, the Asterisk server honors
207  session-timers requests made by remote end-points. A remote
208  end-point can request Asterisk to engage session-timers by either
209  sending it an INVITE request with a "Supported: timer" header in
210  it or by responding to Asterisk's INVITE with a 200 OK that
211  contains Session-Expires: header in it. In this mode, the Asterisk
212  server does not request session-timers from remote
213  end-points. This is the default mode.
214 
215  2. Originate :: In the "originate" mode, the Asterisk server
216  requests the remote end-points to activate session-timers in
217  addition to honoring such requests made by the remote
218  end-points. In order to get as much protection as possible against
219  hanging SIP channels due to network or end-point failures,
220  Asterisk resends periodic re-INVITEs even if a remote end-point
221  does not support the session-timers feature.
222 
223  3. Refuse :: In the "refuse" mode, Asterisk acts as if it does not
224  support session- timers for inbound or outbound requests. If a
225  remote end-point requests session-timers in a dialog, then
226  Asterisk ignores that request unless it's noted as a requirement
227  (Require: header), in which case the INVITE is rejected with a 420
228  Bad Extension response.
229 
230 */
231 
232 #include "asterisk.h"
233 
234 #include <signal.h>
235 #include <regex.h>
236 #include <inttypes.h>
237 
238 #include "asterisk/network.h"
239 #include "asterisk/paths.h" /* need ast_config_AST_SYSTEM_NAME */
240 #include "asterisk/lock.h"
241 #include "asterisk/config.h"
242 #include "asterisk/module.h"
243 #include "asterisk/pbx.h"
244 #include "asterisk/sched.h"
245 #include "asterisk/io.h"
246 #include "asterisk/rtp_engine.h"
247 #include "asterisk/udptl.h"
248 #include "asterisk/acl.h"
249 #include "asterisk/manager.h"
250 #include "asterisk/callerid.h"
251 #include "asterisk/cli.h"
252 #include "asterisk/musiconhold.h"
253 #include "asterisk/dsp.h"
254 #include "asterisk/pickup.h"
255 #include "asterisk/parking.h"
256 #include "asterisk/srv.h"
257 #include "asterisk/astdb.h"
258 #include "asterisk/causes.h"
259 #include "asterisk/utils.h"
260 #include "asterisk/file.h"
261 #include "asterisk/astobj2.h"
262 #include "asterisk/dnsmgr.h"
263 #include "asterisk/devicestate.h"
264 #include "asterisk/netsock2.h"
265 #include "asterisk/localtime.h"
266 #include "asterisk/abstract_jb.h"
267 #include "asterisk/threadstorage.h"
268 #include "asterisk/translate.h"
269 #include "asterisk/ast_version.h"
270 #include "asterisk/aoc.h"
271 #include "asterisk/message.h"
272 #include "sip/include/sip.h"
273 #include "sip/include/globals.h"
276 #include "sip/include/sip_utils.h"
277 #include "asterisk/sdp_srtp.h"
278 #include "asterisk/ccss.h"
279 #include "asterisk/xml.h"
280 #include "sip/include/dialog.h"
281 #include "sip/include/dialplan_functions.h"
283 #include "sip/include/route.h"
284 #include "asterisk/sip_api.h"
285 #include "asterisk/mwi.h"
286 #include "asterisk/bridge.h"
287 #include "asterisk/stasis.h"
289 #include "asterisk/stasis_system.h"
292 #include "asterisk/http_websocket.h"
293 #include "asterisk/format_cache.h"
294 #include "asterisk/linkedlists.h" /* for AST_LIST_NEXT */
295 
296 /*** DOCUMENTATION
297  <application name="SIPDtmfMode" language="en_US">
298  <synopsis>
299  Change the dtmfmode for a SIP call.
300  </synopsis>
301  <syntax>
302  <parameter name="mode" required="true">
303  <enumlist>
304  <enum name="inband" />
305  <enum name="info" />
306  <enum name="rfc2833" />
307  </enumlist>
308  </parameter>
309  </syntax>
310  <description>
311  <para>Changes the dtmfmode for a SIP call.</para>
312  </description>
313  </application>
314  <application name="SIPAddHeader" language="en_US">
315  <synopsis>
316  Add a SIP header to the outbound call.
317  </synopsis>
318  <syntax argsep=":">
319  <parameter name="Header" required="true" />
320  <parameter name="Content" required="true" />
321  </syntax>
322  <description>
323  <para>Adds a header to a SIP call placed with DIAL.</para>
324  <para>Remember to use the X-header if you are adding non-standard SIP
325  headers, like <literal>X-Asterisk-Accountcode:</literal>. Use this with care.
326  Adding the wrong headers may jeopardize the SIP dialog.</para>
327  <para>Always returns <literal>0</literal>.</para>
328  </description>
329  </application>
330  <application name="SIPRemoveHeader" language="en_US">
331  <synopsis>
332  Remove SIP headers previously added with SIPAddHeader
333  </synopsis>
334  <syntax>
335  <parameter name="Header" required="false" />
336  </syntax>
337  <description>
338  <para>SIPRemoveHeader() allows you to remove headers which were previously
339  added with SIPAddHeader(). If no parameter is supplied, all previously added
340  headers will be removed. If a parameter is supplied, only the matching headers
341  will be removed.</para>
342  <para>For example you have added these 2 headers:</para>
343  <para>SIPAddHeader(P-Asserted-Identity: sip:foo@bar);</para>
344  <para>SIPAddHeader(P-Preferred-Identity: sip:bar@foo);</para>
345  <para></para>
346  <para>// remove all headers</para>
347  <para>SIPRemoveHeader();</para>
348  <para>// remove all P- headers</para>
349  <para>SIPRemoveHeader(P-);</para>
350  <para>// remove only the PAI header (note the : at the end)</para>
351  <para>SIPRemoveHeader(P-Asserted-Identity:);</para>
352  <para></para>
353  <para>Always returns <literal>0</literal>.</para>
354  </description>
355  </application>
356  <application name="SIPSendCustomINFO" language="en_US">
357  <synopsis>
358  Send a custom INFO frame on specified channels.
359  </synopsis>
360  <syntax>
361  <parameter name="Data" required="true" />
362  <parameter name="UserAgent" required="false" />
363  </syntax>
364  <description>
365  <para>SIPSendCustomINFO() allows you to send a custom INFO message on all
366  active SIP channels or on channels with the specified User Agent. This
367  application is only available if TEST_FRAMEWORK is defined.</para>
368  </description>
369  </application>
370  <function name="SIP_HEADER" language="en_US">
371  <synopsis>
372  Gets the specified SIP header from an incoming INVITE message.
373  </synopsis>
374  <syntax>
375  <parameter name="name" required="true" />
376  <parameter name="number">
377  <para>If not specified, defaults to <literal>1</literal>.</para>
378  </parameter>
379  </syntax>
380  <description>
381  <para>Since there are several headers (such as Via) which can occur multiple
382  times, SIP_HEADER takes an optional second argument to specify which header with
383  that name to retrieve. Headers start at offset <literal>1</literal>.</para>
384  <para>This function does not access headers from the REFER message if the call
385  was transferred. To obtain the REFER headers, set the dialplan variable
386  <variable>GET_TRANSFERRER_DATA</variable> to the prefix of the headers of the
387  REFER message that you need to access; for example, <literal>X-</literal> to
388  get all headers starting with <literal>X-</literal>. The variable must be set
389  before a call to the application that starts the channel that may eventually
390  transfer back into the dialplan, and must be inherited by that channel, so prefix
391  it with the <literal>_</literal> or <literal>__</literal> when setting (or
392  set it in the pre-dial handler executed on the new channel). To get all headers
393  of the REFER message, set the value to <literal>*</literal>. Headers
394  are returned in the form of a dialplan hash TRANSFER_DATA, and can be accessed
395  with the functions <variable>HASHKEYS(TRANSFER_DATA)</variable> and, e. g.,
396  <variable>HASH(TRANSFER_DATA,X-That-Special-Header)</variable>.</para>
397  <para>Please also note that contents of the SDP (an attachment to the
398  SIP request) can't be accessed with this function.</para>
399  </description>
400  <see-also>
401  <ref type="function">SIP_HEADERS</ref>
402  </see-also>
403  </function>
404  <function name="SIP_HEADERS" language="en_US">
405  <synopsis>
406  Gets the list of SIP header names from an incoming INVITE message.
407  </synopsis>
408  <syntax>
409  <parameter name="prefix">
410  <para>If specified, only the headers matching the given prefix are returned.</para>
411  </parameter>
412  </syntax>
413  <description>
414  <para>Returns a comma-separated list of header names (without values) from the
415  INVITE message that originated the current channel. Multiple headers with the
416  same name are included in the list only once. The returned list can be iterated
417  over using the functions POP() and SIP_HEADER().</para>
418  <para>For example, <literal>${SIP_HEADERS(Co)}</literal> might return
419  <literal>Contact,Content-Length,Content-Type</literal>. As a practical example,
420  you may use <literal>${SIP_HEADERS(X-)}</literal> to enumerate optional extended
421  headers.</para>
422  <para>This function does not access headers from the incoming SIP REFER message;
423  see the documentation of the function SIP_HEADER for how to access them.</para>
424  <para>Please observe that contents of the SDP (an attachment to the
425  SIP request) can't be accessed with this function.</para>
426  </description>
427  <see-also>
428  <ref type="function">SIP_HEADER</ref>
429  <ref type="function">POP</ref>
430  </see-also>
431  </function>
432  <function name="SIPPEER" language="en_US">
433  <synopsis>
434  Gets SIP peer information.
435  </synopsis>
436  <syntax>
437  <parameter name="peername" required="true" />
438  <parameter name="item">
439  <enumlist>
440  <enum name="ip">
441  <para>(default) The IP address.</para>
442  </enum>
443  <enum name="port">
444  <para>The port number.</para>
445  </enum>
446  <enum name="mailbox">
447  <para>The configured mailbox.</para>
448  </enum>
449  <enum name="context">
450  <para>The configured context.</para>
451  </enum>
452  <enum name="expire">
453  <para>The epoch time of the next expire.</para>
454  </enum>
455  <enum name="dynamic">
456  <para>Is it dynamic? (yes/no).</para>
457  </enum>
458  <enum name="callerid_name">
459  <para>The configured Caller ID name.</para>
460  </enum>
461  <enum name="callerid_num">
462  <para>The configured Caller ID number.</para>
463  </enum>
464  <enum name="callgroup">
465  <para>The configured Callgroup.</para>
466  </enum>
467  <enum name="pickupgroup">
468  <para>The configured Pickupgroup.</para>
469  </enum>
470  <enum name="namedcallgroup">
471  <para>The configured Named Callgroup.</para>
472  </enum>
473  <enum name="namedpickupgroup">
474  <para>The configured Named Pickupgroup.</para>
475  </enum>
476  <enum name="codecs">
477  <para>The configured codecs.</para>
478  </enum>
479  <enum name="status">
480  <para>Status (if qualify=yes).</para>
481  </enum>
482  <enum name="regexten">
483  <para>Extension activated at registration.</para>
484  </enum>
485  <enum name="limit">
486  <para>Call limit (call-limit).</para>
487  </enum>
488  <enum name="busylevel">
489  <para>Configured call level for signalling busy.</para>
490  </enum>
491  <enum name="curcalls">
492  <para>Current amount of calls. Only available if call-limit is set.</para>
493  </enum>
494  <enum name="language">
495  <para>Default language for peer.</para>
496  </enum>
497  <enum name="accountcode">
498  <para>Account code for this peer.</para>
499  </enum>
500  <enum name="useragent">
501  <para>Current user agent header used by peer.</para>
502  </enum>
503  <enum name="maxforwards">
504  <para>The value used for SIP loop prevention in outbound requests</para>
505  </enum>
506  <enum name="chanvar[name]">
507  <para>A channel variable configured with setvar for this peer.</para>
508  </enum>
509  <enum name="codec[x]">
510  <para>Preferred codec index number <replaceable>x</replaceable> (beginning with zero).</para>
511  </enum>
512  </enumlist>
513  </parameter>
514  </syntax>
515  <description></description>
516  </function>
517  <function name="CHECKSIPDOMAIN" language="en_US">
518  <synopsis>
519  Checks if domain is a local domain.
520  </synopsis>
521  <syntax>
522  <parameter name="domain" required="true" />
523  </syntax>
524  <description>
525  <para>This function checks if the <replaceable>domain</replaceable> in the argument is configured
526  as a local SIP domain that this Asterisk server is configured to handle.
527  Returns the domain name if it is locally handled, otherwise an empty string.
528  Check the <literal>domain=</literal> configuration in <filename>sip.conf</filename>.</para>
529  </description>
530  </function>
531  <manager name="SIPpeers" language="en_US">
532  <synopsis>
533  List SIP peers (text format).
534  </synopsis>
535  <syntax>
536  <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
537  </syntax>
538  <description>
539  <para>Lists SIP peers in text format with details on current status.
540  <literal>Peerlist</literal> will follow as separate events, followed by a final event called
541  <literal>PeerlistComplete</literal>.</para>
542  </description>
543  </manager>
544  <manager name="SIPshowpeer" language="en_US">
545  <synopsis>
546  show SIP peer (text format).
547  </synopsis>
548  <syntax>
549  <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
550  <parameter name="Peer" required="true">
551  <para>The peer name you want to check.</para>
552  </parameter>
553  </syntax>
554  <description>
555  <para>Show one SIP peer with details on current status.</para>
556  </description>
557  </manager>
558  <manager name="SIPqualifypeer" language="en_US">
559  <synopsis>
560  Qualify SIP peers.
561  </synopsis>
562  <syntax>
563  <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
564  <parameter name="Peer" required="true">
565  <para>The peer name you want to qualify.</para>
566  </parameter>
567  </syntax>
568  <description>
569  <para>Qualify a SIP peer.</para>
570  </description>
571  <see-also>
572  <ref type="managerEvent">SIPQualifyPeerDone</ref>
573  </see-also>
574  </manager>
575  <manager name="SIPshowregistry" language="en_US">
576  <synopsis>
577  Show SIP registrations (text format).
578  </synopsis>
579  <syntax>
580  <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
581  </syntax>
582  <description>
583  <para>Lists all registration requests and status. Registrations will follow as separate
584  events followed by a final event called <literal>RegistrationsComplete</literal>.</para>
585  </description>
586  </manager>
587  <manager name="SIPnotify" language="en_US">
588  <synopsis>
589  Send a SIP notify.
590  </synopsis>
591  <syntax>
592  <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
593  <parameter name="Channel" required="true">
594  <para>Peer to receive the notify.</para>
595  </parameter>
596  <parameter name="Variable" required="true">
597  <para>At least one variable pair must be specified.
598  <replaceable>name</replaceable>=<replaceable>value</replaceable></para>
599  </parameter>
600  <parameter name="Call-ID" required="false">
601  <para>When specified, SIP notity will be sent as a part of an existing dialog.</para>
602  </parameter>
603  </syntax>
604  <description>
605  <para>Sends a SIP Notify event.</para>
606  <para>All parameters for this event must be specified in the body of this request
607  via multiple <literal>Variable: name=value</literal> sequences.</para>
608  </description>
609  </manager>
610  <manager name="SIPpeerstatus" language="en_US">
611  <synopsis>
612  Show the status of one or all of the sip peers.
613  </synopsis>
614  <syntax>
615  <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
616  <parameter name="Peer" required="false">
617  <para>The peer name you want to check.</para>
618  </parameter>
619  </syntax>
620  <description>
621  <para>Retrieves the status of one or all of the sip peers. If no peer name is specified, status
622  for all of the sip peers will be retrieved.</para>
623  </description>
624  </manager>
625  <info name="MessageDestinationInfo" language="en_US" tech="SIP">
626  <para>Specifying a prefix of <literal>sip:</literal> will send the
627  message as a SIP MESSAGE request.</para>
628  </info>
629  <info name="MessageFromInfo" language="en_US" tech="SIP">
630  <para>The <literal>from</literal> parameter can be a configured peer name
631  or in the form of "display-name" &lt;URI&gt;.</para>
632  </info>
633  <info name="MessageToInfo" language="en_US" tech="SIP">
634  <para>Ignored</para>
635  </info>
636  <managerEvent language="en_US" name="SIPQualifyPeerDone">
637  <managerEventInstance class="EVENT_FLAG_CALL">
638  <synopsis>Raised when SIPQualifyPeer has finished qualifying the specified peer.</synopsis>
639  <syntax>
640  <parameter name="Peer">
641  <para>The name of the peer.</para>
642  </parameter>
643  <parameter name="ActionID">
644  <para>This is only included if an ActionID Header was sent with the action request, in which case it will be that ActionID.</para>
645  </parameter>
646  </syntax>
647  <see-also>
648  <ref type="manager">SIPqualifypeer</ref>
649  </see-also>
650  </managerEventInstance>
651  </managerEvent>
652  <managerEvent language="en_US" name="SessionTimeout">
653  <managerEventInstance class="EVENT_FLAG_CALL">
654  <synopsis>Raised when a SIP session times out.</synopsis>
655  <syntax>
656  <channel_snapshot/>
657  <parameter name="Source">
658  <para>The source of the session timeout.</para>
659  <enumlist>
660  <enum name="RTPTimeout" />
661  <enum name="SIPSessionTimer" />
662  </enumlist>
663  </parameter>
664  </syntax>
665  </managerEventInstance>
666  </managerEvent>
667  ***/
668 
669 static int log_level = -1;
670 
671 static int min_expiry = DEFAULT_MIN_EXPIRY; /*!< Minimum accepted registration time */
672 static int max_expiry = DEFAULT_MAX_EXPIRY; /*!< Maximum accepted registration time */
674 static int min_subexpiry = DEFAULT_MIN_EXPIRY; /*!< Minimum accepted subscription time */
675 static int max_subexpiry = DEFAULT_MAX_EXPIRY; /*!< Maximum accepted subscription time */
677 
678 static int unauth_sessions = 0;
681 
682 /*! \brief Global jitterbuffer configuration - by default, jb is disabled
683  * \note Values shown here match the defaults shown in sip.conf.sample */
685 {
686  .flags = 0,
687  .max_size = 200,
688  .resync_threshold = 1000,
689  .impl = "fixed",
690  .target_extra = 40,
691 };
692 static struct ast_jb_conf global_jbconf; /*!< Global jitterbuffer configuration */
693 
694 static const char config[] = "sip.conf"; /*!< Main configuration file */
695 static const char notify_config[] = "sip_notify.conf"; /*!< Configuration file for sending Notify with CLI commands to reconfigure or reboot phones */
696 
697 /*! \brief Readable descriptions of device states.
698  * \note Should be aligned to above table as index */
699 static const struct invstate2stringtable {
700  const enum invitestates state;
701  const char *desc;
702 } invitestate2string[] = {
703  {INV_NONE, "None" },
704  {INV_CALLING, "Calling (Trying)"},
705  {INV_PROCEEDING, "Proceeding "},
706  {INV_EARLY_MEDIA, "Early media"},
707  {INV_COMPLETED, "Completed (done)"},
708  {INV_CONFIRMED, "Confirmed (up)"},
709  {INV_TERMINATED, "Done"},
710  {INV_CANCELLED, "Cancelled"}
711 };
712 
713 /*! \brief Subscription types that we support. We support
714  * - dialoginfo updates (really device status, not dialog info as was the original intent of the standard)
715  * - SIMPLE presence used for device status
716  * - Voicemail notification subscriptions
717  */
718 static const struct cfsubscription_types {
720  const char * const event;
721  const char * const mediatype;
722  const char * const text;
723 } subscription_types[] = {
724  { NONE, "-", "unknown", "unknown" },
725  /* RFC 4235: SIP Dialog event package */
726  { DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
727  { CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" }, /* RFC 3863 */
728  { PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" }, /* RFC 3863 */
729  { XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" }, /* Pre-RFC 3863 with MS additions */
730  { MWI_NOTIFICATION, "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
731 };
732 
733 /*! \brief The core structure to setup dialogs. We parse incoming messages by using
734  * structure and then route the messages according to the type.
735  *
736  * \note Note that sip_methods[i].id == i must hold or the code breaks
737  */
738 static const struct cfsip_methods {
739  enum sipmethod id;
740  int need_rtp; /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
741  char * const text;
742  enum can_create_dialog can_create;
743 } sip_methods[] = {
744  { SIP_UNKNOWN, RTP, "-UNKNOWN-",CAN_CREATE_DIALOG },
745  { SIP_RESPONSE, NO_RTP, "SIP/2.0", CAN_NOT_CREATE_DIALOG },
746  { SIP_REGISTER, NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
747  { SIP_OPTIONS, NO_RTP, "OPTIONS", CAN_CREATE_DIALOG },
748  { SIP_NOTIFY, NO_RTP, "NOTIFY", CAN_CREATE_DIALOG },
749  { SIP_INVITE, RTP, "INVITE", CAN_CREATE_DIALOG },
750  { SIP_ACK, NO_RTP, "ACK", CAN_NOT_CREATE_DIALOG },
751  { SIP_PRACK, NO_RTP, "PRACK", CAN_NOT_CREATE_DIALOG },
752  { SIP_BYE, NO_RTP, "BYE", CAN_NOT_CREATE_DIALOG },
753  { SIP_REFER, NO_RTP, "REFER", CAN_CREATE_DIALOG },
754  { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE",CAN_CREATE_DIALOG },
755  { SIP_MESSAGE, NO_RTP, "MESSAGE", CAN_CREATE_DIALOG },
756  { SIP_UPDATE, NO_RTP, "UPDATE", CAN_NOT_CREATE_DIALOG },
757  { SIP_INFO, NO_RTP, "INFO", CAN_NOT_CREATE_DIALOG },
758  { SIP_CANCEL, NO_RTP, "CANCEL", CAN_NOT_CREATE_DIALOG },
759  { SIP_PUBLISH, NO_RTP, "PUBLISH", CAN_CREATE_DIALOG },
761 };
762 
763 /*! \brief Diversion header reasons
764  *
765  * The core defines a bunch of constants used to define
766  * redirecting reasons. This provides a translation table
767  * between those and the strings which may be present in
768  * a SIP Diversion header
769  */
770 static const struct sip_reasons {
772  const char *text;
773 } sip_reason_table[] = {
774  { AST_REDIRECTING_REASON_UNKNOWN, "unknown" },
775  { AST_REDIRECTING_REASON_USER_BUSY, "user-busy" },
776  { AST_REDIRECTING_REASON_NO_ANSWER, "no-answer" },
777  { AST_REDIRECTING_REASON_UNAVAILABLE, "unavailable" },
778  { AST_REDIRECTING_REASON_UNCONDITIONAL, "unconditional" },
779  { AST_REDIRECTING_REASON_TIME_OF_DAY, "time-of-day" },
780  { AST_REDIRECTING_REASON_DO_NOT_DISTURB, "do-not-disturb" },
781  { AST_REDIRECTING_REASON_DEFLECTION, "deflection" },
782  { AST_REDIRECTING_REASON_FOLLOW_ME, "follow-me" },
783  { AST_REDIRECTING_REASON_OUT_OF_ORDER, "out-of-service" },
784  { AST_REDIRECTING_REASON_AWAY, "away" },
785  { AST_REDIRECTING_REASON_CALL_FWD_DTE, "cf_dte" }, /* Non-standard */
786  { AST_REDIRECTING_REASON_SEND_TO_VM, "send_to_vm" }, /* Non-standard */
787 };
788 
789 
790 /*! \name DefaultSettings
791  Default setttings are used as a channel setting and as a default when
792  configuring devices
793 */
794 static char default_language[MAX_LANGUAGE]; /*!< Default language setting for new channels */
795 static char default_callerid[AST_MAX_EXTENSION]; /*!< Default caller ID for sip messages */
796 static char default_mwi_from[80]; /*!< Default caller ID for MWI updates */
797 static char default_fromdomain[AST_MAX_EXTENSION]; /*!< Default domain on outound messages */
798 static int default_fromdomainport; /*!< Default domain port on outbound messages */
799 static char default_notifymime[AST_MAX_EXTENSION]; /*!< Default MIME media type for MWI notify messages */
800 static char default_vmexten[AST_MAX_EXTENSION]; /*!< Default From Username on MWI updates */
801 static int default_qualify; /*!< Default Qualify= setting */
802 static int default_keepalive; /*!< Default keepalive= setting */
803 static char default_mohinterpret[MAX_MUSICCLASS]; /*!< Global setting for moh class to use when put on hold */
804 static char default_mohsuggest[MAX_MUSICCLASS]; /*!< Global setting for moh class to suggest when putting
805  * a bridged channel on hold */
806 static char default_parkinglot[AST_MAX_CONTEXT]; /*!< Parkinglot */
807 static char default_engine[256]; /*!< Default RTP engine */
808 static int default_maxcallbitrate; /*!< Maximum bitrate for call */
809 static char default_zone[MAX_TONEZONE_COUNTRY]; /*!< Default tone zone for channels created from the SIP driver */
810 static unsigned int default_transports; /*!< Default Transports (enum ast_transport) that are acceptable */
811 static unsigned int default_primary_transport; /*!< Default primary Transport (enum ast_transport) for outbound connections to devices */
812 
813 static struct sip_settings sip_cfg; /*!< SIP configuration data.
814  \note in the future we could have multiple of these (per domain, per device group etc) */
815 
816 /*!< use this macro when ast_uri_decode is dependent on pedantic checking to be on. */
817 #define SIP_PEDANTIC_DECODE(str) \
818  if (sip_cfg.pedanticsipchecking && !ast_strlen_zero(str)) { \
819  ast_uri_decode(str, ast_uri_sip_user); \
820  } \
821 
822 static unsigned int chan_idx; /*!< used in naming sip channel */
823 static int global_match_auth_username; /*!< Match auth username if available instead of From: Default off. */
824 
825 static int global_relaxdtmf; /*!< Relax DTMF */
826 static int global_prematuremediafilter; /*!< Enable/disable premature frames in a call (causing 183 early media) */
827 static int global_rtptimeout; /*!< Time out call if no RTP */
828 static int global_rtpholdtimeout; /*!< Time out call if no RTP during hold */
829 static int global_rtpkeepalive; /*!< Send RTP keepalives */
830 static int global_reg_timeout; /*!< Global time between attempts for outbound registrations */
831 static int global_regattempts_max; /*!< Registration attempts before giving up */
832 static int global_reg_retry_403; /*!< Treat 403 responses to registrations as 401 responses */
833 static int global_shrinkcallerid; /*!< enable or disable shrinking of caller id */
834 static int global_callcounter; /*!< Enable call counters for all devices. This is currently enabled by setting the peer
835  * call-limit to INT_MAX. When we remove the call-limit from the code, we can make it
836  * with just a boolean flag in the device structure */
837 static unsigned int global_tos_sip; /*!< IP type of service for SIP packets */
838 static unsigned int global_tos_audio; /*!< IP type of service for audio RTP packets */
839 static unsigned int global_tos_video; /*!< IP type of service for video RTP packets */
840 static unsigned int global_tos_text; /*!< IP type of service for text RTP packets */
841 static unsigned int global_cos_sip; /*!< 802.1p class of service for SIP packets */
842 static unsigned int global_cos_audio; /*!< 802.1p class of service for audio RTP packets */
843 static unsigned int global_cos_video; /*!< 802.1p class of service for video RTP packets */
844 static unsigned int global_cos_text; /*!< 802.1p class of service for text RTP packets */
845 static unsigned int recordhistory; /*!< Record SIP history. Off by default */
846 static unsigned int dumphistory; /*!< Dump history to verbose before destroying SIP dialog */
847 static char global_useragent[AST_MAX_EXTENSION]; /*!< Useragent for the SIP channel */
848 static char global_sdpsession[AST_MAX_EXTENSION]; /*!< SDP session name for the SIP channel */
849 static char global_sdpowner[AST_MAX_EXTENSION]; /*!< SDP owner name for the SIP channel */
850 static int global_authfailureevents; /*!< Whether we send authentication failure manager events or not. Default no. */
851 static int global_t1; /*!< T1 time */
852 static int global_t1min; /*!< T1 roundtrip time minimum */
853 static int global_timer_b; /*!< Timer B - RFC 3261 Section 17.1.1.2 */
854 static unsigned int global_autoframing; /*!< Turn autoframing on or off. */
855 static int global_qualifyfreq; /*!< Qualify frequency */
856 static int global_qualify_gap; /*!< Time between our group of peer pokes */
857 static int global_qualify_peers; /*!< Number of peers to poke at a given time */
858 
859 static enum st_mode global_st_mode; /*!< Mode of operation for Session-Timers */
860 static enum st_refresher_param global_st_refresher; /*!< Session-Timer refresher */
861 static int global_min_se; /*!< Lowest threshold for session refresh interval */
862 static int global_max_se; /*!< Highest threshold for session refresh interval */
863 
864 static int global_store_sip_cause; /*!< Whether the MASTER_CHANNEL(HASH(SIP_CAUSE,[chan_name])) var should be set */
865 
866 static int global_dynamic_exclude_static = 0; /*!< Exclude static peers from contact registrations */
867 static unsigned char global_refer_addheaders; /*!< Add extra headers to outgoing REFER */
868 /*@}*/
869 
870 /*!
871  * We use libxml2 in order to parse XML that may appear in the body of a SIP message. Currently,
872  * the only usage is for parsing PIDF bodies of incoming PUBLISH requests in the call-completion
873  * event package. This variable is set at module load time and may be checked at runtime to determine
874  * if XML parsing support was found.
875  */
876 static int can_parse_xml;
877 
878 /*! \name Object counters @{
879  *
880  * \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
881  * should be used to modify these values.
882  */
883 static int speerobjs = 0; /*!< Static peers */
884 static int rpeerobjs = 0; /*!< Realtime peers */
885 static int apeerobjs = 0; /*!< Autocreated peer objects */
886 /*! @} */
887 
888 static struct ast_flags global_flags[3] = {{0}}; /*!< global SIP_ flags */
889 static unsigned int global_t38_maxdatagram; /*!< global T.38 FaxMaxDatagram override */
890 
891 static struct stasis_subscription *network_change_sub; /*!< subscription id for network change events */
892 static struct stasis_subscription *acl_change_sub; /*!< subscription id for named ACL system change events */
893 static int network_change_sched_id = -1;
894 
895 static char used_context[AST_MAX_CONTEXT]; /*!< name of automatically created context for unloading */
896 
898 
899 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
900  when it's doing something critical. */
902 
904 
905 /*! \brief This is the thread for the monitor which checks for input on the channels
906  which are not currently in use. */
908 
909 static int sip_reloading = FALSE; /*!< Flag for avoiding multiple reloads at the same time */
910 static enum channelreloadreason sip_reloadreason; /*!< Reason for last reload/load of configuration */
911 
912 struct ast_sched_context *sched; /*!< The scheduling context */
913 static struct io_context *io; /*!< The IO context */
914 static int *sipsock_read_id; /*!< ID of IO entry for sipsock FD */
915 struct sip_pkt;
916 static AST_LIST_HEAD_STATIC(domain_list, domain); /*!< The SIP domain list */
917 
918 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
919 
920 static enum sip_debug_e sipdebug;
921 
922 /*! \brief extra debugging for 'text' related events.
923  * At the moment this is set together with sip_debug_console.
924  * \note It should either go away or be implemented properly.
925  */
926 static int sipdebug_text;
927 
928 static const struct _map_x_s referstatusstrings[] = {
929  { REFER_IDLE, "<none>" },
930  { REFER_SENT, "Request sent" },
931  { REFER_RECEIVED, "Request received" },
932  { REFER_CONFIRMED, "Confirmed" },
933  { REFER_ACCEPTED, "Accepted" },
934  { REFER_RINGING, "Target ringing" },
935  { REFER_200OK, "Done" },
936  { REFER_FAILED, "Failed" },
937  { REFER_NOAUTH, "Failed - auth failure" },
938  { -1, NULL} /* terminator */
939 };
940 
941 /* --- Hash tables of various objects --------*/
942 #ifdef LOW_MEMORY
943 static const int HASH_PEER_SIZE = 17;
944 static const int HASH_DIALOG_SIZE = 17;
945 static const int HASH_REGISTRY_SIZE = 17;
946 #else
947 static const int HASH_PEER_SIZE = 563; /*!< Size of peer hash table, prime number preferred! */
948 static const int HASH_DIALOG_SIZE = 563;
949 static const int HASH_REGISTRY_SIZE = 563;
950 #endif
951 
952 static const struct {
954  const char *service_string;
955 } sip_cc_service_map [] = {
956  [AST_CC_NONE] = { AST_CC_NONE, "" },
957  [AST_CC_CCBS] = { AST_CC_CCBS, "BS" },
958  [AST_CC_CCNR] = { AST_CC_CCNR, "NR" },
959  [AST_CC_CCNL] = { AST_CC_CCNL, "NL" },
960 };
961 
962 static const struct {
964  const char *state_string;
966  [CC_QUEUED] = {CC_QUEUED, "cc-state: queued"},
967  [CC_READY] = {CC_READY, "cc-state: ready"},
968 };
969 
971 
972 
973 /*!
974  * Used to create new entity IDs by ESCs.
975  */
976 static int esc_etag_counter;
977 static const int DEFAULT_PUBLISH_EXPIRES = 3600;
978 
979 #ifdef HAVE_LIBXML2
980 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);
981 
984  .modify_handler = cc_esc_publish_handler,
985 };
986 #endif
987 
988 /*!
989  * \brief The Event State Compositors
990  *
991  * An Event State Compositor is an entity which
992  * accepts PUBLISH requests and acts appropriately
993  * based on these requests.
994  *
995  * The actual event_state_compositor structure is simply
996  * an ao2_container of sip_esc_entrys. When an incoming
997  * PUBLISH is received, we can match the appropriate sip_esc_entry
998  * using the entity ID of the incoming PUBLISH.
999  */
1000 static struct event_state_compositor {
1002  const char * name;
1005 } event_state_compositors [] = {
1006 #ifdef HAVE_LIBXML2
1007  {CALL_COMPLETION, "call-completion", &cc_esc_publish_callbacks},
1008 #endif
1009 };
1010 
1012  int state;
1015  const char *presence_subtype;
1016  const char *presence_message;
1017 };
1018 
1019 
1020 static const int ESC_MAX_BUCKETS = 37;
1021 
1022 /*!
1023  * \details
1024  * Here we implement the container for dialogs which are in the
1025  * dialog_needdestroy state to iterate only through the dialogs
1026  * unlink them instead of iterate through all dialogs
1027  */
1029 
1030 /*!
1031  * \details
1032  * Here we implement the container for dialogs which have rtp
1033  * traffic and rtptimeout, rtpholdtimeout or rtpkeepalive
1034  * set. We use this container instead the whole dialog list.
1035  */
1037 
1038 /*!
1039  * \details
1040  * Here we implement the container for dialogs (sip_pvt), defining
1041  * generic wrapper functions to ease the transition from the current
1042  * implementation (a single linked list) to a different container.
1043  * In addition to a reference to the container, we need functions to lock/unlock
1044  * the container and individual items, and functions to add/remove
1045  * references to the individual items.
1046  */
1047 static struct ao2_container *dialogs;
1048 #define sip_pvt_lock(x) ao2_lock(x)
1049 #define sip_pvt_trylock(x) ao2_trylock(x)
1050 #define sip_pvt_unlock(x) ao2_unlock(x)
1051 
1052 /*! \brief The table of TCP threads */
1053 static struct ao2_container *threadt;
1054 
1055 /*! \brief The peer list: Users, Peers and Friends */
1056 static struct ao2_container *peers;
1058 
1059 /*! \brief A bogus peer, to be used when authentication should fail */
1060 static AO2_GLOBAL_OBJ_STATIC(g_bogus_peer);
1061 /*! \brief We can recognize the bogus peer by this invalid MD5 hash */
1062 #define BOGUS_PEER_MD5SECRET "intentionally_invalid_md5_string"
1063 
1064 /*! \brief The register list: Other SIP proxies we register with and receive calls from */
1066 
1067 /*! \brief The MWI subscription list */
1069 
1070 static int temp_pvt_init(void *);
1071 static void temp_pvt_cleanup(void *);
1072 
1073 /*! \brief A per-thread temporary pvt structure */
1075 
1076 /*! \brief A per-thread buffer for transport to string conversion */
1078 
1079 /*! \brief Size of the SIP transport buffer */
1080 #define SIP_TRANSPORT_STR_BUFSIZE 128
1081 
1082 /*! \brief Authentication container for realm authentication */
1083 static struct sip_auth_container *authl = NULL;
1084 /*! \brief Global authentication container protection while adjusting the references. */
1086 
1088 STASIS_MESSAGE_TYPE_DEFN_LOCAL(session_timeout_type,
1090  );
1091 
1092 /* --- Sockets and networking --------------*/
1093 
1094 /*! \brief Main socket for UDP SIP communication.
1095  *
1096  * sipsock is shared between the SIP manager thread (which handles reload
1097  * requests), the udp io handler (sipsock_read()) and the user routines that
1098  * issue udp writes (using __sip_xmit()).
1099  * The socket is -1 only when opening fails (this is a permanent condition),
1100  * or when we are handling a reload() that changes its address (this is
1101  * a transient situation during which we might have a harmless race, see
1102  * below). Because the conditions for the race to be possible are extremely
1103  * rare, we don't want to pay the cost of locking on every I/O.
1104  * Rather, we remember that when the race may occur, communication is
1105  * bound to fail anyways, so we just live with this event and let
1106  * the protocol handle this above us.
1107  */
1108 static int sipsock = -1;
1109 
1110 struct ast_sockaddr bindaddr; /*!< UDP: The address we bind to */
1111 
1112 /*! \brief our (internal) default address/port to put in SIP/SDP messages
1113  * internip is initialized picking a suitable address from one of the
1114  * interfaces, and the same port number we bind to. It is used as the
1115  * default address/port in SIP messages, and as the default address
1116  * (but not port) in SDP messages.
1117  */
1118 static struct ast_sockaddr internip;
1119 
1120 /*! \brief our external IP address/port for SIP sessions.
1121  * externaddr.sin_addr is only set when we know we might be behind
1122  * a NAT, and this is done using a variety of (mutually exclusive)
1123  * ways from the config file:
1124  *
1125  * + with "externaddr = host[:port]" we specify the address/port explicitly.
1126  * The address is looked up only once when (re)loading the config file;
1127  *
1128  * + with "externhost = host[:port]" we do a similar thing, but the
1129  * hostname is stored in externhost, and the hostname->IP mapping
1130  * is refreshed every 'externrefresh' seconds;
1131  *
1132  * Other variables (externhost, externexpire, externrefresh) are used
1133  * to support the above functions.
1134  */
1135 static struct ast_sockaddr externaddr; /*!< External IP address if we are behind NAT */
1136 static struct ast_sockaddr media_address; /*!< External RTP IP address if we are behind NAT */
1137 static struct ast_sockaddr rtpbindaddr; /*!< RTP: The address we bind to */
1138 
1139 static char externhost[MAXHOSTNAMELEN]; /*!< External host name */
1140 static time_t externexpire; /*!< Expiration counter for re-resolving external host name in dynamic DNS */
1141 static int externrefresh = 10; /*!< Refresh timer for DNS-based external address (dyndns) */
1142 static uint16_t externtcpport; /*!< external tcp port */
1143 static uint16_t externtlsport; /*!< external tls port */
1144 
1145 /*! \brief List of local networks
1146  * We store "localnet" addresses from the config file into an access list,
1147  * marked as 'DENY', so the call to ast_apply_ha() will return
1148  * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
1149  * (i.e. presumably public) addresses.
1150  */
1151 static struct ast_ha *localaddr; /*!< List of local networks, on the same side of NAT as this Asterisk */
1152 
1153 static int ourport_tcp; /*!< The port used for TCP connections */
1154 static int ourport_tls; /*!< The port used for TCP/TLS connections */
1155 static struct ast_sockaddr debugaddr;
1156 
1157 static struct ast_config *notify_types = NULL; /*!< The list of manual NOTIFY types we know how to send */
1158 
1159 /*! some list management macros. */
1160 
1161 #define UNLINK(element, head, prev) do { \
1162  if (prev) \
1163  (prev)->next = (element)->next; \
1164  else \
1165  (head) = (element)->next; \
1166  } while (0)
1167 
1169 
1170 struct show_peers_context;
1171 
1172 /*---------------------------- Forward declarations of functions in chan_sip.c */
1173 /* Note: This is added to help splitting up chan_sip.c into several files
1174  in coming releases. */
1175 
1176 /*--- PBX interface functions */
1177 static struct ast_channel *sip_request_call(const char *type, struct ast_format_cap *cap, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *dest, int *cause);
1178 static int sip_devicestate(const char *data);
1179 static int sip_sendtext(struct ast_channel *ast, const char *text);
1180 static int sip_call(struct ast_channel *ast, const char *dest, int timeout);
1181 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
1182 static int sip_hangup(struct ast_channel *ast);
1183 static int sip_answer(struct ast_channel *ast);
1184 static struct ast_frame *sip_read(struct ast_channel *ast);
1185 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
1186 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
1187 static int sip_transfer(struct ast_channel *ast, const char *dest);
1188 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1189 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
1190 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
1191 static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen);
1192 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
1193 static const char *sip_get_callid(struct ast_channel *chan);
1194 
1195 static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr);
1196 static int sip_standard_port(enum ast_transport type, int port);
1197 static int sip_prepare_socket(struct sip_pvt *p);
1198 static int get_address_family_filter(unsigned int transport);
1199 
1200 /*--- Transmitting responses and requests */
1201 static int sipsock_read(int *id, int fd, short events, void *ignore);
1202 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data);
1203 static int __sip_reliable_xmit(struct sip_pvt *p, uint32_t seqno, int resp, struct ast_str *data, int fatal, int sipmethod);
1204 static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp);
1205 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1206 static int retrans_pkt(const void *data);
1207 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);
1208 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1209 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1210 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1211 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);
1212 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
1213 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);
1214 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
1215 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1216 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable);
1217 static int transmit_request(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch);
1218 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch);
1219 static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri);
1220 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri);
1221 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
1222 static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded);
1223 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
1224 static int transmit_info_with_vidupdate(struct sip_pvt *p);
1225 static int transmit_message(struct sip_pvt *p, int init, int auth);
1226 static int transmit_refer(struct sip_pvt *p, const char *dest);
1227 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
1228 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
1229 static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state);
1230 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
1231 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno);
1232 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno);
1233 static void copy_request(struct sip_request *dst, const struct sip_request *src);
1234 static void receive_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
1235 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward);
1236 static int sip_send_mwi_to_peer(struct sip_peer *peer, int cache_only);
1237 
1238 /* Misc dialog routines */
1239 static int __sip_autodestruct(const void *data);
1240 static int update_call_counter(struct sip_pvt *fup, int event);
1241 static int auto_congest(const void *arg);
1242 static struct sip_pvt *__find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method,
1243  const char *file, int line, const char *func);
1244 #define find_call(req, addr, intended_method) \
1245  __find_call(req, addr, intended_method, __FILE__, __LINE__, __PRETTY_FUNCTION__)
1246 
1247 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards, int resp);
1248 static int build_path(struct sip_pvt *p, struct sip_peer *peer, struct sip_request *req, const char *pathbuf);
1249 static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
1250  struct sip_request *req, const char *uri);
1251 static int get_sip_pvt_from_replaces(const char *callid, const char *totag, const char *fromtag,
1252  struct sip_pvt **out_pvt, struct ast_channel **out_chan);
1253 static void check_pendings(struct sip_pvt *p);
1254 static void sip_set_owner(struct sip_pvt *p, struct ast_channel *chan);
1255 
1256 static void *sip_pickup_thread(void *stuff);
1257 static int sip_pickup(struct ast_channel *chan);
1258 
1259 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1260 static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method);
1261 
1262 /*--- Codec handling / SDP */
1263 static void try_suggested_sip_codec(struct sip_pvt *p);
1264 static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
1265 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
1266 static int find_sdp(struct sip_request *req);
1267 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action, int is_offer);
1268 static int process_sdp_o(const char *o, struct sip_pvt *p);
1269 static int process_sdp_c(const char *c, struct ast_sockaddr *addr);
1270 static int process_sdp_a_sendonly(const char *a, int *sendonly);
1271 static int process_sdp_a_ice(const char *a, struct sip_pvt *p, struct ast_rtp_instance *instance, int rtcp_mux);
1272 static int process_sdp_a_rtcp_mux(const char *a, struct sip_pvt *p, int *requested);
1273 static int process_sdp_a_dtls(const char *a, struct sip_pvt *p, struct ast_rtp_instance *instance);
1274 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec);
1275 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec);
1276 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);
1277 static int process_sdp_a_image(const char *a, struct sip_pvt *p);
1278 static void add_ice_to_sdp(struct ast_rtp_instance *instance, struct ast_str **a_buf);
1279 static void add_dtls_to_sdp(struct ast_rtp_instance *instance, struct ast_str **a_buf);
1280 static void start_ice(struct ast_rtp_instance *instance, int offer);
1281 static void add_codec_to_sdp(const struct sip_pvt *p, struct ast_format *codec,
1282  struct ast_str **m_buf, struct ast_str **a_buf,
1283  int debug, int *min_packet_size, int *max_packet_size);
1284 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
1285  struct ast_str **m_buf, struct ast_str **a_buf,
1286  int debug);
1287 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
1288 static void do_setnat(struct sip_pvt *p);
1289 static void stop_media_flows(struct sip_pvt *p);
1290 
1291 /*--- Authentication stuff */
1292 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1293 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
1294 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1295  const char *secret, const char *md5secret, int sipmethod,
1296  const char *uri, enum xmittype reliable);
1297 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
1298  int sipmethod, const char *uri, enum xmittype reliable,
1299  struct ast_sockaddr *addr, struct sip_peer **authpeer);
1300 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr);
1301 
1302 /*--- Domain handling */
1303 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1304 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
1305 static void clear_sip_domains(void);
1306 
1307 /*--- SIP realm authentication */
1308 static void add_realm_authentication(struct sip_auth_container **credentials, const char *configuration, int lineno);
1309 static struct sip_auth *find_realm_authentication(struct sip_auth_container *credentials, const char *realm);
1310 
1311 /*--- Misc functions */
1312 static int check_rtp_timeout(struct sip_pvt *dialog, time_t t);
1313 static int reload_config(enum channelreloadreason reason);
1314 static void add_diversion(struct sip_request *req, struct sip_pvt *pvt);
1315 static int expire_register(const void *data);
1316 static void *do_monitor(void *data);
1317 static int restart_monitor(void);
1318 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
1319 static struct ast_variable *copy_vars(struct ast_variable *src);
1320 static int dialog_find_multiple(void *obj, void *arg, int flags);
1321 static struct ast_channel *sip_pvt_lock_full(struct sip_pvt *pvt);
1322 /* static int sip_addrcmp(char *name, struct sockaddr_in *sin); Support for peer matching */
1323 static int sip_refer_alloc(struct sip_pvt *p);
1324 static void sip_refer_destroy(struct sip_pvt *p);
1325 static int sip_notify_alloc(struct sip_pvt *p);
1326 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
1327 static void set_peer_nat(const struct sip_pvt *p, struct sip_peer *peer);
1328 static void check_for_nat(const struct ast_sockaddr *them, struct sip_pvt *p);
1329 
1330 /*--- Device monitoring and Device/extension state/event handling */
1331 static int extensionstate_update(const char *context, const char *exten, struct state_notify_data *data, struct sip_pvt *p, int force);
1332 static int cb_extensionstate(const char *context, const char *exten, struct ast_state_cb_info *info, void *data);
1333 static int sip_poke_noanswer(const void *data);
1334 static int sip_poke_peer(struct sip_peer *peer, int force);
1335 static void sip_poke_all_peers(void);
1336 static void sip_peer_hold(struct sip_pvt *p, int hold);
1337 static void mwi_event_cb(void *, struct stasis_subscription *, struct stasis_message *);
1338 static void network_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
1339 static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
1340 static void sip_keepalive_all_peers(void);
1341 #define peer_in_destruction(peer) (ao2_ref(peer, 0) == 0)
1342 
1343 /*--- Applications, functions, CLI and manager command helpers */
1344 static const char *sip_nat_mode(const struct sip_pvt *p);
1345 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1346 static char *transfermode2str(enum transfermodes mode) attribute_const;
1347 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
1348 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1349 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1350 static struct sip_peer *_sip_show_peers_one(int fd, struct mansession *s, struct show_peers_context *cont, struct sip_peer *peer);
1351 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1352 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1353 static void print_group(int fd, ast_group_t group, int crlf);
1354 static void print_named_groups(int fd, struct ast_namedgroups *groups, int crlf);
1355 static const char *dtmfmode2str(int mode) attribute_const;
1356 static int str2dtmfmode(const char *str) attribute_unused;
1357 static const char *insecure2str(int mode) attribute_const;
1358 static const char *allowoverlap2str(int mode) attribute_const;
1359 static void cleanup_stale_contexts(char *new, char *old);
1360 static const char *domain_mode_to_text(const enum domain_mode mode);
1361 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1362 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1363 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1364 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1365 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1366 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1367 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1368 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1369 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1370 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
1371 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1372 static char *complete_sip_peer(const char *word, int state, int flags2);
1373 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
1374 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
1375 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
1376 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
1377 static char *complete_sip_notify(const char *line, const char *word, int pos, int state);
1378 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1379 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1380 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1381 static char *sip_do_debug_ip(int fd, const char *arg);
1382 static char *sip_do_debug_peer(int fd, const char *arg);
1383 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1384 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1385 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1386 static int sip_dtmfmode(struct ast_channel *chan, const char *data);
1387 static int sip_addheader(struct ast_channel *chan, const char *data);
1388 static int sip_do_reload(enum channelreloadreason reason);
1389 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1390 static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
1391  const char *name, int flag);
1392 static int ast_sockaddr_resolve_first_transport(struct ast_sockaddr *addr,
1393  const char *name, int flag, unsigned int transport);
1394 
1395 /*--- Debugging
1396  Functions for enabling debug per IP or fully, or enabling history logging for
1397  a SIP dialog
1398 */
1399 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to debuglog at end of dialog, before destroying data */
1400 static inline int sip_debug_test_addr(const struct ast_sockaddr *addr);
1401 static inline int sip_debug_test_pvt(struct sip_pvt *p);
1402 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
1403 static void sip_dump_history(struct sip_pvt *dialog);
1404 
1405 /*--- Device object handling */
1406 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
1407 static int update_call_counter(struct sip_pvt *fup, int event);
1408 static void sip_destroy_peer(struct sip_peer *peer);
1409 static void sip_destroy_peer_fn(void *peer);
1410 static void set_peer_defaults(struct sip_peer *peer);
1411 static struct sip_peer *temp_peer(const char *name);
1412 static void register_peer_exten(struct sip_peer *peer, int onoff);
1413 static int sip_poke_peer_s(const void *data);
1414 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
1415 static void reg_source_db(struct sip_peer *peer);
1416 static void destroy_association(struct sip_peer *peer);
1417 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
1418 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
1419 static void set_socket_transport(struct sip_socket *socket, int transport);
1420 static int peer_ipcmp_cb_full(void *obj, void *arg, void *data, int flags);
1421 
1422 /* Realtime device support */
1423 static void realtime_update_peer(const char *peername, struct ast_sockaddr *addr, const char *username, const char *fullcontact, const char *useragent, int expirey, unsigned short deprecated_username, int lastms, const char *path);
1424 static void update_peer(struct sip_peer *p, int expire);
1426 static const char *get_name_from_variable(const struct ast_variable *var);
1427 static struct sip_peer *realtime_peer(const char *peername, struct ast_sockaddr *sin, char *callbackexten, int devstate_only, int which_objects);
1428 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1429 
1430 /*--- Internal UA client handling (outbound registrations) */
1431 static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p);
1432 static void sip_registry_destroy(void *reg);
1433 static int sip_register(const char *value, int lineno);
1434 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
1435 static int __sip_do_register(struct sip_registry *r);
1436 static int sip_reg_timeout(const void *data);
1437 static void sip_send_all_registers(void);
1438 static int sip_reinvite_retry(const void *data);
1439 
1440 /*--- Parsing SIP requests and responses */
1441 static int determine_firstline_parts(struct sip_request *req);
1442 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1443 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
1444 static int find_sip_method(const char *msg);
1445 static unsigned int parse_allowed_methods(struct sip_request *req);
1446 static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req);
1447 static int parse_request(struct sip_request *req);
1448 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
1449 static int method_match(enum sipmethod id, const char *name);
1450 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
1451 static void parse_oli(struct sip_request *req, struct ast_channel *chan);
1452 static const char *find_alias(const char *name, const char *_default);
1453 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
1454 static void lws2sws(struct ast_str *msgbuf);
1455 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
1456 static char *remove_uri_parameters(char *uri);
1457 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
1458 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
1459 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
1460 static int use_reason_header(struct sip_pvt *pvt, struct sip_request *req);
1461 static int set_address_from_contact(struct sip_pvt *pvt);
1462 static void check_via(struct sip_pvt *p, const struct sip_request *req);
1463 static int get_rpid(struct sip_pvt *p, struct sip_request *oreq);
1464 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason, char **reason_str);
1465 static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id);
1466 static int transmit_state_notify(struct sip_pvt *p, struct state_notify_data *data, int full, int timeout);
1467 static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen);
1468 static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen);
1469 static int get_domain(const char *str, char *domain, int len);
1470 static void get_realm(struct sip_pvt *p, const struct sip_request *req);
1471 static char *get_content(struct sip_request *req);
1472 
1473 /*-- TCP connection handling ---*/
1474 static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session);
1475 static void *sip_tcp_worker_fn(void *);
1476 
1477 /*--- Constructing requests and responses */
1478 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
1479 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
1480 static void deinit_req(struct sip_request *req);
1481 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, uint32_t seqno, int newbranch);
1482 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri);
1483 static int init_resp(struct sip_request *resp, const char *msg);
1484 static inline int resp_needs_contact(const char *msg, enum sipmethod method);
1485 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
1486 static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p);
1487 static void build_via(struct sip_pvt *p);
1488 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
1489 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog);
1490 static char *generate_random_string(char *buf, size_t size);
1491 static void build_callid_pvt(struct sip_pvt *pvt);
1492 static void change_callid_pvt(struct sip_pvt *pvt, const char *callid);
1493 static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain);
1494 static void build_localtag_registry(struct sip_registry *reg);
1495 static void make_our_tag(struct sip_pvt *pvt);
1496 static int add_header(struct sip_request *req, const char *var, const char *value);
1497 static int add_max_forwards(struct sip_pvt *dialog, struct sip_request *req);
1498 static int add_content(struct sip_request *req, const char *line);
1499 static int finalize_content(struct sip_request *req);
1500 static void destroy_msg_headers(struct sip_pvt *pvt);
1501 static int add_text(struct sip_request *req, struct sip_pvt *p);
1502 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
1503 static int add_rpid(struct sip_request *req, struct sip_pvt *p);
1504 static int add_vidupdate(struct sip_request *req);
1505 static void add_route(struct sip_request *req, struct sip_route *route, int skip);
1506 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1507 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1508 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
1509 static void set_destination(struct sip_pvt *p, const char *uri);
1510 static void add_date(struct sip_request *req);
1511 static void add_expires(struct sip_request *req, int expires);
1512 static void build_contact(struct sip_pvt *p, struct sip_request *req, int incoming);
1513 
1514 /*------Request handling functions */
1515 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock);
1516 static int handle_request_update(struct sip_pvt *p, struct sip_request *req);
1517 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);
1518 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, uint32_t seqno, int *nounlock);
1519 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
1520 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *sin, const char *e);
1521 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
1522 static int handle_request_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
1523 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
1524 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
1525 static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
1526 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req,
1527  int *nounlock, struct sip_pvt *replaces_pvt, struct ast_channel *replaces_chan);
1528 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
1529 static int local_attended_transfer(struct sip_pvt *transferer, struct ast_channel *transferer_chan, uint32_t seqno, int *nounlock);
1530 
1531 /*------Response handling functions */
1532 static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1533 static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1534 static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1535 static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1536 static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1537 static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1538 static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1539 
1540 /*------ SRTP Support -------- */
1541 static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct ast_sdp_srtp **srtp,
1542  const char *a);
1543 
1544 /*------ T38 Support --------- */
1545 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
1546 static void change_t38_state(struct sip_pvt *p, int state);
1547 
1548 /*------ Session-Timers functions --------- */
1549 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
1550 static void stop_session_timer(struct sip_pvt *p);
1551 static void start_session_timer(struct sip_pvt *p);
1552 static void restart_session_timer(struct sip_pvt *p);
1553 static const char *strefresherparam2str(enum st_refresher_param r);
1554 static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher_param *const p_ref);
1555 static int parse_minse(const char *p_hdrval, int *const p_interval);
1556 static int st_get_se(struct sip_pvt *, int max);
1557 static enum st_refresher st_get_refresher(struct sip_pvt *);
1558 static enum st_mode st_get_mode(struct sip_pvt *, int no_cached);
1559 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
1560 
1561 /*------- RTP Glue functions -------- */
1562 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);
1563 
1564 /*!--- SIP MWI Subscription support */
1565 static int sip_subscribe_mwi(const char *value, int lineno);
1566 static void sip_send_all_mwi_subscriptions(void);
1567 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
1568 
1569 /* Scheduler id start/stop/reschedule functions. */
1570 static void stop_provisional_keepalive(struct sip_pvt *pvt);
1571 static void do_stop_session_timer(struct sip_pvt *pvt);
1572 static void stop_reinvite_retry(struct sip_pvt *pvt);
1573 static void stop_retrans_pkt(struct sip_pkt *pkt);
1574 static void stop_t38_abort_timer(struct sip_pvt *pvt);
1575 
1576 /*! \brief Definition of this channel for PBX channel registration */
1578  .type = "SIP",
1579  .description = "Session Initiation Protocol (SIP)",
1581  .requester = sip_request_call, /* called with chan unlocked */
1582  .devicestate = sip_devicestate, /* called with chan unlocked (not chan-specific) */
1583  .call = sip_call, /* called with chan locked */
1584  .send_html = sip_sendhtml,
1585  .hangup = sip_hangup, /* called with chan locked */
1586  .answer = sip_answer, /* called with chan locked */
1587  .read = sip_read, /* called with chan locked */
1588  .write = sip_write, /* called with chan locked */
1589  .write_video = sip_write, /* called with chan locked */
1590  .write_text = sip_write,
1591  .indicate = sip_indicate, /* called with chan locked */
1592  .transfer = sip_transfer, /* called with chan locked */
1593  .fixup = sip_fixup, /* called with chan locked */
1594  .send_digit_begin = sip_senddigit_begin, /* called with chan unlocked */
1595  .send_digit_end = sip_senddigit_end,
1596  .early_bridge = ast_rtp_instance_early_bridge,
1597  .send_text = sip_sendtext, /* called with chan locked */
1598  .func_channel_read = sip_acf_channel_read,
1599  .setoption = sip_setoption,
1600  .queryoption = sip_queryoption,
1601  .get_pvt_uniqueid = sip_get_callid,
1602 };
1603 
1604 /*! \brief This version of the sip channel tech has no send_digit_begin
1605  * callback so that the core knows that the channel does not want
1606  * DTMF BEGIN frames.
1607  * The struct is initialized just before registering the channel driver,
1608  * and is for use with channels using SIP INFO DTMF.
1609  */
1611 
1612 /*------- CC Support -------- */
1613 static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan);
1614 static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent);
1615 static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent);
1616 static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason);
1617 static int sip_cc_agent_status_request(struct ast_cc_agent *agent);
1618 static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent);
1619 static int sip_cc_agent_recall(struct ast_cc_agent *agent);
1620 static void sip_cc_agent_destructor(struct ast_cc_agent *agent);
1621 
1623  .type = "SIP",
1624  .init = sip_cc_agent_init,
1625  .start_offer_timer = sip_cc_agent_start_offer_timer,
1626  .stop_offer_timer = sip_cc_agent_stop_offer_timer,
1627  .respond = sip_cc_agent_respond,
1628  .status_request = sip_cc_agent_status_request,
1629  .start_monitoring = sip_cc_agent_start_monitoring,
1630  .callee_available = sip_cc_agent_recall,
1631  .destructor = sip_cc_agent_destructor,
1632 };
1633 
1634 /* -------- End of declarations of structures, constants and forward declarations of functions
1635  Below starts actual code
1636  ------------------------
1637 */
1638 
1639 static int sip_epa_register(const struct epa_static_data *static_data)
1640 {
1641  struct epa_backend *backend = ast_calloc(1, sizeof(*backend));
1642 
1643  if (!backend) {
1644  return -1;
1645  }
1646 
1647  backend->static_data = static_data;
1648 
1652  return 0;
1653 }
1654 
1655 static void sip_epa_unregister_all(void)
1656 {
1657  struct epa_backend *backend;
1658 
1660  while ((backend = AST_LIST_REMOVE_HEAD(&epa_static_data_list, next))) {
1661  ast_free(backend);
1662  }
1664 }
1665 
1666 static void cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry);
1667 
1668 static void cc_epa_destructor(void *data)
1669 {
1670  struct sip_epa_entry *epa_entry = data;
1671  struct cc_epa_entry *cc_entry = epa_entry->instance_data;
1672  ast_free(cc_entry);
1673 }
1674 
1675 static const struct epa_static_data cc_epa_static_data = {
1677  .name = "call-completion",
1678  .handle_error = cc_handle_publish_error,
1679  .destructor = cc_epa_destructor,
1680 };
1681 
1682 static const struct epa_static_data *find_static_data(const char * const event_package)
1683 {
1684  const struct epa_backend *backend = NULL;
1685 
1688  if (!strcmp(backend->static_data->name, event_package)) {
1689  break;
1690  }
1691  }
1693  return backend ? backend->static_data : NULL;
1694 }
1695 
1696 static struct sip_epa_entry *create_epa_entry (const char * const event_package, const char * const destination)
1697 {
1698  struct sip_epa_entry *epa_entry;
1699  const struct epa_static_data *static_data;
1700 
1701  if (!(static_data = find_static_data(event_package))) {
1702  return NULL;
1703  }
1704 
1705  if (!(epa_entry = ao2_t_alloc(sizeof(*epa_entry), static_data->destructor, "Allocate new EPA entry"))) {
1706  return NULL;
1707  }
1708 
1709  epa_entry->static_data = static_data;
1710  ast_copy_string(epa_entry->destination, destination, sizeof(epa_entry->destination));
1711  return epa_entry;
1712 }
1714 {
1716  for (service = AST_CC_CCBS; service <= AST_CC_CCNL; ++service) {
1717  if (!strcasecmp(service_string, sip_cc_service_map[service].service_string)) {
1718  return service;
1719  }
1720  }
1721  return AST_CC_NONE;
1722 }
1723 
1724 /* Even state compositors code */
1725 static void esc_entry_destructor(void *obj)
1726 {
1727  struct sip_esc_entry *esc_entry = obj;
1728  if (esc_entry->sched_id > -1) {
1729  AST_SCHED_DEL(sched, esc_entry->sched_id);
1730  }
1731 }
1732 
1733 static int esc_hash_fn(const void *obj, const int flags)
1734 {
1735  const struct sip_esc_entry *entry = obj;
1736  return ast_str_hash(entry->entity_tag);
1737 }
1738 
1739 static int esc_cmp_fn(void *obj, void *arg, int flags)
1740 {
1741  struct sip_esc_entry *entry1 = obj;
1742  struct sip_esc_entry *entry2 = arg;
1743 
1744  return (!strcmp(entry1->entity_tag, entry2->entity_tag)) ? (CMP_MATCH | CMP_STOP) : 0;
1745 }
1746 
1747 static struct event_state_compositor *get_esc(const char * const event_package) {
1748  int i;
1749  for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1750  if (!strcasecmp(event_package, event_state_compositors[i].name)) {
1751  return &event_state_compositors[i];
1752  }
1753  }
1754  return NULL;
1755 }
1756 
1757 static struct sip_esc_entry *get_esc_entry(const char * entity_tag, struct event_state_compositor *esc) {
1758  struct sip_esc_entry *entry;
1759  struct sip_esc_entry finder;
1760 
1761  ast_copy_string(finder.entity_tag, entity_tag, sizeof(finder.entity_tag));
1762 
1763  entry = ao2_find(esc->compositor, &finder, OBJ_POINTER);
1764 
1765  return entry;
1766 }
1767 
1768 static int publish_expire(const void *data)
1769 {
1770  struct sip_esc_entry *esc_entry = (struct sip_esc_entry *) data;
1771  struct event_state_compositor *esc = get_esc(esc_entry->event);
1772 
1773  ast_assert(esc != NULL);
1774 
1775  ao2_unlink(esc->compositor, esc_entry);
1776  esc_entry->sched_id = -1;
1777  ao2_ref(esc_entry, -1);
1778  return 0;
1779 }
1780 
1781 static void create_new_sip_etag(struct sip_esc_entry *esc_entry, int is_linked)
1782 {
1783  int new_etag = ast_atomic_fetchadd_int(&esc_etag_counter, +1);
1784  struct event_state_compositor *esc = get_esc(esc_entry->event);
1785 
1786  ast_assert(esc != NULL);
1787  if (is_linked) {
1788  ao2_unlink(esc->compositor, esc_entry);
1789  }
1790  snprintf(esc_entry->entity_tag, sizeof(esc_entry->entity_tag), "%d", new_etag);
1791  ao2_link(esc->compositor, esc_entry);
1792 }
1793 
1794 static struct sip_esc_entry *create_esc_entry(struct event_state_compositor *esc, struct sip_request *req, const int expires)
1795 {
1796  struct sip_esc_entry *esc_entry;
1797  int expires_ms;
1798 
1799  if (!(esc_entry = ao2_alloc(sizeof(*esc_entry), esc_entry_destructor))) {
1800  return NULL;
1801  }
1802 
1803  esc_entry->event = esc->name;
1804 
1805  expires_ms = expires * 1000;
1806  /* Bump refcount for scheduler */
1807  ao2_ref(esc_entry, +1);
1808  esc_entry->sched_id = ast_sched_add(sched, expires_ms, publish_expire, esc_entry);
1809  if (esc_entry->sched_id == -1) {
1810  ao2_ref(esc_entry, -1);
1811  ao2_ref(esc_entry, -1);
1812  return NULL;
1813  }
1814 
1815  /* Note: This links the esc_entry into the ESC properly */
1816  create_new_sip_etag(esc_entry, 0);
1817 
1818  return esc_entry;
1819 }
1820 
1821 static int initialize_escs(void)
1822 {
1823  int i, res = 0;
1824  for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1827  if (!event_state_compositors[i].compositor) {
1828  res = -1;
1829  }
1830  }
1831  return res;
1832 }
1833 
1834 static void destroy_escs(void)
1835 {
1836  int i;
1837  for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1838  ao2_replace(event_state_compositors[i].compositor, NULL);
1839  }
1840 }
1841 
1842 
1843 static int find_by_notify_uri_helper(void *obj, void *arg, int flags)
1844 {
1845  struct ast_cc_agent *agent = obj;
1846  struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1847  const char *uri = arg;
1848 
1849  return !sip_uri_cmp(agent_pvt->notify_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
1850 }
1851 
1852 static struct ast_cc_agent *find_sip_cc_agent_by_notify_uri(const char * const uri)
1853 {
1854  struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_notify_uri_helper, (char *)uri, "SIP");
1855  return agent;
1856 }
1857 
1858 static int find_by_subscribe_uri_helper(void *obj, void *arg, int flags)
1859 {
1860  struct ast_cc_agent *agent = obj;
1861  struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1862  const char *uri = arg;
1863 
1864  return !sip_uri_cmp(agent_pvt->subscribe_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
1865 }
1866 
1867 static struct ast_cc_agent *find_sip_cc_agent_by_subscribe_uri(const char * const uri)
1868 {
1869  struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_subscribe_uri_helper, (char *)uri, "SIP");
1870  return agent;
1871 }
1872 
1873 static int find_by_callid_helper(void *obj, void *arg, int flags)
1874 {
1875  struct ast_cc_agent *agent = obj;
1876  struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1877  struct sip_pvt *call_pvt = arg;
1878 
1879  return !strcmp(agent_pvt->original_callid, call_pvt->callid) ? CMP_MATCH | CMP_STOP : 0;
1880 }
1881 
1883 {
1884  struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_callid_helper, pvt, "SIP");
1885  return agent;
1886 }
1887 
1888 static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan)
1889 {
1890  struct sip_cc_agent_pvt *agent_pvt = ast_calloc(1, sizeof(*agent_pvt));
1891  struct sip_pvt *call_pvt = ast_channel_tech_pvt(chan);
1892 
1893  if (!agent_pvt) {
1894  return -1;
1895  }
1896 
1897  ast_assert(!strcmp(ast_channel_tech(chan)->type, "SIP"));
1898 
1899  ast_copy_string(agent_pvt->original_callid, call_pvt->callid, sizeof(agent_pvt->original_callid));
1900  ast_copy_string(agent_pvt->original_exten, call_pvt->exten, sizeof(agent_pvt->original_exten));
1901  agent_pvt->offer_timer_id = -1;
1902  agent->private_data = agent_pvt;
1903  sip_pvt_lock(call_pvt);
1904  ast_set_flag(&call_pvt->flags[0], SIP_OFFER_CC);
1905  sip_pvt_unlock(call_pvt);
1906  return 0;
1907 }
1908 
1909 static int sip_offer_timer_expire(const void *data)
1910 {
1911  struct ast_cc_agent *agent = (struct ast_cc_agent *) data;
1912  struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1913 
1914  agent_pvt->offer_timer_id = -1;
1915 
1916  return ast_cc_failed(agent->core_id, "SIP agent %s's offer timer expired", agent->device_name);
1917 }
1918 
1920 {
1921  struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1922  int when;
1923 
1924  when = ast_get_cc_offer_timer(agent->cc_params) * 1000;
1925  agent_pvt->offer_timer_id = ast_sched_add(sched, when, sip_offer_timer_expire, agent);
1926  return 0;
1927 }
1928 
1930 {
1931  struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1932 
1933  AST_SCHED_DEL(sched, agent_pvt->offer_timer_id);
1934  return 0;
1935 }
1936 
1937 static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason)
1938 {
1939  struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1940 
1941  sip_pvt_lock(agent_pvt->subscribe_pvt);
1943  if (reason == AST_CC_AGENT_RESPONSE_SUCCESS || !ast_strlen_zero(agent_pvt->notify_uri)) {
1944  /* The second half of this if statement may be a bit hard to grasp,
1945  * so here's an explanation. When a subscription comes into
1946  * chan_sip, as long as it is not malformed, it will be passed
1947  * to the CC core. If the core senses an out-of-order state transition,
1948  * then the core will call this callback with the "reason" set to a
1949  * failure condition.
1950  * However, an out-of-order state transition will occur during a resubscription
1951  * for CC. In such a case, we can see that we have already generated a notify_uri
1952  * and so we can detect that this isn't a *real* failure. Rather, it is just
1953  * something the core doesn't recognize as a legitimate SIP state transition.
1954  * Thus we respond with happiness and flowers.
1955  */
1956  transmit_response(agent_pvt->subscribe_pvt, "200 OK", &agent_pvt->subscribe_pvt->initreq);
1957  transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_QUEUED);
1958  } else {
1959  transmit_response(agent_pvt->subscribe_pvt, "500 Internal Error", &agent_pvt->subscribe_pvt->initreq);
1960  }
1961  sip_pvt_unlock(agent_pvt->subscribe_pvt);
1962  agent_pvt->is_available = TRUE;
1963 }
1964 
1966 {
1967  struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1969  return ast_cc_agent_status_response(agent->core_id, state);
1970 }
1971 
1973 {
1974  /* To start monitoring just means to wait for an incoming PUBLISH
1975  * to tell us that the caller has become available again. No special
1976  * action is needed
1977  */
1978  return 0;
1979 }
1980 
1981 static int sip_cc_agent_recall(struct ast_cc_agent *agent)
1982 {
1983  struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1984  /* If we have received a PUBLISH beforehand stating that the caller in question
1985  * is not available, we can save ourself a bit of effort here and just report
1986  * the caller as busy
1987  */
1988  if (!agent_pvt->is_available) {
1989  return ast_cc_agent_caller_busy(agent->core_id, "Caller %s is busy, reporting to the core",
1990  agent->device_name);
1991  }
1992  /* Otherwise, we transmit a NOTIFY to the caller and await either
1993  * a PUBLISH or an INVITE
1994  */
1995  sip_pvt_lock(agent_pvt->subscribe_pvt);
1996  transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_READY);
1997  sip_pvt_unlock(agent_pvt->subscribe_pvt);
1998  return 0;
1999 }
2000 
2001 static void sip_cc_agent_destructor(struct ast_cc_agent *agent)
2002 {
2003  struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
2004 
2005  if (!agent_pvt) {
2006  /* The agent constructor probably failed. */
2007  return;
2008  }
2009 
2011  if (agent_pvt->subscribe_pvt) {
2012  sip_pvt_lock(agent_pvt->subscribe_pvt);
2014  /* If we haven't sent a 200 OK for the SUBSCRIBE dialog yet, then we need to send a response letting
2015  * the subscriber know something went wrong
2016  */
2017  transmit_response(agent_pvt->subscribe_pvt, "500 Internal Server Error", &agent_pvt->subscribe_pvt->initreq);
2018  }
2019  sip_pvt_unlock(agent_pvt->subscribe_pvt);
2020  agent_pvt->subscribe_pvt = dialog_unref(agent_pvt->subscribe_pvt, "SIP CC agent destructor: Remove ref to subscription");
2021  }
2022  ast_free(agent_pvt);
2023 }
2024 
2025 
2026 static int sip_monitor_instance_hash_fn(const void *obj, const int flags)
2027 {
2028  const struct sip_monitor_instance *monitor_instance = obj;
2029  return monitor_instance->core_id;
2030 }
2031 
2032 static int sip_monitor_instance_cmp_fn(void *obj, void *arg, int flags)
2033 {
2034  struct sip_monitor_instance *monitor_instance1 = obj;
2035  struct sip_monitor_instance *monitor_instance2 = arg;
2036 
2037  return monitor_instance1->core_id == monitor_instance2->core_id ? CMP_MATCH | CMP_STOP : 0;
2038 }
2039 
2040 static void sip_monitor_instance_destructor(void *data)
2041 {
2042  struct sip_monitor_instance *monitor_instance = data;
2043  if (monitor_instance->subscription_pvt) {
2044  sip_pvt_lock(monitor_instance->subscription_pvt);
2045  monitor_instance->subscription_pvt->expiry = 0;
2046  transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 0, monitor_instance->subscribe_uri);
2047  sip_pvt_unlock(monitor_instance->subscription_pvt);
2048  dialog_unref(monitor_instance->subscription_pvt, "Unref monitor instance ref of subscription pvt");
2049  }
2050  if (monitor_instance->suspension_entry) {
2051  monitor_instance->suspension_entry->body[0] = '\0';
2052  transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_REMOVE ,monitor_instance->notify_uri);
2053  ao2_t_ref(monitor_instance->suspension_entry, -1, "Decrementing suspension entry refcount in sip_monitor_instance_destructor");
2054  }
2055  ast_string_field_free_memory(monitor_instance);
2056 }
2057 
2058 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)
2059 {
2060  struct sip_monitor_instance *monitor_instance = ao2_alloc(sizeof(*monitor_instance), sip_monitor_instance_destructor);
2061 
2062  if (!monitor_instance) {
2063  return NULL;
2064  }
2065 
2066  if (ast_string_field_init(monitor_instance, 256)) {
2067  ao2_ref(monitor_instance, -1);
2068  return NULL;
2069  }
2070 
2071  ast_string_field_set(monitor_instance, subscribe_uri, subscribe_uri);
2072  ast_string_field_set(monitor_instance, peername, peername);
2073  ast_string_field_set(monitor_instance, device_name, device_name);
2074  monitor_instance->core_id = core_id;
2075  ao2_link(sip_monitor_instances, monitor_instance);
2076  return monitor_instance;
2077 }
2078 
2079 static int find_sip_monitor_instance_by_subscription_pvt(void *obj, void *arg, int flags)
2080 {
2081  struct sip_monitor_instance *monitor_instance = obj;
2082  return monitor_instance->subscription_pvt == arg ? CMP_MATCH | CMP_STOP : 0;
2083 }
2084 
2085 static int find_sip_monitor_instance_by_suspension_entry(void *obj, void *arg, int flags)
2086 {
2087  struct sip_monitor_instance *monitor_instance = obj;
2088  return monitor_instance->suspension_entry == arg ? CMP_MATCH | CMP_STOP : 0;
2089 }
2090 
2091 static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id);
2092 static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor);
2093 static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor);
2094 static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id);
2095 static void sip_cc_monitor_destructor(void *private_data);
2096 
2098  .type = "SIP",
2099  .request_cc = sip_cc_monitor_request_cc,
2100  .suspend = sip_cc_monitor_suspend,
2101  .unsuspend = sip_cc_monitor_unsuspend,
2102  .cancel_available_timer = sip_cc_monitor_cancel_available_timer,
2103  .destructor = sip_cc_monitor_destructor,
2104 };
2105 
2106 static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id)
2107 {
2108  struct sip_monitor_instance *monitor_instance = monitor->private_data;
2110  int when;
2111 
2112  if (!monitor_instance) {
2113  return -1;
2114  }
2115 
2116  if (!(monitor_instance->subscription_pvt = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL, 0))) {
2117  return -1;
2118  }
2119 
2120  when = service == AST_CC_CCBS ? ast_get_ccbs_available_timer(monitor->interface->config_params) :
2122 
2123  sip_pvt_lock(monitor_instance->subscription_pvt);
2124  ast_set_flag(&monitor_instance->subscription_pvt->flags[0], SIP_OUTGOING);
2125  create_addr(monitor_instance->subscription_pvt, monitor_instance->peername, 0, 1);
2126  ast_sip_ouraddrfor(&monitor_instance->subscription_pvt->sa, &monitor_instance->subscription_pvt->ourip, monitor_instance->subscription_pvt);
2127  monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
2128  monitor_instance->subscription_pvt->expiry = when;
2129 
2130  transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 2, monitor_instance->subscribe_uri);
2131  sip_pvt_unlock(monitor_instance->subscription_pvt);
2132 
2133  ao2_t_ref(monitor, +1, "Adding a ref to the monitor for the scheduler");
2134  *available_timer_id = ast_sched_add(sched, when * 1000, ast_cc_available_timer_expire, monitor);
2135  return 0;
2136 }
2137 
2138 static int construct_pidf_body(enum sip_cc_publish_state state, char *pidf_body, size_t size, const char *presentity)
2139 {
2140  struct ast_str *body = ast_str_alloca(size);
2141  char tuple_id[64];
2142 
2143  generate_random_string(tuple_id, sizeof(tuple_id));
2144 
2145  /* We'll make this a bare-bones pidf body. In state_notify_build_xml, the PIDF
2146  * body gets a lot more extra junk that isn't necessary, so we'll leave it out here.
2147  */
2148  ast_str_append(&body, 0, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
2149  /* XXX The entity attribute is currently set to the peer name associated with the
2150  * dialog. This is because we currently only call this function for call-completion
2151  * PUBLISH bodies. In such cases, the entity is completely disregarded. For other
2152  * event packages, it may be crucial to have a proper URI as the presentity so this
2153  * should be revisited as support is expanded.
2154  */
2155  ast_str_append(&body, 0, "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" entity=\"%s\">\n", presentity);
2156  ast_str_append(&body, 0, "<tuple id=\"%s\">\n", tuple_id);
2157  ast_str_append(&body, 0, "<status><basic>%s</basic></status>\n", state == CC_OPEN ? "open" : "closed");
2158  ast_str_append(&body, 0, "</tuple>\n");
2159  ast_str_append(&body, 0, "</presence>\n");
2160  ast_copy_string(pidf_body, ast_str_buffer(body), size);
2161  return 0;
2162 }
2163 
2164 static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor)
2165 {
2166  struct sip_monitor_instance *monitor_instance = monitor->private_data;
2167  enum sip_publish_type publish_type;
2168  struct cc_epa_entry *cc_entry;
2169 
2170  if (!monitor_instance) {
2171  return -1;
2172  }
2173 
2174  if (!monitor_instance->suspension_entry) {
2175  /* We haven't yet allocated the suspension entry, so let's give it a shot */
2176  if (!(monitor_instance->suspension_entry = create_epa_entry("call-completion", monitor_instance->peername))) {
2177  ast_log(LOG_WARNING, "Unable to allocate sip EPA entry for call-completion\n");
2178  ao2_ref(monitor_instance, -1);
2179  return -1;
2180  }
2181  if (!(cc_entry = ast_calloc(1, sizeof(*cc_entry)))) {
2182  ast_log(LOG_WARNING, "Unable to allocate space for instance data of EPA entry for call-completion\n");
2183  ao2_ref(monitor_instance, -1);
2184  return -1;
2185  }
2186  cc_entry->core_id = monitor->core_id;
2187  monitor_instance->suspension_entry->instance_data = cc_entry;
2188  publish_type = SIP_PUBLISH_INITIAL;
2189  } else {
2190  publish_type = SIP_PUBLISH_MODIFY;
2191  cc_entry = monitor_instance->suspension_entry->instance_data;
2192  }
2193 
2194  cc_entry->current_state = CC_CLOSED;
2195 
2196  if (ast_strlen_zero(monitor_instance->notify_uri)) {
2197  /* If we have no set notify_uri, then what this means is that we have
2198  * not received a NOTIFY from this destination stating that he is
2199  * currently available.
2200  *
2201  * This situation can arise when the core calls the suspend callbacks
2202  * of multiple destinations. If one of the other destinations aside
2203  * from this one notified Asterisk that he is available, then there
2204  * is no reason to take any suspension action on this device. Rather,
2205  * we should return now and if we receive a NOTIFY while monitoring
2206  * is still "suspended" then we can immediately respond with the
2207  * proper PUBLISH to let this endpoint know what is going on.
2208  */
2209  return 0;
2210  }
2211  construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
2212  return transmit_publish(monitor_instance->suspension_entry, publish_type, monitor_instance->notify_uri);
2213 }
2214 
2215 static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor)
2216 {
2217  struct sip_monitor_instance *monitor_instance = monitor->private_data;
2218  struct cc_epa_entry *cc_entry;
2219 
2220  if (!monitor_instance) {
2221  return -1;
2222  }
2223 
2224  ast_assert(monitor_instance->suspension_entry != NULL);
2225 
2226  cc_entry = monitor_instance->suspension_entry->instance_data;
2227  cc_entry->current_state = CC_OPEN;
2228  if (ast_strlen_zero(monitor_instance->notify_uri)) {
2229  /* This means we are being asked to unsuspend a call leg we never
2230  * sent a PUBLISH on. As such, there is no reason to send another
2231  * PUBLISH at this point either. We can just return instead.
2232  */
2233  return 0;
2234  }
2235  construct_pidf_body(CC_OPEN, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
2236  return transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_MODIFY, monitor_instance->notify_uri);
2237 }
2238 
2240 {
2241  if (*sched_id != -1) {
2242  AST_SCHED_DEL(sched, *sched_id);
2243  ao2_t_ref(monitor, -1, "Removing scheduler's reference to the monitor");
2244  }
2245  return 0;
2246 }
2247 
2248 static void sip_cc_monitor_destructor(void *private_data)
2249 {
2250  struct sip_monitor_instance *monitor_instance = private_data;
2251  ao2_unlink(sip_monitor_instances, monitor_instance);
2253 }
2254 
2255 static int sip_get_cc_information(struct sip_request *req, char *subscribe_uri, size_t size, enum ast_cc_service_type *service)
2256 {
2257  char *call_info = ast_strdupa(sip_get_header(req, "Call-Info"));
2258  char *uri;
2259  char *purpose;
2260  char *service_str;
2261  static const char cc_purpose[] = "purpose=call-completion";
2262  static const int cc_purpose_len = sizeof(cc_purpose) - 1;
2263 
2264  if (ast_strlen_zero(call_info)) {
2265  /* No Call-Info present. Definitely no CC offer */
2266  return -1;
2267  }
2268 
2269  uri = strsep(&call_info, ";");
2270 
2271  while ((purpose = strsep(&call_info, ";"))) {
2272  if (!strncmp(purpose, cc_purpose, cc_purpose_len)) {
2273  break;
2274  }
2275  }
2276  if (!purpose) {
2277  /* We didn't find the appropriate purpose= parameter. Oh well */
2278  return -1;
2279  }
2280 
2281  /* Okay, call-completion has been offered. Let's figure out what type of service this is */
2282  while ((service_str = strsep(&call_info, ";"))) {
2283  if (!strncmp(service_str, "m=", 2)) {
2284  break;
2285  }
2286  }
2287  if (!service_str) {
2288  /* So they didn't offer a particular service, We'll just go with CCBS since it really
2289  * doesn't matter anyway
2290  */
2291  service_str = "BS";
2292  } else {
2293  /* We already determined that there is an "m=" so no need to check
2294  * the result of this strsep
2295  */
2296  strsep(&service_str, "=");
2297  }
2298 
2299  if ((*service = service_string_to_service_type(service_str)) == AST_CC_NONE) {
2300  /* Invalid service offered */
2301  return -1;
2302  }
2303 
2304  ast_copy_string(subscribe_uri, get_in_brackets(uri), size);
2305 
2306  return 0;
2307 }
2308 
2309 /*
2310  * \brief Determine what, if any, CC has been offered and queue a CC frame if possible
2311  *
2312  * After taking care of some formalities to be sure that this call is eligible for CC,
2313  * we first try to see if we can make use of native CC. We grab the information from
2314  * the passed-in sip_request (which is always a response to an INVITE). If we can
2315  * use native CC monitoring for the call, then so be it.
2316  *
2317  * If native cc monitoring is not possible or not supported, then we will instead attempt
2318  * to use generic monitoring. Falling back to generic from a failed attempt at using native
2319  * monitoring will only work if the monitor policy of the endpoint is "always"
2320  *
2321  * \param pvt The current dialog. Contains CC parameters for the endpoint
2322  * \param req The response to the INVITE we want to inspect
2323  * \param service The service to use if generic monitoring is to be used. For native
2324  * monitoring, we get the service from the SIP response itself
2325  */
2326 static void sip_handle_cc(struct sip_pvt *pvt, struct sip_request *req, enum ast_cc_service_type service)
2327 {
2328  enum ast_cc_monitor_policies monitor_policy = ast_get_cc_monitor_policy(pvt->cc_params);
2329  int core_id;
2330  char interface_name[AST_CHANNEL_NAME];
2331 
2332  if (monitor_policy == AST_CC_MONITOR_NEVER) {
2333  /* Don't bother, just return */
2334  return;
2335  }
2336 
2337  if ((core_id = ast_cc_get_current_core_id(pvt->owner)) == -1) {
2338  /* For some reason, CC is invalid, so don't try it! */
2339  return;
2340  }
2341 
2342  ast_channel_get_device_name(pvt->owner, interface_name, sizeof(interface_name));
2343 
2344  if (monitor_policy == AST_CC_MONITOR_ALWAYS || monitor_policy == AST_CC_MONITOR_NATIVE) {
2345  char subscribe_uri[SIPBUFSIZE];
2347  enum ast_cc_service_type offered_service;
2348  struct sip_monitor_instance *monitor_instance;
2349  if (sip_get_cc_information(req, subscribe_uri, sizeof(subscribe_uri), &offered_service)) {
2350  /* If CC isn't being offered to us, or for some reason the CC offer is
2351  * not formatted correctly, then it may still be possible to use generic
2352  * call completion since the monitor policy may be "always"
2353  */
2354  goto generic;
2355  }
2356  ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
2357  if (!(monitor_instance = sip_monitor_instance_init(core_id, subscribe_uri, pvt->peername, device_name))) {
2358  /* Same deal. We can try using generic still */
2359  goto generic;
2360  }
2361  /* We bump the refcount of chan_sip because once we queue this frame, the CC core
2362  * will have a reference to callbacks in this module. We decrement the module
2363  * refcount once the monitor destructor is called
2364  */
2366  ast_queue_cc_frame(pvt->owner, "SIP", pvt->dialstring, offered_service, monitor_instance);
2367  ao2_ref(monitor_instance, -1);
2368  return;
2369  }
2370 
2371 generic:
2372  if (monitor_policy == AST_CC_MONITOR_GENERIC || monitor_policy == AST_CC_MONITOR_ALWAYS) {
2373  ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE, interface_name, service, NULL);
2374  }
2375 }
2376 
2377 /*! \brief Working TLS connection configuration */
2379 
2380 /*! \brief Default TLS connection configuration */
2382 
2383 /*! \brief Default DTLS connection configuration */
2385 
2386 /*! \brief The TCP server definition */
2388  .accept_fd = -1,
2389  .master = AST_PTHREADT_NULL,
2390  .tls_cfg = NULL,
2391  .poll_timeout = -1,
2392  .name = "SIP TCP server",
2393  .accept_fn = ast_tcptls_server_root,
2394  .worker_fn = sip_tcp_worker_fn,
2395 };
2396 
2397 /*! \brief The TCP/TLS server definition */
2399  .accept_fd = -1,
2400  .master = AST_PTHREADT_NULL,
2401  .tls_cfg = &sip_tls_cfg,
2402  .poll_timeout = -1,
2403  .name = "SIP TLS server",
2404  .accept_fn = ast_tcptls_server_root,
2405  .worker_fn = sip_tcp_worker_fn,
2406 };
2407 
2408 /*! \brief Append to SIP dialog history
2409  \return Always returns 0 */
2410 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
2411 
2412 /*! \brief map from an integer value to a string.
2413  * If no match is found, return errorstring
2414  */
2415 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
2416 {
2417  const struct _map_x_s *cur;
2418 
2419  for (cur = table; cur->s; cur++) {
2420  if (cur->x == x) {
2421  return cur->s;
2422  }
2423  }
2424  return errorstring;
2425 }
2426 
2427 /*! \brief map from a string to an integer value, case insensitive.
2428  * If no match is found, return errorvalue.
2429  */
2430 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
2431 {
2432  const struct _map_x_s *cur;
2433 
2434  for (cur = table; cur->s; cur++) {
2435  if (!strcasecmp(cur->s, s)) {
2436  return cur->x;
2437  }
2438  }
2439  return errorvalue;
2440 }
2441 
2442 /*!
2443  * \internal
2444  * \brief Determine if the given string is a SIP token.
2445  * \since 13.8.0
2446  *
2447  * \param str String to determine if is a SIP token.
2448  *
2449  * \note A token is defined by RFC3261 Section 25.1
2450  *
2451  * \return Non-zero if the string is a SIP token.
2452  */
2453 static int sip_is_token(const char *str)
2454 {
2455  int is_token;
2456 
2457  if (ast_strlen_zero(str)) {
2458  /* An empty string is not a token. */
2459  return 0;
2460  }
2461 
2462  is_token = 1;
2463  do {
2464  if (!isalnum(*str)
2465  && !strchr("-.!%*_+`'~", *str)) {
2466  /* The character is not allowed in a token. */
2467  is_token = 0;
2468  break;
2469  }
2470  } while (*++str);
2471 
2472  return is_token;
2473 }
2474 
2475 static const char *sip_reason_code_to_str(struct ast_party_redirecting_reason *reason)
2476 {
2477  int idx;
2478  int code;
2479 
2480  /* use specific string if given */
2481  if (!ast_strlen_zero(reason->str)) {
2482  return reason->str;
2483  }
2484 
2485  code = reason->code;
2486  for (idx = 0; idx < ARRAY_LEN(sip_reason_table); ++idx) {
2487  if (code == sip_reason_table[idx].code) {
2488  return sip_reason_table[idx].text;
2489  }
2490  }
2491 
2492  return "unknown";
2493 }
2494 
2495 /*!
2496  * \brief generic function for determining if a correct transport is being
2497  * used to contact a peer
2498  *
2499  * this is done as a macro so that the "tmpl" var can be passed either a
2500  * sip_request or a sip_peer
2501  */
2502 #define check_request_transport(peer, tmpl) ({ \
2503  int ret = 0; \
2504  if (peer->socket.type == tmpl->socket.type) \
2505  ; \
2506  else if (!(peer->transports & tmpl->socket.type)) {\
2507  ast_log(LOG_ERROR, \
2508  "'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
2509  sip_get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
2510  ); \
2511  ret = 1; \
2512  } else if (peer->socket.type & AST_TRANSPORT_TLS) { \
2513  ast_log(LOG_WARNING, \
2514  "peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
2515  peer->name, sip_get_transport(tmpl->socket.type) \
2516  ); \
2517  } else { \
2518  ast_debug(1, \
2519  "peer '%s' has contacted us over %s even though we prefer %s.\n", \
2520  peer->name, sip_get_transport(tmpl->socket.type), sip_get_transport(peer->socket.type) \
2521  ); \
2522  }\
2523  (ret); \
2524 })
2525 
2526 /*! \brief
2527  * duplicate a list of channel variables, \return the copy.
2528  */
2529 static struct ast_variable *copy_vars(struct ast_variable *src)
2530 {
2531  struct ast_variable *res = NULL, *tmp, *v = NULL;
2532 
2533  for (v = src ; v ; v = v->next) {
2534  if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
2535  tmp->next = res;
2536  res = tmp;
2537  }
2538  }
2539  return res;
2540 }
2541 
2542 static void tcptls_packet_destructor(void *obj)
2543 {
2544  struct tcptls_packet *packet = obj;
2545 
2546  ast_free(packet->data);
2547 }
2548 
2550 {
2551  struct ast_tcptls_session_args *args = obj;
2552  if (args->tls_cfg) {
2553  ast_free(args->tls_cfg->certfile);
2554  ast_free(args->tls_cfg->pvtfile);
2555  ast_free(args->tls_cfg->cipher);
2556  ast_free(args->tls_cfg->cafile);
2557  ast_free(args->tls_cfg->capath);
2558 
2559  ast_ssl_teardown(args->tls_cfg);
2560  }
2561  ast_free(args->tls_cfg);
2562  ast_free((char *) args->name);
2563 }
2564 
2565 static void sip_threadinfo_destructor(void *obj)
2566 {
2567  struct sip_threadinfo *th = obj;
2568  struct tcptls_packet *packet;
2569 
2570  if (th->alert_pipe[0] > -1) {
2571  close(th->alert_pipe[0]);
2572  }
2573  if (th->alert_pipe[1] > -1) {
2574  close(th->alert_pipe[1]);
2575  }
2576  th->alert_pipe[0] = th->alert_pipe[1] = -1;
2577 
2578  while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
2579  ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
2580  }
2581 
2582  if (th->tcptls_session) {
2583  ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
2584  }
2585 }
2586 
2587 /*! \brief creates a sip_threadinfo object and links it into the threadt table. */
2588 static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
2589 {
2590  struct sip_threadinfo *th;
2591 
2592  if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
2593  return NULL;
2594  }
2595 
2596  th->alert_pipe[0] = th->alert_pipe[1] = -1;
2597 
2598  if (pipe(th->alert_pipe) == -1) {
2599  ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
2600  ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
2601  return NULL;
2602  }
2603  ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
2604  th->tcptls_session = tcptls_session;
2605  th->type = transport ? transport : (ast_iostream_get_ssl(tcptls_session->stream) ? AST_TRANSPORT_TLS: AST_TRANSPORT_TCP);
2606  ao2_t_link(threadt, th, "Adding new tcptls helper thread");
2607  ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
2608  return th;
2609 }
2610 
2611 /*! \brief used to indicate to a tcptls thread that data is ready to be written */
2612 static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
2613 {
2614  int res = len;
2615  struct sip_threadinfo *th = NULL;
2616  struct tcptls_packet *packet = NULL;
2617  struct sip_threadinfo tmp = {
2618  .tcptls_session = tcptls_session,
2619  };
2620  enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
2621 
2622  if (!tcptls_session) {
2623  return XMIT_ERROR;
2624  }
2625 
2626  ao2_lock(tcptls_session);
2627 
2628  if (!tcptls_session->stream ||
2629  !(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
2630  !(packet->data = ast_str_create(len))) {
2631  goto tcptls_write_setup_error;
2632  }
2633 
2634  if (!(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) {
2635  ast_log(LOG_ERROR, "Unable to locate tcptls_session helper thread.\n");
2636  goto tcptls_write_setup_error;
2637  }
2638 
2639  /* goto tcptls_write_error should _NOT_ be used beyond this point */
2640  ast_str_set(&packet->data, 0, "%s", (char *) buf);
2641  packet->len = len;
2642 
2643  /* alert tcptls thread handler that there is a packet to be sent.
2644  * must lock the thread info object to guarantee control of the
2645  * packet queue */
2646  ao2_lock(th);
2647  if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
2648  ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
2649  ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
2650  packet = NULL;
2651  res = XMIT_ERROR;
2652  } else { /* it is safe to queue the frame after issuing the alert when we hold the threadinfo lock */
2653  AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
2654  }
2655  ao2_unlock(th);
2656 
2657  ao2_unlock(tcptls_session);
2658  ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
2659  return res;
2660 
2661 tcptls_write_setup_error:
2662  if (th) {
2663  ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
2664  }
2665  if (packet) {
2666  ao2_t_ref(packet, -1, "could not allocate packet's data");
2667  }
2668  ao2_unlock(tcptls_session);
2669 
2670  return XMIT_ERROR;
2671 }
2672 
2673 /*! \brief SIP TCP connection handler */
2674 static void *sip_tcp_worker_fn(void *data)
2675 {
2676  struct ast_tcptls_session_instance *tcptls_session = data;
2677 
2678  return _sip_tcp_helper_thread(tcptls_session);
2679 }
2680 
2681 /*! \brief SIP WebSocket connection handler */
2682 static void sip_websocket_callback(struct ast_websocket *session, struct ast_variable *parameters, struct ast_variable *headers)
2683 {
2684  int res;
2685 
2686  if (ast_websocket_set_nonblock(session)) {
2687  goto end;
2688  }
2689 
2691  goto end;
2692  }
2693 
2694  while ((res = ast_wait_for_input(ast_websocket_fd(session), -1)) > 0) {
2695  char *payload;
2696  uint64_t payload_len;
2697  enum ast_websocket_opcode opcode;
2698  int fragmented;
2699 
2700  if (ast_websocket_read(session, &payload, &payload_len, &opcode, &fragmented)) {
2701  /* We err on the side of caution and terminate the session if any error occurs */
2702  break;
2703  }
2704 
2705  if (opcode == AST_WEBSOCKET_OPCODE_TEXT || opcode == AST_WEBSOCKET_OPCODE_BINARY) {
2706  struct sip_request req = { 0, };
2707  char data[payload_len + 1];
2708 
2709  if (!(req.data = ast_str_create(payload_len + 1))) {
2710  goto end;
2711  }
2712 
2713  strncpy(data, payload, payload_len);
2714  data[payload_len] = '\0';
2715 
2716  if (ast_str_set(&req.data, -1, "%s", data) == AST_DYNSTR_BUILD_FAILED) {
2717  deinit_req(&req);
2718  goto end;
2719  }
2720 
2721  req.socket.fd = ast_websocket_fd(session);
2723  req.socket.ws_session = session;
2724 
2726  deinit_req(&req);
2727 
2728  } else if (opcode == AST_WEBSOCKET_OPCODE_CLOSE) {
2729  break;
2730  }
2731  }
2732 
2733 end:
2734  ast_websocket_unref(session);
2735 }
2736 
2737 /*! \brief Check if the authtimeout has expired.
2738  * \param start the time when the session started
2739  *
2740  * \retval 0 the timeout has expired
2741  * \retval -1 error
2742  * \return the number of milliseconds until the timeout will expire
2743  */
2744 static int sip_check_authtimeout(time_t start)
2745 {
2746  int timeout;
2747  time_t now;
2748  if(time(&now) == -1) {
2749  ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
2750  return -1;
2751  }
2752 
2753  timeout = (authtimeout - (now - start)) * 1000;
2754  if (timeout < 0) {
2755  /* we have timed out */
2756  return 0;
2757  }
2758 
2759  return timeout;
2760 }
2761 
2762 /*!
2763  * \brief Indication of a TCP message's integrity
2764  */
2766  /*!
2767  * The message has an error in it with
2768  * regards to its Content-Length header
2769  */
2771  /*!
2772  * The message is incomplete
2773  */
2775  /*!
2776  * The data contains a complete message
2777  * plus a fragment of another.
2778  */
2780  /*!
2781  * The message is complete
2782  */
2784 };
2785 
2786 /*!
2787  * \brief
2788  * Get the content length from an unparsed SIP message
2789  *
2790  * \param message The unparsed SIP message headers
2791  * \return The value of the Content-Length header or -1 if message is invalid
2792  */
2793 static int read_raw_content_length(const char *message)
2794 {
2795  char *content_length_str;
2796  int content_length = -1;
2797 
2798  struct ast_str *msg_copy;
2799  char *msg;
2800 
2801  /* Using a ast_str because lws2sws takes one of those */
2802  if (!(msg_copy = ast_str_create(strlen(message) + 1))) {
2803  return -1;
2804  }
2805  ast_str_set(&msg_copy, 0, "%s", message);
2806 
2808  lws2sws(msg_copy);
2809  }
2810 
2811  msg = ast_str_buffer(msg_copy);
2812 
2813  /* Let's find a Content-Length header */
2814  if ((content_length_str = strcasestr(msg, "\nContent-Length:"))) {
2815  content_length_str += sizeof("\nContent-Length:") - 1;
2816  } else if ((content_length_str = strcasestr(msg, "\nl:"))) {
2817  content_length_str += sizeof("\nl:") - 1;
2818  } else {
2819  /* RFC 3261 18.3
2820  * "In the case of stream-oriented transports such as TCP, the Content-
2821  * Length header field indicates the size of the body. The Content-
2822  * Length header field MUST be used with stream oriented transports."
2823  */
2824  goto done;
2825  }
2826 
2827  /* Double-check that this is a complete header */
2828  if (!strchr(content_length_str, '\n')) {
2829  goto done;
2830  }
2831 
2832  if (sscanf(content_length_str, "%30d", &content_length) != 1) {
2833  content_length = -1;
2834  }
2835 
2836 done:
2837  ast_free(msg_copy);
2838  return content_length;
2839 }
2840 
2841 /*!
2842  * \brief Check that a message received over TCP is a full message
2843  *
2844  * This will take the information read in and then determine if
2845  * 1) The message is a full SIP request
2846  * 2) The message is a partial SIP request
2847  * 3) The message contains a full SIP request along with another partial request
2848  * \param data The unparsed incoming SIP message.
2849  * \param request The resulting request with extra fragments removed.
2850  * \param overflow If the message contains more than a full request, this is the remainder of the message
2851  * \return The resulting integrity of the message
2852  */
2853 static enum message_integrity check_message_integrity(struct ast_str **request, struct ast_str **overflow)
2854 {
2855  char *message = ast_str_buffer(*request);
2856  char *body;
2857  int content_length;
2858  int message_len = ast_str_strlen(*request);
2859  int body_len;
2860 
2861  /* Important pieces to search for in a SIP request are \r\n\r\n. This
2862  * marks either
2863  * 1) The division between the headers and body
2864  * 2) The end of the SIP request
2865  */
2866  body = strstr(message, "\r\n\r\n");
2867  if (!body) {
2868  /* This is clearly a partial message since we haven't reached an end
2869  * yet.
2870  */
2871  return MESSAGE_FRAGMENT;
2872  }
2873  body += sizeof("\r\n\r\n") - 1;
2874  body_len = message_len - (body - message);
2875 
2876  body[-1] = '\0';
2877  content_length = read_raw_content_length(message);
2878  body[-1] = '\n';
2879 
2880  if (content_length < 0) {
2881  return MESSAGE_INVALID;
2882  } else if (content_length == 0) {
2883  /* We've definitely received an entire message. We need
2884  * to check if there's also a fragment of another message
2885  * in addition.
2886  */
2887  if (body_len == 0) {
2888  return MESSAGE_COMPLETE;
2889  } else {
2890  ast_str_append(overflow, 0, "%s", body);
2891  ast_str_truncate(*request, message_len - body_len);
2893  }
2894  }
2895  /* Positive content length. Let's see what sort of
2896  * message body we're dealing with.
2897  */
2898  if (body_len < content_length) {
2899  /* We don't have the full message body yet */
2900  return MESSAGE_FRAGMENT;
2901  } else if (body_len > content_length) {
2902  /* We have the full message plus a fragment of a further
2903  * message
2904  */
2905  ast_str_append(overflow, 0, "%s", body + content_length);
2906  ast_str_truncate(*request, message_len - (body_len - content_length));
2908  } else {
2909  /* Yay! Full message with no extra content */
2910  return MESSAGE_COMPLETE;
2911  }
2912 }
2913 
2914 /*!
2915  * \brief Read SIP request or response from a TCP/TLS connection
2916  *
2917  * \param req The request structure to be filled in
2918  * \param tcptls_session The TCP/TLS connection from which to read
2919  * \retval -1 Failed to read data
2920  * \retval 0 Successfully read data
2921  */
2922 static int sip_tcptls_read(struct sip_request *req, struct ast_tcptls_session_instance *tcptls_session,
2923  int authenticated, time_t start)
2924 {
2926 
2927  while (message_integrity == MESSAGE_FRAGMENT) {
2928  size_t datalen;
2929 
2930  if (ast_str_strlen(tcptls_session->overflow_buf) == 0) {
2931  char readbuf[4097];
2932  int timeout;
2933  int res;
2934  if (!tcptls_session->client && !authenticated) {
2935  if ((timeout = sip_check_authtimeout(start)) < 0) {
2936  return -1;
2937  }
2938 
2939  if (timeout == 0) {
2940  ast_debug(2, "SIP TCP/TLS server timed out\n");
2941  return -1;
2942  }
2943  } else {
2944  timeout = -1;
2945  }
2946  res = ast_wait_for_input(ast_iostream_get_fd(tcptls_session->stream), timeout);
2947  if (res < 0) {
2948  ast_debug(2, "SIP TCP/TLS server :: ast_wait_for_input returned %d\n", res);
2949  return -1;
2950  } else if (res == 0) {
2951  ast_debug(2, "SIP TCP/TLS server timed out\n");
2952  return -1;
2953  }
2954 
2955  res = ast_iostream_read(tcptls_session->stream, readbuf, sizeof(readbuf) - 1);
2956  if (res < 0) {
2957  if (errno == EAGAIN || errno == EINTR) {
2958  continue;
2959  }
2960  ast_debug(2, "SIP TCP/TLS server error when receiving data\n");
2961  return -1;
2962  } else if (res == 0) {
2963  ast_debug(2, "SIP TCP/TLS server has shut down\n");
2964  return -1;
2965  }
2966  readbuf[res] = '\0';
2967  ast_str_append(&req->data, 0, "%s", readbuf);
2968  } else {
2969  ast_str_append(&req->data, 0, "%s", ast_str_buffer(tcptls_session->overflow_buf));
2970  ast_str_reset(tcptls_session->overflow_buf);
2971  }
2972 
2973  datalen = ast_str_strlen(req->data);
2974  if (datalen > SIP_MAX_PACKET_SIZE) {
2975  ast_log(LOG_WARNING, "Rejecting TCP/TLS packet from '%s' because way too large: %zu\n",
2976  ast_sockaddr_stringify(&tcptls_session->remote_address), datalen);
2977  return -1;
2978  }
2979 
2980  message_integrity = check_message_integrity(&req->data, &tcptls_session->overflow_buf);
2981  }
2982 
2983  return 0;
2984 }
2985 
2986 /*! \brief SIP TCP thread management function
2987  This function reads from the socket, parses the packet into a request
2988 */
2989 static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session)
2990 {
2991  int res, timeout = -1, authenticated = 0, flags;
2992  time_t start;
2993  struct sip_request req = { 0, } , reqcpy = { 0, };
2994  struct sip_threadinfo *me = NULL;
2995  char buf[1024] = "";
2996  struct pollfd fds[2] = { { 0 }, { 0 }, };
2997  struct ast_tcptls_session_args *ca = NULL;
2998 
2999  /* If this is a server session, then the connection has already been
3000  * setup. Check if the authlimit has been reached and if not create the
3001  * threadinfo object so we can access this thread for writing.
3002  *
3003  * if this is a client connection more work must be done.
3004  * 1. We own the parent session args for a client connection. This pointer needs
3005  * to be held on to so we can decrement it's ref count on thread destruction.
3006  * 2. The threadinfo object was created before this thread was launched, however
3007  * it must be found within the threadt table.
3008  * 3. Last, the tcptls_session must be started.
3009  */
3010  if (!tcptls_session->client) {
3012  /* unauth_sessions is decremented in the cleanup code */
3013  goto cleanup;
3014  }
3015 
3016  ast_iostream_nonblock(tcptls_session->stream);
3017  if (!(me = sip_threadinfo_create(tcptls_session, ast_iostream_get_ssl(tcptls_session->stream) ? AST_TRANSPORT_TLS : AST_TRANSPORT_TCP))) {
3018  goto cleanup;
3019  }
3020  me->threadid = pthread_self();
3021  ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
3022  } else {
3023  struct sip_threadinfo tmp = {
3024  .tcptls_session = tcptls_session,
3025  };
3026 
3027  if ((!(ca = tcptls_session->parent)) ||
3028  (!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")))) {
3029  goto cleanup;
3030  }
3031 
3032  me->threadid = pthread_self();
3033 
3034  if (!(tcptls_session = ast_tcptls_client_start(tcptls_session))) {
3035  goto cleanup;
3036  }
3037  }
3038 
3039  flags = 1;
3040  if (setsockopt(ast_iostream_get_fd(tcptls_session->stream), SOL_SOCKET, SO_KEEPALIVE, &flags, sizeof(flags))) {
3041  ast_log(LOG_ERROR, "error enabling TCP keep-alives on sip socket: %s\n", strerror(errno));
3042  goto cleanup;
3043  }
3044 
3045  ast_debug(2, "Starting thread for %s server\n", ast_iostream_get_ssl(tcptls_session->stream) ? "TLS" : "TCP");
3046 
3047  /* set up pollfd to watch for reads on both the socket and the alert_pipe */
3048  fds[0].fd = ast_iostream_get_fd(tcptls_session->stream);
3049  fds[1].fd = me->alert_pipe[0];
3050  fds[0].events = fds[1].events = POLLIN | POLLPRI;
3051 
3052  if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
3053  goto cleanup;
3054  }
3055  if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET))) {
3056  goto cleanup;
3057  }
3058 
3059  if(time(&start) == -1) {
3060  ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
3061  goto cleanup;
3062  }
3063 
3064  /*
3065  * We cannot let the stream exclusively wait for data to arrive.
3066  * We have to wake up the task to send outgoing messages.
3067  */
3068  ast_iostream_set_exclusive_input(tcptls_session->stream, 0);
3069 
3071  tcptls_session->client ? -1 : (authtimeout * 1000));
3072 
3073  for (;;) {
3074  struct ast_str *str_save;
3075 
3076  if (!tcptls_session->client && req.authenticated && !authenticated) {
3077  authenticated = 1;
3078  ast_iostream_set_timeout_disable(tcptls_session->stream);
3080  }
3081 
3082  /* calculate the timeout for unauthenticated server sessions */
3083  if (!tcptls_session->client && !authenticated ) {
3084  if ((timeout = sip_check_authtimeout(start)) < 0) {
3085  goto cleanup;
3086  }
3087 
3088  if (timeout == 0) {
3089  ast_debug(2, "SIP %s server timed out\n", ast_iostream_get_ssl(tcptls_session->stream) ? "TLS": "TCP");
3090  goto cleanup;
3091  }
3092  } else {
3093  timeout = -1;
3094  }
3095 
3096  if (ast_str_strlen(tcptls_session->overflow_buf) == 0) {
3097  res = ast_poll(fds, 2, timeout); /* polls for both socket and alert_pipe */
3098  if (res < 0) {
3099  ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", ast_iostream_get_ssl(tcptls_session->stream) ? "TLS": "TCP", res);
3100  goto cleanup;
3101  } else if (res == 0) {
3102  /* timeout */
3103  ast_debug(2, "SIP %s server timed out\n", ast_iostream_get_ssl(tcptls_session->stream) ? "TLS": "TCP");
3104  goto cleanup;
3105  }
3106  }
3107 
3108  /*
3109  * handle the socket event, check for both reads from the socket fd or TCP overflow buffer,
3110  * and writes from alert_pipe fd.
3111  */
3112  if (fds[0].revents || (ast_str_strlen(tcptls_session->overflow_buf) > 0)) { /* there is data on the socket to be read */
3113  fds[0].revents = 0;
3114 
3115  /* clear request structure */
3116  str_save = req.data;
3117  memset(&req, 0, sizeof(req));
3118  req.data = str_save;
3119  ast_str_reset(req.data);
3120 
3121  str_save = reqcpy.data;
3122  memset(&reqcpy, 0, sizeof(reqcpy));
3123  reqcpy.data = str_save;
3124  ast_str_reset(reqcpy.data);
3125 
3126  memset(buf, 0, sizeof(buf));
3127 
3128  if (ast_iostream_get_ssl(tcptls_session->stream)) {
3130  } else {
3132  }
3133  req.socket.fd = ast_iostream_get_fd(tcptls_session->stream);
3134 
3135  res = sip_tcptls_read(&req, tcptls_session, authenticated, start);
3136  if (res < 0) {
3137  goto cleanup;
3138  }
3139 
3140  req.socket.tcptls_session = tcptls_session;
3141  req.socket.ws_session = NULL;
3142  handle_request_do(&req, &tcptls_session->remote_address);
3143  }
3144 
3145  if (fds[1].revents) { /* alert_pipe indicates there is data in the send queue to be sent */
3146  enum sip_tcptls_alert alert;
3147  struct tcptls_packet *packet;
3148 
3149  fds[1].revents = 0;
3150 
3151  if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
3152  ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
3153  goto cleanup;
3154  }
3155 
3156  switch (alert) {
3157  case TCPTLS_ALERT_STOP:
3158  goto cleanup;
3159  case TCPTLS_ALERT_DATA:
3160  ao2_lock(me);
3161  if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
3162  ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty\n");
3163  }
3164  ao2_unlock(me);
3165 
3166  if (packet) {
3167  if (ast_iostream_write(tcptls_session->stream, ast_str_buffer(packet->data), packet->len) == -1) {
3168  ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
3169  }
3170  ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
3171  } else {
3172  goto cleanup;
3173  }
3174  break;
3175  default:
3176  ast_log(LOG_ERROR, "Unknown tcptls thread alert '%u'\n", alert);
3177  goto cleanup;
3178  }
3179  }
3180  }
3181 
3182  ast_debug(2, "Shutting down thread for %s server\n", ast_iostream_get_ssl(tcptls_session->stream) ? "TLS" : "TCP");
3183 
3184 cleanup:
3185  if (tcptls_session && !tcptls_session->client && !authenticated) {
3187  }
3188 
3189  if (me) {
3190  ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
3191  ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
3192  }
3193  deinit_req(&reqcpy);
3194  deinit_req(&req);
3195 
3196  /* if client, we own the parent session arguments and must decrement ref */
3197  if (ca) {
3198  ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
3199  }
3200 
3201  if (tcptls_session) {
3202  ao2_lock(tcptls_session);
3203  ast_tcptls_close_session_file(tcptls_session);
3204  tcptls_session->parent = NULL;
3205  ao2_unlock(tcptls_session);
3206 
3207  ao2_ref(tcptls_session, -1);
3208  tcptls_session = NULL;
3209  }
3210  return NULL;
3211 }
3212 
3213 static void peer_sched_cleanup(struct sip_peer *peer)
3214 {
3215  if (peer->pokeexpire != -1) {
3216  AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
3217  sip_unref_peer(peer, "removing poke peer ref"));
3218  }
3219  if (peer->expire != -1) {
3220  AST_SCHED_DEL_UNREF(sched, peer->expire,
3221  sip_unref_peer(peer, "remove register expire ref"));
3222  }
3223  if (peer->keepalivesend != -1) {
3224  AST_SCHED_DEL_UNREF(sched, peer->keepalivesend,
3225  sip_unref_peer(peer, "remove keepalive peer ref"));
3226  }
3227 }
3228 
3229 typedef enum {
3233 
3234 /* this func is used with ao2_callback to unlink/delete all marked or linked
3235  peers, depending on arg */
3236 static int match_and_cleanup_peer_sched(void *peerobj, void *arg, int flags)
3237 {
3238  struct sip_peer *peer = peerobj;
3239  peer_unlink_flag_t which = *(peer_unlink_flag_t *)arg;
3240 
3241  if (which == SIP_PEERS_ALL || peer->the_mark) {
3242  peer_sched_cleanup(peer);
3243  if (peer->dnsmgr) {
3244  ast_dnsmgr_release(peer->dnsmgr);
3245  peer->dnsmgr = NULL;
3246  sip_unref_peer(peer, "Release peer from dnsmgr");
3247  }
3248  return CMP_MATCH;
3249  }
3250  return 0;
3251 }
3252 
3254 {
3255  struct ao2_iterator *peers_iter;
3256 
3257  /*
3258  * We must remove the ref outside of the peers container to prevent
3259  * a deadlock condition when unsubscribing from stasis while it is
3260  * invoking a subscription event callback.
3261  */
3262  peers_iter = ao2_t_callback(peers, OBJ_UNLINK | OBJ_MULTIPLE,
3263  match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
3264  if (peers_iter) {
3265  ao2_iterator_destroy(peers_iter);
3266  }
3267 
3268  peers_iter = ao2_t_callback(peers_by_ip, OBJ_UNLINK | OBJ_MULTIPLE,
3269  match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers_by_ip");
3270  if (peers_iter) {
3271  ao2_iterator_destroy(peers_iter);
3272  }
3273 }
3274 
3275 /* \brief Unlink all marked peers from ao2 containers */
3277 {
3279 }
3280 
3282 {
3284 }
3285 
3286 /*! \brief maintain proper refcounts for a sip_pvt's outboundproxy
3287  *
3288  * This function sets pvt's outboundproxy pointer to the one referenced
3289  * by the proxy parameter. Because proxy may be a refcounted object, and
3290  * because pvt's old outboundproxy may also be a refcounted object, we need
3291  * to maintain the proper refcounts.
3292  *
3293  * \param pvt The sip_pvt for which we wish to set the outboundproxy
3294  * \param proxy The sip_proxy which we will point pvt towards.
3295  * \return Returns void
3296  */
3297 static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
3298 {
3299  struct sip_proxy *old_obproxy = pvt->outboundproxy;
3300  /* The sip_cfg.outboundproxy is statically allocated, and so
3301  * we don't ever need to adjust refcounts for it
3302  */
3303  if (proxy && proxy != &sip_cfg.outboundproxy) {
3304  ao2_ref(proxy, +1);
3305  }
3306  pvt->outboundproxy = proxy;
3307  if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
3308  ao2_ref(old_obproxy, -1);
3309  }
3310 }
3311 
3312 static void do_dialog_unlink_sched_items(struct sip_pvt *dialog)
3313 {
3314  struct sip_pkt *cp;
3315 
3316  /* remove all current packets in this dialog */
3317  sip_pvt_lock(dialog);
3318  while ((cp = dialog->packets)) {
3319  /* Unlink and destroy the packet object. */
3320  dialog->packets = dialog->packets->next;
3321  AST_SCHED_DEL_UNREF(sched, cp->retransid,
3322  ao2_t_ref(cp, -1, "Stop scheduled packet retransmission"));
3323  ao2_t_ref(cp, -1, "Packet retransmission list");
3324  }
3325  sip_pvt_unlock(dialog);
3326 
3327  AST_SCHED_DEL_UNREF(sched, dialog->waitid,
3328  dialog_unref(dialog, "Stop scheduled waitid"));
3329 
3330  AST_SCHED_DEL_UNREF(sched, dialog->initid,
3331  dialog_unref(dialog, "Stop scheduled initid"));
3332 
3333  AST_SCHED_DEL_UNREF(sched, dialog->reinviteid,
3334  dialog_unref(dialog, "Stop scheduled reinviteid"));
3335 
3336  AST_SCHED_DEL_UNREF(sched, dialog->autokillid,
3337  dialog_unref(dialog, "Stop scheduled autokillid"));
3338 
3340  dialog_unref(dialog, "Stop scheduled request_queue_sched_id"));
3341 
3343  dialog_unref(dialog, "Stop scheduled provisional keepalive"));
3344 
3345  AST_SCHED_DEL_UNREF(sched, dialog->t38id,
3346  dialog_unref(dialog, "Stop scheduled t38id"));
3347 
3348  if (dialog->stimer) {
3349  dialog->stimer->st_active = FALSE;
3350  do_stop_session_timer(dialog);
3351  }
3352 }
3353 
3354 /* Run by the sched thread. */
3355 static int __dialog_unlink_sched_items(const void *data)
3356 {
3357  struct sip_pvt *dialog = (void *) data;
3358 
3360  dialog_unref(dialog, "Stop scheduled items for unlink action");
3361  return 0;
3362 }
3363 
3364 /*!
3365  * \brief Unlink a dialog from the dialogs container, as well as any other places
3366  * that it may be currently stored.
3367  *
3368  * \note A reference to the dialog must be held before calling this function, and this
3369  * function does not release that reference.
3370  */
3371 void dialog_unlink_all(struct sip_pvt *dialog)
3372 {
3373  struct ast_channel *owner;
3374 
3375  dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
3376 
3377  ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
3378  ao2_t_unlink(dialogs_needdestroy, dialog, "unlinking dialog_needdestroy via ao2_unlink");
3379  ao2_t_unlink(dialogs_rtpcheck, dialog, "unlinking dialog_rtpcheck via ao2_unlink");
3380 
3381  /* Unlink us from the owner (channel) if we have one */
3382  owner = sip_pvt_lock_full(dialog);
3383  if (owner) {
3384  ast_debug(1, "Detaching from channel %s\n", ast_channel_name(owner));
3385  ast_channel_tech_pvt_set(owner, dialog_unref(ast_channel_tech_pvt(owner), "resetting channel dialog ptr in unlink_all"));
3386  ast_channel_unlock(owner);
3387  ast_channel_unref(owner);
3388  sip_set_owner(dialog, NULL);
3389  }
3390  sip_pvt_unlock(dialog);
3391 
3392  if (dialog->registry) {
3393  if (dialog->registry->call == dialog) {
3394  dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
3395  }
3396  ao2_t_replace(dialog->registry, NULL, "delete dialog->registry");
3397  }
3398  if (dialog->stateid != -1) {
3400  dialog->stateid = -1;
3401  }
3402  /* Remove link from peer to subscription of MWI */
3403  if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog) {
3404  dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
3405  }
3406  if (dialog->relatedpeer && dialog->relatedpeer->call == dialog) {
3407  dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
3408  }
3409 
3410  dialog_ref(dialog, "Stop scheduled items for unlink action");
3411  if (ast_sched_add(sched, 0, __dialog_unlink_sched_items, dialog) < 0) {
3412  /*
3413  * Uh Oh. Fall back to unscheduling things immediately
3414  * despite the potential deadlock risk.
3415  */
3416  dialog_unref(dialog, "Failed to schedule stop scheduled items for unlink action");
3418  }
3419 
3420  dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
3421 }
3422 
3423 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
3424  __attribute__((format(printf, 2, 3)));
3425 
3426 
3427 /*! \brief Convert transfer status to string */
3428 static const char *referstatus2str(enum referstatus rstatus)
3429 {
3430  return map_x_s(referstatusstrings, rstatus, "");
3431 }
3432 
3433 static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
3434 {
3435  if (pvt->final_destruction_scheduled) {
3436  return; /* This is already scheduled for final destruction, let the scheduler take care of it. */
3437  }
3438  append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
3439  if (!pvt->needdestroy) {
3440  pvt->needdestroy = 1;
3441  ao2_t_link(dialogs_needdestroy, pvt, "link pvt into dialogs_needdestroy container");
3442  }
3443 }
3444 
3445 /*! \brief Initialize the initital request packet in the pvt structure.
3446  This packet is used for creating replies and future requests in
3447  a dialog */
3448 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
3449 {
3450  if (p->initreq.headers) {
3451  ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
3452  } else {
3453  ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
3454  }
3455  /* Use this as the basis */
3456  copy_request(&p->initreq, req);
3457  parse_request(&p->initreq);
3458  if (req->debug) {
3459  ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
3460  }
3461 }
3462 
3463 /*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
3464 static void sip_alreadygone(struct sip_pvt *dialog)
3465 {
3466  ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
3467  dialog->alreadygone = 1;
3468 }
3469 
3470 /*! Resolve DNS srv name or host name in a sip_proxy structure */
3471 static int proxy_update(struct sip_proxy *proxy)
3472 {
3473  /* if it's actually an IP address and not a name,
3474  there's no need for a managed lookup */
3475  if (!ast_sockaddr_parse(&proxy->ip, proxy->name, 0)) {
3476  /* Ok, not an IP address, then let's check if it's a domain or host */
3477  /* XXX Todo - if we have proxy port, don't do SRV */
3478  proxy->ip.ss.ss_family = get_address_family_filter(AST_TRANSPORT_UDP); /* Filter address family */
3479  if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
3480  ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
3481  return FALSE;
3482  }
3483 
3484  }
3485 
3486  ast_sockaddr_set_port(&proxy->ip, proxy->port);
3487 
3488  proxy->last_dnsupdate = time(NULL);
3489  return TRUE;
3490 }
3491 
3492 /*! \brief Parse proxy string and return an ao2_alloc'd proxy. If dest is
3493  * non-NULL, no allocation is performed and dest is used instead.
3494  * On error NULL is returned. */
3495 static struct sip_proxy *proxy_from_config(const char *proxy, int sipconf_lineno, struct sip_proxy *dest)
3496 {
3497  char *mutable_proxy, *sep, *name;
3498  int allocated = 0;
3499 
3500  if (!dest) {
3501  dest = ao2_alloc(sizeof(struct sip_proxy), NULL);
3502  if (!dest) {
3503  ast_log(LOG_WARNING, "Unable to allocate config storage for proxy\n");
3504  return NULL;
3505  }
3506  allocated = 1;
3507  }
3508 
3509  /* Format is: [transport://]name[:port][,force] */
3510  mutable_proxy = ast_skip_blanks(ast_strdupa(proxy));
3511  sep = strchr(mutable_proxy, ',');
3512  if (sep) {
3513  *sep++ = '\0';
3514  dest->force = !strncasecmp(ast_skip_blanks(sep), "force", 5);
3515  } else {
3516  dest->force = FALSE;
3517  }
3518 
3519  sip_parse_host(mutable_proxy, sipconf_lineno, &name, &dest->port, &dest->transport);
3520 
3521  /* Check that there is a name at all */
3522  if (ast_strlen_zero(name)) {
3523  if (allocated) {
3524  ao2_ref(dest, -1);
3525  } else {
3526  dest->name[0] = '\0';
3527  }
3528  return NULL;
3529  }
3530  ast_copy_string(dest->name, name, sizeof(dest->name));
3531 
3532  /* Resolve host immediately */
3533  proxy_update(dest);
3534 
3535  return dest;
3536 }
3537 
3538 /*! \brief converts ascii port to int representation. If no
3539  * pt buffer is provided or the pt has errors when being converted
3540  * to an int value, the port provided as the standard is used.
3541  */
3542 unsigned int port_str2int(const char *pt, unsigned int standard)
3543 {
3544  int port = standard;
3545  if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
3546  port = standard;
3547  }
3548 
3549  return port;
3550 }
3551 
3552 /*! \brief Get default outbound proxy or global proxy */
3553 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
3554 {
3555  if (dialog && dialog->options && dialog->options->outboundproxy) {
3556  if (sipdebug) {
3557  ast_debug(1, "OBPROXY: Applying dialplan set OBproxy to this call\n");
3558  }
3559  append_history(dialog, "OBproxy", "Using dialplan obproxy %s", dialog->options->outboundproxy->name);
3560  return dialog->options->outboundproxy;
3561  }
3562  if (peer && peer->outboundproxy) {
3563  if (sipdebug) {
3564  ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
3565  }
3566  append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
3567  return peer->outboundproxy;
3568  }
3569  if (sip_cfg.outboundproxy.name[0]) {
3570  if (sipdebug) {
3571  ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
3572  }
3573  append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
3574  return &sip_cfg.outboundproxy;
3575  }
3576  if (sipdebug) {
3577  ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
3578  }
3579  return NULL;
3580 }
3581 
3582 /*! \brief returns true if 'name' (with optional trailing whitespace)
3583  * matches the sip method 'id'.
3584  * Strictly speaking, SIP methods are case SENSITIVE, but we do
3585  * a case-insensitive comparison to be more tolerant.
3586  * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
3587  */
3588 static int method_match(enum sipmethod id, const char *name)
3589 {
3590  int len = strlen(sip_methods[id].text);
3591  int l_name = name ? strlen(name) : 0;
3592  /* true if the string is long enough, and ends with whitespace, and matches */
3593  return (l_name >= len && name && name[len] < 33 &&
3594  !strncasecmp(sip_methods[id].text, name, len));
3595 }
3596 
3597 /*! \brief find_sip_method: Find SIP method from header */
3598 static int find_sip_method(const char *msg)
3599 {
3600  int i, res = 0;
3601 
3602  if (ast_strlen_zero(msg)) {
3603  return 0;
3604  }
3605  for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
3606  if (method_match(i, msg)) {
3607  res = sip_methods[i].id;
3608  }
3609  }
3610  return res;
3611 }
3612 
3613 /*! \brief See if we pass debug IP filter */
3614 static inline int sip_debug_test_addr(const struct ast_sockaddr *addr)
3615 {
3616  /* Can't debug if sipdebug is not enabled */
3617  if (!sipdebug) {
3618  return 0;
3619  }
3620 
3621  /* A null debug_addr means we'll debug any address */
3623  return 1;
3624  }
3625 
3626  /* If no port was specified for a debug address, just compare the
3627  * addresses, otherwise compare the address and port
3628  */
3629  if (ast_sockaddr_port(&debugaddr)) {
3630  return !ast_sockaddr_cmp(&debugaddr, addr);
3631  } else {
3632  return !ast_sockaddr_cmp_addr(&debugaddr, addr);
3633  }
3634 }
3635 
3636 /*! \brief The real destination address for a write */
3637 static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p)
3638 {
3639  if (p->outboundproxy) {
3640  return &p->outboundproxy->ip;
3641  }
3642 
3643  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;
3644 }
3645 
3646 /*! \brief Display SIP nat mode */
3647 static const char *sip_nat_mode(const struct sip_pvt *p)
3648 {
3649  return ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) ? "NAT" : "no NAT";
3650 }
3651 
3652 /*! \brief Test PVT for debugging output */
3653 static inline int sip_debug_test_pvt(struct sip_pvt *p)
3654 {
3655  if (!sipdebug) {
3656  return 0;
3657  }
3658  return sip_debug_test_addr(sip_real_dst(p));
3659 }
3660 
3661 /*! \brief Return int representing a bit field of transport types found in const char *transport */
3662 static int get_transport_str2enum(const char *transport)
3663 {
3664  int res = 0;
3665 
3666  if (ast_strlen_zero(transport)) {
3667  return res;
3668  }
3669 
3670  if (!strcasecmp(transport, "udp")) {
3671  res |= AST_TRANSPORT_UDP;
3672  }
3673  if (!strcasecmp(transport, "tcp")) {
3674  res |= AST_TRANSPORT_TCP;
3675  }
3676  if (!strcasecmp(transport, "tls")) {
3677  res |= AST_TRANSPORT_TLS;
3678  }
3679  if (!strcasecmp(transport, "ws")) {
3680  res |= AST_TRANSPORT_WS;
3681  }
3682  if (!strcasecmp(transport, "wss")) {
3683  res |= AST_TRANSPORT_WSS;
3684  }
3685 
3686  return res;
3687 }
3688 
3689 /*! \brief Return configuration of transports for a device */
3690 static inline const char *get_transport_list(unsigned int transports)
3691 {
3692  char *buf;
3693 
3694  if (!transports) {
3695  return "UNKNOWN";
3696  }
3697 
3699  return "";
3700  }
3701 
3702  memset(buf, 0, SIP_TRANSPORT_STR_BUFSIZE);
3703 
3704  if (transports & AST_TRANSPORT_UDP) {
3705  strncat(buf, "UDP,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
3706  }
3707  if (transports & AST_TRANSPORT_TCP) {
3708  strncat(buf, "TCP,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
3709  }
3710  if (transports & AST_TRANSPORT_TLS) {
3711  strncat(buf, "TLS,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
3712  }
3713  if (transports & AST_TRANSPORT_WS) {
3714  strncat(buf, "WS,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
3715  }
3716  if (transports & AST_TRANSPORT_WSS) {
3717  strncat(buf, "WSS,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
3718  }
3719 
3720  /* Remove the trailing ',' if present */
3721  if (strlen(buf)) {
3722  buf[strlen(buf) - 1] = 0;
3723  }
3724 
3725  return buf;
3726 }
3727 
3728 /*! \brief Return transport as string */
3730 {
3731  switch (t) {
3732  case AST_TRANSPORT_UDP:
3733  return "UDP";
3734  case AST_TRANSPORT_TCP:
3735  return "TCP";
3736  case AST_TRANSPORT_TLS:
3737  return "TLS";
3738  case AST_TRANSPORT_WS:
3739  case AST_TRANSPORT_WSS:
3740  return "WS";
3741  }
3742 
3743  return "UNKNOWN";
3744 }
3745 
3746 /*! \brief Return protocol string for srv dns query */
3747 static inline const char *get_srv_protocol(enum ast_transport t)
3748 {
3749  switch (t) {
3750  case AST_TRANSPORT_UDP:
3751  return "udp";
3752  case AST_TRANSPORT_WS:
3753  return "ws";
3754  case AST_TRANSPORT_TLS:
3755  case AST_TRANSPORT_TCP:
3756  return "tcp";
3757  case AST_TRANSPORT_WSS:
3758  return "wss";
3759  }
3760 
3761  return "udp";
3762 }
3763 
3764 /*! \brief Return service string for srv dns query */
3765 static inline const char *get_srv_service(enum ast_transport t)
3766 {
3767  switch (t) {
3768  case AST_TRANSPORT_TCP:
3769  case AST_TRANSPORT_UDP:
3770  case AST_TRANSPORT_WS:
3771  return "sip";
3772  case AST_TRANSPORT_TLS:
3773  case AST_TRANSPORT_WSS:
3774  return "sips";
3775  }
3776  return "sip";
3777 }
3778 
3779 /*! \brief Return transport of dialog.
3780  \note this is based on a false assumption. We don't always use the
3781  outbound proxy for all requests in a dialog. It depends on the
3782  "force" parameter. The FIRST request is always sent to the ob proxy.
3783  \todo Fix this function to work correctly
3784 */
3785 static inline const char *get_transport_pvt(struct sip_pvt *p)
3786 {
3787  if (p->outboundproxy && p->outboundproxy->transport) {
3789  }
3790 
3791  return sip_get_transport(p->socket.type);
3792 }
3793 
3794 /*!
3795  * \internal
3796  * \brief Transmit SIP message
3797  *
3798  * \details
3799  * Sends a SIP request or response on a given socket (in the pvt)
3800  * \note
3801  * Called by retrans_pkt, send_request, send_response and __sip_reliable_xmit
3802  *
3803  * \return length of transmitted message, XMIT_ERROR on known network failures -1 on other failures.
3804  */
3805 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data)
3806 {
3807  int res = 0;
3808  const struct ast_sockaddr *dst = sip_real_dst(p);
3809 
3810  ast_debug(2, "Trying to put '%.11s' onto %s socket destined for %s\n", ast_str_buffer(data), get_transport_pvt(p), ast_sockaddr_stringify(dst));
3811 
3812  if (sip_prepare_socket(p) < 0) {
3813  return XMIT_ERROR;
3814  }
3815 
3816  if (p->socket.type == AST_TRANSPORT_UDP) {
3817  res = ast_sendto(p->socket.fd, ast_str_buffer(data), ast_str_strlen(data), 0, dst);
3818  } else if (p->socket.tcptls_session) {
3820  if (res < -1) {
3821  return res;
3822  }
3823  } else if (p->socket.ws_session) {
3824  if (!(res = ast_websocket_write_string(p->socket.ws_session, ast_str_buffer(data)))) {
3825  /* The WebSocket API just returns 0 on success and -1 on failure, while this code expects the payload length to be returned */
3826  res = ast_str_strlen(data);
3827  }
3828  } else {
3829  ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
3830  return XMIT_ERROR;
3831  }
3832 
3833  if (res == -1) {
3834  switch (errno) {
3835  case EBADF: /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
3836  case EHOSTUNREACH: /* Host can't be reached */
3837  case ENETDOWN: /* Interface down */
3838  case ENETUNREACH: /* Network failure */
3839  case ECONNREFUSED: /* ICMP port unreachable */
3840  res = XMIT_ERROR; /* Don't bother with trying to transmit again */
3841  }
3842  }
3843  if (res != ast_str_strlen(data)) {
3844  ast_log(LOG_WARNING, "sip_xmit of %p (len %zu) to %s returned %d: %s\n", data, ast_str_strlen(data), ast_sockaddr_stringify(dst), res, strerror(errno));
3845  }
3846 
3847  return res;
3848 }
3849 
3850 /*! \brief Build a Via header for a request */
3851 static void build_via(struct sip_pvt *p)
3852 {
3853  /* Work around buggy UNIDEN UIP200 firmware */
3854  const char *rport = (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) || ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)) ? ";rport" : "";
3855 
3856  /* z9hG4bK is a magic cookie. See RFC 3261 section 8.1.1.7 */
3857  snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s;branch=z9hG4bK%08x%s",
3858  get_transport_pvt(p),
3860  (unsigned)p->branch, rport);
3861 }
3862 
3863 /*! \brief NAT fix - decide which IP address to use for Asterisk server?
3864  *
3865  * Using the localaddr structure built up with localnet statements in sip.conf
3866  * apply it to their address to see if we need to substitute our
3867  * externaddr or can get away with our internal bindaddr
3868  * 'us' is always overwritten.
3869  */
3870 static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p)
3871 {
3872  struct ast_sockaddr theirs;
3873 
3874  /* Set want_remap to non-zero if we want to remap 'us' to an externally
3875  * reachable IP address and port. This is done if:
3876  * 1. we have a localaddr list (containing 'internal' addresses marked
3877  * as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
3878  * and AST_SENSE_ALLOW on 'external' ones);
3879  * 2. externaddr is set, so we know what to use as the
3880  * externally visible address;
3881  * 3. the remote address, 'them', is external;
3882  * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
3883  * when passed to ast_apply_ha() so it does need to be remapped.
3884  * This fourth condition is checked later.
3885  */
3886  int want_remap = 0;
3887 
3888  ast_sockaddr_copy(us, &internip); /* starting guess for the internal address */
3889  /* now ask the system what would it use to talk to 'them' */
3890  ast_ouraddrfor(them, us);
3891  ast_sockaddr_copy(&theirs, them);
3892 
3893  if (ast_sockaddr_is_ipv6(&theirs) && !ast_sockaddr_is_ipv4_mapped(&theirs)) {
3894  if (localaddr && !ast_sockaddr_isnull(&externaddr) && !ast_sockaddr_is_any(&bindaddr)) {
3895  ast_log(LOG_WARNING, "Address remapping activated in sip.conf "
3896  "but we're using IPv6, which doesn't need it. Please "
3897  "remove \"localnet\" and/or \"externaddr\" settings.\n");
3898  }
3899  } else {
3900  want_remap = localaddr &&
3902  ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
3903  }
3904 
3905  if (want_remap &&
3906  (!sip_cfg.matchexternaddrlocally || !ast_apply_ha(localaddr, us)) ) {
3907  /* if we used externhost, see if it is time to refresh the info */
3908  if (externexpire && time(NULL) >= externexpire) {
3910  ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
3911  }
3912  externexpire = time(NULL) + externrefresh;
3913  }
3916  switch (p->socket.type) {
3917  case AST_TRANSPORT_TCP:
3919  /* for consistency, default to the externaddr port */
3921  }
3922  if (!externtcpport) {
3924  }
3925  if (!externtcpport) {
3927  }
3929  break;
3930  case AST_TRANSPORT_TLS:
3931  if (!externtlsport) {
3933  }
3934  if (!externtlsport) {
3936  }
3938  break;
3939  case AST_TRANSPORT_UDP:
3940  if (!ast_sockaddr_port(&externaddr)) {
3942  }
3943  break;
3944  default:
3945  break;
3946  }
3947  }
3948  ast_debug(1, "Target address %s is not local, substituting externaddr\n",
3949  ast_sockaddr_stringify(them));
3950  } else {
3951  /* no remapping, but we bind to a specific address, so use it. */
3952  switch (p->socket.type) {
3953  case AST_TRANSPORT_TCP:
3954  if (!ast_sockaddr_isnull(&sip_tcp_desc.local_address)) {
3955  if (!ast_sockaddr_is_any(&sip_tcp_desc.local_address)) {
3956  ast_sockaddr_copy(us,
3957  &sip_tcp_desc.local_address);
3958  } else {
3960  ast_sockaddr_port(&sip_tcp_desc.local_address));
3961  }
3962  break;
3963  } /* fall through on purpose */
3964  case AST_TRANSPORT_TLS:
3965  if (!ast_sockaddr_isnull(&sip_tls_desc.local_address)) {
3966  if (!ast_sockaddr_is_any(&sip_tls_desc.local_address)) {
3967  ast_sockaddr_copy(us,
3968  &sip_tls_desc.local_address);
3969  } else {
3971  ast_sockaddr_port(&sip_tls_desc.local_address));
3972  }
3973  break;
3974  } /* fall through on purpose */
3975  case AST_TRANSPORT_UDP:
3976  /* fall through on purpose */
3977  default:
3978  if (!ast_sockaddr_is_any(&bindaddr)) {
3980  }
3981  if (!ast_sockaddr_port(us)) {
3983  }
3984  }
3985  }
3986  ast_debug(3, "Setting AST_TRANSPORT_%s with address %s\n", sip_get_transport(p->socket.type), ast_sockaddr_stringify(us));
3987 }
3988 
3989 /*! \brief Append to SIP dialog history with arg list */
3990 static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
3991 {
3992  char buf[80], *c = buf; /* max history length */
3993  struct sip_history *hist;
3994  int l;
3995 
3996  vsnprintf(buf, sizeof(buf), fmt, ap);
3997  strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
3998  l = strlen(buf) + 1;
3999  if (!(hist = ast_calloc(1, sizeof(*hist) + l))) {
4000  return;
4001  }
4002  if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
4003  ast_free(hist);
4004  return;
4005  }
4006  memcpy(hist->event, buf, l);
4007  if (p->history_entries == MAX_HISTORY_ENTRIES) {
4008  struct sip_history *oldest;
4009  oldest = AST_LIST_REMOVE_HEAD(p->history, list);
4010  p->history_entries--;
4011  ast_free(oldest);
4012  }
4013  AST_LIST_INSERT_TAIL(p->history, hist, list);
4014  p->history_entries++;
4015  if (log_level != -1) {
4016  ast_log_dynamic_level(log_level, "%s\n", buf);
4017  }
4018 }
4019 
4020 /*! \brief Append to SIP dialog history with arg list */
4021 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
4022 {
4023  va_list ap;
4024 
4025  if (!p) {
4026  return;
4027  }
4028 
4029  if (!p->do_history && !recordhistory && !dumphistory) {
4030  return;
4031  }
4032 
4033  va_start(ap, fmt);
4034  append_history_va(p, fmt, ap);
4035  va_end(ap);
4036 
4037  return;
4038 }
4039 
4040 /*!
4041  * \brief Retransmit SIP message if no answer
4042  *
4043  * \note Run by the sched thread.
4044  */
4045 static int retrans_pkt(const void *data)
4046 {
4047  struct sip_pkt *pkt = (struct sip_pkt *) data;
4048  struct sip_pkt *prev;
4049  struct sip_pkt *cur;
4050  struct ast_channel *owner_chan;
4051  int reschedule = DEFAULT_RETRANS;
4052  int xmitres = 0;
4053  /* how many ms until retrans timeout is reached */
4054  int64_t diff = pkt->retrans_stop_time - ast_tvdiff_ms(ast_tvnow(), pkt->time_sent);
4055 
4056  /* Do not retransmit if time out is reached. This will be negative if the time between
4057  * the first transmission and now is larger than our timeout period. This is a fail safe
4058  * check in case the scheduler gets behind or the clock is changed. */
4059  if ((diff <= 0) || (diff > pkt->retrans_stop_time)) {
4060  pkt->retrans_stop = 1;
4061  }
4062 
4063  /* Lock channel PVT */
4064  sip_pvt_lock(pkt->owner);
4065 
4066  if (!pkt->retrans_stop) {
4067  pkt->retrans++;
4068  if (!pkt->timer_t1) { /* Re-schedule using timer_a and timer_t1 */
4069  if (sipdebug) {
4070  ast_debug(4, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n",
4071  pkt->retransid,
4072  sip_methods[pkt->method].text,
4073  pkt->method);
4074  }
4075  } else {
4076  int siptimer_a;
4077 
4078  if (sipdebug) {
4079  ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n",
4080  pkt->retransid,
4081  pkt->retrans,
4082  sip_methods[pkt->method].text,
4083  pkt->method);
4084  }
4085  if (!pkt->timer_a) {
4086  pkt->timer_a = 2 ;
4087  } else {
4088  pkt->timer_a = 2 * pkt->timer_a;
4089  }
4090 
4091  /* For non-invites, a maximum of 4 secs */
4092  if (INT_MAX / pkt->timer_a < pkt->timer_t1) {
4093  /*
4094  * Uh Oh, we will have an integer overflow.
4095  * Recalculate previous timeout time instead.
4096  */
4097  pkt->timer_a = pkt->timer_a / 2;
4098  }
4099  siptimer_a = pkt->timer_t1 * pkt->timer_a; /* Double each time */
4100  if (pkt->method != SIP_INVITE && siptimer_a > 4000) {
4101  siptimer_a = 4000;
4102  }
4103 
4104  /* Reschedule re-transmit */
4105  reschedule = siptimer_a;
4106  ast_debug(4, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n",
4107  pkt->retrans + 1,
4108  siptimer_a,
4109  pkt->timer_t1,
4110  pkt->retransid);
4111  }
4112 
4113  if (sip_debug_test_pvt(pkt->owner)) {
4114  const struct ast_sockaddr *dst = sip_real_dst(pkt->owner);
4115 
4116  ast_verbose("Retransmitting #%d (%s) to %s:\n%s\n---\n",
4117  pkt->retrans, sip_nat_mode(pkt->owner),
4119  ast_str_buffer(pkt->data));
4120  }
4121 
4122  append_history(pkt->owner, "ReTx", "%d %s", reschedule, ast_str_buffer(pkt->data));
4123  xmitres = __sip_xmit(pkt->owner, pkt->data);
4124 
4125  /* If there was no error during the network transmission, schedule the next retransmission,
4126  * but if the next retransmission is going to be beyond our timeout period, mark the packet's
4127  * stop_retrans value and set the next retransmit to be the exact time of timeout. This will
4128  * allow any responses to the packet to be processed before the packet is destroyed on the next
4129  * call to this function by the scheduler. */
4130  if (xmitres != XMIT_ERROR) {
4131  if (reschedule >= diff) {
4132  pkt->retrans_stop = 1;
4133  reschedule = diff;
4134  }
4135  sip_pvt_unlock(pkt->owner);
4136  return reschedule;
4137  }
4138  }
4139 
4140  /* At this point, either the packet's retransmission timed out, or there was a
4141  * transmission error, either way destroy the scheduler item and this packet. */
4142 
4143  pkt->retransid = -1; /* Kill this scheduler item */
4144 
4145  if (pkt->method != SIP_OPTIONS && xmitres == 0) {
4146  if (pkt->is_fatal || sipdebug) { /* Tell us if it's critical or if we're debugging */
4147  ast_log(LOG_WARNING, "Retransmission timeout reached on transmission %s for seqno %u (%s %s) -- See https://wiki.asterisk.org/wiki/display/AST/SIP+Retransmissions\n"
4148  "Packet timed out after %dms with no response\n",
4149  pkt->owner->callid,
4150  pkt->seqno,
4151  pkt->is_fatal ? "Critical" : "Non-critical",
4152  pkt->is_resp ? "Response" : "Request",
4153  (int) ast_tvdiff_ms(ast_tvnow(), pkt->time_sent));
4154  }
4155  } else if (pkt->method == SIP_OPTIONS && sipdebug) {
4156  ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s) -- See https://wiki.asterisk.org/wiki/display/AST/SIP+Retransmissions\n", pkt->owner->callid);
4157  }
4158 
4159  if (xmitres == XMIT_ERROR) {
4160  ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
4161  append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
4162  } else {
4163  append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
4164  }
4165 
4166  sip_pvt_unlock(pkt->owner); /* SIP_PVT, not channel */
4167  owner_chan = sip_pvt_lock_full(pkt->owner);
4168 
4169  if (pkt->is_fatal) {
4170  if (owner_chan) {
4171  ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet (see https://wiki.asterisk.org/wiki/display/AST/SIP+Retransmissions).\n", pkt->owner->callid);
4172 
4173  if (pkt->is_resp &&
4174  (pkt->response_code >= 200) &&
4175  (pkt->response_code < 300) &&
4176  pkt->owner->pendinginvite &&
4178  /* This is a timeout of the 2XX response to a pending INVITE. In this case terminate the INVITE
4179  * transaction just as if we received the ACK, but immediately hangup with a BYE (sip_hangup
4180  * will send the BYE as long as the dialog is not set as "alreadygone")
4181  * RFC 3261 section 13.3.1.4.
4182  * "If the server retransmits the 2xx response for 64*T1 seconds without receiving
4183  * an ACK, the dialog is confirmed, but the session SHOULD be terminated. This is
4184  * accomplished with a BYE, as described in Section 15." */
4186  pkt->owner->pendinginvite = 0;
4187  } else {
4188  /* there is nothing left to do, mark the dialog as gone */
4189  sip_alreadygone(pkt->owner);
4190  }
4191  if (!ast_channel_hangupcause(owner_chan)) {
4193  }
4195  } else {
4196  /* If no channel owner, destroy now */
4197 
4198  /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
4199  if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
4200  pvt_set_needdestroy(pkt->owner, "no response to critical packet");
4201  sip_alreadygone(pkt->owner);
4202  append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
4203  }
4204  }
4205  } else if (pkt->owner->pendinginvite == pkt->seqno) {
4206  ast_log(LOG_WARNING, "Timeout on %s on non-critical invite transaction.\n", pkt->owner->callid);
4208  pkt->owner->pendinginvite = 0;
4209  check_pendings(pkt->owner);
4210  }
4211 
4212  if (owner_chan) {
4213  ast_channel_unlock(owner_chan);
4214  ast_channel_unref(owner_chan);
4215  }
4216 
4217  if (pkt->method == SIP_BYE) {
4218  /* We're not getting answers on SIP BYE's. Tear down the call anyway. */
4219  sip_alreadygone(pkt->owner);
4220  append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
4221  pvt_set_needdestroy(pkt->owner, "no response to BYE");
4222  }
4223 
4224  /* Unlink and destroy the packet object. */
4225  for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
4226  if (cur == pkt) {
4227  /* Unlink the node from the list. */
4228  UNLINK(cur, pkt->owner->packets, prev);
4229  ao2_t_ref(pkt, -1, "Packet retransmission list (retransmission complete)");
4230  break;
4231  }
4232  }
4233 
4234  /*
4235  * If the object was not in the list then we were in the process of
4236  * stopping retransmisions while we were sending this retransmission.
4237  */
4238 
4239  sip_pvt_unlock(pkt->owner);
4240  ao2_t_ref(pkt, -1, "Scheduled packet retransmission complete");
4241  return 0;
4242 }
4243 
4244 /* Run by the sched thread. */
4245 static int __stop_retrans_pkt(const void *data)
4246 {
4247  struct sip_pkt *pkt = (void *) data;
4248 
4249  AST_SCHED_DEL_UNREF(sched, pkt->retransid,
4250  ao2_t_ref(pkt, -1, "Stop scheduled packet retransmission"));
4251  ao2_t_ref(pkt, -1, "Stop packet retransmission action");
4252  return 0;
4253 }
4254 
4255 static void stop_retrans_pkt(struct sip_pkt *pkt)
4256 {
4257  ao2_t_ref(pkt, +1, "Stop packet retransmission action");
4258  if (ast_sched_add(sched, 0, __stop_retrans_pkt, pkt) < 0) {
4259  /* Uh Oh. Expect bad behavior. */
4260  ao2_t_ref(pkt, -1, "Failed to schedule stop packet retransmission action");
4261  }
4262 }
4263 
4264 static void sip_pkt_dtor(void *vdoomed)
4265 {
4266  struct sip_pkt *pkt = (void *) vdoomed;
4267 
4268  if (pkt->owner) {
4269  dialog_unref(pkt->owner, "Retransmission packet is being destroyed");
4270  }
4271  ast_free(pkt->data);
4272 }
4273 
4274 /*!
4275  * \internal
4276  * \brief Transmit packet with retransmits
4277  * \return 0 on success, -1 on failure to allocate packet
4278  */
4279 static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, uint32_t seqno, int resp, struct ast_str *data, int fatal, int sipmethod)
4280 {
4281  struct sip_pkt *pkt = NULL;
4282  int siptimer_a = DEFAULT_RETRANS;
4283  int xmitres = 0;
4284  unsigned respid;
4285 
4286  if (sipmethod == SIP_INVITE) {
4287  /* Note this is a pending invite */
4288  p->pendinginvite = seqno;
4289  }
4290 
4292  if (!pkt) {
4293  return AST_FAILURE;
4294  }
4295  /* copy data, add a terminator and save length */
4296  pkt->data = ast_str_create(ast_str_strlen(data));
4297  if (!pkt->data) {
4298  ao2_t_ref(pkt, -1, "Failed to initialize");
4299  return AST_FAILURE;
4300  }
4301  ast_str_set(&pkt->data, 0, "%s%s", ast_str_buffer(data), "\0");
4302  /* copy other parameters from the caller */
4303  pkt->method = sipmethod;
4304  pkt->seqno = seqno;
4305  pkt->is_resp = resp;
4306  pkt->is_fatal = fatal;
4307  pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
4308 
4309  /* The retransmission list owns a pkt ref */
4310  pkt->next = p->packets;
4311  p->packets = pkt; /* Add it to the queue */
4312 
4313  if (resp) {
4314  /* Parse out the response code */
4315  if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
4316  pkt->response_code = respid;
4317  }
4318  }
4319  pkt->timer_t1 = p->timer_t1; /* Set SIP timer T1 */
4320  if (pkt->timer_t1) {
4321  siptimer_a = pkt->timer_t1;
4322  }
4323 
4324  pkt->time_sent = ast_tvnow(); /* time packet was sent */
4325  pkt->retrans_stop_time = 64 * (pkt->timer_t1 ? pkt->timer_t1 : DEFAULT_TIMER_T1); /* time in ms after pkt->time_sent to stop retransmission */
4326 
4327  if (!(p->socket.type & AST_TRANSPORT_UDP)) {
4328  /* TCP does not need retransmits as that's built in, but with
4329  * retrans_stop set, we must give it the full timer_H treatment */
4330  pkt->retrans_stop = 1;
4331  siptimer_a = pkt->retrans_stop_time;
4332  }
4333 
4334  /* Schedule retransmission */
4335  ao2_t_ref(pkt, +1, "Schedule packet retransmission");
4336  pkt->retransid = ast_sched_add_variable(sched, siptimer_a, retrans_pkt, pkt, 1);
4337  if (pkt->retransid < 0) {
4338  ao2_t_ref(pkt, -1, "Failed to schedule packet retransmission");
4339  }
4340 
4341  if (sipdebug) {
4342  ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id #%d\n", pkt->retransid);
4343  }
4344 
4345  xmitres = __sip_xmit(pkt->owner, pkt->data); /* Send packet */
4346 
4347  if (xmitres == XMIT_ERROR) { /* Serious network trouble, no need to try again */
4348  append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
4349  ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
4350 
4351  /* Unlink and destroy the packet object. */
4352  p->packets = pkt->next;
4353  stop_retrans_pkt(pkt);
4354  ao2_t_ref(pkt, -1,