Asterisk - The Open Source Telephony Project  18.5.0
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 <[email protected]>
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 <[email protected]>
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  <support_level>deprecated</support_level>
180  ***/
181 
182 /*! \page sip_session_timers SIP Session Timers in Asterisk Chan_sip
183 
184  The SIP Session-Timers is an extension of the SIP protocol that allows end-points and proxies to
185  refresh a session periodically. The sessions are kept alive by sending a RE-INVITE or UPDATE
186  request at a negotiated interval. If a session refresh fails then all the entities that support Session-
187  Timers clear their internal session state. In addition, UAs generate a BYE request in order to clear
188  the state in the proxies and the remote UA (this is done for the benefit of SIP entities in the path
189  that do not support Session-Timers).
190 
191  The Session-Timers can be configured on a system-wide, per-user, or per-peer basis. The peruser/
192  per-peer settings override the global settings. The following new parameters have been
193  added to the sip.conf file.
194  session-timers=["accept", "originate", "refuse"]
195  session-expires=[integer]
196  session-minse=[integer]
197  session-refresher=["uas", "uac"]
198 
199  The session-timers parameter in sip.conf defines the mode of operation of SIP session-timers feature in
200  Asterisk. The Asterisk can be configured in one of the following three modes:
201 
202  1. Accept :: In the "accept" mode, the Asterisk server honors
203  session-timers requests made by remote end-points. A remote
204  end-point can request Asterisk to engage session-timers by either
205  sending it an INVITE request with a "Supported: timer" header in
206  it or by responding to Asterisk's INVITE with a 200 OK that
207  contains Session-Expires: header in it. In this mode, the Asterisk
208  server does not request session-timers from remote
209  end-points. This is the default mode.
210 
211  2. Originate :: In the "originate" mode, the Asterisk server
212  requests the remote end-points to activate session-timers in
213  addition to honoring such requests made by the remote
214  end-points. In order to get as much protection as possible against
215  hanging SIP channels due to network or end-point failures,
216  Asterisk resends periodic re-INVITEs even if a remote end-point
217  does not support the session-timers feature.
218 
219  3. Refuse :: In the "refuse" mode, Asterisk acts as if it does not
220  support session- timers for inbound or outbound requests. If a
221  remote end-point requests session-timers in a dialog, then
222  Asterisk ignores that request unless it's noted as a requirement
223  (Require: header), in which case the INVITE is rejected with a 420
224  Bad Extension response.
225 
226 */
227 
228 #include "asterisk.h"
229 
230 #include <signal.h>
231 #include <regex.h>
232 #include <inttypes.h>
233 
234 #include "asterisk/network.h"
235 #include "asterisk/paths.h" /* need ast_config_AST_SYSTEM_NAME */
236 #include "asterisk/lock.h"
237 #include "asterisk/config.h"
238 #include "asterisk/module.h"
239 #include "asterisk/pbx.h"
240 #include "asterisk/sched.h"
241 #include "asterisk/io.h"
242 #include "asterisk/rtp_engine.h"
243 #include "asterisk/udptl.h"
244 #include "asterisk/acl.h"
245 #include "asterisk/manager.h"
246 #include "asterisk/callerid.h"
247 #include "asterisk/cli.h"
248 #include "asterisk/musiconhold.h"
249 #include "asterisk/dsp.h"
250 #include "asterisk/pickup.h"
251 #include "asterisk/parking.h"
252 #include "asterisk/srv.h"
253 #include "asterisk/astdb.h"
254 #include "asterisk/causes.h"
255 #include "asterisk/utils.h"
256 #include "asterisk/file.h"
257 #include "asterisk/astobj2.h"
258 #include "asterisk/dnsmgr.h"
259 #include "asterisk/devicestate.h"
260 #include "asterisk/netsock2.h"
261 #include "asterisk/localtime.h"
262 #include "asterisk/abstract_jb.h"
263 #include "asterisk/threadstorage.h"
264 #include "asterisk/translate.h"
265 #include "asterisk/ast_version.h"
266 #include "asterisk/aoc.h"
267 #include "asterisk/message.h"
268 #include "sip/include/sip.h"
269 #include "sip/include/globals.h"
272 #include "sip/include/sip_utils.h"
273 #include "asterisk/sdp_srtp.h"
274 #include "asterisk/ccss.h"
275 #include "asterisk/xml.h"
276 #include "sip/include/dialog.h"
277 #include "sip/include/dialplan_functions.h"
279 #include "sip/include/route.h"
280 #include "asterisk/sip_api.h"
281 #include "asterisk/mwi.h"
282 #include "asterisk/bridge.h"
283 #include "asterisk/stasis.h"
285 #include "asterisk/stasis_system.h"
288 #include "asterisk/http_websocket.h"
289 #include "asterisk/format_cache.h"
290 #include "asterisk/linkedlists.h" /* for AST_LIST_NEXT */
291 
292 /*** DOCUMENTATION
293  <application name="SIPDtmfMode" language="en_US">
294  <synopsis>
295  Change the dtmfmode for a SIP call.
296  </synopsis>
297  <syntax>
298  <parameter name="mode" required="true">
299  <enumlist>
300  <enum name="inband" />
301  <enum name="info" />
302  <enum name="rfc2833" />
303  </enumlist>
304  </parameter>
305  </syntax>
306  <description>
307  <para>Changes the dtmfmode for a SIP call.</para>
308  </description>
309  </application>
310  <application name="SIPAddHeader" language="en_US">
311  <synopsis>
312  Add a SIP header to the outbound call.
313  </synopsis>
314  <syntax argsep=":">
315  <parameter name="Header" required="true" />
316  <parameter name="Content" required="true" />
317  </syntax>
318  <description>
319  <para>Adds a header to a SIP call placed with DIAL.</para>
320  <para>Remember to use the X-header if you are adding non-standard SIP
321  headers, like <literal>X-Asterisk-Accountcode:</literal>. Use this with care.
322  Adding the wrong headers may jeopardize the SIP dialog.</para>
323  <para>Always returns <literal>0</literal>.</para>
324  </description>
325  </application>
326  <application name="SIPRemoveHeader" language="en_US">
327  <synopsis>
328  Remove SIP headers previously added with SIPAddHeader
329  </synopsis>
330  <syntax>
331  <parameter name="Header" required="false" />
332  </syntax>
333  <description>
334  <para>SIPRemoveHeader() allows you to remove headers which were previously
335  added with SIPAddHeader(). If no parameter is supplied, all previously added
336  headers will be removed. If a parameter is supplied, only the matching headers
337  will be removed.</para>
338  <para>For example you have added these 2 headers:</para>
339  <para>SIPAddHeader(P-Asserted-Identity: sip:[email protected]);</para>
340  <para>SIPAddHeader(P-Preferred-Identity: sip:[email protected]);</para>
341  <para></para>
342  <para>// remove all headers</para>
343  <para>SIPRemoveHeader();</para>
344  <para>// remove all P- headers</para>
345  <para>SIPRemoveHeader(P-);</para>
346  <para>// remove only the PAI header (note the : at the end)</para>
347  <para>SIPRemoveHeader(P-Asserted-Identity:);</para>
348  <para></para>
349  <para>Always returns <literal>0</literal>.</para>
350  </description>
351  </application>
352  <application name="SIPSendCustomINFO" language="en_US">
353  <synopsis>
354  Send a custom INFO frame on specified channels.
355  </synopsis>
356  <syntax>
357  <parameter name="Data" required="true" />
358  <parameter name="UserAgent" required="false" />
359  </syntax>
360  <description>
361  <para>SIPSendCustomINFO() allows you to send a custom INFO message on all
362  active SIP channels or on channels with the specified User Agent. This
363  application is only available if TEST_FRAMEWORK is defined.</para>
364  </description>
365  </application>
366  <function name="SIP_HEADER" language="en_US">
367  <synopsis>
368  Gets the specified SIP header from an incoming INVITE message.
369  </synopsis>
370  <syntax>
371  <parameter name="name" required="true" />
372  <parameter name="number">
373  <para>If not specified, defaults to <literal>1</literal>.</para>
374  </parameter>
375  </syntax>
376  <description>
377  <para>Since there are several headers (such as Via) which can occur multiple
378  times, SIP_HEADER takes an optional second argument to specify which header with
379  that name to retrieve. Headers start at offset <literal>1</literal>.</para>
380  <para>This function does not access headers from the REFER message if the call
381  was transferred. To obtain the REFER headers, set the dialplan variable
382  <variable>GET_TRANSFERRER_DATA</variable> to the prefix of the headers of the
383  REFER message that you need to access; for example, <literal>X-</literal> to
384  get all headers starting with <literal>X-</literal>. The variable must be set
385  before a call to the application that starts the channel that may eventually
386  transfer back into the dialplan, and must be inherited by that channel, so prefix
387  it with the <literal>_</literal> or <literal>__</literal> when setting (or
388  set it in the pre-dial handler executed on the new channel). To get all headers
389  of the REFER message, set the value to <literal>*</literal>. Headers
390  are returned in the form of a dialplan hash TRANSFER_DATA, and can be accessed
391  with the functions <variable>HASHKEYS(TRANSFER_DATA)</variable> and, e. g.,
392  <variable>HASH(TRANSFER_DATA,X-That-Special-Header)</variable>.</para>
393  <para>Please also note that contents of the SDP (an attachment to the
394  SIP request) can't be accessed with this function.</para>
395  </description>
396  <see-also>
397  <ref type="function">SIP_HEADERS</ref>
398  </see-also>
399  </function>
400  <function name="SIP_HEADERS" language="en_US">
401  <synopsis>
402  Gets the list of SIP header names from an incoming INVITE message.
403  </synopsis>
404  <syntax>
405  <parameter name="prefix">
406  <para>If specified, only the headers matching the given prefix are returned.</para>
407  </parameter>
408  </syntax>
409  <description>
410  <para>Returns a comma-separated list of header names (without values) from the
411  INVITE message that originated the current channel. Multiple headers with the
412  same name are included in the list only once. The returned list can be iterated
413  over using the functions POP() and SIP_HEADER().</para>
414  <para>For example, <literal>${SIP_HEADERS(Co)}</literal> might return
415  <literal>Contact,Content-Length,Content-Type</literal>. As a practical example,
416  you may use <literal>${SIP_HEADERS(X-)}</literal> to enumerate optional extended
417  headers.</para>
418  <para>This function does not access headers from the incoming SIP REFER message;
419  see the documentation of the function SIP_HEADER for how to access them.</para>
420  <para>Please observe that contents of the SDP (an attachment to the
421  SIP request) can't be accessed with this function.</para>
422  </description>
423  <see-also>
424  <ref type="function">SIP_HEADER</ref>
425  <ref type="function">POP</ref>
426  </see-also>
427  </function>
428  <function name="SIPPEER" language="en_US">
429  <synopsis>
430  Gets SIP peer information.
431  </synopsis>
432  <syntax>
433  <parameter name="peername" required="true" />
434  <parameter name="item">
435  <enumlist>
436  <enum name="ip">
437  <para>(default) The IP address.</para>
438  </enum>
439  <enum name="port">
440  <para>The port number.</para>
441  </enum>
442  <enum name="mailbox">
443  <para>The configured mailbox.</para>
444  </enum>
445  <enum name="context">
446  <para>The configured context.</para>
447  </enum>
448  <enum name="expire">
449  <para>The epoch time of the next expire.</para>
450  </enum>
451  <enum name="dynamic">
452  <para>Is it dynamic? (yes/no).</para>
453  </enum>
454  <enum name="callerid_name">
455  <para>The configured Caller ID name.</para>
456  </enum>
457  <enum name="callerid_num">
458  <para>The configured Caller ID number.</para>
459  </enum>
460  <enum name="callgroup">
461  <para>The configured Callgroup.</para>
462  </enum>
463  <enum name="pickupgroup">
464  <para>The configured Pickupgroup.</para>
465  </enum>
466  <enum name="namedcallgroup">
467  <para>The configured Named Callgroup.</para>
468  </enum>
469  <enum name="namedpickupgroup">
470  <para>The configured Named Pickupgroup.</para>
471  </enum>
472  <enum name="codecs">
473  <para>The configured codecs.</para>
474  </enum>
475  <enum name="status">
476  <para>Status (if qualify=yes).</para>
477  </enum>
478  <enum name="regexten">
479  <para>Extension activated at registration.</para>
480  </enum>
481  <enum name="limit">
482  <para>Call limit (call-limit).</para>
483  </enum>
484  <enum name="busylevel">
485  <para>Configured call level for signalling busy.</para>
486  </enum>
487  <enum name="curcalls">
488  <para>Current amount of calls. Only available if call-limit is set.</para>
489  </enum>
490  <enum name="language">
491  <para>Default language for peer.</para>
492  </enum>
493  <enum name="accountcode">
494  <para>Account code for this peer.</para>
495  </enum>
496  <enum name="useragent">
497  <para>Current user agent header used by peer.</para>
498  </enum>
499  <enum name="maxforwards">
500  <para>The value used for SIP loop prevention in outbound requests</para>
501  </enum>
502  <enum name="chanvar[name]">
503  <para>A channel variable configured with setvar for this peer.</para>
504  </enum>
505  <enum name="codec[x]">
506  <para>Preferred codec index number <replaceable>x</replaceable> (beginning with zero).</para>
507  </enum>
508  </enumlist>
509  </parameter>
510  </syntax>
511  <description></description>
512  </function>
513  <function name="CHECKSIPDOMAIN" language="en_US">
514  <synopsis>
515  Checks if domain is a local domain.
516  </synopsis>
517  <syntax>
518  <parameter name="domain" required="true" />
519  </syntax>
520  <description>
521  <para>This function checks if the <replaceable>domain</replaceable> in the argument is configured
522  as a local SIP domain that this Asterisk server is configured to handle.
523  Returns the domain name if it is locally handled, otherwise an empty string.
524  Check the <literal>domain=</literal> configuration in <filename>sip.conf</filename>.</para>
525  </description>
526  </function>
527  <manager name="SIPpeers" language="en_US">
528  <synopsis>
529  List SIP peers (text format).
530  </synopsis>
531  <syntax>
532  <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
533  </syntax>
534  <description>
535  <para>Lists SIP peers in text format with details on current status.
536  <literal>Peerlist</literal> will follow as separate events, followed by a final event called
537  <literal>PeerlistComplete</literal>.</para>
538  </description>
539  </manager>
540  <manager name="SIPshowpeer" language="en_US">
541  <synopsis>
542  show SIP peer (text format).
543  </synopsis>
544  <syntax>
545  <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
546  <parameter name="Peer" required="true">
547  <para>The peer name you want to check.</para>
548  </parameter>
549  </syntax>
550  <description>
551  <para>Show one SIP peer with details on current status.</para>
552  </description>
553  </manager>
554  <manager name="SIPqualifypeer" language="en_US">
555  <synopsis>
556  Qualify SIP peers.
557  </synopsis>
558  <syntax>
559  <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
560  <parameter name="Peer" required="true">
561  <para>The peer name you want to qualify.</para>
562  </parameter>
563  </syntax>
564  <description>
565  <para>Qualify a SIP peer.</para>
566  </description>
567  <see-also>
568  <ref type="managerEvent">SIPQualifyPeerDone</ref>
569  </see-also>
570  </manager>
571  <manager name="SIPshowregistry" language="en_US">
572  <synopsis>
573  Show SIP registrations (text format).
574  </synopsis>
575  <syntax>
576  <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
577  </syntax>
578  <description>
579  <para>Lists all registration requests and status. Registrations will follow as separate
580  events followed by a final event called <literal>RegistrationsComplete</literal>.</para>
581  </description>
582  </manager>
583  <manager name="SIPnotify" language="en_US">
584  <synopsis>
585  Send a SIP notify.
586  </synopsis>
587  <syntax>
588  <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
589  <parameter name="Channel" required="true">
590  <para>Peer to receive the notify.</para>
591  </parameter>
592  <parameter name="Variable" required="true">
593  <para>At least one variable pair must be specified.
594  <replaceable>name</replaceable>=<replaceable>value</replaceable></para>
595  </parameter>
596  <parameter name="Call-ID" required="false">
597  <para>When specified, SIP notity will be sent as a part of an existing dialog.</para>
598  </parameter>
599  </syntax>
600  <description>
601  <para>Sends a SIP Notify event.</para>
602  <para>All parameters for this event must be specified in the body of this request
603  via multiple <literal>Variable: name=value</literal> sequences.</para>
604  </description>
605  </manager>
606  <manager name="SIPpeerstatus" language="en_US">
607  <synopsis>
608  Show the status of one or all of the sip peers.
609  </synopsis>
610  <syntax>
611  <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
612  <parameter name="Peer" required="false">
613  <para>The peer name you want to check.</para>
614  </parameter>
615  </syntax>
616  <description>
617  <para>Retrieves the status of one or all of the sip peers. If no peer name is specified, status
618  for all of the sip peers will be retrieved.</para>
619  </description>
620  </manager>
621  <info name="MessageDestinationInfo" language="en_US" tech="SIP">
622  <para>Specifying a prefix of <literal>sip:</literal> will send the
623  message as a SIP MESSAGE request.</para>
624  </info>
625  <info name="MessageFromInfo" language="en_US" tech="SIP">
626  <para>The <literal>from</literal> parameter can be a configured peer name
627  or in the form of "display-name" &lt;URI&gt;.</para>
628  </info>
629  <info name="MessageToInfo" language="en_US" tech="SIP">
630  <para>Ignored</para>
631  </info>
632  <managerEvent language="en_US" name="SIPQualifyPeerDone">
633  <managerEventInstance class="EVENT_FLAG_CALL">
634  <synopsis>Raised when SIPQualifyPeer has finished qualifying the specified peer.</synopsis>
635  <syntax>
636  <parameter name="Peer">
637  <para>The name of the peer.</para>
638  </parameter>
639  <parameter name="ActionID">
640  <para>This is only included if an ActionID Header was sent with the action request, in which case it will be that ActionID.</para>
641  </parameter>
642  </syntax>
643  <see-also>
644  <ref type="manager">SIPqualifypeer</ref>
645  </see-also>
646  </managerEventInstance>
647  </managerEvent>
648  <managerEvent language="en_US" name="SessionTimeout">
649  <managerEventInstance class="EVENT_FLAG_CALL">
650  <synopsis>Raised when a SIP session times out.</synopsis>
651  <syntax>
652  <channel_snapshot/>
653  <parameter name="Source">
654  <para>The source of the session timeout.</para>
655  <enumlist>
656  <enum name="RTPTimeout" />
657  <enum name="SIPSessionTimer" />
658  </enumlist>
659  </parameter>
660  </syntax>
661  </managerEventInstance>
662  </managerEvent>
663  ***/
664 
665 static int log_level = -1;
666 
667 static int min_expiry = DEFAULT_MIN_EXPIRY; /*!< Minimum accepted registration time */
668 static int max_expiry = DEFAULT_MAX_EXPIRY; /*!< Maximum accepted registration time */
670 static int min_subexpiry = DEFAULT_MIN_EXPIRY; /*!< Minimum accepted subscription time */
671 static int max_subexpiry = DEFAULT_MAX_EXPIRY; /*!< Maximum accepted subscription time */
673 
674 static int unauth_sessions = 0;
677 
678 /*! \brief Global jitterbuffer configuration - by default, jb is disabled
679  * \note Values shown here match the defaults shown in sip.conf.sample */
681 {
682  .flags = 0,
683  .max_size = 200,
684  .resync_threshold = 1000,
685  .impl = "fixed",
686  .target_extra = 40,
687 };
688 static struct ast_jb_conf global_jbconf; /*!< Global jitterbuffer configuration */
689 
690 static const char config[] = "sip.conf"; /*!< Main configuration file */
691 static const char notify_config[] = "sip_notify.conf"; /*!< Configuration file for sending Notify with CLI commands to reconfigure or reboot phones */
692 
693 /*! \brief Readable descriptions of device states.
694  * \note Should be aligned to above table as index */
695 static const struct invstate2stringtable {
696  const enum invitestates state;
697  const char *desc;
698 } invitestate2string[] = {
699  {INV_NONE, "None" },
700  {INV_CALLING, "Calling (Trying)"},
701  {INV_PROCEEDING, "Proceeding "},
702  {INV_EARLY_MEDIA, "Early media"},
703  {INV_COMPLETED, "Completed (done)"},
704  {INV_CONFIRMED, "Confirmed (up)"},
705  {INV_TERMINATED, "Done"},
706  {INV_CANCELLED, "Cancelled"}
707 };
708 
709 /*! \brief Subscription types that we support. We support
710  * - dialoginfo updates (really device status, not dialog info as was the original intent of the standard)
711  * - SIMPLE presence used for device status
712  * - Voicemail notification subscriptions
713  */
714 static const struct cfsubscription_types {
716  const char * const event;
717  const char * const mediatype;
718  const char * const text;
719 } subscription_types[] = {
720  { NONE, "-", "unknown", "unknown" },
721  /* RFC 4235: SIP Dialog event package */
722  { DIALOG_INFO_XML, "dialog", "application/dialog-info+xml", "dialog-info+xml" },
723  { CPIM_PIDF_XML, "presence", "application/cpim-pidf+xml", "cpim-pidf+xml" }, /* RFC 3863 */
724  { PIDF_XML, "presence", "application/pidf+xml", "pidf+xml" }, /* RFC 3863 */
725  { XPIDF_XML, "presence", "application/xpidf+xml", "xpidf+xml" }, /* Pre-RFC 3863 with MS additions */
726  { MWI_NOTIFICATION, "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
727 };
728 
729 /*! \brief The core structure to setup dialogs. We parse incoming messages by using
730  * structure and then route the messages according to the type.
731  *
732  * \note Note that sip_methods[i].id == i must hold or the code breaks
733  */
734 static const struct cfsip_methods {
735  enum sipmethod id;
736  int need_rtp; /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
737  char * const text;
738  enum can_create_dialog can_create;
739 } sip_methods[] = {
740  { SIP_UNKNOWN, RTP, "-UNKNOWN-",CAN_CREATE_DIALOG },
741  { SIP_RESPONSE, NO_RTP, "SIP/2.0", CAN_NOT_CREATE_DIALOG },
742  { SIP_REGISTER, NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
743  { SIP_OPTIONS, NO_RTP, "OPTIONS", CAN_CREATE_DIALOG },
744  { SIP_NOTIFY, NO_RTP, "NOTIFY", CAN_CREATE_DIALOG },
745  { SIP_INVITE, RTP, "INVITE", CAN_CREATE_DIALOG },
746  { SIP_ACK, NO_RTP, "ACK", CAN_NOT_CREATE_DIALOG },
747  { SIP_PRACK, NO_RTP, "PRACK", CAN_NOT_CREATE_DIALOG },
748  { SIP_BYE, NO_RTP, "BYE", CAN_NOT_CREATE_DIALOG },
749  { SIP_REFER, NO_RTP, "REFER", CAN_CREATE_DIALOG },
750  { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE",CAN_CREATE_DIALOG },
751  { SIP_MESSAGE, NO_RTP, "MESSAGE", CAN_CREATE_DIALOG },
752  { SIP_UPDATE, NO_RTP, "UPDATE", CAN_NOT_CREATE_DIALOG },
753  { SIP_INFO, NO_RTP, "INFO", CAN_NOT_CREATE_DIALOG },
754  { SIP_CANCEL, NO_RTP, "CANCEL", CAN_NOT_CREATE_DIALOG },
755  { SIP_PUBLISH, NO_RTP, "PUBLISH", CAN_CREATE_DIALOG },
757 };
758 
759 /*! \brief Diversion header reasons
760  *
761  * The core defines a bunch of constants used to define
762  * redirecting reasons. This provides a translation table
763  * between those and the strings which may be present in
764  * a SIP Diversion header
765  */
766 static const struct sip_reasons {
768  const char *text;
769 } sip_reason_table[] = {
770  { AST_REDIRECTING_REASON_UNKNOWN, "unknown" },
771  { AST_REDIRECTING_REASON_USER_BUSY, "user-busy" },
772  { AST_REDIRECTING_REASON_NO_ANSWER, "no-answer" },
773  { AST_REDIRECTING_REASON_UNAVAILABLE, "unavailable" },
774  { AST_REDIRECTING_REASON_UNCONDITIONAL, "unconditional" },
775  { AST_REDIRECTING_REASON_TIME_OF_DAY, "time-of-day" },
776  { AST_REDIRECTING_REASON_DO_NOT_DISTURB, "do-not-disturb" },
777  { AST_REDIRECTING_REASON_DEFLECTION, "deflection" },
778  { AST_REDIRECTING_REASON_FOLLOW_ME, "follow-me" },
779  { AST_REDIRECTING_REASON_OUT_OF_ORDER, "out-of-service" },
780  { AST_REDIRECTING_REASON_AWAY, "away" },
781  { AST_REDIRECTING_REASON_CALL_FWD_DTE, "cf_dte" }, /* Non-standard */
782  { AST_REDIRECTING_REASON_SEND_TO_VM, "send_to_vm" }, /* Non-standard */
783 };
784 
785 
786 /*! \name DefaultSettings
787  Default setttings are used as a channel setting and as a default when
788  configuring devices
789 */
790 static char default_language[MAX_LANGUAGE]; /*!< Default language setting for new channels */
791 static char default_callerid[AST_MAX_EXTENSION]; /*!< Default caller ID for sip messages */
792 static char default_mwi_from[80]; /*!< Default caller ID for MWI updates */
793 static char default_fromdomain[AST_MAX_EXTENSION]; /*!< Default domain on outound messages */
794 static int default_fromdomainport; /*!< Default domain port on outbound messages */
795 static char default_notifymime[AST_MAX_EXTENSION]; /*!< Default MIME media type for MWI notify messages */
796 static char default_vmexten[AST_MAX_EXTENSION]; /*!< Default From Username on MWI updates */
797 static int default_qualify; /*!< Default Qualify= setting */
798 static int default_keepalive; /*!< Default keepalive= setting */
799 static char default_mohinterpret[MAX_MUSICCLASS]; /*!< Global setting for moh class to use when put on hold */
800 static char default_mohsuggest[MAX_MUSICCLASS]; /*!< Global setting for moh class to suggest when putting
801  * a bridged channel on hold */
802 static char default_parkinglot[AST_MAX_CONTEXT]; /*!< Parkinglot */
803 static char default_engine[256]; /*!< Default RTP engine */
804 static int default_maxcallbitrate; /*!< Maximum bitrate for call */
805 static char default_zone[MAX_TONEZONE_COUNTRY]; /*!< Default tone zone for channels created from the SIP driver */
806 static unsigned int default_transports; /*!< Default Transports (enum ast_transport) that are acceptable */
807 static unsigned int default_primary_transport; /*!< Default primary Transport (enum ast_transport) for outbound connections to devices */
808 
809 static struct sip_settings sip_cfg; /*!< SIP configuration data.
810  \note in the future we could have multiple of these (per domain, per device group etc) */
811 
812 /*!< use this macro when ast_uri_decode is dependent on pedantic checking to be on. */
813 #define SIP_PEDANTIC_DECODE(str) \
814  if (sip_cfg.pedanticsipchecking && !ast_strlen_zero(str)) { \
815  ast_uri_decode(str, ast_uri_sip_user); \
816  } \
817 
818 static unsigned int chan_idx; /*!< used in naming sip channel */
819 static int global_match_auth_username; /*!< Match auth username if available instead of From: Default off. */
820 
821 static int global_relaxdtmf; /*!< Relax DTMF */
822 static int global_prematuremediafilter; /*!< Enable/disable premature frames in a call (causing 183 early media) */
823 static int global_rtptimeout; /*!< Time out call if no RTP */
824 static int global_rtpholdtimeout; /*!< Time out call if no RTP during hold */
825 static int global_rtpkeepalive; /*!< Send RTP keepalives */
826 static int global_reg_timeout; /*!< Global time between attempts for outbound registrations */
827 static int global_regattempts_max; /*!< Registration attempts before giving up */
828 static int global_reg_retry_403; /*!< Treat 403 responses to registrations as 401 responses */
829 static int global_shrinkcallerid; /*!< enable or disable shrinking of caller id */
830 static int global_callcounter; /*!< Enable call counters for all devices. This is currently enabled by setting the peer
831  * call-limit to INT_MAX. When we remove the call-limit from the code, we can make it
832  * with just a boolean flag in the device structure */
833 static unsigned int global_tos_sip; /*!< IP type of service for SIP packets */
834 static unsigned int global_tos_audio; /*!< IP type of service for audio RTP packets */
835 static unsigned int global_tos_video; /*!< IP type of service for video RTP packets */
836 static unsigned int global_tos_text; /*!< IP type of service for text RTP packets */
837 static unsigned int global_cos_sip; /*!< 802.1p class of service for SIP packets */
838 static unsigned int global_cos_audio; /*!< 802.1p class of service for audio RTP packets */
839 static unsigned int global_cos_video; /*!< 802.1p class of service for video RTP packets */
840 static unsigned int global_cos_text; /*!< 802.1p class of service for text RTP packets */
841 static unsigned int recordhistory; /*!< Record SIP history. Off by default */
842 static unsigned int dumphistory; /*!< Dump history to verbose before destroying SIP dialog */
843 static char global_useragent[AST_MAX_EXTENSION]; /*!< Useragent for the SIP channel */
844 static char global_sdpsession[AST_MAX_EXTENSION]; /*!< SDP session name for the SIP channel */
845 static char global_sdpowner[AST_MAX_EXTENSION]; /*!< SDP owner name for the SIP channel */
846 static int global_authfailureevents; /*!< Whether we send authentication failure manager events or not. Default no. */
847 static int global_t1; /*!< T1 time */
848 static int global_t1min; /*!< T1 roundtrip time minimum */
849 static int global_timer_b; /*!< Timer B - RFC 3261 Section 17.1.1.2 */
850 static unsigned int global_autoframing; /*!< Turn autoframing on or off. */
851 static int global_qualifyfreq; /*!< Qualify frequency */
852 static int global_qualify_gap; /*!< Time between our group of peer pokes */
853 static int global_qualify_peers; /*!< Number of peers to poke at a given time */
854 
855 static enum st_mode global_st_mode; /*!< Mode of operation for Session-Timers */
856 static enum st_refresher_param global_st_refresher; /*!< Session-Timer refresher */
857 static int global_min_se; /*!< Lowest threshold for session refresh interval */
858 static int global_max_se; /*!< Highest threshold for session refresh interval */
859 
860 static int global_store_sip_cause; /*!< Whether the MASTER_CHANNEL(HASH(SIP_CAUSE,[chan_name])) var should be set */
861 
862 static int global_dynamic_exclude_static = 0; /*!< Exclude static peers from contact registrations */
863 static unsigned char global_refer_addheaders; /*!< Add extra headers to outgoing REFER */
864 /*@}*/
865 
866 /*!
867  * We use libxml2 in order to parse XML that may appear in the body of a SIP message. Currently,
868  * the only usage is for parsing PIDF bodies of incoming PUBLISH requests in the call-completion
869  * event package. This variable is set at module load time and may be checked at runtime to determine
870  * if XML parsing support was found.
871  */
872 static int can_parse_xml;
873 
874 /*! \name Object counters @{
875  *
876  * \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
877  * should be used to modify these values.
878  */
879 static int speerobjs = 0; /*!< Static peers */
880 static int rpeerobjs = 0; /*!< Realtime peers */
881 static int apeerobjs = 0; /*!< Autocreated peer objects */
882 /*! @} */
883 
884 static struct ast_flags global_flags[3] = {{0}}; /*!< global SIP_ flags */
885 static unsigned int global_t38_maxdatagram; /*!< global T.38 FaxMaxDatagram override */
886 
887 static struct stasis_subscription *network_change_sub; /*!< subscription id for network change events */
888 static struct stasis_subscription *acl_change_sub; /*!< subscription id for named ACL system change events */
889 static int network_change_sched_id = -1;
890 
891 static char used_context[AST_MAX_CONTEXT]; /*!< name of automatically created context for unloading */
892 
894 
895 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
896  when it's doing something critical. */
898 
900 
901 /*! \brief This is the thread for the monitor which checks for input on the channels
902  which are not currently in use. */
904 
905 static int sip_reloading = FALSE; /*!< Flag for avoiding multiple reloads at the same time */
906 static enum channelreloadreason sip_reloadreason; /*!< Reason for last reload/load of configuration */
907 
908 struct ast_sched_context *sched; /*!< The scheduling context */
909 static struct io_context *io; /*!< The IO context */
910 static int *sipsock_read_id; /*!< ID of IO entry for sipsock FD */
911 struct sip_pkt;
912 static AST_LIST_HEAD_STATIC(domain_list, domain); /*!< The SIP domain list */
913 
914 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
915 
916 static enum sip_debug_e sipdebug;
917 
918 /*! \brief extra debugging for 'text' related events.
919  * At the moment this is set together with sip_debug_console.
920  * \note It should either go away or be implemented properly.
921  */
922 static int sipdebug_text;
923 
924 static const struct _map_x_s referstatusstrings[] = {
925  { REFER_IDLE, "<none>" },
926  { REFER_SENT, "Request sent" },
927  { REFER_RECEIVED, "Request received" },
928  { REFER_CONFIRMED, "Confirmed" },
929  { REFER_ACCEPTED, "Accepted" },
930  { REFER_RINGING, "Target ringing" },
931  { REFER_200OK, "Done" },
932  { REFER_FAILED, "Failed" },
933  { REFER_NOAUTH, "Failed - auth failure" },
934  { -1, NULL} /* terminator */
935 };
936 
937 /* --- Hash tables of various objects --------*/
938 #ifdef LOW_MEMORY
939 static const int HASH_PEER_SIZE = 17;
940 static const int HASH_DIALOG_SIZE = 17;
941 static const int HASH_REGISTRY_SIZE = 17;
942 #else
943 static const int HASH_PEER_SIZE = 563; /*!< Size of peer hash table, prime number preferred! */
944 static const int HASH_DIALOG_SIZE = 563;
945 static const int HASH_REGISTRY_SIZE = 563;
946 #endif
947 
948 static const struct {
950  const char *service_string;
951 } sip_cc_service_map [] = {
952  [AST_CC_NONE] = { AST_CC_NONE, "" },
953  [AST_CC_CCBS] = { AST_CC_CCBS, "BS" },
954  [AST_CC_CCNR] = { AST_CC_CCNR, "NR" },
955  [AST_CC_CCNL] = { AST_CC_CCNL, "NL" },
956 };
957 
958 static const struct {
960  const char *state_string;
962  [CC_QUEUED] = {CC_QUEUED, "cc-state: queued"},
963  [CC_READY] = {CC_READY, "cc-state: ready"},
964 };
965 
967 
968 
969 /*!
970  * Used to create new entity IDs by ESCs.
971  */
972 static int esc_etag_counter;
973 static const int DEFAULT_PUBLISH_EXPIRES = 3600;
974 
975 #ifdef HAVE_LIBXML2
976 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);
977 
980  .modify_handler = cc_esc_publish_handler,
981 };
982 #endif
983 
984 /*!
985  * \brief The Event State Compositors
986  *
987  * An Event State Compositor is an entity which
988  * accepts PUBLISH requests and acts appropriately
989  * based on these requests.
990  *
991  * The actual event_state_compositor structure is simply
992  * an ao2_container of sip_esc_entrys. When an incoming
993  * PUBLISH is received, we can match the appropriate sip_esc_entry
994  * using the entity ID of the incoming PUBLISH.
995  */
996 static struct event_state_compositor {
998  const char * name;
1001 } event_state_compositors [] = {
1002 #ifdef HAVE_LIBXML2
1003  {CALL_COMPLETION, "call-completion", &cc_esc_publish_callbacks},
1004 #endif
1005 };
1006 
1008  int state;
1011  const char *presence_subtype;
1012  const char *presence_message;
1013 };
1014 
1015 
1016 static const int ESC_MAX_BUCKETS = 37;
1017 
1018 /*!
1019  * \details
1020  * Here we implement the container for dialogs which are in the
1021  * dialog_needdestroy state to iterate only through the dialogs
1022  * unlink them instead of iterate through all dialogs
1023  */
1025 
1026 /*!
1027  * \details
1028  * Here we implement the container for dialogs which have rtp
1029  * traffic and rtptimeout, rtpholdtimeout or rtpkeepalive
1030  * set. We use this container instead the whole dialog list.
1031  */
1033 
1034 /*!
1035  * \details
1036  * Here we implement the container for dialogs (sip_pvt), defining
1037  * generic wrapper functions to ease the transition from the current
1038  * implementation (a single linked list) to a different container.
1039  * In addition to a reference to the container, we need functions to lock/unlock
1040  * the container and individual items, and functions to add/remove
1041  * references to the individual items.
1042  */
1043 static struct ao2_container *dialogs;
1044 #define sip_pvt_lock(x) ao2_lock(x)
1045 #define sip_pvt_trylock(x) ao2_trylock(x)
1046 #define sip_pvt_unlock(x) ao2_unlock(x)
1047 
1048 /*! \brief The table of TCP threads */
1049 static struct ao2_container *threadt;
1050 
1051 /*! \brief The peer list: Users, Peers and Friends */
1052 static struct ao2_container *peers;
1054 
1055 /*! \brief A bogus peer, to be used when authentication should fail */
1056 static AO2_GLOBAL_OBJ_STATIC(g_bogus_peer);
1057 /*! \brief We can recognize the bogus peer by this invalid MD5 hash */
1058 #define BOGUS_PEER_MD5SECRET "intentionally_invalid_md5_string"
1059 
1060 /*! \brief The register list: Other SIP proxies we register with and receive calls from */
1062 
1063 /*! \brief The MWI subscription list */
1065 
1066 static int temp_pvt_init(void *);
1067 static void temp_pvt_cleanup(void *);
1068 
1069 /*! \brief A per-thread temporary pvt structure */
1071 
1072 /*! \brief A per-thread buffer for transport to string conversion */
1074 
1075 /*! \brief Size of the SIP transport buffer */
1076 #define SIP_TRANSPORT_STR_BUFSIZE 128
1077 
1078 /*! \brief Authentication container for realm authentication */
1079 static struct sip_auth_container *authl = NULL;
1080 /*! \brief Global authentication container protection while adjusting the references. */
1082 
1084 STASIS_MESSAGE_TYPE_DEFN_LOCAL(session_timeout_type,
1086  );
1087 
1088 /* --- Sockets and networking --------------*/
1089 
1090 /*! \brief Main socket for UDP SIP communication.
1091  *
1092  * sipsock is shared between the SIP manager thread (which handles reload
1093  * requests), the udp io handler (sipsock_read()) and the user routines that
1094  * issue udp writes (using __sip_xmit()).
1095  * The socket is -1 only when opening fails (this is a permanent condition),
1096  * or when we are handling a reload() that changes its address (this is
1097  * a transient situation during which we might have a harmless race, see
1098  * below). Because the conditions for the race to be possible are extremely
1099  * rare, we don't want to pay the cost of locking on every I/O.
1100  * Rather, we remember that when the race may occur, communication is
1101  * bound to fail anyways, so we just live with this event and let
1102  * the protocol handle this above us.
1103  */
1104 static int sipsock = -1;
1105 
1106 struct ast_sockaddr bindaddr; /*!< UDP: The address we bind to */
1107 
1108 /*! \brief our (internal) default address/port to put in SIP/SDP messages
1109  * internip is initialized picking a suitable address from one of the
1110  * interfaces, and the same port number we bind to. It is used as the
1111  * default address/port in SIP messages, and as the default address
1112  * (but not port) in SDP messages.
1113  */
1114 static struct ast_sockaddr internip;
1115 
1116 /*! \brief our external IP address/port for SIP sessions.
1117  * externaddr.sin_addr is only set when we know we might be behind
1118  * a NAT, and this is done using a variety of (mutually exclusive)
1119  * ways from the config file:
1120  *
1121  * + with "externaddr = host[:port]" we specify the address/port explicitly.
1122  * The address is looked up only once when (re)loading the config file;
1123  *
1124  * + with "externhost = host[:port]" we do a similar thing, but the
1125  * hostname is stored in externhost, and the hostname->IP mapping
1126  * is refreshed every 'externrefresh' seconds;
1127  *
1128  * Other variables (externhost, externexpire, externrefresh) are used
1129  * to support the above functions.
1130  */
1131 static struct ast_sockaddr externaddr; /*!< External IP address if we are behind NAT */
1132 static struct ast_sockaddr media_address; /*!< External RTP IP address if we are behind NAT */
1133 static struct ast_sockaddr rtpbindaddr; /*!< RTP: The address we bind to */
1134 
1135 static char externhost[MAXHOSTNAMELEN]; /*!< External host name */
1136 static time_t externexpire; /*!< Expiration counter for re-resolving external host name in dynamic DNS */
1137 static int externrefresh = 10; /*!< Refresh timer for DNS-based external address (dyndns) */
1138 static uint16_t externtcpport; /*!< external tcp port */
1139 static uint16_t externtlsport; /*!< external tls port */
1140 
1141 /*! \brief List of local networks
1142  * We store "localnet" addresses from the config file into an access list,
1143  * marked as 'DENY', so the call to ast_apply_ha() will return
1144  * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
1145  * (i.e. presumably public) addresses.
1146  */
1147 static struct ast_ha *localaddr; /*!< List of local networks, on the same side of NAT as this Asterisk */
1148 
1149 static int ourport_tcp; /*!< The port used for TCP connections */
1150 static int ourport_tls; /*!< The port used for TCP/TLS connections */
1151 static struct ast_sockaddr debugaddr;
1152 
1153 static struct ast_config *notify_types = NULL; /*!< The list of manual NOTIFY types we know how to send */
1154 
1155 /*! some list management macros. */
1156 
1157 #define UNLINK(element, head, prev) do { \
1158  if (prev) \
1159  (prev)->next = (element)->next; \
1160  else \
1161  (head) = (element)->next; \
1162  } while (0)
1163 
1165 
1166 struct show_peers_context;
1167 
1168 /*---------------------------- Forward declarations of functions in chan_sip.c */
1169 /* Note: This is added to help splitting up chan_sip.c into several files
1170  in coming releases. */
1171 
1172 /*--- PBX interface functions */
1173 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);
1174 static int sip_devicestate(const char *data);
1175 static int sip_sendtext(struct ast_channel *ast, const char *text);
1176 static int sip_call(struct ast_channel *ast, const char *dest, int timeout);
1177 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
1178 static int sip_hangup(struct ast_channel *ast);
1179 static int sip_answer(struct ast_channel *ast);
1180 static struct ast_frame *sip_read(struct ast_channel *ast);
1181 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
1182 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
1183 static int sip_transfer(struct ast_channel *ast, const char *dest);
1184 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1185 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
1186 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
1187 static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen);
1188 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
1189 static const char *sip_get_callid(struct ast_channel *chan);
1190 
1191 static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr);
1192 static int sip_standard_port(enum ast_transport type, int port);
1193 static int sip_prepare_socket(struct sip_pvt *p);
1194 static int get_address_family_filter(unsigned int transport);
1195 
1196 /*--- Transmitting responses and requests */
1197 static int sipsock_read(int *id, int fd, short events, void *ignore);
1198 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data);
1199 static int __sip_reliable_xmit(struct sip_pvt *p, uint32_t seqno, int resp, struct ast_str *data, int fatal, int sipmethod);
1200 static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp);
1201 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1202 static int retrans_pkt(const void *data);
1203 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);
1204 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1205 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1206 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1207 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);
1208 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
1209 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);
1210 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
1211 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1212 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable);
1213 static int transmit_request(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch);
1214 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch);
1215 static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri);
1216 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri);
1217 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
1218 static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded);
1219 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
1220 static int transmit_info_with_vidupdate(struct sip_pvt *p);
1221 static int transmit_message(struct sip_pvt *p, int init, int auth);
1222 static int transmit_refer(struct sip_pvt *p, const char *dest);
1223 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
1224 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
1225 static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state);
1226 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
1227 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno);
1228 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno);
1229 static void copy_request(struct sip_request *dst, const struct sip_request *src);
1230 static void receive_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
1231 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward);
1232 static int sip_send_mwi_to_peer(struct sip_peer *peer, int cache_only);
1233 
1234 /* Misc dialog routines */
1235 static int __sip_autodestruct(const void *data);
1236 static int update_call_counter(struct sip_pvt *fup, int event);
1237 static int auto_congest(const void *arg);
1238 static struct sip_pvt *__find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method,
1239  const char *file, int line, const char *func);
1240 #define find_call(req, addr, intended_method) \
1241  __find_call(req, addr, intended_method, __FILE__, __LINE__, __PRETTY_FUNCTION__)
1242 
1243 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards, int resp);
1244 static int build_path(struct sip_pvt *p, struct sip_peer *peer, struct sip_request *req, const char *pathbuf);
1245 static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
1246  struct sip_request *req, const char *uri);
1247 static int get_sip_pvt_from_replaces(const char *callid, const char *totag, const char *fromtag,
1248  struct sip_pvt **out_pvt, struct ast_channel **out_chan);
1249 static void check_pendings(struct sip_pvt *p);
1250 static void sip_set_owner(struct sip_pvt *p, struct ast_channel *chan);
1251 
1252 static void *sip_pickup_thread(void *stuff);
1253 static int sip_pickup(struct ast_channel *chan);
1254 
1255 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1256 static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method);
1257 
1258 /*--- Codec handling / SDP */
1259 static void try_suggested_sip_codec(struct sip_pvt *p);
1260 static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
1261 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
1262 static int find_sdp(struct sip_request *req);
1263 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action, int is_offer);
1264 static int process_sdp_o(const char *o, struct sip_pvt *p);
1265 static int process_sdp_c(const char *c, struct ast_sockaddr *addr);
1266 static int process_sdp_a_sendonly(const char *a, int *sendonly);
1267 static int process_sdp_a_ice(const char *a, struct sip_pvt *p, struct ast_rtp_instance *instance, int rtcp_mux);
1268 static int process_sdp_a_rtcp_mux(const char *a, struct sip_pvt *p, int *requested);
1269 static int process_sdp_a_dtls(const char *a, struct sip_pvt *p, struct ast_rtp_instance *instance);
1270 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec);
1271 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec);
1272 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);
1273 static int process_sdp_a_image(const char *a, struct sip_pvt *p);
1274 static void add_ice_to_sdp(struct ast_rtp_instance *instance, struct ast_str **a_buf);
1275 static void add_dtls_to_sdp(struct ast_rtp_instance *instance, struct ast_str **a_buf);
1276 static void start_ice(struct ast_rtp_instance *instance, int offer);
1277 static void add_codec_to_sdp(const struct sip_pvt *p, struct ast_format *codec,
1278  struct ast_str **m_buf, struct ast_str **a_buf,
1279  int debug, int *min_packet_size, int *max_packet_size);
1280 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
1281  struct ast_str **m_buf, struct ast_str **a_buf,
1282  int debug);
1283 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
1284 static void do_setnat(struct sip_pvt *p);
1285 static void stop_media_flows(struct sip_pvt *p);
1286 
1287 /*--- Authentication stuff */
1288 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1289 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
1290 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1291  const char *secret, const char *md5secret, int sipmethod,
1292  const char *uri, enum xmittype reliable);
1293 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
1294  int sipmethod, const char *uri, enum xmittype reliable,
1295  struct ast_sockaddr *addr, struct sip_peer **authpeer);
1296 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr);
1297 
1298 /*--- Domain handling */
1299 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1300 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
1301 static void clear_sip_domains(void);
1302 
1303 /*--- SIP realm authentication */
1304 static void add_realm_authentication(struct sip_auth_container **credentials, const char *configuration, int lineno);
1305 static struct sip_auth *find_realm_authentication(struct sip_auth_container *credentials, const char *realm);
1306 
1307 /*--- Misc functions */
1308 static int check_rtp_timeout(struct sip_pvt *dialog, time_t t);
1309 static int reload_config(enum channelreloadreason reason);
1310 static void add_diversion(struct sip_request *req, struct sip_pvt *pvt);
1311 static int expire_register(const void *data);
1312 static void *do_monitor(void *data);
1313 static int restart_monitor(void);
1314 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
1315 static struct ast_variable *copy_vars(struct ast_variable *src);
1316 static int dialog_find_multiple(void *obj, void *arg, int flags);
1317 static struct ast_channel *sip_pvt_lock_full(struct sip_pvt *pvt);
1318 /* static int sip_addrcmp(char *name, struct sockaddr_in *sin); Support for peer matching */
1319 static int sip_refer_alloc(struct sip_pvt *p);
1320 static void sip_refer_destroy(struct sip_pvt *p);
1321 static int sip_notify_alloc(struct sip_pvt *p);
1322 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
1323 static void set_peer_nat(const struct sip_pvt *p, struct sip_peer *peer);
1324 static void check_for_nat(const struct ast_sockaddr *them, struct sip_pvt *p);
1325 
1326 /*--- Device monitoring and Device/extension state/event handling */
1327 static int extensionstate_update(const char *context, const char *exten, struct state_notify_data *data, struct sip_pvt *p, int force);
1328 static int cb_extensionstate(const char *context, const char *exten, struct ast_state_cb_info *info, void *data);
1329 static int sip_poke_noanswer(const void *data);
1330 static int sip_poke_peer(struct sip_peer *peer, int force);
1331 static void sip_poke_all_peers(void);
1332 static void sip_peer_hold(struct sip_pvt *p, int hold);
1333 static void mwi_event_cb(void *, struct stasis_subscription *, struct stasis_message *);
1334 static void network_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
1335 static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
1336 static void sip_keepalive_all_peers(void);
1337 #define peer_in_destruction(peer) (ao2_ref(peer, 0) == 0)
1338 
1339 /*--- Applications, functions, CLI and manager command helpers */
1340 static const char *sip_nat_mode(const struct sip_pvt *p);
1341 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1342 static char *transfermode2str(enum transfermodes mode) attribute_const;
1343 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
1344 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1345 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1346 static struct sip_peer *_sip_show_peers_one(int fd, struct mansession *s, struct show_peers_context *cont, struct sip_peer *peer);
1347 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1348 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1349 static void print_group(int fd, ast_group_t group, int crlf);
1350 static void print_named_groups(int fd, struct ast_namedgroups *groups, int crlf);
1351 static const char *dtmfmode2str(int mode) attribute_const;
1352 static int str2dtmfmode(const char *str) attribute_unused;
1353 static const char *insecure2str(int mode) attribute_const;
1354 static const char *allowoverlap2str(int mode) attribute_const;
1355 static void cleanup_stale_contexts(char *new, char *old);
1356 static const char *domain_mode_to_text(const enum domain_mode mode);
1357 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1358 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1359 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1360 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1361 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1362 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1363 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1364 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1365 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1366 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
1367 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1368 static char *complete_sip_peer(const char *word, int state, int flags2);
1369 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
1370 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
1371 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
1372 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
1373 static char *complete_sip_notify(const char *line, const char *word, int pos, int state);
1374 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1375 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1376 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1377 static char *sip_do_debug_ip(int fd, const char *arg);
1378 static char *sip_do_debug_peer(int fd, const char *arg);
1379 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1380 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1381 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1382 static int sip_dtmfmode(struct ast_channel *chan, const char *data);
1383 static int sip_addheader(struct ast_channel *chan, const char *data);
1384 static int sip_do_reload(enum channelreloadreason reason);
1385 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1386 static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
1387  const char *name, int flag);
1388 static int ast_sockaddr_resolve_first_transport(struct ast_sockaddr *addr,
1389  const char *name, int flag, unsigned int transport);
1390 
1391 /*--- Debugging
1392  Functions for enabling debug per IP or fully, or enabling history logging for
1393  a SIP dialog
1394 */
1395 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to debuglog at end of dialog, before destroying data */
1396 static inline int sip_debug_test_addr(const struct ast_sockaddr *addr);
1397 static inline int sip_debug_test_pvt(struct sip_pvt *p);
1398 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
1399 static void sip_dump_history(struct sip_pvt *dialog);
1400 
1401 /*--- Device object handling */
1402 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
1403 static int update_call_counter(struct sip_pvt *fup, int event);
1404 static void sip_destroy_peer(struct sip_peer *peer);
1405 static void sip_destroy_peer_fn(void *peer);
1406 static void set_peer_defaults(struct sip_peer *peer);
1407 static struct sip_peer *temp_peer(const char *name);
1408 static void register_peer_exten(struct sip_peer *peer, int onoff);
1409 static int sip_poke_peer_s(const void *data);
1410 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
1411 static void reg_source_db(struct sip_peer *peer);
1412 static void destroy_association(struct sip_peer *peer);
1413 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
1414 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
1415 static void set_socket_transport(struct sip_socket *socket, int transport);
1416 static int peer_ipcmp_cb_full(void *obj, void *arg, void *data, int flags);
1417 
1418 /* Realtime device support */
1419 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);
1420 static void update_peer(struct sip_peer *p, int expire);
1422 static const char *get_name_from_variable(const struct ast_variable *var);
1423 static struct sip_peer *realtime_peer(const char *peername, struct ast_sockaddr *sin, char *callbackexten, int devstate_only, int which_objects);
1424 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1425 
1426 /*--- Internal UA client handling (outbound registrations) */
1427 static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p);
1428 static void sip_registry_destroy(void *reg);
1429 static int sip_register(const char *value, int lineno);
1430 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
1431 static int __sip_do_register(struct sip_registry *r);
1432 static int sip_reg_timeout(const void *data);
1433 static void sip_send_all_registers(void);
1434 static int sip_reinvite_retry(const void *data);
1435 
1436 /*--- Parsing SIP requests and responses */
1437 static int determine_firstline_parts(struct sip_request *req);
1438 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1439 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
1440 static int find_sip_method(const char *msg);
1441 static unsigned int parse_allowed_methods(struct sip_request *req);
1442 static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req);
1443 static int parse_request(struct sip_request *req);
1444 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
1445 static int method_match(enum sipmethod id, const char *name);
1446 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
1447 static void parse_oli(struct sip_request *req, struct ast_channel *chan);
1448 static const char *find_alias(const char *name, const char *_default);
1449 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
1450 static void lws2sws(struct ast_str *msgbuf);
1451 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
1452 static char *remove_uri_parameters(char *uri);
1453 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
1454 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
1455 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
1456 static int use_reason_header(struct sip_pvt *pvt, struct sip_request *req);
1457 static int set_address_from_contact(struct sip_pvt *pvt);
1458 static void check_via(struct sip_pvt *p, const struct sip_request *req);
1459 static int get_rpid(struct sip_pvt *p, struct sip_request *oreq);
1460 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason, char **reason_str);
1461 static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id);
1462 static int transmit_state_notify(struct sip_pvt *p, struct state_notify_data *data, int full, int timeout);
1463 static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen);
1464 static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen);
1465 static int get_domain(const char *str, char *domain, int len);
1466 static void get_realm(struct sip_pvt *p, const struct sip_request *req);
1467 static char *get_content(struct sip_request *req);
1468 
1469 /*-- TCP connection handling ---*/
1470 static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session);
1471 static void *sip_tcp_worker_fn(void *);
1472 
1473 /*--- Constructing requests and responses */
1474 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
1475 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
1476 static void deinit_req(struct sip_request *req);
1477 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, uint32_t seqno, int newbranch);
1478 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri);
1479 static int init_resp(struct sip_request *resp, const char *msg);
1480 static inline int resp_needs_contact(const char *msg, enum sipmethod method);
1481 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
1482 static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p);
1483 static void build_via(struct sip_pvt *p);
1484 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
1485 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog);
1486 static char *generate_random_string(char *buf, size_t size);
1487 static void build_callid_pvt(struct sip_pvt *pvt);
1488 static void change_callid_pvt(struct sip_pvt *pvt, const char *callid);
1489 static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain);
1490 static void build_localtag_registry(struct sip_registry *reg);
1491 static void make_our_tag(struct sip_pvt *pvt);
1492 static int add_header(struct sip_request *req, const char *var, const char *value);
1493 static int add_max_forwards(struct sip_pvt *dialog, struct sip_request *req);
1494 static int add_content(struct sip_request *req, const char *line);
1495 static int finalize_content(struct sip_request *req);
1496 static void destroy_msg_headers(struct sip_pvt *pvt);
1497 static int add_text(struct sip_request *req, struct sip_pvt *p);
1498 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
1499 static int add_rpid(struct sip_request *req, struct sip_pvt *p);
1500 static int add_vidupdate(struct sip_request *req);
1501 static void add_route(struct sip_request *req, struct sip_route *route, int skip);
1502 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1503 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1504 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
1505 static void set_destination(struct sip_pvt *p, const char *uri);
1506 static void add_date(struct sip_request *req);
1507 static void add_expires(struct sip_request *req, int expires);
1508 static void build_contact(struct sip_pvt *p, struct sip_request *req, int incoming);
1509 
1510 /*------Request handling functions */
1511 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock);
1512 static int handle_request_update(struct sip_pvt *p, struct sip_request *req);
1513 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);
1514 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, uint32_t seqno, int *nounlock);
1515 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
1516 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *sin, const char *e);
1517 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
1518 static int handle_request_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
1519 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
1520 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
1521 static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
1522 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req,
1523  int *nounlock, struct sip_pvt *replaces_pvt, struct ast_channel *replaces_chan);
1524 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
1525 static int local_attended_transfer(struct sip_pvt *transferer, struct ast_channel *transferer_chan, uint32_t seqno, int *nounlock);
1526 
1527 /*------Response handling functions */
1528 static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1529 static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1530 static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1531 static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1532 static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1533 static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1534 static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
1535 
1536 /*------ SRTP Support -------- */
1537 static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct ast_sdp_srtp **srtp,
1538  const char *a);
1539 
1540 /*------ T38 Support --------- */
1541 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
1542 static void change_t38_state(struct sip_pvt *p, int state);
1543 
1544 /*------ Session-Timers functions --------- */
1545 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
1546 static void stop_session_timer(struct sip_pvt *p);
1547 static void start_session_timer(struct sip_pvt *p);
1548 static void restart_session_timer(struct sip_pvt *p);
1549 static const char *strefresherparam2str(enum st_refresher_param r);
1550 static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher_param *const p_ref);
1551 static int parse_minse(const char *p_hdrval, int *const p_interval);
1552 static int st_get_se(struct sip_pvt *, int max);
1553 static enum st_refresher st_get_refresher(struct sip_pvt *);
1554 static enum st_mode st_get_mode(struct sip_pvt *, int no_cached);
1555 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
1556 
1557 /*------- RTP Glue functions -------- */
1558 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);
1559 
1560 /*!--- SIP MWI Subscription support */
1561 static int sip_subscribe_mwi(const char *value, int lineno);
1562 static void sip_send_all_mwi_subscriptions(void);
1563 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
1564 
1565 /* Scheduler id start/stop/reschedule functions. */
1566 static void stop_provisional_keepalive(struct sip_pvt *pvt);
1567 static void do_stop_session_timer(struct sip_pvt *pvt);
1568 static void stop_reinvite_retry(struct sip_pvt *pvt);
1569 static void stop_retrans_pkt(struct sip_pkt *pkt);
1570 static void stop_t38_abort_timer(struct sip_pvt *pvt);
1571 
1572 /*! \brief Definition of this channel for PBX channel registration */
1574  .type = "SIP",
1575  .description = "Session Initiation Protocol (SIP)",
1577  .requester = sip_request_call, /* called with chan unlocked */
1578  .devicestate = sip_devicestate, /* called with chan unlocked (not chan-specific) */
1579  .call = sip_call, /* called with chan locked */
1580  .send_html = sip_sendhtml,
1581  .hangup = sip_hangup, /* called with chan locked */
1582  .answer = sip_answer, /* called with chan locked */
1583  .read = sip_read, /* called with chan locked */
1584  .write = sip_write, /* called with chan locked */
1585  .write_video = sip_write, /* called with chan locked */
1586  .write_text = sip_write,
1587  .indicate = sip_indicate, /* called with chan locked */
1588  .transfer = sip_transfer, /* called with chan locked */
1589  .fixup = sip_fixup, /* called with chan locked */
1590  .send_digit_begin = sip_senddigit_begin, /* called with chan unlocked */
1591  .send_digit_end = sip_senddigit_end,
1592  .early_bridge = ast_rtp_instance_early_bridge,
1593  .send_text = sip_sendtext, /* called with chan locked */
1594  .func_channel_read = sip_acf_channel_read,
1595  .setoption = sip_setoption,
1596  .queryoption = sip_queryoption,
1597  .get_pvt_uniqueid = sip_get_callid,
1598 };
1599 
1600 /*! \brief This version of the sip channel tech has no send_digit_begin
1601  * callback so that the core knows that the channel does not want
1602  * DTMF BEGIN frames.
1603  * The struct is initialized just before registering the channel driver,
1604  * and is for use with channels using SIP INFO DTMF.
1605  */
1607 
1608 /*------- CC Support -------- */
1609 static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan);
1610 static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent);
1611 static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent);
1612 static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason);
1613 static int sip_cc_agent_status_request(struct ast_cc_agent *agent);
1614 static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent);
1615 static int sip_cc_agent_recall(struct ast_cc_agent *agent);
1616 static void sip_cc_agent_destructor(struct ast_cc_agent *agent);
1617 
1619  .type = "SIP",
1620  .init = sip_cc_agent_init,
1621  .start_offer_timer = sip_cc_agent_start_offer_timer,
1622  .stop_offer_timer = sip_cc_agent_stop_offer_timer,
1623  .respond = sip_cc_agent_respond,
1624  .status_request = sip_cc_agent_status_request,
1625  .start_monitoring = sip_cc_agent_start_monitoring,
1626  .callee_available = sip_cc_agent_recall,
1627  .destructor = sip_cc_agent_destructor,
1628 };
1629 
1630 /* -------- End of declarations of structures, constants and forward declarations of functions
1631  Below starts actual code
1632  ------------------------
1633 */
1634 
1635 static int sip_epa_register(const struct epa_static_data *static_data)
1636 {
1637  struct epa_backend *backend = ast_calloc(1, sizeof(*backend));
1638 
1639  if (!backend) {
1640  return -1;
1641  }
1642 
1643  backend->static_data = static_data;
1644 
1648  return 0;
1649 }
1650 
1651 static void sip_epa_unregister_all(void)
1652 {
1653  struct epa_backend *backend;
1654 
1656  while ((backend = AST_LIST_REMOVE_HEAD(&epa_static_data_list, next))) {
1657  ast_free(backend);
1658  }
1660 }
1661 
1662 static void cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry);
1663 
1664 static void cc_epa_destructor(void *data)
1665 {
1666  struct sip_epa_entry *epa_entry = data;
1667  struct cc_epa_entry *cc_entry = epa_entry->instance_data;
1668  ast_free(cc_entry);
1669 }
1670 
1671 static const struct epa_static_data cc_epa_static_data = {
1673  .name = "call-completion",
1674  .handle_error = cc_handle_publish_error,
1675  .destructor = cc_epa_destructor,
1676 };
1677 
1678 static const struct epa_static_data *find_static_data(const char * const event_package)
1679 {
1680  const struct epa_backend *backend = NULL;
1681 
1684  if (!strcmp(backend->static_data->name, event_package)) {
1685  break;
1686  }
1687  }
1689  return backend ? backend->static_data : NULL;
1690 }
1691 
1692 static struct sip_epa_entry *create_epa_entry (const char * const event_package, const char * const destination)
1693 {
1694  struct sip_epa_entry *epa_entry;
1695  const struct epa_static_data *static_data;
1696 
1697  if (!(static_data = find_static_data(event_package))) {
1698  return NULL;
1699  }
1700 
1701  if (!(epa_entry = ao2_t_alloc(sizeof(*epa_entry), static_data->destructor, "Allocate new EPA entry"))) {
1702  return NULL;
1703  }
1704 
1705  epa_entry->static_data = static_data;
1706  ast_copy_string(epa_entry->destination, destination, sizeof(epa_entry->destination));
1707  return epa_entry;
1708 }
1710 {
1712  for (service = AST_CC_CCBS; service <= AST_CC_CCNL; ++service) {
1713  if (!strcasecmp(service_string, sip_cc_service_map[service].service_string)) {
1714  return service;
1715  }
1716  }
1717  return AST_CC_NONE;
1718 }
1719 
1720 /* Even state compositors code */
1721 static void esc_entry_destructor(void *obj)
1722 {
1723  struct sip_esc_entry *esc_entry = obj;
1724  if (esc_entry->sched_id > -1) {
1725  AST_SCHED_DEL(sched, esc_entry->sched_id);
1726  }
1727 }
1728 
1729 static int esc_hash_fn(const void *obj, const int flags)
1730 {
1731  const struct sip_esc_entry *entry = obj;
1732  return ast_str_hash(entry->entity_tag);
1733 }
1734 
1735 static int esc_cmp_fn(void *obj, void *arg, int flags)
1736 {
1737  struct sip_esc_entry *entry1 = obj;
1738  struct sip_esc_entry *entry2 = arg;
1739 
1740  return (!strcmp(entry1->entity_tag, entry2->entity_tag)) ? (CMP_MATCH | CMP_STOP) : 0;
1741 }
1742 
1743 static struct event_state_compositor *get_esc(const char * const event_package) {
1744  int i;
1745  for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1746  if (!strcasecmp(event_package, event_state_compositors[i].name)) {
1747  return &event_state_compositors[i];
1748  }
1749  }
1750  return NULL;
1751 }
1752 
1753 static struct sip_esc_entry *get_esc_entry(const char * entity_tag, struct event_state_compositor *esc) {
1754  struct sip_esc_entry *entry;
1755  struct sip_esc_entry finder;
1756 
1757  ast_copy_string(finder.entity_tag, entity_tag, sizeof(finder.entity_tag));
1758 
1759  entry = ao2_find(esc->compositor, &finder, OBJ_POINTER);
1760 
1761  return entry;
1762 }
1763 
1764 static int publish_expire(const void *data)
1765 {
1766  struct sip_esc_entry *esc_entry = (struct sip_esc_entry *) data;
1767  struct event_state_compositor *esc = get_esc(esc_entry->event);
1768 
1769  ast_assert(esc != NULL);
1770 
1771  ao2_unlink(esc->compositor, esc_entry);
1772  esc_entry->sched_id = -1;
1773  ao2_ref(esc_entry, -1);
1774  return 0;
1775 }
1776 
1777 static void create_new_sip_etag(struct sip_esc_entry *esc_entry, int is_linked)
1778 {
1779  int new_etag = ast_atomic_fetchadd_int(&esc_etag_counter, +1);
1780  struct event_state_compositor *esc = get_esc(esc_entry->event);
1781 
1782  ast_assert(esc != NULL);
1783  if (is_linked) {
1784  ao2_unlink(esc->compositor, esc_entry);
1785  }
1786  snprintf(esc_entry->entity_tag, sizeof(esc_entry->entity_tag), "%d", new_etag);
1787  ao2_link(esc->compositor, esc_entry);
1788 }
1789 
1790 static struct sip_esc_entry *create_esc_entry(struct event_state_compositor *esc, struct sip_request *req, const int expires)
1791 {
1792  struct sip_esc_entry *esc_entry;
1793  int expires_ms;
1794 
1795  if (!(esc_entry = ao2_alloc(sizeof(*esc_entry), esc_entry_destructor))) {
1796  return NULL;
1797  }
1798 
1799  esc_entry->event = esc->name;
1800 
1801  expires_ms = expires * 1000;
1802  /* Bump refcount for scheduler */
1803  ao2_ref(esc_entry, +1);
1804  esc_entry->sched_id = ast_sched_add(sched, expires_ms, publish_expire, esc_entry);
1805  if (esc_entry->sched_id == -1) {
1806  ao2_ref(esc_entry, -1);
1807  ao2_ref(esc_entry, -1);
1808  return NULL;
1809  }
1810 
1811  /* Note: This links the esc_entry into the ESC properly */
1812  create_new_sip_etag(esc_entry, 0);
1813 
1814  return esc_entry;
1815 }
1816 
1817 static int initialize_escs(void)
1818 {
1819  int i, res = 0;
1820  for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1823  if (!event_state_compositors[i].compositor) {
1824  res = -1;
1825  }
1826  }
1827  return res;
1828 }
1829 
1830 static void destroy_escs(void)
1831 {
1832  int i;
1833  for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1834  ao2_replace(event_state_compositors[i].compositor, NULL);
1835  }
1836 }
1837 
1838 
1839 static int find_by_notify_uri_helper(void *obj, void *arg, int flags)
1840 {
1841  struct ast_cc_agent *agent = obj;
1842  struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1843  const char *uri = arg;
1844 
1845  return !sip_uri_cmp(agent_pvt->notify_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
1846 }
1847 
1848 static struct ast_cc_agent *find_sip_cc_agent_by_notify_uri(const char * const uri)
1849 {
1850  struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_notify_uri_helper, (char *)uri, "SIP");
1851  return agent;
1852 }
1853 
1854 static int find_by_subscribe_uri_helper(void *obj, void *arg, int flags)
1855 {
1856  struct ast_cc_agent *agent = obj;
1857  struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1858  const char *uri = arg;
1859 
1860  return !sip_uri_cmp(agent_pvt->subscribe_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
1861 }
1862 
1863 static struct ast_cc_agent *find_sip_cc_agent_by_subscribe_uri(const char * const uri)
1864 {
1865  struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_subscribe_uri_helper, (char *)uri, "SIP");
1866  return agent;
1867 }
1868 
1869 static int find_by_callid_helper(void *obj, void *arg, int flags)
1870 {
1871  struct ast_cc_agent *agent = obj;
1872  struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1873  struct sip_pvt *call_pvt = arg;
1874 
1875  return !strcmp(agent_pvt->original_callid, call_pvt->callid) ? CMP_MATCH | CMP_STOP : 0;
1876 }
1877 
1879 {
1880  struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_callid_helper, pvt, "SIP");
1881  return agent;
1882 }
1883 
1884 static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan)
1885 {
1886  struct sip_cc_agent_pvt *agent_pvt = ast_calloc(1, sizeof(*agent_pvt));
1887  struct sip_pvt *call_pvt = ast_channel_tech_pvt(chan);
1888 
1889  if (!agent_pvt) {
1890  return -1;
1891  }
1892 
1893  ast_assert(!strcmp(ast_channel_tech(chan)->type, "SIP"));
1894 
1895  ast_copy_string(agent_pvt->original_callid, call_pvt->callid, sizeof(agent_pvt->original_callid));
1896  ast_copy_string(agent_pvt->original_exten, call_pvt->exten, sizeof(agent_pvt->original_exten));
1897  agent_pvt->offer_timer_id = -1;
1898  agent->private_data = agent_pvt;
1899  sip_pvt_lock(call_pvt);
1900  ast_set_flag(&call_pvt->flags[0], SIP_OFFER_CC);
1901  sip_pvt_unlock(call_pvt);
1902  return 0;
1903 }
1904 
1905 static int sip_offer_timer_expire(const void *data)
1906 {
1907  struct ast_cc_agent *agent = (struct ast_cc_agent *) data;
1908  struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1909 
1910  agent_pvt->offer_timer_id = -1;
1911 
1912  return ast_cc_failed(agent->core_id, "SIP agent %s's offer timer expired", agent->device_name);
1913 }
1914 
1916 {
1917  struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1918  int when;
1919 
1920  when = ast_get_cc_offer_timer(agent->cc_params) * 1000;
1921  agent_pvt->offer_timer_id = ast_sched_add(sched, when, sip_offer_timer_expire, agent);
1922  return 0;
1923 }
1924 
1926 {
1927  struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1928 
1929  AST_SCHED_DEL(sched, agent_pvt->offer_timer_id);
1930  return 0;
1931 }
1932 
1933 static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason)
1934 {
1935  struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1936 
1937  sip_pvt_lock(agent_pvt->subscribe_pvt);
1939  if (reason == AST_CC_AGENT_RESPONSE_SUCCESS || !ast_strlen_zero(agent_pvt->notify_uri)) {
1940  /* The second half of this if statement may be a bit hard to grasp,
1941  * so here's an explanation. When a subscription comes into
1942  * chan_sip, as long as it is not malformed, it will be passed
1943  * to the CC core. If the core senses an out-of-order state transition,
1944  * then the core will call this callback with the "reason" set to a
1945  * failure condition.
1946  * However, an out-of-order state transition will occur during a resubscription
1947  * for CC. In such a case, we can see that we have already generated a notify_uri
1948  * and so we can detect that this isn't a *real* failure. Rather, it is just
1949  * something the core doesn't recognize as a legitimate SIP state transition.
1950  * Thus we respond with happiness and flowers.
1951  */
1952  transmit_response(agent_pvt->subscribe_pvt, "200 OK", &agent_pvt->subscribe_pvt->initreq);
1953  transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_QUEUED);
1954  } else {
1955  transmit_response(agent_pvt->subscribe_pvt, "500 Internal Error", &agent_pvt->subscribe_pvt->initreq);
1956  }
1957  sip_pvt_unlock(agent_pvt->subscribe_pvt);
1958  agent_pvt->is_available = TRUE;
1959 }
1960 
1962 {
1963  struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1965  return ast_cc_agent_status_response(agent->core_id, state);
1966 }
1967 
1969 {
1970  /* To start monitoring just means to wait for an incoming PUBLISH
1971  * to tell us that the caller has become available again. No special
1972  * action is needed
1973  */
1974  return 0;
1975 }
1976 
1977 static int sip_cc_agent_recall(struct ast_cc_agent *agent)
1978 {
1979  struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1980  /* If we have received a PUBLISH beforehand stating that the caller in question
1981  * is not available, we can save ourself a bit of effort here and just report
1982  * the caller as busy
1983  */
1984  if (!agent_pvt->is_available) {
1985  return ast_cc_agent_caller_busy(agent->core_id, "Caller %s is busy, reporting to the core",
1986  agent->device_name);
1987  }
1988  /* Otherwise, we transmit a NOTIFY to the caller and await either
1989  * a PUBLISH or an INVITE
1990  */
1991  sip_pvt_lock(agent_pvt->subscribe_pvt);
1992  transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_READY);
1993  sip_pvt_unlock(agent_pvt->subscribe_pvt);
1994  return 0;
1995 }
1996 
1997 static void sip_cc_agent_destructor(struct ast_cc_agent *agent)
1998 {
1999  struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
2000 
2001  if (!agent_pvt) {
2002  /* The agent constructor probably failed. */
2003  return;
2004  }
2005 
2007  if (agent_pvt->subscribe_pvt) {
2008  sip_pvt_lock(agent_pvt->subscribe_pvt);
2010  /* If we haven't sent a 200 OK for the SUBSCRIBE dialog yet, then we need to send a response letting
2011  * the subscriber know something went wrong
2012  */
2013  transmit_response(agent_pvt->subscribe_pvt, "500 Internal Server Error", &agent_pvt->subscribe_pvt->initreq);
2014  }
2015  sip_pvt_unlock(agent_pvt->subscribe_pvt);
2016  agent_pvt->subscribe_pvt = dialog_unref(agent_pvt->subscribe_pvt, "SIP CC agent destructor: Remove ref to subscription");
2017  }
2018  ast_free(agent_pvt);
2019 }
2020 
2021 
2022 static int sip_monitor_instance_hash_fn(const void *obj, const int flags)
2023 {
2024  const struct sip_monitor_instance *monitor_instance = obj;
2025  return monitor_instance->core_id;
2026 }
2027 
2028 static int sip_monitor_instance_cmp_fn(void *obj, void *arg, int flags)
2029 {
2030  struct sip_monitor_instance *monitor_instance1 = obj;
2031  struct sip_monitor_instance *monitor_instance2 = arg;
2032 
2033  return monitor_instance1->core_id == monitor_instance2->core_id ? CMP_MATCH | CMP_STOP : 0;
2034 }
2035 
2036 static void sip_monitor_instance_destructor(void *data)
2037 {
2038  struct sip_monitor_instance *monitor_instance = data;
2039  if (monitor_instance->subscription_pvt) {
2040  sip_pvt_lock(monitor_instance->subscription_pvt);
2041  monitor_instance->subscription_pvt->expiry = 0;
2042  transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 0, monitor_instance->subscribe_uri);
2043  sip_pvt_unlock(monitor_instance->subscription_pvt);
2044  dialog_unref(monitor_instance->subscription_pvt, "Unref monitor instance ref of subscription pvt");
2045  }
2046  if (monitor_instance->suspension_entry) {
2047  monitor_instance->suspension_entry->body[0] = '\0';
2048  transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_REMOVE ,monitor_instance->notify_uri);
2049  ao2_t_ref(monitor_instance->suspension_entry, -1, "Decrementing suspension entry refcount in sip_monitor_instance_destructor");
2050  }
2051  ast_string_field_free_memory(monitor_instance);
2052 }
2053 
2054 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)
2055 {
2056  struct sip_monitor_instance *monitor_instance = ao2_alloc(sizeof(*monitor_instance), sip_monitor_instance_destructor);
2057 
2058  if (!monitor_instance) {
2059  return NULL;
2060  }
2061 
2062  if (ast_string_field_init(monitor_instance, 256)) {
2063  ao2_ref(monitor_instance, -1);
2064  return NULL;
2065  }
2066 
2067  ast_string_field_set(monitor_instance, subscribe_uri, subscribe_uri);
2068  ast_string_field_set(monitor_instance, peername, peername);
2069  ast_string_field_set(monitor_instance, device_name, device_name);
2070  monitor_instance->core_id = core_id;
2071  ao2_link(sip_monitor_instances, monitor_instance);
2072  return monitor_instance;
2073 }
2074 
2075 static int find_sip_monitor_instance_by_subscription_pvt(void *obj, void *arg, int flags)
2076 {
2077  struct sip_monitor_instance *monitor_instance = obj;
2078  return monitor_instance->subscription_pvt == arg ? CMP_MATCH | CMP_STOP : 0;
2079 }
2080 
2081 static int find_sip_monitor_instance_by_suspension_entry(void *obj, void *arg, int flags)
2082 {
2083  struct sip_monitor_instance *monitor_instance = obj;
2084  return monitor_instance->suspension_entry == arg ? CMP_MATCH | CMP_STOP : 0;
2085 }
2086 
2087 static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id);
2088 static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor);
2089 static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor);
2090 static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id);
2091 static void sip_cc_monitor_destructor(void *private_data);
2092 
2094  .type = "SIP",
2095  .request_cc = sip_cc_monitor_request_cc,
2096  .suspend = sip_cc_monitor_suspend,
2097  .unsuspend = sip_cc_monitor_unsuspend,
2098  .cancel_available_timer = sip_cc_monitor_cancel_available_timer,
2099  .destructor = sip_cc_monitor_destructor,
2100 };
2101 
2102 static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id)
2103 {
2104  struct sip_monitor_instance *monitor_instance = monitor->private_data;
2106  int when;
2107 
2108  if (!monitor_instance) {
2109  return -1;
2110  }
2111 
2112  if (!(monitor_instance->subscription_pvt = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL, 0))) {
2113  return -1;
2114  }
2115 
2116  when = service == AST_CC_CCBS ? ast_get_ccbs_available_timer(monitor->interface->config_params) :
2118 
2119  sip_pvt_lock(monitor_instance->subscription_pvt);
2120  ast_set_flag(&monitor_instance->subscription_pvt->flags[0], SIP_OUTGOING);
2121  create_addr(monitor_instance->subscription_pvt, monitor_instance->peername, 0, 1);
2122  ast_sip_ouraddrfor(&monitor_instance->subscription_pvt->sa, &monitor_instance->subscription_pvt->ourip, monitor_instance->subscription_pvt);
2123  monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
2124  monitor_instance->subscription_pvt->expiry = when;
2125 
2126  transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 2, monitor_instance->subscribe_uri);
2127  sip_pvt_unlock(monitor_instance->subscription_pvt);
2128 
2129  ao2_t_ref(monitor, +1, "Adding a ref to the monitor for the scheduler");
2130  *available_timer_id = ast_sched_add(sched, when * 1000, ast_cc_available_timer_expire, monitor);
2131  return 0;
2132 }
2133 
2134 static int construct_pidf_body(enum sip_cc_publish_state state, char *pidf_body, size_t size, const char *presentity)
2135 {
2136  struct ast_str *body = ast_str_alloca(size);
2137  char tuple_id[64];
2138 
2139  generate_random_string(tuple_id, sizeof(tuple_id));
2140 
2141  /* We'll make this a bare-bones pidf body. In state_notify_build_xml, the PIDF
2142  * body gets a lot more extra junk that isn't necessary, so we'll leave it out here.
2143  */
2144  ast_str_append(&body, 0, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
2145  /* XXX The entity attribute is currently set to the peer name associated with the
2146  * dialog. This is because we currently only call this function for call-completion
2147  * PUBLISH bodies. In such cases, the entity is completely disregarded. For other
2148  * event packages, it may be crucial to have a proper URI as the presentity so this
2149  * should be revisited as support is expanded.
2150  */
2151  ast_str_append(&body, 0, "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" entity=\"%s\">\n", presentity);
2152  ast_str_append(&body, 0, "<tuple id=\"%s\">\n", tuple_id);
2153  ast_str_append(&body, 0, "<status><basic>%s</basic></status>\n", state == CC_OPEN ? "open" : "closed");
2154  ast_str_append(&body, 0, "</tuple>\n");
2155  ast_str_append(&body, 0, "</presence>\n");
2156  ast_copy_string(pidf_body, ast_str_buffer(body), size);
2157  return 0;
2158 }
2159 
2160 static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor)
2161 {
2162  struct sip_monitor_instance *monitor_instance = monitor->private_data;
2163  enum sip_publish_type publish_type;
2164  struct cc_epa_entry *cc_entry;
2165 
2166  if (!monitor_instance) {
2167  return -1;
2168  }
2169 
2170  if (!monitor_instance->suspension_entry) {
2171  /* We haven't yet allocated the suspension entry, so let's give it a shot */
2172  if (!(monitor_instance->suspension_entry = create_epa_entry("call-completion", monitor_instance->peername))) {
2173  ast_log(LOG_WARNING, "Unable to allocate sip EPA entry for call-completion\n");
2174  ao2_ref(monitor_instance, -1);
2175  return -1;
2176  }
2177  if (!(cc_entry = ast_calloc(1, sizeof(*cc_entry)))) {
2178  ast_log(LOG_WARNING, "Unable to allocate space for instance data of EPA entry for call-completion\n");
2179  ao2_ref(monitor_instance, -1);
2180  return -1;
2181  }
2182  cc_entry->core_id = monitor->core_id;
2183  monitor_instance->suspension_entry->instance_data = cc_entry;
2184  publish_type = SIP_PUBLISH_INITIAL;
2185  } else {
2186  publish_type = SIP_PUBLISH_MODIFY;
2187  cc_entry = monitor_instance->suspension_entry->instance_data;
2188  }
2189 
2190  cc_entry->current_state = CC_CLOSED;
2191 
2192  if (ast_strlen_zero(monitor_instance->notify_uri)) {
2193  /* If we have no set notify_uri, then what this means is that we have
2194  * not received a NOTIFY from this destination stating that he is
2195  * currently available.
2196  *
2197  * This situation can arise when the core calls the suspend callbacks
2198  * of multiple destinations. If one of the other destinations aside
2199  * from this one notified Asterisk that he is available, then there
2200  * is no reason to take any suspension action on this device. Rather,
2201  * we should return now and if we receive a NOTIFY while monitoring
2202  * is still "suspended" then we can immediately respond with the
2203  * proper PUBLISH to let this endpoint know what is going on.
2204  */
2205  return 0;
2206  }
2207  construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
2208  return transmit_publish(monitor_instance->suspension_entry, publish_type, monitor_instance->notify_uri);
2209 }
2210 
2211 static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor)
2212 {
2213  struct sip_monitor_instance *monitor_instance = monitor->private_data;
2214  struct cc_epa_entry *cc_entry;
2215 
2216  if (!monitor_instance) {
2217  return -1;
2218  }
2219 
2220  ast_assert(monitor_instance->suspension_entry != NULL);
2221 
2222  cc_entry = monitor_instance->suspension_entry->instance_data;
2223  cc_entry->current_state = CC_OPEN;
2224  if (ast_strlen_zero(monitor_instance->notify_uri)) {
2225  /* This means we are being asked to unsuspend a call leg we never
2226  * sent a PUBLISH on. As such, there is no reason to send another
2227  * PUBLISH at this point either. We can just return instead.
2228  */
2229  return 0;
2230  }
2231  construct_pidf_body(CC_OPEN, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
2232  return transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_MODIFY, monitor_instance->notify_uri);
2233 }
2234 
2236 {
2237  if (*sched_id != -1) {
2238  AST_SCHED_DEL(sched, *sched_id);
2239  ao2_t_ref(monitor, -1, "Removing scheduler's reference to the monitor");
2240  }
2241  return 0;
2242 }
2243 
2244 static void sip_cc_monitor_destructor(void *private_data)
2245 {
2246  struct sip_monitor_instance *monitor_instance = private_data;
2247  ao2_unlink(sip_monitor_instances, monitor_instance);
2249 }
2250 
2251 static int sip_get_cc_information(struct sip_request *req, char *subscribe_uri, size_t size, enum ast_cc_service_type *service)
2252 {
2253  char *call_info = ast_strdupa(sip_get_header(req, "Call-Info"));
2254  char *uri;
2255  char *purpose;
2256  char *service_str;
2257  static const char cc_purpose[] = "purpose=call-completion";
2258  static const int cc_purpose_len = sizeof(cc_purpose) - 1;
2259 
2260  if (ast_strlen_zero(call_info)) {
2261  /* No Call-Info present. Definitely no CC offer */
2262  return -1;
2263  }
2264 
2265  uri = strsep(&call_info, ";");
2266 
2267  while ((purpose = strsep(&call_info, ";"))) {
2268  if (!strncmp(purpose, cc_purpose, cc_purpose_len)) {
2269  break;
2270  }
2271  }
2272  if (!purpose) {
2273  /* We didn't find the appropriate purpose= parameter. Oh well */
2274  return -1;
2275  }
2276 
2277  /* Okay, call-completion has been offered. Let's figure out what type of service this is */
2278  while ((service_str = strsep(&call_info, ";"))) {
2279  if (!strncmp(service_str, "m=", 2)) {
2280  break;
2281  }
2282  }
2283  if (!service_str) {
2284  /* So they didn't offer a particular service, We'll just go with CCBS since it really
2285  * doesn't matter anyway
2286  */
2287  service_str = "BS";
2288  } else {
2289  /* We already determined that there is an "m=" so no need to check
2290  * the result of this strsep
2291  */
2292  strsep(&service_str, "=");
2293  }
2294 
2295  if ((*service = service_string_to_service_type(service_str)) == AST_CC_NONE) {
2296  /* Invalid service offered */
2297  return -1;
2298  }
2299 
2300  ast_copy_string(subscribe_uri, get_in_brackets(uri), size);
2301 
2302  return 0;
2303 }
2304 
2305 /*
2306  * \brief Determine what, if any, CC has been offered and queue a CC frame if possible
2307  *
2308  * After taking care of some formalities to be sure that this call is eligible for CC,
2309  * we first try to see if we can make use of native CC. We grab the information from
2310  * the passed-in sip_request (which is always a response to an INVITE). If we can
2311  * use native CC monitoring for the call, then so be it.
2312  *
2313  * If native cc monitoring is not possible or not supported, then we will instead attempt
2314  * to use generic monitoring. Falling back to generic from a failed attempt at using native
2315  * monitoring will only work if the monitor policy of the endpoint is "always"
2316  *
2317  * \param pvt The current dialog. Contains CC parameters for the endpoint
2318  * \param req The response to the INVITE we want to inspect
2319  * \param service The service to use if generic monitoring is to be used. For native
2320  * monitoring, we get the service from the SIP response itself
2321  */
2322 static void sip_handle_cc(struct sip_pvt *pvt, struct sip_request *req, enum ast_cc_service_type service)
2323 {
2324  enum ast_cc_monitor_policies monitor_policy = ast_get_cc_monitor_policy(pvt->cc_params);
2325  int core_id;
2326  char interface_name[AST_CHANNEL_NAME];
2327 
2328  if (monitor_policy == AST_CC_MONITOR_NEVER) {
2329  /* Don't bother, just return */
2330  return;
2331  }
2332 
2333  if ((core_id = ast_cc_get_current_core_id(pvt->owner)) == -1) {
2334  /* For some reason, CC is invalid, so don't try it! */
2335  return;
2336  }
2337 
2338  ast_channel_get_device_name(pvt->owner, interface_name, sizeof(interface_name));
2339 
2340  if (monitor_policy == AST_CC_MONITOR_ALWAYS || monitor_policy == AST_CC_MONITOR_NATIVE) {
2341  char subscribe_uri[SIPBUFSIZE];
2343  enum ast_cc_service_type offered_service;
2344  struct sip_monitor_instance *monitor_instance;
2345  if (sip_get_cc_information(req, subscribe_uri, sizeof(subscribe_uri), &offered_service)) {
2346  /* If CC isn't being offered to us, or for some reason the CC offer is
2347  * not formatted correctly, then it may still be possible to use generic
2348  * call completion since the monitor policy may be "always"
2349  */
2350  goto generic;
2351  }
2352  ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
2353  if (!(monitor_instance = sip_monitor_instance_init(core_id, subscribe_uri, pvt->peername, device_name))) {
2354  /* Same deal. We can try using generic still */
2355  goto generic;
2356  }
2357  /* We bump the refcount of chan_sip because once we queue this frame, the CC core
2358  * will have a reference to callbacks in this module. We decrement the module
2359  * refcount once the monitor destructor is called
2360  */
2362  ast_queue_cc_frame(pvt->owner, "SIP", pvt->dialstring, offered_service, monitor_instance);
2363  ao2_ref(monitor_instance, -1);
2364  return;
2365  }
2366 
2367 generic:
2368  if (monitor_policy == AST_CC_MONITOR_GENERIC || monitor_policy == AST_CC_MONITOR_ALWAYS) {
2369  ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE, interface_name, service, NULL);
2370  }
2371 }
2372 
2373 /*! \brief Working TLS connection configuration */
2375 
2376 /*! \brief Default TLS connection configuration */
2378 
2379 /*! \brief Default DTLS connection configuration */
2381 
2382 /*! \brief The TCP server definition */
2384  .accept_fd = -1,
2385  .master = AST_PTHREADT_NULL,
2386  .tls_cfg = NULL,
2387  .poll_timeout = -1,
2388  .name = "SIP TCP server",
2389  .accept_fn = ast_tcptls_server_root,
2390  .worker_fn = sip_tcp_worker_fn,
2391 };
2392 
2393 /*! \brief The TCP/TLS server definition */
2395  .accept_fd = -1,
2396  .master = AST_PTHREADT_NULL,
2397  .tls_cfg = &sip_tls_cfg,
2398  .poll_timeout = -1,
2399  .name = "SIP TLS server",
2400  .accept_fn = ast_tcptls_server_root,
2401  .worker_fn = sip_tcp_worker_fn,
2402 };
2403 
2404 /*! \brief Append to SIP dialog history
2405  \return Always returns 0 */
2406 #define append_history(p, event, fmt , args... ) append_history_full(p, "%-15s " fmt, event, ## args)
2407 
2408 /*! \brief map from an integer value to a string.
2409  * If no match is found, return errorstring
2410  */
2411 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
2412 {
2413  const struct _map_x_s *cur;
2414 
2415  for (cur = table; cur->s; cur++) {
2416  if (cur->x == x) {
2417  return cur->s;
2418  }
2419  }
2420  return errorstring;
2421 }
2422 
2423 /*! \brief map from a string to an integer value, case insensitive.
2424  * If no match is found, return errorvalue.
2425  */
2426 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
2427 {
2428  const struct _map_x_s *cur;
2429 
2430  for (cur = table; cur->s; cur++) {
2431  if (!strcasecmp(cur->s, s)) {
2432  return cur->x;
2433  }
2434  }
2435  return errorvalue;
2436 }
2437 
2438 /*!
2439  * \internal
2440  * \brief Determine if the given string is a SIP token.
2441  * \since 13.8.0
2442  *
2443  * \param str String to determine if is a SIP token.
2444  *
2445  * \note A token is defined by RFC3261 Section 25.1
2446  *
2447  * \return Non-zero if the string is a SIP token.
2448  */
2449 static int sip_is_token(const char *str)
2450 {
2451  int is_token;
2452 
2453  if (ast_strlen_zero(str)) {
2454  /* An empty string is not a token. */
2455  return 0;
2456  }
2457 
2458  is_token = 1;
2459  do {
2460  if (!isalnum(*str)
2461  && !strchr("-.!%*_+`'~", *str)) {
2462  /* The character is not allowed in a token. */
2463  is_token = 0;
2464  break;
2465  }
2466  } while (*++str);
2467 
2468  return is_token;
2469 }
2470 
2471 static const char *sip_reason_code_to_str(struct ast_party_redirecting_reason *reason)
2472 {
2473  int idx;
2474  int code;
2475 
2476  /* use specific string if given */
2477  if (!ast_strlen_zero(reason->str)) {
2478  return reason->str;
2479  }
2480 
2481  code = reason->code;
2482  for (idx = 0; idx < ARRAY_LEN(sip_reason_table); ++idx) {
2483  if (code == sip_reason_table[idx].code) {
2484  return sip_reason_table[idx].text;
2485  }
2486  }
2487 
2488  return "unknown";
2489 }
2490 
2491 /*!
2492  * \brief generic function for determining if a correct transport is being
2493  * used to contact a peer
2494  *
2495  * this is done as a macro so that the "tmpl" var can be passed either a
2496  * sip_request or a sip_peer
2497  */
2498 #define check_request_transport(peer, tmpl) ({ \
2499  int ret = 0; \
2500  if (peer->socket.type == tmpl->socket.type) \
2501  ; \
2502  else if (!(peer->transports & tmpl->socket.type)) {\
2503  ast_log(LOG_ERROR, \
2504  "'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
2505  sip_get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
2506  ); \
2507  ret = 1; \
2508  } else if (peer->socket.type & AST_TRANSPORT_TLS) { \
2509  ast_log(LOG_WARNING, \
2510  "peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
2511  peer->name, sip_get_transport(tmpl->socket.type) \
2512  ); \
2513  } else { \
2514  ast_debug(1, \
2515  "peer '%s' has contacted us over %s even though we prefer %s.\n", \
2516  peer->name, sip_get_transport(tmpl->socket.type), sip_get_transport(peer->socket.type) \
2517  ); \
2518  }\
2519  (ret); \
2520 })
2521 
2522 /*! \brief
2523  * duplicate a list of channel variables, \return the copy.
2524  */
2525 static struct ast_variable *copy_vars(struct ast_variable *src)
2526 {
2527  struct ast_variable *res = NULL, *tmp, *v = NULL;
2528 
2529  for (v = src ; v ; v = v->next) {
2530  if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
2531  tmp->next = res;
2532  res = tmp;
2533  }
2534  }
2535  return res;
2536 }
2537 
2538 static void tcptls_packet_destructor(void *obj)
2539 {
2540  struct tcptls_packet *packet = obj;
2541 
2542  ast_free(packet->data);
2543 }
2544 
2546 {
2547  struct ast_tcptls_session_args *args = obj;
2548  if (args->tls_cfg) {
2549  ast_free(args->tls_cfg->certfile);
2550  ast_free(args->tls_cfg->pvtfile);
2551  ast_free(args->tls_cfg->cipher);
2552  ast_free(args->tls_cfg->cafile);
2553  ast_free(args->tls_cfg->capath);
2554 
2555  ast_ssl_teardown(args->tls_cfg);
2556  }
2557  ast_free(args->tls_cfg);
2558  ast_free((char *) args->name);
2559 }
2560 
2561 static void sip_threadinfo_destructor(void *obj)
2562 {
2563  struct sip_threadinfo *th = obj;
2564  struct tcptls_packet *packet;
2565 
2566  if (th->alert_pipe[0] > -1) {
2567  close(th->alert_pipe[0]);
2568  }
2569  if (th->alert_pipe[1] > -1) {
2570  close(th->alert_pipe[1]);
2571  }
2572  th->alert_pipe[0] = th->alert_pipe[1] = -1;
2573 
2574  while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
2575  ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
2576  }
2577 
2578  if (th->tcptls_session) {
2579  ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
2580  }
2581 }
2582 
2583 /*! \brief creates a sip_threadinfo object and links it into the threadt table. */
2584 static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
2585 {
2586  struct sip_threadinfo *th;
2587 
2588  if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
2589  return NULL;
2590  }
2591 
2592  th->alert_pipe[0] = th->alert_pipe[1] = -1;
2593 
2594  if (pipe(th->alert_pipe) == -1) {
2595  ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
2596  ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
2597  return NULL;
2598  }
2599  ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
2600  th->tcptls_session = tcptls_session;
2601  th->type = transport ? transport : (ast_iostream_get_ssl(tcptls_session->stream) ? AST_TRANSPORT_TLS: AST_TRANSPORT_TCP);
2602  ao2_t_link(threadt, th, "Adding new tcptls helper thread");
2603  ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
2604  return th;
2605 }
2606 
2607 /*! \brief used to indicate to a tcptls thread that data is ready to be written */
2608 static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
2609 {
2610  int res = len;
2611  struct sip_threadinfo *th = NULL;
2612  struct tcptls_packet *packet = NULL;
2613  struct sip_threadinfo tmp = {
2614  .tcptls_session = tcptls_session,
2615  };
2616  enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
2617 
2618  if (!tcptls_session) {
2619  return XMIT_ERROR;
2620  }
2621 
2622  ao2_lock(tcptls_session);
2623 
2624  if (!tcptls_session->stream ||
2625  !(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
2626  !(packet->data = ast_str_create(len))) {
2627  goto tcptls_write_setup_error;
2628  }
2629 
2630  if (!(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) {
2631  ast_log(LOG_ERROR, "Unable to locate tcptls_session helper thread.\n");
2632  goto tcptls_write_setup_error;
2633  }
2634 
2635  /* goto tcptls_write_error should _NOT_ be used beyond this point */
2636  ast_str_set(&packet->data, 0, "%s", (char *) buf);
2637  packet->len = len;
2638 
2639  /* alert tcptls thread handler that there is a packet to be sent.
2640  * must lock the thread info object to guarantee control of the
2641  * packet queue */
2642  ao2_lock(th);
2643  if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
2644  ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
2645  ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
2646  packet = NULL;
2647  res = XMIT_ERROR;
2648  } else { /* it is safe to queue the frame after issuing the alert when we hold the threadinfo lock */
2649  AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
2650  }
2651  ao2_unlock(th);
2652 
2653  ao2_unlock(tcptls_session);
2654  ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
2655  return res;
2656 
2657 tcptls_write_setup_error:
2658  if (th) {
2659  ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
2660  }
2661  if (packet) {
2662  ao2_t_ref(packet, -1, "could not allocate packet's data");
2663  }
2664  ao2_unlock(tcptls_session);
2665 
2666  return XMIT_ERROR;
2667 }
2668 
2669 /*! \brief SIP TCP connection handler */
2670 static void *sip_tcp_worker_fn(void *data)
2671 {
2672  struct ast_tcptls_session_instance *tcptls_session = data;
2673 
2674  return _sip_tcp_helper_thread(tcptls_session);
2675 }
2676 
2677 /*! \brief SIP WebSocket connection handler */
2678 static void sip_websocket_callback(struct ast_websocket *session, struct ast_variable *parameters, struct ast_variable *headers)
2679 {
2680  int res;
2681 
2682  if (ast_websocket_set_nonblock(session)) {
2683  goto end;
2684  }
2685 
2687  goto end;
2688  }
2689 
2690  while ((res = ast_wait_for_input(ast_websocket_fd(session), -1)) > 0) {
2691  char *payload;
2692  uint64_t payload_len;
2693  enum ast_websocket_opcode opcode;
2694  int fragmented;
2695 
2696  if (ast_websocket_read(session, &payload, &payload_len, &opcode, &fragmented)) {
2697  /* We err on the side of caution and terminate the session if any error occurs */
2698  break;
2699  }
2700 
2701  if (opcode == AST_WEBSOCKET_OPCODE_TEXT || opcode == AST_WEBSOCKET_OPCODE_BINARY) {
2702  struct sip_request req = { 0, };
2703  char data[payload_len + 1];
2704 
2705  if (!(req.data = ast_str_create(payload_len + 1))) {
2706  goto end;
2707  }
2708 
2709  strncpy(data, payload, payload_len);
2710  data[payload_len] = '\0';
2711 
2712  if (ast_str_set(&req.data, -1, "%s", data) == AST_DYNSTR_BUILD_FAILED) {
2713  deinit_req(&req);
2714  goto end;
2715  }
2716 
2717  req.socket.fd = ast_websocket_fd(session);
2719  req.socket.ws_session = session;
2720 
2722  deinit_req(&req);
2723 
2724  } else if (opcode == AST_WEBSOCKET_OPCODE_CLOSE) {
2725  break;
2726  }
2727  }
2728 
2729 end:
2730  ast_websocket_unref(session);
2731 }
2732 
2733 /*! \brief Check if the authtimeout has expired.
2734  * \param start the time when the session started
2735  *
2736  * \retval 0 the timeout has expired
2737  * \retval -1 error
2738  * \return the number of milliseconds until the timeout will expire
2739  */
2740 static int sip_check_authtimeout(time_t start)
2741 {
2742  int timeout;
2743  time_t now;
2744  if(time(&now) == -1) {
2745  ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
2746  return -1;
2747  }
2748 
2749  timeout = (authtimeout - (now - start)) * 1000;
2750  if (timeout < 0) {
2751  /* we have timed out */
2752  return 0;
2753  }
2754 
2755  return timeout;
2756 }
2757 
2758 /*!
2759  * \brief Indication of a TCP message's integrity
2760  */
2762  /*!
2763  * The message has an error in it with
2764  * regards to its Content-Length header
2765  */
2767  /*!
2768  * The message is incomplete
2769  */
2771  /*!
2772  * The data contains a complete message
2773  * plus a fragment of another.
2774  */
2776  /*!
2777  * The message is complete
2778  */
2780 };
2781 
2782 /*!
2783  * \brief
2784  * Get the content length from an unparsed SIP message
2785  *
2786  * \param message The unparsed SIP message headers
2787  * \return The value of the Content-Length header or -1 if message is invalid
2788  */
2789 static int read_raw_content_length(const char *message)
2790 {
2791  char *content_length_str;
2792  int content_length = -1;
2793 
2794  struct ast_str *msg_copy;
2795  char *msg;
2796 
2797  /* Using a ast_str because lws2sws takes one of those */
2798  if (!(msg_copy = ast_str_create(strlen(message) + 1))) {
2799  return -1;
2800  }
2801  ast_str_set(&msg_copy, 0, "%s", message);
2802 
2804  lws2sws(msg_copy);
2805  }
2806 
2807  msg = ast_str_buffer(msg_copy);
2808 
2809  /* Let's find a Content-Length header */
2810  if ((content_length_str = strcasestr(msg, "\nContent-Length:"))) {
2811  content_length_str += sizeof("\nContent-Length:") - 1;
2812  } else if ((content_length_str = strcasestr(msg, "\nl:"))) {
2813  content_length_str += sizeof("\nl:") - 1;
2814  } else {
2815  /* RFC 3261 18.3
2816  * "In the case of stream-oriented transports such as TCP, the Content-
2817  * Length header field indicates the size of the body. The Content-
2818  * Length header field MUST be used with stream oriented transports."
2819  */
2820  goto done;
2821  }
2822 
2823  /* Double-check that this is a complete header */
2824  if (!strchr(content_length_str, '\n')) {
2825  goto done;
2826  }
2827 
2828  if (sscanf(content_length_str, "%30d", &content_length) != 1) {
2829  content_length = -1;
2830  }
2831 
2832 done:
2833  ast_free(msg_copy);
2834  return content_length;
2835 }
2836 
2837 /*!
2838  * \brief Check that a message received over TCP is a full message
2839  *
2840  * This will take the information read in and then determine if
2841  * 1) The message is a full SIP request
2842  * 2) The message is a partial SIP request
2843  * 3) The message contains a full SIP request along with another partial request
2844  * \param data The unparsed incoming SIP message.
2845  * \param request The resulting request with extra fragments removed.
2846  * \param overflow If the message contains more than a full request, this is the remainder of the message
2847  * \return The resulting integrity of the message
2848  */
2849 static enum message_integrity check_message_integrity(struct ast_str **request, struct ast_str **overflow)
2850 {
2851  char *message = ast_str_buffer(*request);
2852  char *body;
2853  int content_length;
2854  int message_len = ast_str_strlen(*request);
2855  int body_len;
2856 
2857  /* Important pieces to search for in a SIP request are \r\n\r\n. This
2858  * marks either
2859  * 1) The division between the headers and body
2860  * 2) The end of the SIP request
2861  */
2862  body = strstr(message, "\r\n\r\n");
2863  if (!body) {
2864  /* This is clearly a partial message since we haven't reached an end
2865  * yet.
2866  */
2867  return MESSAGE_FRAGMENT;
2868  }
2869  body += sizeof("\r\n\r\n") - 1;
2870  body_len = message_len - (body - message);
2871 
2872  body[-1] = '\0';
2873  content_length = read_raw_content_length(message);
2874  body[-1] = '\n';
2875 
2876  if (content_length < 0) {
2877  return MESSAGE_INVALID;
2878  } else if (content_length == 0) {
2879  /* We've definitely received an entire message. We need
2880  * to check if there's also a fragment of another message
2881  * in addition.
2882  */
2883  if (body_len == 0) {
2884  return MESSAGE_COMPLETE;
2885  } else {
2886  ast_str_append(overflow, 0, "%s", body);
2887  ast_str_truncate(*request, message_len - body_len);
2889  }
2890  }
2891  /* Positive content length. Let's see what sort of
2892  * message body we're dealing with.
2893  */
2894  if (body_len < content_length) {
2895  /* We don't have the full message body yet */
2896  return MESSAGE_FRAGMENT;
2897  } else if (body_len > content_length) {
2898  /* We have the full message plus a fragment of a further
2899  * message
2900  */
2901  ast_str_append(overflow, 0, "%s", body + content_length);
2902  ast_str_truncate(*request, message_len - (body_len - content_length));
2904  } else {
2905  /* Yay! Full message with no extra content */
2906  return MESSAGE_COMPLETE;
2907  }
2908 }
2909 
2910 /*!
2911  * \brief Read SIP request or response from a TCP/TLS connection
2912  *
2913  * \param req The request structure to be filled in
2914  * \param tcptls_session The TCP/TLS connection from which to read
2915  * \retval -1 Failed to read data
2916  * \retval 0 Successfully read data
2917  */
2918 static int sip_tcptls_read(struct sip_request *req, struct ast_tcptls_session_instance *tcptls_session,
2919  int authenticated, time_t start)
2920 {
2922 
2923  while (message_integrity == MESSAGE_FRAGMENT) {
2924  size_t datalen;
2925 
2926  if (ast_str_strlen(tcptls_session->overflow_buf) == 0) {
2927  char readbuf[4097];
2928  int timeout;
2929  int res;
2930  if (!tcptls_session->client && !authenticated) {
2931  if ((timeout = sip_check_authtimeout(start)) < 0) {
2932  return -1;
2933  }
2934 
2935  if (timeout == 0) {
2936  ast_debug(2, "SIP TCP/TLS server timed out\n");
2937  return -1;
2938  }
2939  } else {
2940  timeout = -1;
2941  }
2942  res = ast_wait_for_input(ast_iostream_get_fd(tcptls_session->stream), timeout);
2943  if (res < 0) {
2944  ast_debug(2, "SIP TCP/TLS server :: ast_wait_for_input returned %d\n", res);
2945  return -1;
2946  } else if (res == 0) {
2947  ast_debug(2, "SIP TCP/TLS server timed out\n");
2948  return -1;
2949  }
2950 
2951  res = ast_iostream_read(tcptls_session->stream, readbuf, sizeof(readbuf) - 1);
2952  if (res < 0) {
2953  if (errno == EAGAIN || errno == EINTR) {
2954  continue;
2955  }
2956  ast_debug(2, "SIP TCP/TLS server error when receiving data\n");
2957  return -1;
2958  } else if (res == 0) {
2959  ast_debug(2, "SIP TCP/TLS server has shut down\n");
2960  return -1;
2961  }
2962  readbuf[res] = '\0';
2963  ast_str_append(&req->data, 0, "%s", readbuf);
2964  } else {
2965  ast_str_append(&req->data, 0, "%s", ast_str_buffer(tcptls_session->overflow_buf));
2966  ast_str_reset(tcptls_session->overflow_buf);
2967  }
2968 
2969  datalen = ast_str_strlen(req->data);
2970  if (datalen > SIP_MAX_PACKET_SIZE) {
2971  ast_log(LOG_WARNING, "Rejecting TCP/TLS packet from '%s' because way too large: %zu\n",
2972  ast_sockaddr_stringify(&tcptls_session->remote_address), datalen);
2973  return -1;
2974  }
2975 
2976  message_integrity = check_message_integrity(&req->data, &tcptls_session->overflow_buf);
2977  }
2978 
2979  return 0;
2980 }
2981 
2982 /*! \brief SIP TCP thread management function
2983  This function reads from the socket, parses the packet into a request
2984 */
2985 static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session)
2986 {
2987  int res, timeout = -1, authenticated = 0, flags;
2988  time_t start;
2989  struct sip_request req = { 0, } , reqcpy = { 0, };
2990  struct sip_threadinfo *me = NULL;
2991  char buf[1024] = "";
2992  struct pollfd fds[2] = { { 0 }, { 0 }, };
2993  struct ast_tcptls_session_args *ca = NULL;
2994 
2995  /* If this is a server session, then the connection has already been
2996  * setup. Check if the authlimit has been reached and if not create the
2997  * threadinfo object so we can access this thread for writing.
2998  *
2999  * if this is a client connection more work must be done.
3000  * 1. We own the parent session args for a client connection. This pointer needs
3001  * to be held on to so we can decrement it's ref count on thread destruction.
3002  * 2. The threadinfo object was created before this thread was launched, however
3003  * it must be found within the threadt table.
3004  * 3. Last, the tcptls_session must be started.
3005  */
3006  if (!tcptls_session->client) {
3008  /* unauth_sessions is decremented in the cleanup code */
3009  goto cleanup;
3010  }
3011 
3012  ast_iostream_nonblock(tcptls_session->stream);
3013  if (!(me = sip_threadinfo_create(tcptls_session, ast_iostream_get_ssl(tcptls_session->stream) ? AST_TRANSPORT_TLS : AST_TRANSPORT_TCP))) {
3014  goto cleanup;
3015  }
3016  me->threadid = pthread_self();
3017  ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
3018  } else {
3019  struct sip_threadinfo tmp = {
3020  .tcptls_session = tcptls_session,
3021  };
3022 
3023  if ((!(ca = tcptls_session->parent)) ||
3024  (!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")))) {
3025  goto cleanup;
3026  }
3027 
3028  me->threadid = pthread_self();
3029 
3030  if (!(tcptls_session = ast_tcptls_client_start(tcptls_session))) {
3031  goto cleanup;
3032  }
3033  }
3034 
3035  flags = 1;
3036  if (setsockopt(ast_iostream_get_fd(tcptls_session->stream), SOL_SOCKET, SO_KEEPALIVE, &flags, sizeof(flags))) {
3037  ast_log(LOG_ERROR, "error enabling TCP keep-alives on sip socket: %s\n", strerror(errno));
3038  goto cleanup;
3039  }
3040 
3041  ast_debug(2, "Starting thread for %s server\n", ast_iostream_get_ssl(tcptls_session->stream) ? "TLS" : "TCP");
3042 
3043  /* set up pollfd to watch for reads on both the socket and the alert_pipe */
3044  fds[0].fd = ast_iostream_get_fd(tcptls_session->stream);
3045  fds[1].fd = me->alert_pipe[0];
3046  fds[0].events = fds[1].events = POLLIN | POLLPRI;
3047 
3048  if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
3049  goto cleanup;
3050  }
3051  if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET))) {
3052  goto cleanup;
3053  }
3054 
3055  if(time(&start) == -1) {
3056  ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
3057  goto cleanup;
3058  }
3059 
3060  /*
3061  * We cannot let the stream exclusively wait for data to arrive.
3062  * We have to wake up the task to send outgoing messages.
3063  */
3064  ast_iostream_set_exclusive_input(tcptls_session->stream, 0);
3065 
3067  tcptls_session->client ? -1 : (authtimeout * 1000));
3068 
3069  for (;;) {
3070  struct ast_str *str_save;
3071 
3072  if (!tcptls_session->client && req.authenticated && !authenticated) {
3073  authenticated = 1;
3074  ast_iostream_set_timeout_disable(tcptls_session->stream);
3076  }
3077 
3078  /* calculate the timeout for unauthenticated server sessions */
3079  if (!tcptls_session->client && !authenticated ) {
3080  if ((timeout = sip_check_authtimeout(start)) < 0) {
3081  goto cleanup;
3082  }
3083 
3084  if (timeout == 0) {
3085  ast_debug(2, "SIP %s server timed out\n", ast_iostream_get_ssl(tcptls_session->stream) ? "TLS": "TCP");
3086  goto cleanup;
3087  }
3088  } else {
3089  timeout = -1;
3090  }
3091 
3092  if (ast_str_strlen(tcptls_session->overflow_buf) == 0) {
3093  res = ast_poll(fds, 2, timeout); /* polls for both socket and alert_pipe */
3094  if (res < 0) {
3095  ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", ast_iostream_get_ssl(tcptls_session->stream) ? "TLS": "TCP", res);
3096  goto cleanup;
3097  } else if (res == 0) {
3098  /* timeout */
3099  ast_debug(2, "SIP %s server timed out\n", ast_iostream_get_ssl(tcptls_session->stream) ? "TLS": "TCP");
3100  goto cleanup;
3101  }
3102  }
3103 
3104  /*
3105  * handle the socket event, check for both reads from the socket fd or TCP overflow buffer,
3106  * and writes from alert_pipe fd.
3107  */
3108  if (fds[0].revents || (ast_str_strlen(tcptls_session->overflow_buf) > 0)) { /* there is data on the socket to be read */
3109  fds[0].revents = 0;
3110 
3111  /* clear request structure */
3112  str_save = req.data;
3113  memset(&req, 0, sizeof(req));
3114  req.data = str_save;
3115  ast_str_reset(req.data);
3116 
3117  str_save = reqcpy.data;
3118  memset(&reqcpy, 0, sizeof(reqcpy));
3119  reqcpy.data = str_save;
3120  ast_str_reset(reqcpy.data);
3121 
3122  memset(buf, 0, sizeof(buf));
3123 
3124  if (ast_iostream_get_ssl(tcptls_session->stream)) {
3126  } else {
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->packets = pkt->next;
4349  stop_retrans_pkt(pkt);
4350  ao2_t_ref(pkt, -1, "Packet retransmission list");
4351  return AST_FAILURE;
4352  } else {
4353  /* This is odd, but since the retrans timer starts at 500ms and the do_monitor thread
4354  * only wakes up every 1000ms by default, we have to poke the thread here to make
4355  * sure it successfully detects this must be retransmitted in less time than
4356  * it usually sleeps for. Otherwise it might not retransmit this packet for 1000ms. */
4358  pthread_kill(monitor_thread, SIGURG);
4359  }
4360  return AST_SUCCESS;
4361  }
4362 }
4363 
4364 /*! \brief Kill a SIP dialog (called only by the scheduler)
4365  * The scheduler has a reference to this dialog when p->autokillid != -1,
4366  * and we are called using that reference. So if the event is not
4367  * rescheduled, we need to call dialog_unref().
4368  */
4369 static int __sip_autodestruct(const void *data)
4370 {
4371  struct sip_pvt *p = (struct sip_pvt *)data;
4372  struct ast_channel *owner;
4373 
4374  /* If this is a subscription, tell the phone that we got a timeout */
4376  struct state_notify_data data = { 0, };
4377 
4379 
4380  transmit_state_notify(p, &data, 1, TRUE); /* Send last notification */
4381  p->subscribed = NONE;
4382  append_history(p, "Subscribestatus", "timeout");
4383  ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
4384  return 10000; /* Reschedule this destruction so that we know that it's gone */
4385  }
4386 
4387  /* If there are packets still waiting for delivery, delay the destruction */
4388  if (p->packets) {
4389  if (!p->needdestroy) {
4390  char method_str[31];
4391 
4392  ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
4393  append_history(p, "ReliableXmit", "timeout");
4394  if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
4395  if (p->ongoing_reinvite || method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
4396  pvt_set_needdestroy(p, "autodestruct");
4397  }
4398  }
4399  return 10000;
4400  } else {
4401  /* They've had their chance to respond. Time to bail */
4402  __sip_pretend_ack(p);
4403  }
4404  }
4405 
4406  /*
4407  * Lock both the pvt and the channel safely so that we can queue up a frame.
4408  */
4409  owner = sip_pvt_lock_full(p);
4410  if (owner) {
4412  "Autodestruct on dialog '%s' with owner %s in place (Method: %s). Rescheduling destruction for 10000 ms\n",
4413  p->callid, ast_channel_name(owner), sip_methods[p->