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