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