chan_sip.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 1999 - 2012, Digium, Inc.
00005  *
00006  * Mark Spencer <markster@digium.com>
00007  *
00008  * See http://www.asterisk.org for more information about
00009  * the Asterisk project. Please do not directly contact
00010  * any of the maintainers of this project for assistance;
00011  * the project provides a web site, mailing lists and IRC
00012  * channels for your use.
00013  *
00014  * This program is free software, distributed under the terms of
00015  * the GNU General Public License Version 2. See the LICENSE file
00016  * at the top of the source tree.
00017  */
00018 
00019 /*!
00020  * \file
00021  * \brief Implementation of Session Initiation Protocol
00022  *
00023  * \author Mark Spencer <markster@digium.com>
00024  *
00025  * See Also:
00026  * \arg \ref AstCREDITS
00027  *
00028  * Implementation of RFC 3261 - without S/MIME, and experimental TCP and TLS support
00029  * Configuration file \link Config_sip sip.conf \endlink
00030  *
00031  * ********** IMPORTANT *
00032  * \note TCP/TLS support is EXPERIMENTAL and WILL CHANGE. This applies to configuration
00033  * settings, dialplan commands and dialplans apps/functions
00034  * See \ref sip_tcp_tls
00035  *
00036  *
00037  * ******** General TODO:s
00038  * \todo Better support of forking
00039  * \todo VIA branch tag transaction checking
00040  * \todo Transaction support
00041  *
00042  * ******** Wishlist: Improvements
00043  * - Support of SIP domains for devices, so that we match on username\@domain in the From: header
00044  * - Connect registrations with a specific device on the incoming call. It's not done
00045  *   automatically in Asterisk
00046  *
00047  * \ingroup channel_drivers
00048  *
00049  * \par Overview of the handling of SIP sessions
00050  * The SIP channel handles several types of SIP sessions, or dialogs,
00051  * not all of them being "telephone calls".
00052  * - Incoming calls that will be sent to the PBX core
00053  * - Outgoing calls, generated by the PBX
00054  * - SIP subscriptions and notifications of states and voicemail messages
00055  * - SIP registrations, both inbound and outbound
00056  * - SIP peer management (peerpoke, OPTIONS)
00057  * - SIP text messages
00058  *
00059  * In the SIP channel, there's a list of active SIP dialogs, which includes
00060  * all of these when they are active. "sip show channels" in the CLI will
00061  * show most of these, excluding subscriptions which are shown by
00062  * "sip show subscriptions"
00063  *
00064  * \par incoming packets
00065  * Incoming packets are received in the monitoring thread, then handled by
00066  * sipsock_read() for udp only. In tcp, packets are read by the tcp_helper thread.
00067  * sipsock_read() function parses the packet and matches an existing
00068  * dialog or starts a new SIP dialog.
00069  *
00070  * sipsock_read sends the packet to handle_incoming(), that parses a bit more.
00071  * If it is a response to an outbound request, the packet is sent to handle_response().
00072  * If it is a request, handle_incoming() sends it to one of a list of functions
00073  * depending on the request type - INVITE, OPTIONS, REFER, BYE, CANCEL etc
00074  * sipsock_read locks the ast_channel if it exists (an active call) and
00075  * unlocks it after we have processed the SIP message.
00076  *
00077  * A new INVITE is sent to handle_request_invite(), that will end up
00078  * starting a new channel in the PBX, the new channel after that executing
00079  * in a separate channel thread. This is an incoming "call".
00080  * When the call is answered, either by a bridged channel or the PBX itself
00081  * the sip_answer() function is called.
00082  *
00083  * The actual media - Video or Audio - is mostly handled by the RTP subsystem
00084  * in rtp.c
00085  *
00086  * \par Outbound calls
00087  * Outbound calls are set up by the PBX through the sip_request_call()
00088  * function. After that, they are activated by sip_call().
00089  *
00090  * \par Hanging up
00091  * The PBX issues a hangup on both incoming and outgoing calls through
00092  * the sip_hangup() function
00093  */
00094 
00095 /*! \li \ref chan_sip.c uses configuration files \ref sip.conf and \ref sip_notify.conf
00096  * \addtogroup configuration_file
00097  */
00098 
00099 /*! \page sip.conf sip.conf
00100  * \verbinclude sip.conf.sample
00101  */
00102 
00103 /*! \page sip_notify.conf sip_notify.conf
00104  * \verbinclude sip_notify.conf.sample
00105  */
00106 
00107 /*!
00108  * \page sip_tcp_tls SIP TCP and TLS support
00109  *
00110  * \par tcpfixes TCP implementation changes needed
00111  * \todo Fix TCP/TLS handling in dialplan, SRV records, transfers and much more
00112  * \todo Save TCP/TLS sessions in registry
00113  * If someone registers a SIPS uri, this forces us to set up a TLS connection back.
00114  * \todo Add TCP/TLS information to function SIPPEER and CHANNEL function
00115  * \todo If tcpenable=yes, we must open a TCP socket on the same address as the IP for UDP.
00116  *    The tcpbindaddr config option should only be used to open ADDITIONAL ports
00117  *    So we should propably go back to
00118  *    bindaddr= the default address to bind to. If tcpenable=yes, then bind this to both udp and TCP
00119  *          if tlsenable=yes, open TLS port (provided we also have cert)
00120  *    tcpbindaddr = extra address for additional TCP connections
00121  *    tlsbindaddr = extra address for additional TCP/TLS connections
00122  *    udpbindaddr = extra address for additional UDP connections
00123  *       These three options should take multiple IP/port pairs
00124  * Note: Since opening additional listen sockets is a *new* feature we do not have today
00125  *    the XXXbindaddr options needs to be disabled until we have support for it
00126  *
00127  * \todo re-evaluate the transport= setting in sip.conf. This is right now not well
00128  *    thought of. If a device in sip.conf contacts us via TCP, we should not switch transport,
00129  * even if udp is the configured first transport.
00130  *
00131  * \todo Be prepared for one outbound and another incoming socket per pvt. This applies
00132  *       specially to communication with other peers (proxies).
00133  * \todo We need to test TCP sessions with SIP proxies and in regards
00134  *       to the SIP outbound specs.
00135  * \todo ;transport=tls was deprecated in RFC3261 and should not be used at all. See section 26.2.2.
00136  *
00137  * \todo If the message is smaller than the given Content-length, the request should get a 400 Bad request
00138  *       message. If it's a response, it should be dropped. (RFC 3261, Section 18.3)
00139  * \todo Since we have had multidomain support in Asterisk for quite a while, we need to support
00140  *       multiple domains in our TLS implementation, meaning one socket and one cert per domain
00141  * \todo Selection of transport for a request needs to be done after we've parsed all route headers,
00142  *  also considering outbound proxy options.
00143  *    First request: Outboundproxy, routes, (reg contact or URI. If URI doesn't have port:  DNS naptr, srv, AAA)
00144  *    Intermediate requests: Outboundproxy(only when forced), routes, contact/uri
00145  * DNS naptr support is crucial. A SIP uri might lead to a TLS connection.
00146  * Also note that due to outbound proxy settings, a SIPS uri might have to be sent on UDP (not to recommend though)
00147  * \todo Default transports are set to UDP, which cause the wrong behaviour when contacting remote
00148  * devices directly from the dialplan. UDP is only a fallback if no other method works,
00149  * in order to be compatible with RFC2543 (SIP/1.0) devices. For transactions that exceed the
00150  * MTU (like INIVTE with video, audio and RTT)  TCP should be preferred.
00151  *
00152  * When dialling unconfigured peers (with no port number)  or devices in external domains
00153  * NAPTR records MUST be consulted to find configured transport. If they are not found,
00154  * SRV records for both TCP and UDP should be checked. If there's a record for TCP, use that.
00155  * If there's no record for TCP, then use UDP as a last resort. If there's no SRV records,
00156  * \note this only applies if there's no outbound proxy configured for the session. If an outbound
00157  * proxy is configured, these procedures might apply for locating the proxy and determining
00158  * the transport to use for communication with the proxy.
00159  * \par Other bugs to fix ----
00160  * __set_address_from_contact(const char *fullcontact, struct sockaddr_in *sin, int tcp)
00161  * - sets TLS port as default for all TCP connections, unless other port is given in contact.
00162  * parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
00163  * - assumes that the contact the UA registers is using the same transport as the REGISTER request, which is
00164  *   a bad guess.
00165  *      - Does not save any information about TCP/TLS connected devices, which is a severe BUG, as discussed on the mailing list.
00166  * get_destination(struct sip_pvt *p, struct sip_request *oreq)
00167  * - Doesn't store the information that we got an incoming SIPS request in the channel, so that
00168  *   we can require a secure signalling path OUT of Asterisk (on SIP or IAX2). Possibly, the call should
00169  *   fail on in-secure signalling paths if there's no override in our configuration. At least, provide a
00170  *   channel variable in the dialplan.
00171  * get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
00172  * - As above, if we have a SIPS: uri in the refer-to header
00173  * - Does not check transport in refer_to uri.
00174  */
00175 
00176 /*** MODULEINFO
00177    <use type="module">res_crypto</use>
00178    <use type="module">res_http_websocket</use>
00179    <support_level>extended</support_level>
00180  ***/
00181 
00182 /*!  \page sip_session_timers SIP Session Timers in Asterisk Chan_sip
00183 
00184    The SIP Session-Timers is an extension of the SIP protocol that allows end-points and proxies to
00185    refresh a session periodically. The sessions are kept alive by sending a RE-INVITE or UPDATE
00186    request at a negotiated interval. If a session refresh fails then all the entities that support Session-
00187    Timers clear their internal session state. In addition, UAs generate a BYE request in order to clear
00188    the state in the proxies and the remote UA (this is done for the benefit of SIP entities in the path
00189    that do not support Session-Timers).
00190 
00191    The Session-Timers can be configured on a system-wide, per-user, or per-peer basis. The peruser/
00192    per-peer settings override the global settings. The following new parameters have been
00193    added to the sip.conf file.
00194       session-timers=["accept", "originate", "refuse"]
00195       session-expires=[integer]
00196       session-minse=[integer]
00197       session-refresher=["uas", "uac"]
00198 
00199    The session-timers parameter in sip.conf defines the mode of operation of SIP session-timers feature in
00200    Asterisk. The Asterisk can be configured in one of the following three modes:
00201 
00202    1. Accept :: In the "accept" mode, the Asterisk server honors session-timers requests
00203       made by remote end-points. A remote end-point can request Asterisk to engage
00204       session-timers by either sending it an INVITE request with a "Supported: timer"
00205       header in it or by responding to Asterisk's INVITE with a 200 OK that contains
00206       Session-Expires: header in it. In this mode, the Asterisk server does not
00207       request session-timers from remote end-points. This is the default mode.
00208    2. Originate :: In the "originate" mode, the Asterisk server requests the remote
00209       end-points to activate session-timers in addition to honoring such requests
00210       made by the remote end-pints. In order to get as much protection as possible
00211       against hanging SIP channels due to network or end-point failures, Asterisk
00212       resends periodic re-INVITEs even if a remote end-point does not support
00213       the session-timers feature.
00214    3. Refuse :: In the "refuse" mode, Asterisk acts as if it does not support session-
00215       timers for inbound or outbound requests. If a remote end-point requests
00216       session-timers in a dialog, then Asterisk ignores that request unless it's
00217       noted as a requirement (Require: header), in which case the INVITE is
00218       rejected with a 420 Bad Extension response.
00219 
00220 */
00221 
00222 #include "asterisk.h"
00223 
00224 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 434655 $")
00225 
00226 #include <signal.h>
00227 #include <sys/signal.h>
00228 #include <regex.h>
00229 #include <inttypes.h>
00230 
00231 #include "asterisk/network.h"
00232 #include "asterisk/paths.h"   /* need ast_config_AST_SYSTEM_NAME */
00233 #include "asterisk/lock.h"
00234 #include "asterisk/config.h"
00235 #include "asterisk/module.h"
00236 #include "asterisk/pbx.h"
00237 #include "asterisk/sched.h"
00238 #include "asterisk/io.h"
00239 #include "asterisk/rtp_engine.h"
00240 #include "asterisk/udptl.h"
00241 #include "asterisk/acl.h"
00242 #include "asterisk/manager.h"
00243 #include "asterisk/callerid.h"
00244 #include "asterisk/cli.h"
00245 #include "asterisk/musiconhold.h"
00246 #include "asterisk/dsp.h"
00247 #include "asterisk/pickup.h"
00248 #include "asterisk/parking.h"
00249 #include "asterisk/srv.h"
00250 #include "asterisk/astdb.h"
00251 #include "asterisk/causes.h"
00252 #include "asterisk/utils.h"
00253 #include "asterisk/file.h"
00254 #include "asterisk/astobj2.h"
00255 #include "asterisk/dnsmgr.h"
00256 #include "asterisk/devicestate.h"
00257 #include "asterisk/monitor.h"
00258 #include "asterisk/netsock2.h"
00259 #include "asterisk/localtime.h"
00260 #include "asterisk/abstract_jb.h"
00261 #include "asterisk/threadstorage.h"
00262 #include "asterisk/translate.h"
00263 #include "asterisk/ast_version.h"
00264 #include "asterisk/data.h"
00265 #include "asterisk/aoc.h"
00266 #include "asterisk/message.h"
00267 #include "sip/include/sip.h"
00268 #include "sip/include/globals.h"
00269 #include "sip/include/config_parser.h"
00270 #include "sip/include/reqresp_parser.h"
00271 #include "sip/include/sip_utils.h"
00272 #include "asterisk/sdp_srtp.h"
00273 #include "asterisk/ccss.h"
00274 #include "asterisk/xml.h"
00275 #include "sip/include/dialog.h"
00276 #include "sip/include/dialplan_functions.h"
00277 #include "sip/include/security_events.h"
00278 #include "sip/include/route.h"
00279 #include "asterisk/sip_api.h"
00280 #include "asterisk/app.h"
00281 #include "asterisk/bridge.h"
00282 #include "asterisk/stasis.h"
00283 #include "asterisk/stasis_endpoints.h"
00284 #include "asterisk/stasis_system.h"
00285 #include "asterisk/stasis_channels.h"
00286 #include "asterisk/features_config.h"
00287 #include "asterisk/http_websocket.h"
00288 #include "asterisk/format_cache.h"
00289 
00290 /*** DOCUMENTATION
00291    <application name="SIPDtmfMode" language="en_US">
00292       <synopsis>
00293          Change the dtmfmode for a SIP call.
00294       </synopsis>
00295       <syntax>
00296          <parameter name="mode" required="true">
00297             <enumlist>
00298                <enum name="inband" />
00299                <enum name="info" />
00300                <enum name="rfc2833" />
00301             </enumlist>
00302          </parameter>
00303       </syntax>
00304       <description>
00305          <para>Changes the dtmfmode for a SIP call.</para>
00306       </description>
00307    </application>
00308    <application name="SIPAddHeader" language="en_US">
00309       <synopsis>
00310          Add a SIP header to the outbound call.
00311       </synopsis>
00312       <syntax argsep=":">
00313          <parameter name="Header" required="true" />
00314          <parameter name="Content" required="true" />
00315       </syntax>
00316       <description>
00317          <para>Adds a header to a SIP call placed with DIAL.</para>
00318          <para>Remember to use the X-header if you are adding non-standard SIP
00319          headers, like <literal>X-Asterisk-Accountcode:</literal>. Use this with care.
00320          Adding the wrong headers may jeopardize the SIP dialog.</para>
00321          <para>Always returns <literal>0</literal>.</para>
00322       </description>
00323    </application>
00324    <application name="SIPRemoveHeader" language="en_US">
00325       <synopsis>
00326          Remove SIP headers previously added with SIPAddHeader
00327       </synopsis>
00328       <syntax>
00329          <parameter name="Header" required="false" />
00330       </syntax>
00331       <description>
00332          <para>SIPRemoveHeader() allows you to remove headers which were previously
00333          added with SIPAddHeader(). If no parameter is supplied, all previously added
00334          headers will be removed. If a parameter is supplied, only the matching headers
00335          will be removed.</para>
00336          <para>For example you have added these 2 headers:</para>
00337          <para>SIPAddHeader(P-Asserted-Identity: sip:foo@bar);</para>
00338          <para>SIPAddHeader(P-Preferred-Identity: sip:bar@foo);</para>
00339          <para></para>
00340          <para>// remove all headers</para>
00341          <para>SIPRemoveHeader();</para>
00342          <para>// remove all P- headers</para>
00343          <para>SIPRemoveHeader(P-);</para>
00344          <para>// remove only the PAI header (note the : at the end)</para>
00345          <para>SIPRemoveHeader(P-Asserted-Identity:);</para>
00346          <para></para>
00347          <para>Always returns <literal>0</literal>.</para>
00348       </description>
00349    </application>
00350    <application name="SIPSendCustomINFO" language="en_US">
00351       <synopsis>
00352          Send a custom INFO frame on specified channels.
00353       </synopsis>
00354       <syntax>
00355          <parameter name="Data" required="true" />
00356          <parameter name="UserAgent" required="false" />
00357       </syntax>
00358       <description>
00359          <para>SIPSendCustomINFO() allows you to send a custom INFO message on all
00360          active SIP channels or on channels with the specified User Agent. This
00361          application is only available if TEST_FRAMEWORK is defined.</para>
00362       </description>
00363    </application>
00364    <function name="SIP_HEADER" language="en_US">
00365       <synopsis>
00366          Gets the specified SIP header from an incoming INVITE message.
00367       </synopsis>
00368       <syntax>
00369          <parameter name="name" required="true" />
00370          <parameter name="number">
00371             <para>If not specified, defaults to <literal>1</literal>.</para>
00372          </parameter>
00373       </syntax>
00374       <description>
00375          <para>Since there are several headers (such as Via) which can occur multiple
00376          times, SIP_HEADER takes an optional second argument to specify which header with
00377          that name to retrieve. Headers start at offset <literal>1</literal>.</para>
00378          <para>Please observe that contents of the SDP (an attachment to the
00379          SIP request) can't be accessed with this function.</para>
00380       </description>
00381    </function>
00382    <function name="SIPPEER" language="en_US">
00383       <synopsis>
00384          Gets SIP peer information.
00385       </synopsis>
00386       <syntax>
00387          <parameter name="peername" required="true" />
00388          <parameter name="item">
00389             <enumlist>
00390                <enum name="ip">
00391                   <para>(default) The IP address.</para>
00392                </enum>
00393                <enum name="port">
00394                   <para>The port number.</para>
00395                </enum>
00396                <enum name="mailbox">
00397                   <para>The configured mailbox.</para>
00398                </enum>
00399                <enum name="context">
00400                   <para>The configured context.</para>
00401                </enum>
00402                <enum name="expire">
00403                   <para>The epoch time of the next expire.</para>
00404                </enum>
00405                <enum name="dynamic">
00406                   <para>Is it dynamic? (yes/no).</para>
00407                </enum>
00408                <enum name="callerid_name">
00409                   <para>The configured Caller ID name.</para>
00410                </enum>
00411                <enum name="callerid_num">
00412                   <para>The configured Caller ID number.</para>
00413                </enum>
00414                <enum name="callgroup">
00415                   <para>The configured Callgroup.</para>
00416                </enum>
00417                <enum name="pickupgroup">
00418                   <para>The configured Pickupgroup.</para>
00419                </enum>
00420                <enum name="namedcallgroup">
00421                   <para>The configured Named Callgroup.</para>
00422                </enum>
00423                <enum name="namedpickupgroup">
00424                   <para>The configured Named Pickupgroup.</para>
00425                </enum>
00426                <enum name="codecs">
00427                   <para>The configured codecs.</para>
00428                </enum>
00429                <enum name="status">
00430                   <para>Status (if qualify=yes).</para>
00431                </enum>
00432                <enum name="regexten">
00433                   <para>Extension activated at registration.</para>
00434                </enum>
00435                <enum name="limit">
00436                   <para>Call limit (call-limit).</para>
00437                </enum>
00438                <enum name="busylevel">
00439                   <para>Configured call level for signalling busy.</para>
00440                </enum>
00441                <enum name="curcalls">
00442                   <para>Current amount of calls. Only available if call-limit is set.</para>
00443                </enum>
00444                <enum name="language">
00445                   <para>Default language for peer.</para>
00446                </enum>
00447                <enum name="accountcode">
00448                   <para>Account code for this peer.</para>
00449                </enum>
00450                <enum name="useragent">
00451                   <para>Current user agent header used by peer.</para>
00452                </enum>
00453                <enum name="maxforwards">
00454                   <para>The value used for SIP loop prevention in outbound requests</para>
00455                </enum>
00456                <enum name="chanvar[name]">
00457                   <para>A channel variable configured with setvar for this peer.</para>
00458                </enum>
00459                <enum name="codec[x]">
00460                   <para>Preferred codec index number <replaceable>x</replaceable> (beginning with zero).</para>
00461                </enum>
00462             </enumlist>
00463          </parameter>
00464       </syntax>
00465       <description></description>
00466    </function>
00467    <function name="CHECKSIPDOMAIN" language="en_US">
00468       <synopsis>
00469          Checks if domain is a local domain.
00470       </synopsis>
00471       <syntax>
00472          <parameter name="domain" required="true" />
00473       </syntax>
00474       <description>
00475          <para>This function checks if the <replaceable>domain</replaceable> in the argument is configured
00476          as a local SIP domain that this Asterisk server is configured to handle.
00477          Returns the domain name if it is locally handled, otherwise an empty string.
00478          Check the <literal>domain=</literal> configuration in <filename>sip.conf</filename>.</para>
00479       </description>
00480    </function>
00481    <manager name="SIPpeers" language="en_US">
00482       <synopsis>
00483          List SIP peers (text format).
00484       </synopsis>
00485       <syntax>
00486          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00487       </syntax>
00488       <description>
00489          <para>Lists SIP peers in text format with details on current status.
00490          <literal>Peerlist</literal> will follow as separate events, followed by a final event called
00491          <literal>PeerlistComplete</literal>.</para>
00492       </description>
00493    </manager>
00494    <manager name="SIPshowpeer" language="en_US">
00495       <synopsis>
00496          show SIP peer (text format).
00497       </synopsis>
00498       <syntax>
00499          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00500          <parameter name="Peer" required="true">
00501             <para>The peer name you want to check.</para>
00502          </parameter>
00503       </syntax>
00504       <description>
00505          <para>Show one SIP peer with details on current status.</para>
00506       </description>
00507    </manager>
00508    <manager name="SIPqualifypeer" language="en_US">
00509       <synopsis>
00510          Qualify SIP peers.
00511       </synopsis>
00512       <syntax>
00513          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00514          <parameter name="Peer" required="true">
00515             <para>The peer name you want to qualify.</para>
00516          </parameter>
00517       </syntax>
00518       <description>
00519          <para>Qualify a SIP peer.</para>
00520       </description>
00521       <see-also>
00522          <ref type="managerEvent">SIPQualifyPeerDone</ref>
00523       </see-also>
00524    </manager>
00525    <manager name="SIPshowregistry" language="en_US">
00526       <synopsis>
00527          Show SIP registrations (text format).
00528       </synopsis>
00529       <syntax>
00530          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00531       </syntax>
00532       <description>
00533          <para>Lists all registration requests and status. Registrations will follow as separate
00534          events followed by a final event called <literal>RegistrationsComplete</literal>.</para>
00535       </description>
00536    </manager>
00537    <manager name="SIPnotify" language="en_US">
00538       <synopsis>
00539          Send a SIP notify.
00540       </synopsis>
00541       <syntax>
00542          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00543          <parameter name="Channel" required="true">
00544             <para>Peer to receive the notify.</para>
00545          </parameter>
00546          <parameter name="Variable" required="true">
00547             <para>At least one variable pair must be specified.
00548             <replaceable>name</replaceable>=<replaceable>value</replaceable></para>
00549          </parameter>
00550       </syntax>
00551       <description>
00552          <para>Sends a SIP Notify event.</para>
00553          <para>All parameters for this event must be specified in the body of this request
00554          via multiple <literal>Variable: name=value</literal> sequences.</para>
00555       </description>
00556    </manager>
00557    <manager name="SIPpeerstatus" language="en_US">
00558       <synopsis>
00559          Show the status of one or all of the sip peers.
00560       </synopsis>
00561       <syntax>
00562          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00563          <parameter name="Peer" required="false">
00564             <para>The peer name you want to check.</para>
00565          </parameter>
00566       </syntax>
00567       <description>
00568          <para>Retrieves the status of one or all of the sip peers.  If no peer name is specified, status
00569          for all of the sip peers will be retrieved.</para>
00570       </description>
00571    </manager>
00572    <info name="SIPMessageFromInfo" language="en_US" tech="SIP">
00573       <para>The <literal>from</literal> parameter can be a configured peer name
00574       or in the form of "display-name" &lt;URI&gt;.</para>
00575    </info>
00576    <info name="SIPMessageToInfo" language="en_US" tech="SIP">
00577       <para>Specifying a prefix of <literal>sip:</literal> will send the
00578       message as a SIP MESSAGE request.</para>
00579    </info>
00580    <managerEvent language="en_US" name="SIPQualifyPeerDone">
00581       <managerEventInstance class="EVENT_FLAG_CALL">
00582          <synopsis>Raised when SIPQualifyPeer has finished qualifying the specified peer.</synopsis>
00583          <syntax>
00584             <parameter name="Peer">
00585                <para>The name of the peer.</para>
00586             </parameter>
00587             <parameter name="ActionID">
00588                <para>This is only included if an ActionID Header was sent with the action request, in which case it will be that ActionID.</para>
00589             </parameter>
00590          </syntax>
00591          <see-also>
00592             <ref type="manager">SIPqualifypeer</ref>
00593          </see-also>
00594       </managerEventInstance>
00595    </managerEvent>
00596    <managerEvent language="en_US" name="SessionTimeout">
00597       <managerEventInstance class="EVENT_FLAG_CALL">
00598          <synopsis>Raised when a SIP session times out.</synopsis>
00599          <syntax>
00600             <channel_snapshot/>
00601             <parameter name="Source">
00602                <para>The source of the session timeout.</para>
00603                <enumlist>
00604                   <enum name="RTPTimeout" />
00605                   <enum name="SIPSessionTimer" />
00606                </enumlist>
00607             </parameter>
00608          </syntax>
00609       </managerEventInstance>
00610    </managerEvent>
00611  ***/
00612 
00613 static int min_expiry = DEFAULT_MIN_EXPIRY;        /*!< Minimum accepted registration time */
00614 static int max_expiry = DEFAULT_MAX_EXPIRY;        /*!< Maximum accepted registration time */
00615 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
00616 static int min_subexpiry = DEFAULT_MIN_EXPIRY;     /*!< Minimum accepted subscription time */
00617 static int max_subexpiry = DEFAULT_MAX_EXPIRY;     /*!< Maximum accepted subscription time */
00618 static int mwi_expiry = DEFAULT_MWI_EXPIRY;
00619 
00620 static int unauth_sessions = 0;
00621 static int authlimit = DEFAULT_AUTHLIMIT;
00622 static int authtimeout = DEFAULT_AUTHTIMEOUT;
00623 
00624 /*! \brief Global jitterbuffer configuration - by default, jb is disabled
00625  *  \note Values shown here match the defaults shown in sip.conf.sample */
00626 static struct ast_jb_conf default_jbconf =
00627 {
00628    .flags = 0,
00629    .max_size = 200,
00630    .resync_threshold = 1000,
00631    .impl = "fixed",
00632    .target_extra = 40,
00633 };
00634 static struct ast_jb_conf global_jbconf;                /*!< Global jitterbuffer configuration */
00635 
00636 static const char config[] = "sip.conf";                /*!< Main configuration file */
00637 static const char notify_config[] = "sip_notify.conf";  /*!< Configuration file for sending Notify with CLI commands to reconfigure or reboot phones */
00638 
00639 /*! \brief Readable descriptions of device states.
00640  *  \note Should be aligned to above table as index */
00641 static const struct invstate2stringtable {
00642    const enum invitestates state;
00643    const char *desc;
00644 } invitestate2string[] = {
00645    {INV_NONE,              "None"  },
00646    {INV_CALLING,           "Calling (Trying)"},
00647    {INV_PROCEEDING,        "Proceeding "},
00648    {INV_EARLY_MEDIA,       "Early media"},
00649    {INV_COMPLETED,         "Completed (done)"},
00650    {INV_CONFIRMED,         "Confirmed (up)"},
00651    {INV_TERMINATED,        "Done"},
00652    {INV_CANCELLED,         "Cancelled"}
00653 };
00654 
00655 /*! \brief Subscription types that we support. We support
00656  * - dialoginfo updates (really device status, not dialog info as was the original intent of the standard)
00657  * - SIMPLE presence used for device status
00658  * - Voicemail notification subscriptions
00659  */
00660 static const struct cfsubscription_types {
00661    enum subscriptiontype type;
00662    const char * const event;
00663    const char * const mediatype;
00664    const char * const text;
00665 } subscription_types[] = {
00666    { NONE,        "-",        "unknown",               "unknown" },
00667    /* RFC 4235: SIP Dialog event package */
00668    { DIALOG_INFO_XML, "dialog",   "application/dialog-info+xml", "dialog-info+xml" },
00669    { CPIM_PIDF_XML,   "presence", "application/cpim-pidf+xml",   "cpim-pidf+xml" },  /* RFC 3863 */
00670    { PIDF_XML,        "presence", "application/pidf+xml",        "pidf+xml" },       /* RFC 3863 */
00671    { XPIDF_XML,       "presence", "application/xpidf+xml",       "xpidf+xml" },       /* Pre-RFC 3863 with MS additions */
00672    { MWI_NOTIFICATION,  "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
00673 };
00674 
00675 /*! \brief The core structure to setup dialogs. We parse incoming messages by using
00676  *  structure and then route the messages according to the type.
00677  *
00678  *  \note Note that sip_methods[i].id == i must hold or the code breaks
00679  */
00680 static const struct  cfsip_methods {
00681    enum sipmethod id;
00682    int need_rtp;     /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
00683    char * const text;
00684    enum can_create_dialog can_create;
00685 } sip_methods[] = {
00686    { SIP_UNKNOWN,   RTP,    "-UNKNOWN-",CAN_CREATE_DIALOG },
00687    { SIP_RESPONSE,  NO_RTP, "SIP/2.0",  CAN_NOT_CREATE_DIALOG },
00688    { SIP_REGISTER,  NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
00689    { SIP_OPTIONS,   NO_RTP, "OPTIONS",  CAN_CREATE_DIALOG },
00690    { SIP_NOTIFY,    NO_RTP, "NOTIFY",   CAN_CREATE_DIALOG },
00691    { SIP_INVITE,    RTP,    "INVITE",   CAN_CREATE_DIALOG },
00692    { SIP_ACK,       NO_RTP, "ACK",      CAN_NOT_CREATE_DIALOG },
00693    { SIP_PRACK,     NO_RTP, "PRACK",    CAN_NOT_CREATE_DIALOG },
00694    { SIP_BYE,       NO_RTP, "BYE",      CAN_NOT_CREATE_DIALOG },
00695    { SIP_REFER,     NO_RTP, "REFER",    CAN_CREATE_DIALOG },
00696    { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE",CAN_CREATE_DIALOG },
00697    { SIP_MESSAGE,   NO_RTP, "MESSAGE",  CAN_CREATE_DIALOG },
00698    { SIP_UPDATE,    NO_RTP, "UPDATE",   CAN_NOT_CREATE_DIALOG },
00699    { SIP_INFO,      NO_RTP, "INFO",     CAN_NOT_CREATE_DIALOG },
00700    { SIP_CANCEL,    NO_RTP, "CANCEL",   CAN_NOT_CREATE_DIALOG },
00701    { SIP_PUBLISH,   NO_RTP, "PUBLISH",  CAN_CREATE_DIALOG },
00702    { SIP_PING,      NO_RTP, "PING",     CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
00703 };
00704 
00705 /*! \brief Diversion header reasons
00706  *
00707  * The core defines a bunch of constants used to define
00708  * redirecting reasons. This provides a translation table
00709  * between those and the strings which may be present in
00710  * a SIP Diversion header
00711  */
00712 static const struct sip_reasons {
00713    enum AST_REDIRECTING_REASON code;
00714    char * const text;
00715 } sip_reason_table[] = {
00716    { AST_REDIRECTING_REASON_UNKNOWN, "unknown" },
00717    { AST_REDIRECTING_REASON_USER_BUSY, "user-busy" },
00718    { AST_REDIRECTING_REASON_NO_ANSWER, "no-answer" },
00719    { AST_REDIRECTING_REASON_UNAVAILABLE, "unavailable" },
00720    { AST_REDIRECTING_REASON_UNCONDITIONAL, "unconditional" },
00721    { AST_REDIRECTING_REASON_TIME_OF_DAY, "time-of-day" },
00722    { AST_REDIRECTING_REASON_DO_NOT_DISTURB, "do-not-disturb" },
00723    { AST_REDIRECTING_REASON_DEFLECTION, "deflection" },
00724    { AST_REDIRECTING_REASON_FOLLOW_ME, "follow-me" },
00725    { AST_REDIRECTING_REASON_OUT_OF_ORDER, "out-of-service" },
00726    { AST_REDIRECTING_REASON_AWAY, "away" },
00727    { AST_REDIRECTING_REASON_CALL_FWD_DTE, "unknown"},
00728    { AST_REDIRECTING_REASON_SEND_TO_VM, "send_to_vm"},
00729 };
00730 
00731 
00732 /*! \name DefaultSettings
00733    Default setttings are used as a channel setting and as a default when
00734    configuring devices
00735 */
00736 static char default_language[MAX_LANGUAGE];      /*!< Default language setting for new channels */
00737 static char default_callerid[AST_MAX_EXTENSION]; /*!< Default caller ID for sip messages */
00738 static char default_mwi_from[80];                /*!< Default caller ID for MWI updates */
00739 static char default_fromdomain[AST_MAX_EXTENSION]; /*!< Default domain on outound messages */
00740 static int default_fromdomainport;                 /*!< Default domain port on outbound messages */
00741 static char default_notifymime[AST_MAX_EXTENSION]; /*!< Default MIME media type for MWI notify messages */
00742 static char default_vmexten[AST_MAX_EXTENSION];    /*!< Default From Username on MWI updates */
00743 static int default_qualify;                        /*!< Default Qualify= setting */
00744 static int default_keepalive;                      /*!< Default keepalive= setting */
00745 static char default_mohinterpret[MAX_MUSICCLASS];  /*!< Global setting for moh class to use when put on hold */
00746 static char default_mohsuggest[MAX_MUSICCLASS];    /*!< Global setting for moh class to suggest when putting
00747                                                     *   a bridged channel on hold */
00748 static char default_parkinglot[AST_MAX_CONTEXT];   /*!< Parkinglot */
00749 static char default_engine[256];                   /*!< Default RTP engine */
00750 static int default_maxcallbitrate;                 /*!< Maximum bitrate for call */
00751 static char default_zone[MAX_TONEZONE_COUNTRY];        /*!< Default tone zone for channels created from the SIP driver */
00752 static unsigned int default_transports;            /*!< Default Transports (enum ast_transport) that are acceptable */
00753 static unsigned int default_primary_transport;     /*!< Default primary Transport (enum ast_transport) for outbound connections to devices */
00754 
00755 static struct sip_settings sip_cfg;    /*!< SIP configuration data.
00756                \note in the future we could have multiple of these (per domain, per device group etc) */
00757 
00758 /*!< use this macro when ast_uri_decode is dependent on pedantic checking to be on. */
00759 #define SIP_PEDANTIC_DECODE(str) \
00760    if (sip_cfg.pedanticsipchecking && !ast_strlen_zero(str)) { \
00761       ast_uri_decode(str, ast_uri_sip_user); \
00762    }  \
00763 
00764 static unsigned int chan_idx;       /*!< used in naming sip channel */
00765 static int global_match_auth_username;    /*!< Match auth username if available instead of From: Default off. */
00766 
00767 static int global_relaxdtmf;        /*!< Relax DTMF */
00768 static int global_prematuremediafilter;   /*!< Enable/disable premature frames in a call (causing 183 early media) */
00769 static int global_rtptimeout;       /*!< Time out call if no RTP */
00770 static int global_rtpholdtimeout;   /*!< Time out call if no RTP during hold */
00771 static int global_rtpkeepalive;     /*!< Send RTP keepalives */
00772 static int global_reg_timeout;      /*!< Global time between attempts for outbound registrations */
00773 static int global_regattempts_max;  /*!< Registration attempts before giving up */
00774 static int global_reg_retry_403;    /*!< Treat 403 responses to registrations as 401 responses */
00775 static int global_shrinkcallerid;   /*!< enable or disable shrinking of caller id  */
00776 static int global_callcounter;      /*!< Enable call counters for all devices. This is currently enabled by setting the peer
00777                                      *   call-limit to INT_MAX. When we remove the call-limit from the code, we can make it
00778                                      *   with just a boolean flag in the device structure */
00779 static unsigned int global_tos_sip;      /*!< IP type of service for SIP packets */
00780 static unsigned int global_tos_audio;    /*!< IP type of service for audio RTP packets */
00781 static unsigned int global_tos_video;    /*!< IP type of service for video RTP packets */
00782 static unsigned int global_tos_text;     /*!< IP type of service for text RTP packets */
00783 static unsigned int global_cos_sip;      /*!< 802.1p class of service for SIP packets */
00784 static unsigned int global_cos_audio;    /*!< 802.1p class of service for audio RTP packets */
00785 static unsigned int global_cos_video;    /*!< 802.1p class of service for video RTP packets */
00786 static unsigned int global_cos_text;     /*!< 802.1p class of service for text RTP packets */
00787 static unsigned int recordhistory;       /*!< Record SIP history. Off by default */
00788 static unsigned int dumphistory;         /*!< Dump history to verbose before destroying SIP dialog */
00789 static char global_useragent[AST_MAX_EXTENSION];    /*!< Useragent for the SIP channel */
00790 static char global_sdpsession[AST_MAX_EXTENSION];   /*!< SDP session name for the SIP channel */
00791 static char global_sdpowner[AST_MAX_EXTENSION];     /*!< SDP owner name for the SIP channel */
00792 static int global_authfailureevents;     /*!< Whether we send authentication failure manager events or not. Default no. */
00793 static int global_t1;           /*!< T1 time */
00794 static int global_t1min;        /*!< T1 roundtrip time minimum */
00795 static int global_timer_b;      /*!< Timer B - RFC 3261 Section 17.1.1.2 */
00796 static unsigned int global_autoframing; /*!< Turn autoframing on or off. */
00797 static int global_qualifyfreq;          /*!< Qualify frequency */
00798 static int global_qualify_gap;          /*!< Time between our group of peer pokes */
00799 static int global_qualify_peers;        /*!< Number of peers to poke at a given time */
00800 
00801 static enum st_mode global_st_mode;           /*!< Mode of operation for Session-Timers           */
00802 static enum st_refresher_param global_st_refresher; /*!< Session-Timer refresher                        */
00803 static int global_min_se;                     /*!< Lowest threshold for session refresh interval  */
00804 static int global_max_se;                     /*!< Highest threshold for session refresh interval */
00805 
00806 static int global_store_sip_cause;    /*!< Whether the MASTER_CHANNEL(HASH(SIP_CAUSE,[chan_name])) var should be set */
00807 
00808 static int global_dynamic_exclude_static = 0; /*!< Exclude static peers from contact registrations */
00809 static unsigned char global_refer_addheaders; /*!< Add extra headers to outgoing REFER */
00810 /*@}*/
00811 
00812 /*!
00813  * We use libxml2 in order to parse XML that may appear in the body of a SIP message. Currently,
00814  * the only usage is for parsing PIDF bodies of incoming PUBLISH requests in the call-completion
00815  * event package. This variable is set at module load time and may be checked at runtime to determine
00816  * if XML parsing support was found.
00817  */
00818 static int can_parse_xml;
00819 
00820 /*! \name Object counters @{
00821  *
00822  * \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
00823  * should be used to modify these values.
00824  */
00825 static int speerobjs = 0;     /*!< Static peers */
00826 static int rpeerobjs = 0;     /*!< Realtime peers */
00827 static int apeerobjs = 0;     /*!< Autocreated peer objects */
00828 /*! @} */
00829 
00830 static struct ast_flags global_flags[3] = {{0}};  /*!< global SIP_ flags */
00831 static unsigned int global_t38_maxdatagram;                /*!< global T.38 FaxMaxDatagram override */
00832 
00833 static struct stasis_subscription *network_change_sub; /*!< subscription id for network change events */
00834 static struct stasis_subscription *acl_change_sub; /*!< subscription id for named ACL system change events */
00835 static int network_change_sched_id = -1;
00836 
00837 static char used_context[AST_MAX_CONTEXT];        /*!< name of automatically created context for unloading */
00838 
00839 AST_MUTEX_DEFINE_STATIC(netlock);
00840 
00841 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
00842    when it's doing something critical. */
00843 AST_MUTEX_DEFINE_STATIC(monlock);
00844 
00845 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
00846 
00847 /*! \brief This is the thread for the monitor which checks for input on the channels
00848    which are not currently in use.  */
00849 static pthread_t monitor_thread = AST_PTHREADT_NULL;
00850 
00851 static int sip_reloading = FALSE;                       /*!< Flag for avoiding multiple reloads at the same time */
00852 static enum channelreloadreason sip_reloadreason;       /*!< Reason for last reload/load of configuration */
00853 
00854 struct ast_sched_context *sched;     /*!< The scheduling context */
00855 static struct io_context *io;           /*!< The IO context */
00856 static int *sipsock_read_id;            /*!< ID of IO entry for sipsock FD */
00857 struct sip_pkt;
00858 static AST_LIST_HEAD_STATIC(domain_list, domain);    /*!< The SIP domain list */
00859 
00860 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
00861 
00862 static enum sip_debug_e sipdebug;
00863 
00864 /*! \brief extra debugging for 'text' related events.
00865  *  At the moment this is set together with sip_debug_console.
00866  *  \note It should either go away or be implemented properly.
00867  */
00868 static int sipdebug_text;
00869 
00870 static const struct _map_x_s referstatusstrings[] = {
00871    { REFER_IDLE,      "<none>" },
00872    { REFER_SENT,      "Request sent" },
00873    { REFER_RECEIVED,  "Request received" },
00874    { REFER_CONFIRMED, "Confirmed" },
00875    { REFER_ACCEPTED,  "Accepted" },
00876    { REFER_RINGING,   "Target ringing" },
00877    { REFER_200OK,     "Done" },
00878    { REFER_FAILED,    "Failed" },
00879    { REFER_NOAUTH,    "Failed - auth failure" },
00880    { -1,               NULL} /* terminator */
00881 };
00882 
00883 /* --- Hash tables of various objects --------*/
00884 #ifdef LOW_MEMORY
00885 static const int HASH_PEER_SIZE = 17;
00886 static const int HASH_DIALOG_SIZE = 17;
00887 static const int HASH_REGISTRY_SIZE = 17;
00888 #else
00889 static const int HASH_PEER_SIZE = 563; /*!< Size of peer hash table, prime number preferred! */
00890 static const int HASH_DIALOG_SIZE = 563;
00891 static const int HASH_REGISTRY_SIZE = 563;
00892 #endif
00893 
00894 static const struct {
00895    enum ast_cc_service_type service;
00896    const char *service_string;
00897 } sip_cc_service_map [] = {
00898    [AST_CC_NONE] = { AST_CC_NONE, "" },
00899    [AST_CC_CCBS] = { AST_CC_CCBS, "BS" },
00900    [AST_CC_CCNR] = { AST_CC_CCNR, "NR" },
00901    [AST_CC_CCNL] = { AST_CC_CCNL, "NL" },
00902 };
00903 
00904 static const struct {
00905    enum sip_cc_notify_state state;
00906    const char *state_string;
00907 } sip_cc_notify_state_map [] = {
00908    [CC_QUEUED] = {CC_QUEUED, "cc-state: queued"},
00909    [CC_READY] = {CC_READY, "cc-state: ready"},
00910 };
00911 
00912 AST_LIST_HEAD_STATIC(epa_static_data_list, epa_backend);
00913 
00914 
00915 /*!
00916  * Used to create new entity IDs by ESCs.
00917  */
00918 static int esc_etag_counter;
00919 static const int DEFAULT_PUBLISH_EXPIRES = 3600;
00920 
00921 #ifdef HAVE_LIBXML2
00922 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);
00923 
00924 static const struct sip_esc_publish_callbacks cc_esc_publish_callbacks = {
00925    .initial_handler = cc_esc_publish_handler,
00926    .modify_handler = cc_esc_publish_handler,
00927 };
00928 #endif
00929 
00930 /*!
00931  * \brief The Event State Compositors
00932  *
00933  * An Event State Compositor is an entity which
00934  * accepts PUBLISH requests and acts appropriately
00935  * based on these requests.
00936  *
00937  * The actual event_state_compositor structure is simply
00938  * an ao2_container of sip_esc_entrys. When an incoming
00939  * PUBLISH is received, we can match the appropriate sip_esc_entry
00940  * using the entity ID of the incoming PUBLISH.
00941  */
00942 static struct event_state_compositor {
00943    enum subscriptiontype event;
00944    const char * name;
00945    const struct sip_esc_publish_callbacks *callbacks;
00946    struct ao2_container *compositor;
00947 } event_state_compositors [] = {
00948 #ifdef HAVE_LIBXML2
00949    {CALL_COMPLETION, "call-completion", &cc_esc_publish_callbacks},
00950 #endif
00951 };
00952 
00953 struct state_notify_data {
00954    int state;
00955    struct ao2_container *device_state_info;
00956    int presence_state;
00957    const char *presence_subtype;
00958    const char *presence_message;
00959 };
00960 
00961 
00962 static const int ESC_MAX_BUCKETS = 37;
00963 
00964 /*!
00965  * \details
00966  * Here we implement the container for dialogs which are in the
00967  * dialog_needdestroy state to iterate only through the dialogs
00968  * unlink them instead of iterate through all dialogs
00969  */
00970 struct ao2_container *dialogs_needdestroy;
00971 
00972 /*!
00973  * \details
00974  * Here we implement the container for dialogs which have rtp
00975  * traffic and rtptimeout, rtpholdtimeout or rtpkeepalive
00976  * set. We use this container instead the whole dialog list.
00977  */
00978 struct ao2_container *dialogs_rtpcheck;
00979 
00980 /*!
00981  * \details
00982  * Here we implement the container for dialogs (sip_pvt), defining
00983  * generic wrapper functions to ease the transition from the current
00984  * implementation (a single linked list) to a different container.
00985  * In addition to a reference to the container, we need functions to lock/unlock
00986  * the container and individual items, and functions to add/remove
00987  * references to the individual items.
00988  */
00989 static struct ao2_container *dialogs;
00990 #define sip_pvt_lock(x) ao2_lock(x)
00991 #define sip_pvt_trylock(x) ao2_trylock(x)
00992 #define sip_pvt_unlock(x) ao2_unlock(x)
00993 
00994 /*! \brief  The table of TCP threads */
00995 static struct ao2_container *threadt;
00996 
00997 /*! \brief  The peer list: Users, Peers and Friends */
00998 static struct ao2_container *peers;
00999 static struct ao2_container *peers_by_ip;
01000 
01001 /*! \brief  A bogus peer, to be used when authentication should fail */
01002 static struct sip_peer *bogus_peer;
01003 /*! \brief  We can recognise the bogus peer by this invalid MD5 hash */
01004 #define BOGUS_PEER_MD5SECRET "intentionally_invalid_md5_string"
01005 
01006 /*! \brief  The register list: Other SIP proxies we register with and receive calls from */
01007 static struct ao2_container *registry_list;
01008 
01009 /*! \brief  The MWI subscription list */
01010 static struct ao2_container *subscription_mwi_list;
01011 
01012 static int temp_pvt_init(void *);
01013 static void temp_pvt_cleanup(void *);
01014 
01015 /*! \brief A per-thread temporary pvt structure */
01016 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
01017 
01018 /*! \brief A per-thread buffer for transport to string conversion */
01019 AST_THREADSTORAGE(sip_transport_str_buf);
01020 
01021 /*! \brief Size of the SIP transport buffer */
01022 #define SIP_TRANSPORT_STR_BUFSIZE 128
01023 
01024 /*! \brief Authentication container for realm authentication */
01025 static struct sip_auth_container *authl = NULL;
01026 /*! \brief Global authentication container protection while adjusting the references. */
01027 AST_MUTEX_DEFINE_STATIC(authl_lock);
01028 
01029 static struct ast_manager_event_blob *session_timeout_to_ami(struct stasis_message *msg);
01030 STASIS_MESSAGE_TYPE_DEFN_LOCAL(session_timeout_type,
01031    .to_ami = session_timeout_to_ami,
01032    );
01033 
01034 /* --- Sockets and networking --------------*/
01035 
01036 /*! \brief Main socket for UDP SIP communication.
01037  *
01038  * sipsock is shared between the SIP manager thread (which handles reload
01039  * requests), the udp io handler (sipsock_read()) and the user routines that
01040  * issue udp writes (using __sip_xmit()).
01041  * The socket is -1 only when opening fails (this is a permanent condition),
01042  * or when we are handling a reload() that changes its address (this is
01043  * a transient situation during which we might have a harmless race, see
01044  * below). Because the conditions for the race to be possible are extremely
01045  * rare, we don't want to pay the cost of locking on every I/O.
01046  * Rather, we remember that when the race may occur, communication is
01047  * bound to fail anyways, so we just live with this event and let
01048  * the protocol handle this above us.
01049  */
01050 static int sipsock  = -1;
01051 
01052 struct ast_sockaddr bindaddr; /*!< UDP: The address we bind to */
01053 
01054 /*! \brief our (internal) default address/port to put in SIP/SDP messages
01055  *  internip is initialized picking a suitable address from one of the
01056  * interfaces, and the same port number we bind to. It is used as the
01057  * default address/port in SIP messages, and as the default address
01058  * (but not port) in SDP messages.
01059  */
01060 static struct ast_sockaddr internip;
01061 
01062 /*! \brief our external IP address/port for SIP sessions.
01063  * externaddr.sin_addr is only set when we know we might be behind
01064  * a NAT, and this is done using a variety of (mutually exclusive)
01065  * ways from the config file:
01066  *
01067  * + with "externaddr = host[:port]" we specify the address/port explicitly.
01068  *   The address is looked up only once when (re)loading the config file;
01069  *
01070  * + with "externhost = host[:port]" we do a similar thing, but the
01071  *   hostname is stored in externhost, and the hostname->IP mapping
01072  *   is refreshed every 'externrefresh' seconds;
01073  *
01074  * Other variables (externhost, externexpire, externrefresh) are used
01075  * to support the above functions.
01076  */
01077 static struct ast_sockaddr externaddr;      /*!< External IP address if we are behind NAT */
01078 static struct ast_sockaddr media_address; /*!< External RTP IP address if we are behind NAT */
01079 static struct ast_sockaddr rtpbindaddr;   /*!< RTP: The address we bind to */
01080 
01081 static char externhost[MAXHOSTNAMELEN];   /*!< External host name */
01082 static time_t externexpire;             /*!< Expiration counter for re-resolving external host name in dynamic DNS */
01083 static int externrefresh = 10;          /*!< Refresh timer for DNS-based external address (dyndns) */
01084 static uint16_t externtcpport;          /*!< external tcp port */
01085 static uint16_t externtlsport;          /*!< external tls port */
01086 
01087 /*! \brief  List of local networks
01088  * We store "localnet" addresses from the config file into an access list,
01089  * marked as 'DENY', so the call to ast_apply_ha() will return
01090  * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
01091  * (i.e. presumably public) addresses.
01092  */
01093 static struct ast_ha *localaddr;    /*!< List of local networks, on the same side of NAT as this Asterisk */
01094 
01095 static int ourport_tcp;             /*!< The port used for TCP connections */
01096 static int ourport_tls;             /*!< The port used for TCP/TLS connections */
01097 static struct ast_sockaddr debugaddr;
01098 
01099 static struct ast_config *notify_types = NULL;    /*!< The list of manual NOTIFY types we know how to send */
01100 
01101 /*! some list management macros. */
01102 
01103 #define UNLINK(element, head, prev) do {  \
01104    if (prev)            \
01105       (prev)->next = (element)->next;  \
01106    else              \
01107       (head) = (element)->next;  \
01108    } while (0)
01109 
01110 struct ao2_container *sip_monitor_instances;
01111 
01112 struct show_peers_context;
01113 
01114 /*---------------------------- Forward declarations of functions in chan_sip.c */
01115 /* Note: This is added to help splitting up chan_sip.c into several files
01116    in coming releases. */
01117 
01118 /*--- PBX interface functions */
01119 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);
01120 static int sip_devicestate(const char *data);
01121 static int sip_sendtext(struct ast_channel *ast, const char *text);
01122 static int sip_call(struct ast_channel *ast, const char *dest, int timeout);
01123 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
01124 static int sip_hangup(struct ast_channel *ast);
01125 static int sip_answer(struct ast_channel *ast);
01126 static struct ast_frame *sip_read(struct ast_channel *ast);
01127 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
01128 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
01129 static int sip_transfer(struct ast_channel *ast, const char *dest);
01130 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
01131 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
01132 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
01133 static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen);
01134 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
01135 static const char *sip_get_callid(struct ast_channel *chan);
01136 
01137 static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr);
01138 static int sip_standard_port(enum ast_transport type, int port);
01139 static int sip_prepare_socket(struct sip_pvt *p);
01140 static int get_address_family_filter(unsigned int transport);
01141 
01142 /*--- Transmitting responses and requests */
01143 static int sipsock_read(int *id, int fd, short events, void *ignore);
01144 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data);
01145 static int __sip_reliable_xmit(struct sip_pvt *p, uint32_t seqno, int resp, struct ast_str *data, int fatal, int sipmethod);
01146 static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp);
01147 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
01148 static int retrans_pkt(const void *data);
01149 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);
01150 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01151 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01152 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01153 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);
01154 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
01155 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);
01156 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
01157 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
01158 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable);
01159 static int transmit_request(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch);
01160 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch);
01161 static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri);
01162 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri);
01163 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
01164 static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded);
01165 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
01166 static int transmit_info_with_vidupdate(struct sip_pvt *p);
01167 static int transmit_message(struct sip_pvt *p, int init, int auth);
01168 static int transmit_refer(struct sip_pvt *p, const char *dest);
01169 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
01170 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
01171 static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state);
01172 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
01173 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno);
01174 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno);
01175 static void copy_request(struct sip_request *dst, const struct sip_request *src);
01176 static void receive_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
01177 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward);
01178 static int sip_send_mwi_to_peer(struct sip_peer *peer, int cache_only);
01179 
01180 /* Misc dialog routines */
01181 static int __sip_autodestruct(const void *data);
01182 static int update_call_counter(struct sip_pvt *fup, int event);
01183 static int auto_congest(const void *arg);
01184 static struct sip_pvt *__find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method,
01185    const char *file, int line, const char *func);
01186 #define find_call(req, addr, intended_method) \
01187    __find_call(req, addr, intended_method, __FILE__, __LINE__, __PRETTY_FUNCTION__)
01188 
01189 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards, int resp);
01190 static int build_path(struct sip_pvt *p, struct sip_peer *peer, struct sip_request *req, const char *pathbuf);
01191 static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
01192                      struct sip_request *req, const char *uri);
01193 static int get_sip_pvt_from_replaces(const char *callid, const char *totag, const char *fromtag,
01194       struct sip_pvt **out_pvt, struct ast_channel **out_chan);
01195 static void check_pendings(struct sip_pvt *p);
01196 static void sip_set_owner(struct sip_pvt *p, struct ast_channel *chan);
01197 
01198 static void *sip_pickup_thread(void *stuff);
01199 static int sip_pickup(struct ast_channel *chan);
01200 
01201 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
01202 static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method);
01203 
01204 /*--- Codec handling / SDP */
01205 static void try_suggested_sip_codec(struct sip_pvt *p);
01206 static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
01207 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
01208 static int find_sdp(struct sip_request *req);
01209 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
01210 static int process_sdp_o(const char *o, struct sip_pvt *p);
01211 static int process_sdp_c(const char *c, struct ast_sockaddr *addr);
01212 static int process_sdp_a_sendonly(const char *a, int *sendonly);
01213 static int process_sdp_a_ice(const char *a, struct sip_pvt *p, struct ast_rtp_instance *instance);
01214 static int process_sdp_a_dtls(const char *a, struct sip_pvt *p, struct ast_rtp_instance *instance);
01215 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec);
01216 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec);
01217 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);
01218 static int process_sdp_a_image(const char *a, struct sip_pvt *p);
01219 static void add_ice_to_sdp(struct ast_rtp_instance *instance, struct ast_str **a_buf);
01220 static void add_dtls_to_sdp(struct ast_rtp_instance *instance, struct ast_str **a_buf);
01221 static void start_ice(struct ast_rtp_instance *instance, int offer);
01222 static void add_codec_to_sdp(const struct sip_pvt *p, struct ast_format *codec,
01223               struct ast_str **m_buf, struct ast_str **a_buf,
01224               int debug, int *min_packet_size, int *max_packet_size);
01225 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
01226             struct ast_str **m_buf, struct ast_str **a_buf,
01227             int debug);
01228 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
01229 static void do_setnat(struct sip_pvt *p);
01230 static void stop_media_flows(struct sip_pvt *p);
01231 
01232 /*--- Authentication stuff */
01233 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
01234 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
01235 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
01236                 const char *secret, const char *md5secret, int sipmethod,
01237                 const char *uri, enum xmittype reliable);
01238 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
01239                      int sipmethod, const char *uri, enum xmittype reliable,
01240                      struct ast_sockaddr *addr, struct sip_peer **authpeer);
01241 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr);
01242 
01243 /*--- Domain handling */
01244 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
01245 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
01246 static void clear_sip_domains(void);
01247 
01248 /*--- SIP realm authentication */
01249 static void add_realm_authentication(struct sip_auth_container **credentials, const char *configuration, int lineno);
01250 static struct sip_auth *find_realm_authentication(struct sip_auth_container *credentials, const char *realm);
01251 
01252 /*--- Misc functions */
01253 static int check_rtp_timeout(struct sip_pvt *dialog, time_t t);
01254 static int reload_config(enum channelreloadreason reason);
01255 static void add_diversion(struct sip_request *req, struct sip_pvt *pvt);
01256 static int expire_register(const void *data);
01257 static void *do_monitor(void *data);
01258 static int restart_monitor(void);
01259 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
01260 static struct ast_variable *copy_vars(struct ast_variable *src);
01261 static int dialog_find_multiple(void *obj, void *arg, int flags);
01262 static struct ast_channel *sip_pvt_lock_full(struct sip_pvt *pvt);
01263 /* static int sip_addrcmp(char *name, struct sockaddr_in *sin);   Support for peer matching */
01264 static int sip_refer_alloc(struct sip_pvt *p);
01265 static void sip_refer_destroy(struct sip_pvt *p);
01266 static int sip_notify_alloc(struct sip_pvt *p);
01267 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
01268 static void set_peer_nat(const struct sip_pvt *p, struct sip_peer *peer);
01269 static void check_for_nat(const struct ast_sockaddr *them, struct sip_pvt *p);
01270 
01271 /*--- Device monitoring and Device/extension state/event handling */
01272 static int extensionstate_update(const char *context, const char *exten, struct state_notify_data *data, struct sip_pvt *p, int force);
01273 static int cb_extensionstate(char *context, char *exten, struct ast_state_cb_info *info, void *data);
01274 static int sip_poke_noanswer(const void *data);
01275 static int sip_poke_peer(struct sip_peer *peer, int force);
01276 static void sip_poke_all_peers(void);
01277 static void sip_peer_hold(struct sip_pvt *p, int hold);
01278 static void mwi_event_cb(void *, struct stasis_subscription *, struct stasis_message *);
01279 static void network_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
01280 static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
01281 static void sip_keepalive_all_peers(void);
01282 
01283 /*--- Applications, functions, CLI and manager command helpers */
01284 static const char *sip_nat_mode(const struct sip_pvt *p);
01285 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01286 static char *transfermode2str(enum transfermodes mode) attribute_const;
01287 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
01288 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01289 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01290 static struct sip_peer *_sip_show_peers_one(int fd, struct mansession *s, struct show_peers_context *cont, struct sip_peer *peer);
01291 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01292 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01293 static void  print_group(int fd, ast_group_t group, int crlf);
01294 static void  print_named_groups(int fd, struct ast_namedgroups *groups, int crlf);
01295 static const char *dtmfmode2str(int mode) attribute_const;
01296 static int str2dtmfmode(const char *str) attribute_unused;
01297 static const char *insecure2str(int mode) attribute_const;
01298 static const char *allowoverlap2str(int mode) attribute_const;
01299 static void cleanup_stale_contexts(char *new, char *old);
01300 static const char *domain_mode_to_text(const enum domain_mode mode);
01301 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01302 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01303 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01304 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01305 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01306 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01307 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01308 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01309 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01310 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
01311 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
01312 static char *complete_sip_peer(const char *word, int state, int flags2);
01313 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
01314 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
01315 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
01316 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
01317 static char *complete_sip_notify(const char *line, const char *word, int pos, int state);
01318 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01319 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01320 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01321 static char *sip_do_debug_ip(int fd, const char *arg);
01322 static char *sip_do_debug_peer(int fd, const char *arg);
01323 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01324 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01325 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01326 static int sip_dtmfmode(struct ast_channel *chan, const char *data);
01327 static int sip_addheader(struct ast_channel *chan, const char *data);
01328 static int sip_do_reload(enum channelreloadreason reason);
01329 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01330 static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
01331                   const char *name, int flag, int family);
01332 static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
01333                   const char *name, int flag);
01334 static int ast_sockaddr_resolve_first_transport(struct ast_sockaddr *addr,
01335                   const char *name, int flag, unsigned int transport);
01336 
01337 /*--- Debugging
01338    Functions for enabling debug per IP or fully, or enabling history logging for
01339    a SIP dialog
01340 */
01341 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to debuglog at end of dialog, before destroying data */
01342 static inline int sip_debug_test_addr(const struct ast_sockaddr *addr);
01343 static inline int sip_debug_test_pvt(struct sip_pvt *p);
01344 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
01345 static void sip_dump_history(struct sip_pvt *dialog);
01346 
01347 /*--- Device object handling */
01348 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
01349 static int update_call_counter(struct sip_pvt *fup, int event);
01350 static void sip_destroy_peer(struct sip_peer *peer);
01351 static void sip_destroy_peer_fn(void *peer);
01352 static void set_peer_defaults(struct sip_peer *peer);
01353 static struct sip_peer *temp_peer(const char *name);
01354 static void register_peer_exten(struct sip_peer *peer, int onoff);
01355 static int sip_poke_peer_s(const void *data);
01356 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
01357 static void reg_source_db(struct sip_peer *peer);
01358 static void destroy_association(struct sip_peer *peer);
01359 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
01360 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
01361 static void set_socket_transport(struct sip_socket *socket, int transport);
01362 static int peer_ipcmp_cb_full(void *obj, void *arg, void *data, int flags);
01363 
01364 /* Realtime device support */
01365 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);
01366 static void update_peer(struct sip_peer *p, int expire);
01367 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
01368 static const char *get_name_from_variable(const struct ast_variable *var);
01369 static struct sip_peer *realtime_peer(const char *peername, struct ast_sockaddr *sin, char *callbackexten, int devstate_only, int which_objects);
01370 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01371 
01372 /*--- Internal UA client handling (outbound registrations) */
01373 static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p);
01374 static void sip_registry_destroy(void *reg);
01375 static int sip_register(const char *value, int lineno);
01376 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
01377 static int sip_reregister(const void *data);
01378 static int __sip_do_register(struct sip_registry *r);
01379 static int sip_reg_timeout(const void *data);
01380 static void sip_send_all_registers(void);
01381 static int sip_reinvite_retry(const void *data);
01382 
01383 /*--- Parsing SIP requests and responses */
01384 static int determine_firstline_parts(struct sip_request *req);
01385 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
01386 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
01387 static int find_sip_method(const char *msg);
01388 static unsigned int parse_allowed_methods(struct sip_request *req);
01389 static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req);
01390 static int parse_request(struct sip_request *req);
01391 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
01392 static int method_match(enum sipmethod id, const char *name);
01393 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
01394 static void parse_oli(struct sip_request *req, struct ast_channel *chan);
01395 static const char *find_alias(const char *name, const char *_default);
01396 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
01397 static void lws2sws(struct ast_str *msgbuf);
01398 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
01399 static char *remove_uri_parameters(char *uri);
01400 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
01401 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
01402 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
01403 static int set_address_from_contact(struct sip_pvt *pvt);
01404 static void check_via(struct sip_pvt *p, const struct sip_request *req);
01405 static int get_rpid(struct sip_pvt *p, struct sip_request *oreq);
01406 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason, char **reason_str);
01407 static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id);
01408 static int transmit_state_notify(struct sip_pvt *p, struct state_notify_data *data, int full, int timeout);
01409 static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen);
01410 static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen);
01411 static int get_domain(const char *str, char *domain, int len);
01412 static void get_realm(struct sip_pvt *p, const struct sip_request *req);
01413 static char *get_content(struct sip_request *req);
01414 
01415 /*-- TCP connection handling ---*/
01416 static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session);
01417 static void *sip_tcp_worker_fn(void *);
01418 
01419 /*--- Constructing requests and responses */
01420 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
01421 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
01422 static void deinit_req(struct sip_request *req);
01423 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, uint32_t seqno, int newbranch);
01424 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri);
01425 static int init_resp(struct sip_request *resp, const char *msg);
01426 static inline int resp_needs_contact(const char *msg, enum sipmethod method);
01427 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
01428 static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p);
01429 static void build_via(struct sip_pvt *p);
01430 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
01431 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog);
01432 static char *generate_random_string(char *buf, size_t size);
01433 static void build_callid_pvt(struct sip_pvt *pvt);
01434 static void change_callid_pvt(struct sip_pvt *pvt, const char *callid);
01435 static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain);
01436 static void build_localtag_registry(struct sip_registry *reg);
01437 static void make_our_tag(struct sip_pvt *pvt);
01438 static int add_header(struct sip_request *req, const char *var, const char *value);
01439 static int add_max_forwards(struct sip_pvt *dialog, struct sip_request *req);
01440 static int add_content(struct sip_request *req, const char *line);
01441 static int finalize_content(struct sip_request *req);
01442 static void destroy_msg_headers(struct sip_pvt *pvt);
01443 static int add_text(struct sip_request *req, struct sip_pvt *p);
01444 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
01445 static int add_rpid(struct sip_request *req, struct sip_pvt *p);
01446 static int add_vidupdate(struct sip_request *req);
01447 static void add_route(struct sip_request *req, struct sip_route *route, int skip);
01448 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
01449 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
01450 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
01451 static void set_destination(struct sip_pvt *p, const char *uri);
01452 static void add_date(struct sip_request *req);
01453 static void add_expires(struct sip_request *req, int expires);
01454 static void build_contact(struct sip_pvt *p, struct sip_request *req, int incoming);
01455 
01456 /*------Request handling functions */
01457 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock);
01458 static int handle_request_update(struct sip_pvt *p, struct sip_request *req);
01459 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);
01460 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, uint32_t seqno, int *nounlock);
01461 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
01462 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *sin, const char *e);
01463 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
01464 static int handle_request_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
01465 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
01466 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
01467 static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
01468 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req,
01469       int *nounlock, struct sip_pvt *replaces_pvt, struct ast_channel *replaces_chan);
01470 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
01471 static int local_attended_transfer(struct sip_pvt *transferer, struct ast_channel *transferer_chan, uint32_t seqno, int *nounlock);
01472 
01473 /*------Response handling functions */
01474 static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01475 static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01476 static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01477 static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01478 static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01479 static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01480 static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01481 
01482 /*------ SRTP Support -------- */
01483 static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct ast_sdp_srtp **srtp, const char *a);
01484 
01485 /*------ T38 Support --------- */
01486 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
01487 static void change_t38_state(struct sip_pvt *p, int state);
01488 
01489 /*------ Session-Timers functions --------- */
01490 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
01491 static int  proc_session_timer(const void *vp);
01492 static void stop_session_timer(struct sip_pvt *p);
01493 static void start_session_timer(struct sip_pvt *p);
01494 static void restart_session_timer(struct sip_pvt *p);
01495 static const char *strefresherparam2str(enum st_refresher_param r);
01496 static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher_param *const p_ref);
01497 static int parse_minse(const char *p_hdrval, int *const p_interval);
01498 static int st_get_se(struct sip_pvt *, int max);
01499 static enum st_refresher st_get_refresher(struct sip_pvt *);
01500 static enum st_mode st_get_mode(struct sip_pvt *, int no_cached);
01501 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
01502 
01503 /*------- RTP Glue functions -------- */
01504 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);
01505 
01506 /*!--- SIP MWI Subscription support */
01507 static int sip_subscribe_mwi(const char *value, int lineno);
01508 static void sip_subscribe_mwi_destroy(void *data);
01509 static void sip_send_all_mwi_subscriptions(void);
01510 static int sip_subscribe_mwi_do(const void *data);
01511 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
01512 
01513 /*! \brief Definition of this channel for PBX channel registration */
01514 struct ast_channel_tech sip_tech = {
01515    .type = "SIP",
01516    .description = "Session Initiation Protocol (SIP)",
01517    .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
01518    .requester = sip_request_call,         /* called with chan unlocked */
01519    .devicestate = sip_devicestate,        /* called with chan unlocked (not chan-specific) */
01520    .call = sip_call,       /* called with chan locked */
01521    .send_html = sip_sendhtml,
01522    .hangup = sip_hangup,         /* called with chan locked */
01523    .answer = sip_answer,         /* called with chan locked */
01524    .read = sip_read,       /* called with chan locked */
01525    .write = sip_write,        /* called with chan locked */
01526    .write_video = sip_write,     /* called with chan locked */
01527    .write_text = sip_write,
01528    .indicate = sip_indicate,     /* called with chan locked */
01529    .transfer = sip_transfer,     /* called with chan locked */
01530    .fixup = sip_fixup,        /* called with chan locked */
01531    .send_digit_begin = sip_senddigit_begin,  /* called with chan unlocked */
01532    .send_digit_end = sip_senddigit_end,
01533    .early_bridge = ast_rtp_instance_early_bridge,
01534    .send_text = sip_sendtext,    /* called with chan locked */
01535    .func_channel_read = sip_acf_channel_read,
01536    .setoption = sip_setoption,
01537    .queryoption = sip_queryoption,
01538    .get_pvt_uniqueid = sip_get_callid,
01539 };
01540 
01541 /*! \brief This version of the sip channel tech has no send_digit_begin
01542  * callback so that the core knows that the channel does not want
01543  * DTMF BEGIN frames.
01544  * The struct is initialized just before registering the channel driver,
01545  * and is for use with channels using SIP INFO DTMF.
01546  */
01547 struct ast_channel_tech sip_tech_info;
01548 
01549 /*------- CC Support -------- */
01550 static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan);
01551 static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent);
01552 static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent);
01553 static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason);
01554 static int sip_cc_agent_status_request(struct ast_cc_agent *agent);
01555 static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent);
01556 static int sip_cc_agent_recall(struct ast_cc_agent *agent);
01557 static void sip_cc_agent_destructor(struct ast_cc_agent *agent);
01558 
01559 static struct ast_cc_agent_callbacks sip_cc_agent_callbacks = {
01560    .type = "SIP",
01561    .init = sip_cc_agent_init,
01562    .start_offer_timer = sip_cc_agent_start_offer_timer,
01563    .stop_offer_timer = sip_cc_agent_stop_offer_timer,
01564    .respond = sip_cc_agent_respond,
01565    .status_request = sip_cc_agent_status_request,
01566    .start_monitoring = sip_cc_agent_start_monitoring,
01567    .callee_available = sip_cc_agent_recall,
01568    .destructor = sip_cc_agent_destructor,
01569 };
01570 
01571 /* -------- End of declarations of structures, constants and forward declarations of functions
01572    Below starts actual code
01573    ------------------------
01574 */
01575 
01576 static int sip_epa_register(const struct epa_static_data *static_data)
01577 {
01578    struct epa_backend *backend = ast_calloc(1, sizeof(*backend));
01579 
01580    if (!backend) {
01581       return -1;
01582    }
01583 
01584    backend->static_data = static_data;
01585 
01586    AST_LIST_LOCK(&epa_static_data_list);
01587    AST_LIST_INSERT_TAIL(&epa_static_data_list, backend, next);
01588    AST_LIST_UNLOCK(&epa_static_data_list);
01589    return 0;
01590 }
01591 
01592 static void sip_epa_unregister_all(void)
01593 {
01594    struct epa_backend *backend;
01595 
01596    AST_LIST_LOCK(&epa_static_data_list);
01597    while ((backend = AST_LIST_REMOVE_HEAD(&epa_static_data_list, next))) {
01598       ast_free(backend);
01599    }
01600    AST_LIST_UNLOCK(&epa_static_data_list);
01601 }
01602 
01603 static void cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry);
01604 
01605 static void cc_epa_destructor(void *data)
01606 {
01607    struct sip_epa_entry *epa_entry = data;
01608    struct cc_epa_entry *cc_entry = epa_entry->instance_data;
01609    ast_free(cc_entry);
01610 }
01611 
01612 static const struct epa_static_data cc_epa_static_data  = {
01613    .event = CALL_COMPLETION,
01614    .name = "call-completion",
01615    .handle_error = cc_handle_publish_error,
01616    .destructor = cc_epa_destructor,
01617 };
01618 
01619 static const struct epa_static_data *find_static_data(const char * const event_package)
01620 {
01621    const struct epa_backend *backend = NULL;
01622 
01623    AST_LIST_LOCK(&epa_static_data_list);
01624    AST_LIST_TRAVERSE(&epa_static_data_list, backend, next) {
01625       if (!strcmp(backend->static_data->name, event_package)) {
01626          break;
01627       }
01628    }
01629    AST_LIST_UNLOCK(&epa_static_data_list);
01630    return backend ? backend->static_data : NULL;
01631 }
01632 
01633 static struct sip_epa_entry *create_epa_entry (const char * const event_package, const char * const destination)
01634 {
01635    struct sip_epa_entry *epa_entry;
01636    const struct epa_static_data *static_data;
01637 
01638    if (!(static_data = find_static_data(event_package))) {
01639       return NULL;
01640    }
01641 
01642    if (!(epa_entry = ao2_t_alloc(sizeof(*epa_entry), static_data->destructor, "Allocate new EPA entry"))) {
01643       return NULL;
01644    }
01645 
01646    epa_entry->static_data = static_data;
01647    ast_copy_string(epa_entry->destination, destination, sizeof(epa_entry->destination));
01648    return epa_entry;
01649 }
01650 static enum ast_cc_service_type service_string_to_service_type(const char * const service_string)
01651 {
01652    enum ast_cc_service_type service;
01653    for (service = AST_CC_CCBS; service <= AST_CC_CCNL; ++service) {
01654       if (!strcasecmp(service_string, sip_cc_service_map[service].service_string)) {
01655          return service;
01656       }
01657    }
01658    return AST_CC_NONE;
01659 }
01660 
01661 /* Even state compositors code */
01662 static void esc_entry_destructor(void *obj)
01663 {
01664    struct sip_esc_entry *esc_entry = obj;
01665    if (esc_entry->sched_id > -1) {
01666       AST_SCHED_DEL(sched, esc_entry->sched_id);
01667    }
01668 }
01669 
01670 static int esc_hash_fn(const void *obj, const int flags)
01671 {
01672    const struct sip_esc_entry *entry = obj;
01673    return ast_str_hash(entry->entity_tag);
01674 }
01675 
01676 static int esc_cmp_fn(void *obj, void *arg, int flags)
01677 {
01678    struct sip_esc_entry *entry1 = obj;
01679    struct sip_esc_entry *entry2 = arg;
01680 
01681    return (!strcmp(entry1->entity_tag, entry2->entity_tag)) ? (CMP_MATCH | CMP_STOP) : 0;
01682 }
01683 
01684 static struct event_state_compositor *get_esc(const char * const event_package) {
01685    int i;
01686    for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
01687       if (!strcasecmp(event_package, event_state_compositors[i].name)) {
01688          return &event_state_compositors[i];
01689       }
01690    }
01691    return NULL;
01692 }
01693 
01694 static struct sip_esc_entry *get_esc_entry(const char * entity_tag, struct event_state_compositor *esc) {
01695    struct sip_esc_entry *entry;
01696    struct sip_esc_entry finder;
01697 
01698    ast_copy_string(finder.entity_tag, entity_tag, sizeof(finder.entity_tag));
01699 
01700    entry = ao2_find(esc->compositor, &finder, OBJ_POINTER);
01701 
01702    return entry;
01703 }
01704 
01705 static int publish_expire(const void *data)
01706 {
01707    struct sip_esc_entry *esc_entry = (struct sip_esc_entry *) data;
01708    struct event_state_compositor *esc = get_esc(esc_entry->event);
01709 
01710    ast_assert(esc != NULL);
01711 
01712    ao2_unlink(esc->compositor, esc_entry);
01713    ao2_ref(esc_entry, -1);
01714    return 0;
01715 }
01716 
01717 static void create_new_sip_etag(struct sip_esc_entry *esc_entry, int is_linked)
01718 {
01719    int new_etag = ast_atomic_fetchadd_int(&esc_etag_counter, +1);
01720    struct event_state_compositor *esc = get_esc(esc_entry->event);
01721 
01722    ast_assert(esc != NULL);
01723    if (is_linked) {
01724       ao2_unlink(esc->compositor, esc_entry);
01725    }
01726    snprintf(esc_entry->entity_tag, sizeof(esc_entry->entity_tag), "%d", new_etag);
01727    ao2_link(esc->compositor, esc_entry);
01728 }
01729 
01730 static struct sip_esc_entry *create_esc_entry(struct event_state_compositor *esc, struct sip_request *req, const int expires)
01731 {
01732    struct sip_esc_entry *esc_entry;
01733    int expires_ms;
01734 
01735    if (!(esc_entry = ao2_alloc(sizeof(*esc_entry), esc_entry_destructor))) {
01736       return NULL;
01737    }
01738 
01739    esc_entry->event = esc->name;
01740 
01741    expires_ms = expires * 1000;
01742    /* Bump refcount for scheduler */
01743    ao2_ref(esc_entry, +1);
01744    esc_entry->sched_id = ast_sched_add(sched, expires_ms, publish_expire, esc_entry);
01745 
01746    /* Note: This links the esc_entry into the ESC properly */
01747    create_new_sip_etag(esc_entry, 0);
01748 
01749    return esc_entry;
01750 }
01751 
01752 static int initialize_escs(void)
01753 {
01754    int i, res = 0;
01755    for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
01756       if (!((event_state_compositors[i].compositor) =
01757                ao2_container_alloc(ESC_MAX_BUCKETS, esc_hash_fn, esc_cmp_fn))) {
01758          res = -1;
01759       }
01760    }
01761    return res;
01762 }
01763 
01764 static void destroy_escs(void)
01765 {
01766    int i;
01767    for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
01768       ao2_cleanup(event_state_compositors[i].compositor);
01769    }
01770 }
01771 
01772 
01773 static int find_by_notify_uri_helper(void *obj, void *arg, int flags)
01774 {
01775    struct ast_cc_agent *agent = obj;
01776    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01777    const char *uri = arg;
01778 
01779    return !sip_uri_cmp(agent_pvt->notify_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
01780 }
01781 
01782 static struct ast_cc_agent *find_sip_cc_agent_by_notify_uri(const char * const uri)
01783 {
01784    struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_notify_uri_helper, (char *)uri, "SIP");
01785    return agent;
01786 }
01787 
01788 static int find_by_subscribe_uri_helper(void *obj, void *arg, int flags)
01789 {
01790    struct ast_cc_agent *agent = obj;
01791    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01792    const char *uri = arg;
01793 
01794    return !sip_uri_cmp(agent_pvt->subscribe_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
01795 }
01796 
01797 static struct ast_cc_agent *find_sip_cc_agent_by_subscribe_uri(const char * const uri)
01798 {
01799    struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_subscribe_uri_helper, (char *)uri, "SIP");
01800    return agent;
01801 }
01802 
01803 static int find_by_callid_helper(void *obj, void *arg, int flags)
01804 {
01805    struct ast_cc_agent *agent = obj;
01806    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01807    struct sip_pvt *call_pvt = arg;
01808 
01809    return !strcmp(agent_pvt->original_callid, call_pvt->callid) ? CMP_MATCH | CMP_STOP : 0;
01810 }
01811 
01812 static struct ast_cc_agent *find_sip_cc_agent_by_original_callid(struct sip_pvt *pvt)
01813 {
01814    struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_callid_helper, pvt, "SIP");
01815    return agent;
01816 }
01817 
01818 static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan)
01819 {
01820    struct sip_cc_agent_pvt *agent_pvt = ast_calloc(1, sizeof(*agent_pvt));
01821    struct sip_pvt *call_pvt = ast_channel_tech_pvt(chan);
01822 
01823    if (!agent_pvt) {
01824       return -1;
01825    }
01826 
01827    ast_assert(!strcmp(ast_channel_tech(chan)->type, "SIP"));
01828 
01829    ast_copy_string(agent_pvt->original_callid, call_pvt->callid, sizeof(agent_pvt->original_callid));
01830    ast_copy_string(agent_pvt->original_exten, call_pvt->exten, sizeof(agent_pvt->original_exten));
01831    agent_pvt->offer_timer_id = -1;
01832    agent->private_data = agent_pvt;
01833    sip_pvt_lock(call_pvt);
01834    ast_set_flag(&call_pvt->flags[0], SIP_OFFER_CC);
01835    sip_pvt_unlock(call_pvt);
01836    return 0;
01837 }
01838 
01839 static int sip_offer_timer_expire(const void *data)
01840 {
01841    struct ast_cc_agent *agent = (struct ast_cc_agent *) data;
01842    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01843 
01844    agent_pvt->offer_timer_id = -1;
01845 
01846    return ast_cc_failed(agent->core_id, "SIP agent %s's offer timer expired", agent->device_name);
01847 }
01848 
01849 static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent)
01850 {
01851    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01852    int when;
01853 
01854    when = ast_get_cc_offer_timer(agent->cc_params) * 1000;
01855    agent_pvt->offer_timer_id = ast_sched_add(sched, when, sip_offer_timer_expire, agent);
01856    return 0;
01857 }
01858 
01859 static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent)
01860 {
01861    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01862 
01863    AST_SCHED_DEL(sched, agent_pvt->offer_timer_id);
01864    return 0;
01865 }
01866 
01867 static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason)
01868 {
01869    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01870 
01871    sip_pvt_lock(agent_pvt->subscribe_pvt);
01872    ast_set_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
01873    if (reason == AST_CC_AGENT_RESPONSE_SUCCESS || !ast_strlen_zero(agent_pvt->notify_uri)) {
01874       /* The second half of this if statement may be a bit hard to grasp,
01875        * so here's an explanation. When a subscription comes into
01876        * chan_sip, as long as it is not malformed, it will be passed
01877        * to the CC core. If the core senses an out-of-order state transition,
01878        * then the core will call this callback with the "reason" set to a
01879        * failure condition.
01880        * However, an out-of-order state transition will occur during a resubscription
01881        * for CC. In such a case, we can see that we have already generated a notify_uri
01882        * and so we can detect that this isn't a *real* failure. Rather, it is just
01883        * something the core doesn't recognize as a legitimate SIP state transition.
01884        * Thus we respond with happiness and flowers.
01885        */
01886       transmit_response(agent_pvt->subscribe_pvt, "200 OK", &agent_pvt->subscribe_pvt->initreq);
01887       transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_QUEUED);
01888    } else {
01889       transmit_response(agent_pvt->subscribe_pvt, "500 Internal Error", &agent_pvt->subscribe_pvt->initreq);
01890    }
01891    sip_pvt_unlock(agent_pvt->subscribe_pvt);
01892    agent_pvt->is_available = TRUE;
01893 }
01894 
01895 static int sip_cc_agent_status_request(struct ast_cc_agent *agent)
01896 {
01897    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01898    enum ast_device_state state = agent_pvt->is_available ? AST_DEVICE_NOT_INUSE : AST_DEVICE_INUSE;
01899    return ast_cc_agent_status_response(agent->core_id, state);
01900 }
01901 
01902 static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent)
01903 {
01904    /* To start monitoring just means to wait for an incoming PUBLISH
01905     * to tell us that the caller has become available again. No special
01906     * action is needed
01907     */
01908    return 0;
01909 }
01910 
01911 static int sip_cc_agent_recall(struct ast_cc_agent *agent)
01912 {
01913    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01914    /* If we have received a PUBLISH beforehand stating that the caller in question
01915     * is not available, we can save ourself a bit of effort here and just report
01916     * the caller as busy
01917     */
01918    if (!agent_pvt->is_available) {
01919       return ast_cc_agent_caller_busy(agent->core_id, "Caller %s is busy, reporting to the core",
01920             agent->device_name);
01921    }
01922    /* Otherwise, we transmit a NOTIFY to the caller and await either
01923     * a PUBLISH or an INVITE
01924     */
01925    sip_pvt_lock(agent_pvt->subscribe_pvt);
01926    transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_READY);
01927    sip_pvt_unlock(agent_pvt->subscribe_pvt);
01928    return 0;
01929 }
01930 
01931 static void sip_cc_agent_destructor(struct ast_cc_agent *agent)
01932 {
01933    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01934 
01935    if (!agent_pvt) {
01936       /* The agent constructor probably failed. */
01937       return;
01938    }
01939 
01940    sip_cc_agent_stop_offer_timer(agent);
01941    if (agent_pvt->subscribe_pvt) {
01942       sip_pvt_lock(agent_pvt->subscribe_pvt);
01943       if (!ast_test_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
01944          /* If we haven't sent a 200 OK for the SUBSCRIBE dialog yet, then we need to send a response letting
01945           * the subscriber know something went wrong
01946           */
01947          transmit_response(agent_pvt->subscribe_pvt, "500 Internal Server Error", &agent_pvt->subscribe_pvt->initreq);
01948       }
01949       sip_pvt_unlock(agent_pvt->subscribe_pvt);
01950       agent_pvt->subscribe_pvt = dialog_unref(agent_pvt->subscribe_pvt, "SIP CC agent destructor: Remove ref to subscription");
01951    }
01952    ast_free(agent_pvt);
01953 }
01954 
01955 
01956 static int sip_monitor_instance_hash_fn(const void *obj, const int flags)
01957 {
01958    const struct sip_monitor_instance *monitor_instance = obj;
01959    return monitor_instance->core_id;
01960 }
01961 
01962 static int sip_monitor_instance_cmp_fn(void *obj, void *arg, int flags)
01963 {
01964    struct sip_monitor_instance *monitor_instance1 = obj;
01965    struct sip_monitor_instance *monitor_instance2 = arg;
01966 
01967    return monitor_instance1->core_id == monitor_instance2->core_id ? CMP_MATCH | CMP_STOP : 0;
01968 }
01969 
01970 static void sip_monitor_instance_destructor(void *data)
01971 {
01972    struct sip_monitor_instance *monitor_instance = data;
01973    if (monitor_instance->subscription_pvt) {
01974       sip_pvt_lock(monitor_instance->subscription_pvt);
01975       monitor_instance->subscription_pvt->expiry = 0;
01976       transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 0, monitor_instance->subscribe_uri);
01977       sip_pvt_unlock(monitor_instance->subscription_pvt);
01978       dialog_unref(monitor_instance->subscription_pvt, "Unref monitor instance ref of subscription pvt");
01979    }
01980    if (monitor_instance->suspension_entry) {
01981       monitor_instance->suspension_entry->body[0] = '\0';
01982       transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_REMOVE ,monitor_instance->notify_uri);
01983       ao2_t_ref(monitor_instance->suspension_entry, -1, "Decrementing suspension entry refcount in sip_monitor_instance_destructor");
01984    }
01985    ast_string_field_free_memory(monitor_instance);
01986 }
01987 
01988 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)
01989 {
01990    struct sip_monitor_instance *monitor_instance = ao2_alloc(sizeof(*monitor_instance), sip_monitor_instance_destructor);
01991 
01992    if (!monitor_instance) {
01993       return NULL;
01994    }
01995 
01996    if (ast_string_field_init(monitor_instance, 256)) {
01997       ao2_ref(monitor_instance, -1);
01998       return NULL;
01999    }
02000 
02001    ast_string_field_set(monitor_instance, subscribe_uri, subscribe_uri);
02002    ast_string_field_set(monitor_instance, peername, peername);
02003    ast_string_field_set(monitor_instance, device_name, device_name);
02004    monitor_instance->core_id = core_id;
02005    ao2_link(sip_monitor_instances, monitor_instance);
02006    return monitor_instance;
02007 }
02008 
02009 static int find_sip_monitor_instance_by_subscription_pvt(void *obj, void *arg, int flags)
02010 {
02011    struct sip_monitor_instance *monitor_instance = obj;
02012    return monitor_instance->subscription_pvt == arg ? CMP_MATCH | CMP_STOP : 0;
02013 }
02014 
02015 static int find_sip_monitor_instance_by_suspension_entry(void *obj, void *arg, int flags)
02016 {
02017    struct sip_monitor_instance *monitor_instance = obj;
02018    return monitor_instance->suspension_entry == arg ? CMP_MATCH | CMP_STOP : 0;
02019 }
02020 
02021 static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id);
02022 static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor);
02023 static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor);
02024 static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id);
02025 static void sip_cc_monitor_destructor(void *private_data);
02026 
02027 static struct ast_cc_monitor_callbacks sip_cc_monitor_callbacks = {
02028    .type = "SIP",
02029    .request_cc = sip_cc_monitor_request_cc,
02030    .suspend = sip_cc_monitor_suspend,
02031    .unsuspend = sip_cc_monitor_unsuspend,
02032    .cancel_available_timer = sip_cc_monitor_cancel_available_timer,
02033    .destructor = sip_cc_monitor_destructor,
02034 };
02035 
02036 static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id)
02037 {
02038    struct sip_monitor_instance *monitor_instance = monitor->private_data;
02039    enum ast_cc_service_type service = monitor->service_offered;
02040    int when;
02041 
02042    if (!monitor_instance) {
02043       return -1;
02044    }
02045 
02046    if (!(monitor_instance->subscription_pvt = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL, 0))) {
02047       return -1;
02048    }
02049 
02050    when = service == AST_CC_CCBS ? ast_get_ccbs_available_timer(monitor->interface->config_params) :
02051       ast_get_ccnr_available_timer(monitor->interface->config_params);
02052 
02053    sip_pvt_lock(monitor_instance->subscription_pvt);
02054    ast_set_flag(&monitor_instance->subscription_pvt->flags[0], SIP_OUTGOING);
02055    create_addr(monitor_instance->subscription_pvt, monitor_instance->peername, 0, 1);
02056    ast_sip_ouraddrfor(&monitor_instance->subscription_pvt->sa, &monitor_instance->subscription_pvt->ourip, monitor_instance->subscription_pvt);
02057    monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
02058    monitor_instance->subscription_pvt->expiry = when;
02059 
02060    transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 2, monitor_instance->subscribe_uri);
02061    sip_pvt_unlock(monitor_instance->subscription_pvt);
02062 
02063    ao2_t_ref(monitor, +1, "Adding a ref to the monitor for the scheduler");
02064    *available_timer_id = ast_sched_add(sched, when * 1000, ast_cc_available_timer_expire, monitor);
02065    return 0;
02066 }
02067 
02068 static int construct_pidf_body(enum sip_cc_publish_state state, char *pidf_body, size_t size, const char *presentity)
02069 {
02070    struct ast_str *body = ast_str_alloca(size);
02071    char tuple_id[32];
02072 
02073    generate_random_string(tuple_id, sizeof(tuple_id));
02074 
02075    /* We'll make this a bare-bones pidf body. In state_notify_build_xml, the PIDF
02076     * body gets a lot more extra junk that isn't necessary, so we'll leave it out here.
02077     */
02078    ast_str_append(&body, 0, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
02079    /* XXX The entity attribute is currently set to the peer name associated with the
02080     * dialog. This is because we currently only call this function for call-completion
02081     * PUBLISH bodies. In such cases, the entity is completely disregarded. For other
02082     * event packages, it may be crucial to have a proper URI as the presentity so this
02083     * should be revisited as support is expanded.
02084     */
02085    ast_str_append(&body, 0, "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" entity=\"%s\">\n", presentity);
02086    ast_str_append(&body, 0, "<tuple id=\"%s\">\n", tuple_id);
02087    ast_str_append(&body, 0, "<status><basic>%s</basic></status>\n", state == CC_OPEN ? "open" : "closed");
02088    ast_str_append(&body, 0, "</tuple>\n");
02089    ast_str_append(&body, 0, "</presence>\n");
02090    ast_copy_string(pidf_body, ast_str_buffer(body), size);
02091    return 0;
02092 }
02093 
02094 static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor)
02095 {
02096    struct sip_monitor_instance *monitor_instance = monitor->private_data;
02097    enum sip_publish_type publish_type;
02098    struct cc_epa_entry *cc_entry;
02099 
02100    if (!monitor_instance) {
02101       return -1;
02102    }
02103 
02104    if (!monitor_instance->suspension_entry) {
02105       /* We haven't yet allocated the suspension entry, so let's give it a shot */
02106       if (!(monitor_instance->suspension_entry = create_epa_entry("call-completion", monitor_instance->peername))) {
02107          ast_log(LOG_WARNING, "Unable to allocate sip EPA entry for call-completion\n");
02108          ao2_ref(monitor_instance, -1);
02109          return -1;
02110       }
02111       if (!(cc_entry = ast_calloc(1, sizeof(*cc_entry)))) {
02112          ast_log(LOG_WARNING, "Unable to allocate space for instance data of EPA entry for call-completion\n");
02113          ao2_ref(monitor_instance, -1);
02114          return -1;
02115       }
02116       cc_entry->core_id = monitor->core_id;
02117       monitor_instance->suspension_entry->instance_data = cc_entry;
02118       publish_type = SIP_PUBLISH_INITIAL;
02119    } else {
02120       publish_type = SIP_PUBLISH_MODIFY;
02121       cc_entry = monitor_instance->suspension_entry->instance_data;
02122    }
02123 
02124    cc_entry->current_state = CC_CLOSED;
02125 
02126    if (ast_strlen_zero(monitor_instance->notify_uri)) {
02127       /* If we have no set notify_uri, then what this means is that we have
02128        * not received a NOTIFY from this destination stating that he is
02129        * currently available.
02130        *
02131        * This situation can arise when the core calls the suspend callbacks
02132        * of multiple destinations. If one of the other destinations aside
02133        * from this one notified Asterisk that he is available, then there
02134        * is no reason to take any suspension action on this device. Rather,
02135        * we should return now and if we receive a NOTIFY while monitoring
02136        * is still "suspended" then we can immediately respond with the
02137        * proper PUBLISH to let this endpoint know what is going on.
02138        */
02139       return 0;
02140    }
02141    construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
02142    return transmit_publish(monitor_instance->suspension_entry, publish_type, monitor_instance->notify_uri);
02143 }
02144 
02145 static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor)
02146 {
02147    struct sip_monitor_instance *monitor_instance = monitor->private_data;
02148    struct cc_epa_entry *cc_entry;
02149 
02150    if (!monitor_instance) {
02151       return -1;
02152    }
02153 
02154    ast_assert(monitor_instance->suspension_entry != NULL);
02155 
02156    cc_entry = monitor_instance->suspension_entry->instance_data;
02157    cc_entry->current_state = CC_OPEN;
02158    if (ast_strlen_zero(monitor_instance->notify_uri)) {
02159       /* This means we are being asked to unsuspend a call leg we never
02160        * sent a PUBLISH on. As such, there is no reason to send another
02161        * PUBLISH at this point either. We can just return instead.
02162        */
02163       return 0;
02164    }
02165    construct_pidf_body(CC_OPEN, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
02166    return transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_MODIFY, monitor_instance->notify_uri);
02167 }
02168 
02169 static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id)
02170 {
02171    if (*sched_id != -1) {
02172       AST_SCHED_DEL(sched, *sched_id);
02173       ao2_t_ref(monitor, -1, "Removing scheduler's reference to the monitor");
02174    }
02175    return 0;
02176 }
02177 
02178 static void sip_cc_monitor_destructor(void *private_data)
02179 {
02180    struct sip_monitor_instance *monitor_instance = private_data;
02181    ao2_unlink(sip_monitor_instances, monitor_instance);
02182    ast_module_unref(ast_module_info->self);
02183 }
02184 
02185 static int sip_get_cc_information(struct sip_request *req, char *subscribe_uri, size_t size, enum ast_cc_service_type *service)
02186 {
02187    char *call_info = ast_strdupa(sip_get_header(req, "Call-Info"));
02188    char *uri;
02189    char *purpose;
02190    char *service_str;
02191    static const char cc_purpose[] = "purpose=call-completion";
02192    static const int cc_purpose_len = sizeof(cc_purpose) - 1;
02193 
02194    if (ast_strlen_zero(call_info)) {
02195       /* No Call-Info present. Definitely no CC offer */
02196       return -1;
02197    }
02198 
02199    uri = strsep(&call_info, ";");
02200 
02201    while ((purpose = strsep(&call_info, ";"))) {
02202       if (!strncmp(purpose, cc_purpose, cc_purpose_len)) {
02203          break;
02204       }
02205    }
02206    if (!purpose) {
02207       /* We didn't find the appropriate purpose= parameter. Oh well */
02208       return -1;
02209    }
02210 
02211    /* Okay, call-completion has been offered. Let's figure out what type of service this is */
02212    while ((service_str = strsep(&call_info, ";"))) {
02213       if (!strncmp(service_str, "m=", 2)) {
02214          break;
02215       }
02216    }
02217    if (!service_str) {
02218       /* So they didn't offer a particular service, We'll just go with CCBS since it really
02219        * doesn't matter anyway
02220        */
02221       service_str = "BS";
02222    } else {
02223       /* We already determined that there is an "m=" so no need to check
02224        * the result of this strsep
02225        */
02226       strsep(&service_str, "=");
02227    }
02228 
02229    if ((*service = service_string_to_service_type(service_str)) == AST_CC_NONE) {
02230       /* Invalid service offered */
02231       return -1;
02232    }
02233 
02234    ast_copy_string(subscribe_uri, get_in_brackets(uri), size);
02235 
02236    return 0;
02237 }
02238 
02239 /*
02240  * \brief Determine what, if any, CC has been offered and queue a CC frame if possible
02241  *
02242  * After taking care of some formalities to be sure that this call is eligible for CC,
02243  * we first try to see if we can make use of native CC. We grab the information from
02244  * the passed-in sip_request (which is always a response to an INVITE). If we can
02245  * use native CC monitoring for the call, then so be it.
02246  *
02247  * If native cc monitoring is not possible or not supported, then we will instead attempt
02248  * to use generic monitoring. Falling back to generic from a failed attempt at using native
02249  * monitoring will only work if the monitor policy of the endpoint is "always"
02250  *
02251  * \param pvt The current dialog. Contains CC parameters for the endpoint
02252  * \param req The response to the INVITE we want to inspect
02253  * \param service The service to use if generic monitoring is to be used. For native
02254  * monitoring, we get the service from the SIP response itself
02255  */
02256 static void sip_handle_cc(struct sip_pvt *pvt, struct sip_request *req, enum ast_cc_service_type service)
02257 {
02258    enum ast_cc_monitor_policies monitor_policy = ast_get_cc_monitor_policy(pvt->cc_params);
02259    int core_id;
02260    char interface_name[AST_CHANNEL_NAME];
02261 
02262    if (monitor_policy == AST_CC_MONITOR_NEVER) {
02263       /* Don't bother, just return */
02264       return;
02265    }
02266 
02267    if ((core_id = ast_cc_get_current_core_id(pvt->owner)) == -1) {
02268       /* For some reason, CC is invalid, so don't try it! */
02269       return;
02270    }
02271 
02272    ast_channel_get_device_name(pvt->owner, interface_name, sizeof(interface_name));
02273 
02274    if (monitor_policy == AST_CC_MONITOR_ALWAYS || monitor_policy == AST_CC_MONITOR_NATIVE) {
02275       char subscribe_uri[SIPBUFSIZE];
02276       char device_name[AST_CHANNEL_NAME];
02277       enum ast_cc_service_type offered_service;
02278       struct sip_monitor_instance *monitor_instance;
02279       if (sip_get_cc_information(req, subscribe_uri, sizeof(subscribe_uri), &offered_service)) {
02280          /* If CC isn't being offered to us, or for some reason the CC offer is
02281           * not formatted correctly, then it may still be possible to use generic
02282           * call completion since the monitor policy may be "always"
02283           */
02284          goto generic;
02285       }
02286       ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
02287       if (!(monitor_instance = sip_monitor_instance_init(core_id, subscribe_uri, pvt->peername, device_name))) {
02288          /* Same deal. We can try using generic still */
02289          goto generic;
02290       }
02291       /* We bump the refcount of chan_sip because once we queue this frame, the CC core
02292        * will have a reference to callbacks in this module. We decrement the module
02293        * refcount once the monitor destructor is called
02294        */
02295       ast_module_ref(ast_module_info->self);
02296       ast_queue_cc_frame(pvt->owner, "SIP", pvt->dialstring, offered_service, monitor_instance);
02297       ao2_ref(monitor_instance, -1);
02298       return;
02299    }
02300 
02301 generic:
02302    if (monitor_policy == AST_CC_MONITOR_GENERIC || monitor_policy == AST_CC_MONITOR_ALWAYS) {
02303       ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE, interface_name, service, NULL);
02304    }
02305 }
02306 
02307 /*! \brief Working TLS connection configuration */
02308 static struct ast_tls_config sip_tls_cfg;
02309 
02310 /*! \brief Default TLS connection configuration */
02311 static struct ast_tls_config default_tls_cfg;
02312 
02313 /*! \brief Default DTLS connection configuration */
02314 static struct ast_rtp_dtls_cfg default_dtls_cfg;
02315 
02316 /*! \brief The TCP server definition */
02317 static struct ast_tcptls_session_args sip_tcp_desc = {
02318    .accept_fd = -1,
02319    .master = AST_PTHREADT_NULL,
02320    .tls_cfg = NULL,
02321    .poll_timeout = -1,
02322    .name = "SIP TCP server",
02323    .accept_fn = ast_tcptls_server_root,
02324    .worker_fn = sip_tcp_worker_fn,
02325 };
02326 
02327 /*! \brief The TCP/TLS server definition */
02328 static struct ast_tcptls_session_args sip_tls_desc = {
02329    .accept_fd = -1,
02330    .master = AST_PTHREADT_NULL,
02331    .tls_cfg = &sip_tls_cfg,
02332    .poll_timeout = -1,
02333    .name = "SIP TLS server",
02334    .accept_fn = ast_tcptls_server_root,
02335    .worker_fn = sip_tcp_worker_fn,
02336 };
02337 
02338 /*! \brief Append to SIP dialog history
02339    \return Always returns 0 */
02340 #define append_history(p, event, fmt , args... )   append_history_full(p, "%-15s " fmt, event, ## args)
02341 
02342 /*! \brief map from an integer value to a string.
02343  * If no match is found, return errorstring
02344  */
02345 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
02346 {
02347    const struct _map_x_s *cur;
02348 
02349    for (cur = table; cur->s; cur++) {
02350       if (cur->x == x) {
02351          return cur->s;
02352       }
02353    }
02354    return errorstring;
02355 }
02356 
02357 /*! \brief map from a string to an integer value, case insensitive.
02358  * If no match is found, return errorvalue.
02359  */
02360 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
02361 {
02362    const struct _map_x_s *cur;
02363 
02364    for (cur = table; cur->s; cur++) {
02365       if (!strcasecmp(cur->s, s)) {
02366          return cur->x;
02367       }
02368    }
02369    return errorvalue;
02370 }
02371 
02372 static enum AST_REDIRECTING_REASON sip_reason_str_to_code(const char *text)
02373 {
02374    enum AST_REDIRECTING_REASON ast = AST_REDIRECTING_REASON_UNKNOWN;
02375    int i;
02376 
02377    for (i = 0; i < ARRAY_LEN(sip_reason_table); ++i) {
02378       if (!strcasecmp(text, sip_reason_table[i].text)) {
02379          ast = sip_reason_table[i].code;
02380          break;
02381       }
02382    }
02383 
02384    return ast;
02385 }
02386 
02387 static const char *sip_reason_code_to_str(struct ast_party_redirecting_reason *reason, int *table_lookup)
02388 {
02389    int code = reason->code;
02390 
02391    /* If there's a specific string set, then we just
02392     * use it.
02393     */
02394    if (!ast_strlen_zero(reason->str)) {
02395       /* If we care about whether this can be found in
02396        * the table, then we need to check about that.
02397        */
02398       if (table_lookup) {
02399          /* If the string is literally "unknown" then don't bother with the lookup
02400           * because it can lead to a false negative.
02401           */
02402          if (!strcasecmp(reason->str, "unknown") ||
02403                sip_reason_str_to_code(reason->str) != AST_REDIRECTING_REASON_UNKNOWN) {
02404             *table_lookup = TRUE;
02405          } else {
02406             *table_lookup = FALSE;
02407          }
02408       }
02409       return reason->str;
02410    }
02411 
02412    if (table_lookup) {
02413       *table_lookup = TRUE;
02414    }
02415 
02416    if (code >= 0 && code < ARRAY_LEN(sip_reason_table)) {
02417       return sip_reason_table[code].text;
02418    }
02419 
02420    return "unknown";
02421 }
02422 
02423 /*!
02424  * \brief generic function for determining if a correct transport is being
02425  * used to contact a peer
02426  *
02427  * this is done as a macro so that the "tmpl" var can be passed either a
02428  * sip_request or a sip_peer
02429  */
02430 #define check_request_transport(peer, tmpl) ({ \
02431    int ret = 0; \
02432    if (peer->socket.type == tmpl->socket.type) \
02433       ; \
02434    else if (!(peer->transports & tmpl->socket.type)) {\
02435       ast_log(LOG_ERROR, \
02436          "'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
02437          sip_get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
02438          ); \
02439       ret = 1; \
02440    } else if (peer->socket.type & AST_TRANSPORT_TLS) { \
02441       ast_log(LOG_WARNING, \
02442          "peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
02443          peer->name, sip_get_transport(tmpl->socket.type) \
02444       ); \
02445    } else { \
02446       ast_debug(1, \
02447          "peer '%s' has contacted us over %s even though we prefer %s.\n", \
02448          peer->name, sip_get_transport(tmpl->socket.type), sip_get_transport(peer->socket.type) \
02449       ); \
02450    }\
02451    (ret); \
02452 })
02453 
02454 /*! \brief
02455  * duplicate a list of channel variables, \return the copy.
02456  */
02457 static struct ast_variable *copy_vars(struct ast_variable *src)
02458 {
02459    struct ast_variable *res = NULL, *tmp, *v = NULL;
02460 
02461    for (v = src ; v ; v = v->next) {
02462       if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
02463          tmp->next = res;
02464          res = tmp;
02465       }
02466    }
02467    return res;
02468 }
02469 
02470 static void tcptls_packet_destructor(void *obj)
02471 {
02472    struct tcptls_packet *packet = obj;
02473 
02474    ast_free(packet->data);
02475 }
02476 
02477 static void sip_tcptls_client_args_destructor(void *obj)
02478 {
02479    struct ast_tcptls_session_args *args = obj;
02480    if (args->tls_cfg) {
02481       ast_free(args->tls_cfg->certfile);
02482       ast_free(args->tls_cfg->pvtfile);
02483       ast_free(args->tls_cfg->cipher);
02484       ast_free(args->tls_cfg->cafile);
02485       ast_free(args->tls_cfg->capath);
02486 
02487       ast_ssl_teardown(args->tls_cfg);
02488    }
02489    ast_free(args->tls_cfg);
02490    ast_free((char *) args->name);
02491 }
02492 
02493 static void sip_threadinfo_destructor(void *obj)
02494 {
02495    struct sip_threadinfo *th = obj;
02496    struct tcptls_packet *packet;
02497 
02498    if (th->alert_pipe[1] > -1) {
02499       close(th->alert_pipe[0]);
02500    }
02501    if (th->alert_pipe[1] > -1) {
02502       close(th->alert_pipe[1]);
02503    }
02504    th->alert_pipe[0] = th->alert_pipe[1] = -1;
02505 
02506    while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
02507       ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
02508    }
02509 
02510    if (th->tcptls_session) {
02511       ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
02512    }
02513 }
02514 
02515 /*! \brief creates a sip_threadinfo object and links it into the threadt table. */
02516 static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
02517 {
02518    struct sip_threadinfo *th;
02519 
02520    if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
02521       return NULL;
02522    }
02523 
02524    th->alert_pipe[0] = th->alert_pipe[1] = -1;
02525 
02526    if (pipe(th->alert_pipe) == -1) {
02527       ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
02528       ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
02529       return NULL;
02530    }
02531    ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
02532    th->tcptls_session = tcptls_session;
02533    th->type = transport ? transport : (tcptls_session->ssl ? AST_TRANSPORT_TLS: AST_TRANSPORT_TCP);
02534    ao2_t_link(threadt, th, "Adding new tcptls helper thread");
02535    ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
02536    return th;
02537 }
02538 
02539 /*! \brief used to indicate to a tcptls thread that data is ready to be written */
02540 static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
02541 {
02542    int res = len;
02543    struct sip_threadinfo *th = NULL;
02544    struct tcptls_packet *packet = NULL;
02545    struct sip_threadinfo tmp = {
02546       .tcptls_session = tcptls_session,
02547    };
02548    enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
02549 
02550    if (!tcptls_session) {
02551       return XMIT_ERROR;
02552    }
02553 
02554    ao2_lock(tcptls_session);
02555 
02556    if ((tcptls_session->fd == -1) ||
02557       !(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
02558       !(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
02559       !(packet->data = ast_str_create(len))) {
02560       goto tcptls_write_setup_error;
02561    }
02562 
02563    /* goto tcptls_write_error should _NOT_ be used beyond this point */
02564    ast_str_set(&packet->data, 0, "%s", (char *) buf);
02565    packet->len = len;
02566 
02567    /* alert tcptls thread handler that there is a packet to be sent.
02568     * must lock the thread info object to guarantee control of the
02569     * packet queue */
02570    ao2_lock(th);
02571    if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
02572       ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
02573       ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
02574       packet = NULL;
02575       res = XMIT_ERROR;
02576    } else { /* it is safe to queue the frame after issuing the alert when we hold the threadinfo lock */
02577       AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
02578    }
02579    ao2_unlock(th);
02580 
02581    ao2_unlock(tcptls_session);
02582    ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
02583    return res;
02584 
02585 tcptls_write_setup_error:
02586    if (th) {
02587       ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
02588    }
02589    if (packet) {
02590       ao2_t_ref(packet, -1, "could not allocate packet's data");
02591    }
02592    ao2_unlock(tcptls_session);
02593 
02594    return XMIT_ERROR;
02595 }
02596 
02597 /*! \brief SIP TCP connection handler */
02598 static void *sip_tcp_worker_fn(void *data)
02599 {
02600    struct ast_tcptls_session_instance *tcptls_session = data;
02601 
02602    return _sip_tcp_helper_thread(tcptls_session);
02603 }
02604 
02605 /*! \brief SIP WebSocket connection handler */
02606 static void sip_websocket_callback(struct ast_websocket *session, struct ast_variable *parameters, struct ast_variable *headers)
02607 {
02608    int res;
02609 
02610    if (ast_websocket_set_nonblock(session)) {
02611       goto end;
02612    }
02613 
02614    if (ast_websocket_set_timeout(session, sip_cfg.websocket_write_timeout)) {
02615       goto end;
02616    }
02617 
02618    while ((res = ast_wait_for_input(ast_websocket_fd(session), -1)) > 0) {
02619       char *payload;
02620       uint64_t payload_len;
02621       enum ast_websocket_opcode opcode;
02622       int fragmented;
02623 
02624       if (ast_websocket_read(session, &payload, &payload_len, &opcode, &fragmented)) {
02625          /* We err on the side of caution and terminate the session if any error occurs */
02626          break;
02627       }
02628 
02629       if (opcode == AST_WEBSOCKET_OPCODE_TEXT || opcode == AST_WEBSOCKET_OPCODE_BINARY) {
02630          struct sip_request req = { 0, };
02631          char data[payload_len + 1];
02632 
02633          if (!(req.data = ast_str_create(payload_len + 1))) {
02634             goto end;
02635          }
02636 
02637          strncpy(data, payload, payload_len);
02638          data[payload_len] = '\0';
02639 
02640          if (ast_str_set(&req.data, -1, "%s", data) == AST_DYNSTR_BUILD_FAILED) {
02641             deinit_req(&req);
02642             goto end;
02643          }
02644 
02645          req.socket.fd = ast_websocket_fd(session);
02646          set_socket_transport(&req.socket, ast_websocket_is_secure(session) ? AST_TRANSPORT_WSS : AST_TRANSPORT_WS);
02647          req.socket.ws_session = session;
02648 
02649          handle_request_do(&req, ast_websocket_remote_address(session));
02650          deinit_req(&req);
02651 
02652       } else if (opcode == AST_WEBSOCKET_OPCODE_CLOSE) {
02653          break;
02654       }
02655    }
02656 
02657 end:
02658    ast_websocket_unref(session);
02659 }
02660 
02661 /*! \brief Check if the authtimeout has expired.
02662  * \param start the time when the session started
02663  *
02664  * \retval 0 the timeout has expired
02665  * \retval -1 error
02666  * \return the number of milliseconds until the timeout will expire
02667  */
02668 static int sip_check_authtimeout(time_t start)
02669 {
02670    int timeout;
02671    time_t now;
02672    if(time(&now) == -1) {
02673       ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
02674       return -1;
02675    }
02676 
02677    timeout = (authtimeout - (now - start)) * 1000;
02678    if (timeout < 0) {
02679       /* we have timed out */
02680       return 0;
02681    }
02682 
02683    return timeout;
02684 }
02685 
02686 /*!
02687  * \brief Indication of a TCP message's integrity
02688  */
02689 enum message_integrity {
02690    /*!
02691     * The message has an error in it with
02692     * regards to its Content-Length header
02693     */
02694    MESSAGE_INVALID,
02695    /*!
02696     * The message is incomplete
02697     */
02698    MESSAGE_FRAGMENT,
02699    /*!
02700     * The data contains a complete message
02701     * plus a fragment of another.
02702     */
02703    MESSAGE_FRAGMENT_COMPLETE,
02704    /*!
02705     * The message is complete
02706     */
02707    MESSAGE_COMPLETE,
02708 };
02709 
02710 /*!
02711  * \brief
02712  * Get the content length from an unparsed SIP message
02713  *
02714  * \param message The unparsed SIP message headers
02715  * \return The value of the Content-Length header or -1 if message is invalid
02716  */
02717 static int read_raw_content_length(const char *message)
02718 {
02719    char *content_length_str;
02720    int content_length = -1;
02721 
02722    struct ast_str *msg_copy;
02723    char *msg;
02724 
02725    /* Using a ast_str because lws2sws takes one of those */
02726    if (!(msg_copy = ast_str_create(strlen(message) + 1))) {
02727       return -1;
02728    }
02729    ast_str_set(&msg_copy, 0, "%s", message);
02730 
02731    if (sip_cfg.pedanticsipchecking) {
02732       lws2sws(msg_copy);
02733    }
02734 
02735    msg = ast_str_buffer(msg_copy);
02736 
02737    /* Let's find a Content-Length header */
02738    if ((content_length_str = strcasestr(msg, "\nContent-Length:"))) {
02739       content_length_str += sizeof("\nContent-Length:") - 1;
02740    } else if ((content_length_str = strcasestr(msg, "\nl:"))) {
02741       content_length_str += sizeof("\nl:") - 1;
02742    } else {
02743       /* RFC 3261 18.3
02744        * "In the case of stream-oriented transports such as TCP, the Content-
02745        *  Length header field indicates the size of the body.  The Content-
02746        *  Length header field MUST be used with stream oriented transports."
02747        */
02748       goto done;
02749    }
02750 
02751    /* Double-check that this is a complete header */
02752    if (!strchr(content_length_str, '\n')) {
02753       goto done;
02754    }
02755 
02756    if (sscanf(content_length_str, "%30d", &content_length) != 1) {
02757       content_length = -1;
02758    }
02759 
02760 done:
02761    ast_free(msg_copy);
02762    return content_length;
02763 }
02764 
02765 /*!
02766  * \brief Check that a message received over TCP is a full message
02767  *
02768  * This will take the information read in and then determine if
02769  * 1) The message is a full SIP request
02770  * 2) The message is a partial SIP request
02771  * 3) The message contains a full SIP request along with another partial request
02772  * \param data The unparsed incoming SIP message.
02773  * \param request The resulting request with extra fragments removed.
02774  * \param overflow If the message contains more than a full request, this is the remainder of the message
02775  * \return The resulting integrity of the message
02776  */
02777 static enum message_integrity check_message_integrity(struct ast_str **request, struct ast_str **overflow)
02778 {
02779    char *message = ast_str_buffer(*request);
02780    char *body;
02781    int content_length;
02782    int message_len = ast_str_strlen(*request);
02783    int body_len;
02784 
02785    /* Important pieces to search for in a SIP request are \r\n\r\n. This
02786     * marks either
02787     * 1) The division between the headers and body
02788     * 2) The end of the SIP request
02789     */
02790    body = strstr(message, "\r\n\r\n");
02791    if (!body) {
02792       /* This is clearly a partial message since we haven't reached an end
02793        * yet.
02794        */
02795       return MESSAGE_FRAGMENT;
02796    }
02797    body += sizeof("\r\n\r\n") - 1;
02798    body_len = message_len - (body - message);
02799 
02800    body[-1] = '\0';
02801    content_length = read_raw_content_length(message);
02802    body[-1] = '\n';
02803 
02804    if (content_length < 0) {
02805       return MESSAGE_INVALID;
02806    } else if (content_length == 0) {
02807       /* We've definitely received an entire message. We need
02808        * to check if there's also a fragment of another message
02809        * in addition.
02810        */
02811       if (body_len == 0) {
02812          return MESSAGE_COMPLETE;
02813       } else {
02814          ast_str_append(overflow, 0, "%s", body);
02815          ast_str_truncate(*request, message_len - body_len);
02816          return MESSAGE_FRAGMENT_COMPLETE;
02817       }
02818    }
02819    /* Positive content length. Let's see what sort of
02820     * message body we're dealing with.
02821     */
02822    if (body_len < content_length) {
02823       /* We don't have the full message body yet */
02824       return MESSAGE_FRAGMENT;
02825    } else if (body_len > content_length) {
02826       /* We have the full message plus a fragment of a further
02827        * message
02828        */
02829       ast_str_append(overflow, 0, "%s", body + content_length);
02830       ast_str_truncate(*request, message_len - (body_len - content_length));
02831       return MESSAGE_FRAGMENT_COMPLETE;
02832    } else {
02833       /* Yay! Full message with no extra content */
02834       return MESSAGE_COMPLETE;
02835    }
02836 }
02837 
02838 /*!
02839  * \brief Read SIP request or response from a TCP/TLS connection
02840  *
02841  * \param req The request structure to be filled in
02842  * \param tcptls_session The TCP/TLS connection from which to read
02843  * \retval -1 Failed to read data
02844  * \retval 0 Successfully read data
02845  */
02846 static int sip_tcptls_read(struct sip_request *req, struct ast_tcptls_session_instance *tcptls_session,
02847       int authenticated, time_t start)
02848 {
02849    enum message_integrity message_integrity = MESSAGE_FRAGMENT;
02850 
02851    while (message_integrity == MESSAGE_FRAGMENT) {
02852       size_t datalen;
02853 
02854       if (ast_str_strlen(tcptls_session->overflow_buf) == 0) {
02855          char readbuf[4097];
02856          int timeout;
02857          int res;
02858          if (!tcptls_session->client && !authenticated) {
02859             if ((timeout = sip_check_authtimeout(start)) < 0) {
02860                return -1;
02861             }
02862 
02863             if (timeout == 0) {
02864                ast_debug(2, "SIP TCP/TLS server timed out\n");
02865                return -1;
02866             }
02867          } else {
02868             timeout = -1;
02869          }
02870          res = ast_wait_for_input(tcptls_session->fd, timeout);
02871          if (res < 0) {
02872             ast_debug(2, "SIP TCP/TLS server :: ast_wait_for_input returned %d\n", res);
02873             return -1;
02874          } else if (res == 0) {
02875             ast_debug(2, "SIP TCP/TLS server timed out\n");
02876             return -1;
02877          }
02878 
02879          res = ast_tcptls_server_read(tcptls_session, readbuf, sizeof(readbuf) - 1);
02880          if (res < 0) {
02881             if (errno == EAGAIN || errno == EINTR) {
02882                continue;
02883             }
02884             ast_debug(2, "SIP TCP/TLS server error when receiving data\n");
02885             return -1;
02886          } else if (res == 0) {
02887             ast_debug(2, "SIP TCP/TLS server has shut down\n");
02888             return -1;
02889          }
02890          readbuf[res] = '\0';
02891          ast_str_append(&req->data, 0, "%s", readbuf);
02892       } else {
02893          ast_str_append(&req->data, 0, "%s", ast_str_buffer(tcptls_session->overflow_buf));
02894          ast_str_reset(tcptls_session->overflow_buf);
02895       }
02896 
02897       datalen = ast_str_strlen(req->data);
02898       if (datalen > SIP_MAX_PACKET_SIZE) {
02899          ast_log(LOG_WARNING, "Rejecting TCP/TLS packet from '%s' because way too large: %zu\n",
02900             ast_sockaddr_stringify(&tcptls_session->remote_address), datalen);
02901          return -1;
02902       }
02903 
02904       message_integrity = check_message_integrity(&req->data, &tcptls_session->overflow_buf);
02905    }
02906 
02907    return 0;
02908 }
02909 
02910 /*! \brief SIP TCP thread management function
02911    This function reads from the socket, parses the packet into a request
02912 */
02913 static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session)
02914 {
02915    int res, timeout = -1, authenticated = 0, flags;
02916    time_t start;
02917    struct sip_request req = { 0, } , reqcpy = { 0, };
02918    struct sip_threadinfo *me = NULL;
02919    char buf[1024] = "";
02920    struct pollfd fds[2] = { { 0 }, { 0 }, };
02921    struct ast_tcptls_session_args *ca = NULL;
02922 
02923    /* If this is a server session, then the connection has already been
02924     * setup. Check if the authlimit has been reached and if not create the
02925     * threadinfo object so we can access this thread for writing.
02926     *
02927     * if this is a client connection more work must be done.
02928     * 1. We own the parent session args for a client connection.  This pointer needs
02929     *    to be held on to so we can decrement it's ref count on thread destruction.
02930     * 2. The threadinfo object was created before this thread was launched, however
02931     *    it must be found within the threadt table.
02932     * 3. Last, the tcptls_session must be started.
02933     */
02934    if (!tcptls_session->client) {
02935       if (ast_atomic_fetchadd_int(&unauth_sessions, +1) >= authlimit) {
02936          /* unauth_sessions is decremented in the cleanup code */
02937          goto cleanup;
02938       }
02939 
02940       if ((flags = fcntl(tcptls_session->fd, F_GETFL)) == -1) {
02941          ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
02942          goto cleanup;
02943       }
02944 
02945       flags |= O_NONBLOCK;
02946       if (fcntl(tcptls_session->fd, F_SETFL, flags) == -1) {
02947          ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
02948          goto cleanup;
02949       }
02950 
02951       if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? AST_TRANSPORT_TLS : AST_TRANSPORT_TCP))) {
02952          goto cleanup;
02953       }
02954       ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
02955    } else {
02956       struct sip_threadinfo tmp = {
02957          .tcptls_session = tcptls_session,
02958       };
02959 
02960       if ((!(ca = tcptls_session->parent)) ||
02961          (!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
02962          (!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
02963          goto cleanup;
02964       }
02965    }
02966 
02967    flags = 1;
02968    if (setsockopt(tcptls_session->fd, SOL_SOCKET, SO_KEEPALIVE, &flags, sizeof(flags))) {
02969       ast_log(LOG_ERROR, "error enabling TCP keep-alives on sip socket: %s\n", strerror(errno));
02970       goto cleanup;
02971    }
02972 
02973    me->threadid = pthread_self();
02974    ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "TLS" : "TCP");
02975 
02976    /* set up pollfd to watch for reads on both the socket and the alert_pipe */
02977    fds[0].fd = tcptls_session->fd;
02978    fds[1].fd = me->alert_pipe[0];
02979    fds[0].events = fds[1].events = POLLIN | POLLPRI;
02980 
02981    if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
02982       goto cleanup;
02983    }
02984    if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET))) {
02985       goto cleanup;
02986    }
02987 
02988    if(time(&start) == -1) {
02989       ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
02990       goto cleanup;
02991    }
02992 
02993    /*
02994     * We cannot let the stream exclusively wait for data to arrive.
02995     * We have to wake up the task to send outgoing messages.
02996     */
02997    ast_tcptls_stream_set_exclusive_input(tcptls_session->stream_cookie, 0);
02998 
02999    ast_tcptls_stream_set_timeout_sequence(tcptls_session->stream_cookie, ast_tvnow(),
03000       tcptls_session->client ? -1 : (authtimeout * 1000));
03001 
03002    for (;;) {
03003       struct ast_str *str_save;
03004 
03005       if (!tcptls_session->client && req.authenticated && !authenticated) {
03006          authenticated = 1;
03007          ast_tcptls_stream_set_timeout_disable(tcptls_session->stream_cookie);
03008          ast_atomic_fetchadd_int(&unauth_sessions, -1);
03009       }
03010 
03011       /* calculate the timeout for unauthenticated server sessions */
03012       if (!tcptls_session->client && !authenticated ) {
03013          if ((timeout = sip_check_authtimeout(start)) < 0) {
03014             goto cleanup;
03015          }
03016 
03017          if (timeout == 0) {
03018             ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "TLS": "TCP");
03019             goto cleanup;
03020          }
03021       } else {
03022          timeout = -1;
03023       }
03024 
03025       if (ast_str_strlen(tcptls_session->overflow_buf) == 0) {
03026          res = ast_poll(fds, 2, timeout); /* polls for both socket and alert_pipe */
03027          if (res < 0) {
03028             ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "TLS": "TCP", res);
03029             goto cleanup;
03030          } else if (res == 0) {
03031             /* timeout */
03032             ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "TLS": "TCP");
03033             goto cleanup;
03034          }
03035       }
03036 
03037       /*
03038        * handle the socket event, check for both reads from the socket fd or TCP overflow buffer,
03039        * and writes from alert_pipe fd.
03040        */
03041       if (fds[0].revents || (ast_str_strlen(tcptls_session->overflow_buf) > 0)) { /* there is data on the socket to be read */
03042          fds[0].revents = 0;
03043 
03044          /* clear request structure */
03045          str_save = req.data;
03046          memset(&req, 0, sizeof(req));
03047          req.data = str_save;
03048          ast_str_reset(req.data);
03049 
03050          str_save = reqcpy.data;
03051          memset(&reqcpy, 0, sizeof(reqcpy));
03052          reqcpy.data = str_save;
03053          ast_str_reset(reqcpy.data);
03054 
03055          memset(buf, 0, sizeof(buf));
03056 
03057          if (tcptls_session->ssl) {
03058             set_socket_transport(&req.socket, AST_TRANSPORT_TLS);
03059             req.socket.port = htons(ourport_tls);
03060          } else {
03061             set_socket_transport(&req.socket, AST_TRANSPORT_TCP);
03062             req.socket.port = htons(ourport_tcp);
03063          }
03064          req.socket.fd = tcptls_session->fd;
03065 
03066          res = sip_tcptls_read(&req, tcptls_session, authenticated, start);
03067          if (res < 0) {
03068             goto cleanup;
03069          }
03070 
03071          req.socket.tcptls_session = tcptls_session;
03072          req.socket.ws_session = NULL;
03073          handle_request_do(&req, &tcptls_session->remote_address);
03074       }
03075 
03076       if (fds[1].revents) { /* alert_pipe indicates there is data in the send queue to be sent */
03077          enum sip_tcptls_alert alert;
03078          struct tcptls_packet *packet;
03079 
03080          fds[1].revents = 0;
03081 
03082          if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
03083             ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
03084             continue;
03085          }
03086 
03087          switch (alert) {
03088          case TCPTLS_ALERT_STOP:
03089             goto cleanup;
03090          case TCPTLS_ALERT_DATA:
03091             ao2_lock(me);
03092             if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
03093                ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty\n");
03094             }
03095             ao2_unlock(me);
03096 
03097             if (packet) {
03098                if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
03099                   ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
03100                }
03101                ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
03102             }
03103             break;
03104          default:
03105             ast_log(LOG_ERROR, "Unknown tcptls thread alert '%u'\n", alert);
03106          }
03107       }
03108    }
03109 
03110    ast_debug(2, "Shutting down thread for %s server\n", tcptls_session->ssl ? "TLS" : "TCP");
03111 
03112 cleanup:
03113    if (tcptls_session && !tcptls_session->client && !authenticated) {
03114       ast_atomic_fetchadd_int(&unauth_sessions, -1);
03115    }
03116 
03117    if (me) {
03118       ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
03119       ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
03120    }
03121    deinit_req(&reqcpy);
03122    deinit_req(&req);
03123 
03124    /* if client, we own the parent session arguments and must decrement ref */
03125    if (ca) {
03126       ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
03127    }
03128 
03129    if (tcptls_session) {
03130       ao2_lock(tcptls_session);
03131       ast_tcptls_close_session_file(tcptls_session);
03132       tcptls_session->parent = NULL;
03133       ao2_unlock(tcptls_session);
03134 
03135       ao2_ref(tcptls_session, -1);
03136       tcptls_session = NULL;
03137    }
03138    return NULL;
03139 }
03140 
03141 static void peer_sched_cleanup(struct sip_peer *peer)
03142 {
03143    if (peer->pokeexpire != -1) {
03144       AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
03145             sip_unref_peer(peer, "removing poke peer ref"));
03146    }
03147    if (peer->expire != -1) {
03148       AST_SCHED_DEL_UNREF(sched, peer->expire,
03149             sip_unref_peer(peer, "remove register expire ref"));
03150    }
03151    if (peer->keepalivesend != -1) {
03152       AST_SCHED_DEL_UNREF(sched, peer->keepalivesend,
03153                 sip_unref_peer(peer, "remove keepalive peer ref"));
03154    }
03155 }
03156 
03157 typedef enum {
03158    SIP_PEERS_MARKED,
03159    SIP_PEERS_ALL,
03160 } peer_unlink_flag_t;
03161 
03162 /* this func is used with ao2_callback to unlink/delete all marked or linked
03163    peers, depending on arg */
03164 static int match_and_cleanup_peer_sched(void *peerobj, void *arg, int flags)
03165 {
03166    struct sip_peer *peer = peerobj;
03167    peer_unlink_flag_t which = *(peer_unlink_flag_t *)arg;
03168 
03169    if (which == SIP_PEERS_ALL || peer->the_mark) {
03170       peer_sched_cleanup(peer);
03171       if (peer->dnsmgr) {
03172          ast_dnsmgr_release(peer->dnsmgr);
03173          peer->dnsmgr = NULL;
03174          sip_unref_peer(peer, "Release peer from dnsmgr");
03175       }
03176       return CMP_MATCH;
03177    }
03178    return 0;
03179 }
03180 
03181 static void unlink_peers_from_tables(peer_unlink_flag_t flag)
03182 {
03183    ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
03184       match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
03185    ao2_t_callback(peers_by_ip, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
03186       match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers_by_ip");
03187 }
03188 
03189 /* \brief Unlink all marked peers from ao2 containers */
03190 static void unlink_marked_peers_from_tables(void)
03191 {
03192    unlink_peers_from_tables(SIP_PEERS_MARKED);
03193 }
03194 
03195 static void unlink_all_peers_from_tables(void)
03196 {
03197    unlink_peers_from_tables(SIP_PEERS_ALL);
03198 }
03199 
03200 /*! \brief maintain proper refcounts for a sip_pvt's outboundproxy
03201  *
03202  * This function sets pvt's outboundproxy pointer to the one referenced
03203  * by the proxy parameter. Because proxy may be a refcounted object, and
03204  * because pvt's old outboundproxy may also be a refcounted object, we need
03205  * to maintain the proper refcounts.
03206  *
03207  * \param pvt The sip_pvt for which we wish to set the outboundproxy
03208  * \param proxy The sip_proxy which we will point pvt towards.
03209  * \return Returns void
03210  */
03211 static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
03212 {
03213    struct sip_proxy *old_obproxy = pvt->outboundproxy;
03214    /* The sip_cfg.outboundproxy is statically allocated, and so
03215     * we don't ever need to adjust refcounts for it
03216     */
03217    if (proxy && proxy != &sip_cfg.outboundproxy) {
03218       ao2_ref(proxy, +1);
03219    }
03220    pvt->outboundproxy = proxy;
03221    if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
03222       ao2_ref(old_obproxy, -1);
03223    }
03224 }
03225 
03226 /*!
03227  * \brief Unlink a dialog from the dialogs container, as well as any other places
03228  * that it may be currently stored.
03229  *
03230  * \note A reference to the dialog must be held before calling this function, and this
03231  * function does not release that reference.
03232  */
03233 void dialog_unlink_all(struct sip_pvt *dialog)
03234 {
03235    struct sip_pkt *cp;
03236    struct ast_channel *owner;
03237 
03238    dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
03239 
03240    ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
03241    ao2_t_unlink(dialogs_needdestroy, dialog, "unlinking dialog_needdestroy via ao2_unlink");
03242    ao2_t_unlink(dialogs_rtpcheck, dialog, "unlinking dialog_rtpcheck via ao2_unlink");
03243 
03244    /* Unlink us from the owner (channel) if we have one */
03245    owner = sip_pvt_lock_full(dialog);
03246    if (owner) {
03247       ast_debug(1, "Detaching from channel %s\n", ast_channel_name(owner));
03248       ast_channel_tech_pvt_set(owner, dialog_unref(ast_channel_tech_pvt(owner), "resetting channel dialog ptr in unlink_all"));
03249       ast_channel_unlock(owner);
03250       ast_channel_unref(owner);
03251       sip_set_owner(dialog, NULL);
03252    }
03253    sip_pvt_unlock(dialog);
03254 
03255    if (dialog->registry) {
03256       if (dialog->registry->call == dialog) {
03257          dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
03258       }
03259       ao2_t_replace(dialog->registry, NULL, "delete dialog->registry");
03260    }
03261    if (dialog->stateid != -1) {
03262       ast_extension_state_del(dialog->stateid, cb_extensionstate);
03263       dialog->stateid = -1;
03264    }
03265    /* Remove link from peer to subscription of MWI */
03266    if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog) {
03267       dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
03268    }
03269    if (dialog->relatedpeer && dialog->relatedpeer->call == dialog) {
03270       dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
03271    }
03272 
03273    /* remove all current packets in this dialog */
03274    while((cp = dialog->packets)) {
03275       dialog->packets = dialog->packets->next;
03276       AST_SCHED_DEL(sched, cp->retransid);
03277       dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
03278       if (cp->data) {
03279          ast_free(cp->data);
03280       }
03281       ast_free(cp);
03282    }
03283 
03284    AST_SCHED_DEL_UNREF(sched, dialog->waitid, dialog_unref(dialog, "when you delete the waitid sched, you should dec the refcount for the stored dialog ptr"));
03285 
03286    AST_SCHED_DEL_UNREF(sched, dialog->initid, dialog_unref(dialog, "when you delete the initid sched, you should dec the refcount for the stored dialog ptr"));
03287 
03288    if (dialog->reinviteid > -1) {
03289       AST_SCHED_DEL_UNREF(sched, dialog->reinviteid, dialog_unref(dialog, "clear ref for reinvite_timeout"));
03290    }
03291 
03292    if (dialog->autokillid > -1) {
03293       AST_SCHED_DEL_UNREF(sched, dialog->autokillid, dialog_unref(dialog, "when you delete the autokillid sched, you should dec the refcount for the stored dialog ptr"));
03294    }
03295 
03296    if (dialog->request_queue_sched_id > -1) {
03297       AST_SCHED_DEL_UNREF(sched, dialog->request_queue_sched_id, dialog_unref(dialog, "when you delete the request_queue_sched_id sched, you should dec the refcount for the stored dialog ptr"));
03298    }
03299 
03300    AST_SCHED_DEL_UNREF(sched, dialog->provisional_keepalive_sched_id, dialog_unref(dialog, "when you delete the provisional_keepalive_sched_id, you should dec the refcount for the stored dialog ptr"));
03301 
03302    if (dialog->t38id > -1) {
03303       AST_SCHED_DEL_UNREF(sched, dialog->t38id, dialog_unref(dialog, "when you delete the t38id sched, you should dec the refcount for the stored dialog ptr"));
03304    }
03305 
03306    if (dialog->stimer) {
03307       stop_session_timer(dialog);
03308    }
03309 
03310    dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
03311 }
03312 
03313 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03314    __attribute__((format(printf, 2, 3)));
03315 
03316 
03317 /*! \brief Convert transfer status to string */
03318 static const char *referstatus2str(enum referstatus rstatus)
03319 {
03320    return map_x_s(referstatusstrings, rstatus, "");
03321 }
03322 
03323 static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
03324 {
03325    if (pvt->final_destruction_scheduled) {
03326       return; /* This is already scheduled for final destruction, let the scheduler take care of it. */
03327    }
03328    append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
03329    if (!pvt->needdestroy) {
03330       pvt->needdestroy = 1;
03331       ao2_t_link(dialogs_needdestroy, pvt, "link pvt into dialogs_needdestroy container");
03332    }
03333 }
03334 
03335 /*! \brief Initialize the initital request packet in the pvt structure.
03336    This packet is used for creating replies and future requests in
03337    a dialog */
03338 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
03339 {
03340    if (p->initreq.headers) {
03341       ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
03342    } else {
03343       ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
03344    }
03345    /* Use this as the basis */
03346    copy_request(&p->initreq, req);
03347    parse_request(&p->initreq);
03348    if (req->debug) {
03349       ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
03350    }
03351 }
03352 
03353 /*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
03354 static void sip_alreadygone(struct sip_pvt *dialog)
03355 {
03356    ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
03357    dialog->alreadygone = 1;
03358 }
03359 
03360 /*! Resolve DNS srv name or host name in a sip_proxy structure */
03361 static int proxy_update(struct sip_proxy *proxy)
03362 {
03363    /* if it's actually an IP address and not a name,
03364            there's no need for a managed lookup */
03365    if (!ast_sockaddr_parse(&proxy->ip, proxy->name, 0)) {
03366       /* Ok, not an IP address, then let's check if it's a domain or host */
03367       /* XXX Todo - if we have proxy port, don't do SRV */
03368       proxy->ip.ss.ss_family = get_address_family_filter(AST_TRANSPORT_UDP); /* Filter address family */
03369       if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
03370             ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
03371             return FALSE;
03372       }
03373 
03374    }
03375 
03376    ast_sockaddr_set_port(&proxy->ip, proxy->port);
03377 
03378    proxy->last_dnsupdate = time(NULL);
03379    return TRUE;
03380 }
03381 
03382 /*! \brief Parse proxy string and return an ao2_alloc'd proxy. If dest is
03383  *         non-NULL, no allocation is performed and dest is used instead.
03384  *         On error NULL is returned. */
03385 static struct sip_proxy *proxy_from_config(const char *proxy, int sipconf_lineno, struct sip_proxy *dest)
03386 {
03387    char *mutable_proxy, *sep, *name;
03388    int allocated = 0;
03389 
03390    if (!dest) {
03391       dest = ao2_alloc(sizeof(struct sip_proxy), NULL);
03392       if (!dest) {
03393          ast_log(LOG_WARNING, "Unable to allocate config storage for proxy\n");
03394          return NULL;
03395       }
03396       allocated = 1;
03397    }
03398 
03399    /* Format is: [transport://]name[:port][,force] */
03400    mutable_proxy = ast_skip_blanks(ast_strdupa(proxy));
03401    sep = strchr(mutable_proxy, ',');
03402    if (sep) {
03403       *sep++ = '\0';
03404       dest->force = !strncasecmp(ast_skip_blanks(sep), "force", 5);
03405    } else {
03406       dest->force = FALSE;
03407    }
03408 
03409    sip_parse_host(mutable_proxy, sipconf_lineno, &name, &dest->port, &dest->transport);
03410 
03411    /* Check that there is a name at all */
03412    if (ast_strlen_zero(name)) {
03413       if (allocated) {
03414          ao2_ref(dest, -1);
03415       } else {
03416          dest->name[0] = '\0';
03417       }
03418       return NULL;
03419    }
03420    ast_copy_string(dest->name, name, sizeof(dest->name));
03421 
03422    /* Resolve host immediately */
03423    proxy_update(dest);
03424 
03425    return dest;
03426 }
03427 
03428 /*! \brief converts ascii port to int representation. If no
03429  *  pt buffer is provided or the pt has errors when being converted
03430  *  to an int value, the port provided as the standard is used.
03431  */
03432 unsigned int port_str2int(const char *pt, unsigned int standard)
03433 {
03434    int port = standard;
03435    if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
03436       port = standard;
03437    }
03438 
03439    return port;
03440 }
03441 
03442 /*! \brief Get default outbound proxy or global proxy */
03443 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
03444 {
03445    if (dialog && dialog->options && dialog->options->outboundproxy) {
03446       if (sipdebug) {
03447          ast_debug(1, "OBPROXY: Applying dialplan set OBproxy to this call\n");
03448       }
03449       append_history(dialog, "OBproxy", "Using dialplan obproxy %s", dialog->options->outboundproxy->name);
03450       return dialog->options->outboundproxy;
03451    }
03452    if (peer && peer->outboundproxy) {
03453       if (sipdebug) {
03454          ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
03455       }
03456       append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
03457       return peer->outboundproxy;
03458    }
03459    if (sip_cfg.outboundproxy.name[0]) {
03460       if (sipdebug) {
03461          ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
03462       }
03463       append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
03464       return &sip_cfg.outboundproxy;
03465    }
03466    if (sipdebug) {
03467       ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
03468    }
03469    return NULL;
03470 }
03471 
03472 /*! \brief returns true if 'name' (with optional trailing whitespace)
03473  * matches the sip method 'id'.
03474  * Strictly speaking, SIP methods are case SENSITIVE, but we do
03475  * a case-insensitive comparison to be more tolerant.
03476  * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
03477  */
03478 static int method_match(enum sipmethod id, const char *name)
03479 {
03480    int len = strlen(sip_methods[id].text);
03481    int l_name = name ? strlen(name) : 0;
03482    /* true if the string is long enough, and ends with whitespace, and matches */
03483    return (l_name >= len && name && name[len] < 33 &&
03484       !strncasecmp(sip_methods[id].text, name, len));
03485 }
03486 
03487 /*! \brief  find_sip_method: Find SIP method from header */
03488 static int find_sip_method(const char *msg)
03489 {
03490    int i, res = 0;
03491 
03492    if (ast_strlen_zero(msg)) {
03493       return 0;
03494    }
03495    for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
03496       if (method_match(i, msg)) {
03497          res = sip_methods[i].id;
03498       }
03499    }
03500    return res;
03501 }
03502 
03503 /*! \brief See if we pass debug IP filter */
03504 static inline int sip_debug_test_addr(const struct ast_sockaddr *addr)
03505 {
03506    /* Can't debug if sipdebug is not enabled */
03507    if (!sipdebug) {
03508       return 0;
03509    }
03510 
03511    /* A null debug_addr means we'll debug any address */
03512    if (ast_sockaddr_isnull(&debugaddr)) {
03513       return 1;
03514    }
03515 
03516    /* If no port was specified for a debug address, just compare the
03517     * addresses, otherwise compare the address and port
03518     */
03519    if (ast_sockaddr_port(&debugaddr)) {
03520       return !ast_sockaddr_cmp(&debugaddr, addr);
03521    } else {
03522       return !ast_sockaddr_cmp_addr(&debugaddr, addr);
03523    }
03524 }
03525 
03526 /*! \brief The real destination address for a write */
03527 static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p)
03528 {
03529    if (p->outboundproxy) {
03530       return &p->outboundproxy->ip;
03531    }
03532 
03533    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;
03534 }
03535 
03536 /*! \brief Display SIP nat mode */
03537 static const char *sip_nat_mode(const struct sip_pvt *p)
03538 {
03539    return ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) ? "NAT" : "no NAT";
03540 }
03541 
03542 /*! \brief Test PVT for debugging output */
03543 static inline int sip_debug_test_pvt(struct sip_pvt *p)
03544 {
03545    if (!sipdebug) {
03546       return 0;
03547    }
03548    return sip_debug_test_addr(sip_real_dst(p));
03549 }
03550 
03551 /*! \brief Return int representing a bit field of transport types found in const char *transport */
03552 static int get_transport_str2enum(const char *transport)
03553 {
03554    int res = 0;
03555 
03556    if (ast_strlen_zero(transport)) {
03557       return res;
03558    }
03559 
03560    if (!strcasecmp(transport, "udp")) {
03561       res |= AST_TRANSPORT_UDP;
03562    }
03563    if (!strcasecmp(transport, "tcp")) {
03564       res |= AST_TRANSPORT_TCP;
03565    }
03566    if (!strcasecmp(transport, "tls")) {
03567       res |= AST_TRANSPORT_TLS;
03568    }
03569    if (!strcasecmp(transport, "ws")) {
03570       res |= AST_TRANSPORT_WS;
03571    }
03572    if (!strcasecmp(transport, "wss")) {
03573       res |= AST_TRANSPORT_WSS;
03574    }
03575 
03576    return res;
03577 }
03578 
03579 /*! \brief Return configuration of transports for a device */
03580 static inline const char *get_transport_list(unsigned int transports)
03581 {
03582    char *buf;
03583 
03584    if (!transports) {
03585       return "UNKNOWN";
03586    }
03587 
03588    if (!(buf = ast_threadstorage_get(&sip_transport_str_buf, SIP_TRANSPORT_STR_BUFSIZE))) {
03589       return "";
03590    }
03591 
03592    memset(buf, 0, SIP_TRANSPORT_STR_BUFSIZE);
03593 
03594    if (transports & AST_TRANSPORT_UDP) {
03595       strncat(buf, "UDP,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
03596    }
03597    if (transports & AST_TRANSPORT_TCP) {
03598       strncat(buf, "TCP,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
03599    }
03600    if (transports & AST_TRANSPORT_TLS) {
03601       strncat(buf, "TLS,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
03602    }
03603    if (transports & AST_TRANSPORT_WS) {
03604       strncat(buf, "WS,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
03605    }
03606    if (transports & AST_TRANSPORT_WSS) {
03607       strncat(buf, "WSS,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
03608    }
03609 
03610    /* Remove the trailing ',' if present */
03611    if (strlen(buf)) {
03612       buf[strlen(buf) - 1] = 0;
03613    }
03614 
03615    return buf;
03616 }
03617 
03618 /*! \brief Return transport as string */
03619 const char *sip_get_transport(enum ast_transport t)
03620 {
03621    switch (t) {
03622    case AST_TRANSPORT_UDP:
03623       return "UDP";
03624    case AST_TRANSPORT_TCP:
03625       return "TCP";
03626    case AST_TRANSPORT_TLS:
03627       return "TLS";
03628    case AST_TRANSPORT_WS:
03629    case AST_TRANSPORT_WSS:
03630       return "WS";
03631    }
03632 
03633    return "UNKNOWN";
03634 }
03635 
03636 /*! \brief Return protocol string for srv dns query */
03637 static inline const char *get_srv_protocol(enum ast_transport t)
03638 {
03639    switch (t) {
03640    case AST_TRANSPORT_UDP:
03641       return "udp";
03642    case AST_TRANSPORT_WS:
03643       return "ws";
03644    case AST_TRANSPORT_TLS:
03645    case AST_TRANSPORT_TCP:
03646       return "tcp";
03647    case AST_TRANSPORT_WSS:
03648       return "wss";
03649    }
03650 
03651    return "udp";
03652 }
03653 
03654 /*! \brief Return service string for srv dns query */
03655 static inline const char *get_srv_service(enum ast_transport t)
03656 {
03657    switch (t) {
03658    case AST_TRANSPORT_TCP:
03659    case AST_TRANSPORT_UDP:
03660    case AST_TRANSPORT_WS:
03661       return "sip";
03662    case AST_TRANSPORT_TLS:
03663    case AST_TRANSPORT_WSS:
03664       return "sips";
03665    }
03666    return "sip";
03667 }
03668 
03669 /*! \brief Return transport of dialog.
03670    \note this is based on a false assumption. We don't always use the
03671    outbound proxy for all requests in a dialog. It depends on the
03672    "force" parameter. The FIRST request is always sent to the ob proxy.
03673    \todo Fix this function to work correctly
03674 */
03675 static inline const char *get_transport_pvt(struct sip_pvt *p)
03676 {
03677    if (p->outboundproxy && p->outboundproxy->transport) {
03678       set_socket_transport(&p->socket, p->outboundproxy->transport);
03679    }
03680 
03681    return sip_get_transport(p->socket.type);
03682 }
03683 
03684 /*!
03685  * \internal
03686  * \brief Transmit SIP message
03687  *
03688  * \details
03689  * Sends a SIP request or response on a given socket (in the pvt)
03690  * \note
03691  * Called by retrans_pkt, send_request, send_response and __sip_reliable_xmit
03692  *
03693  * \return length of transmitted message, XMIT_ERROR on known network failures -1 on other failures.
03694  */
03695 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data)
03696 {
03697    int res = 0;
03698    const struct ast_sockaddr *dst = sip_real_dst(p);
03699 
03700    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));
03701 
03702    if (sip_prepare_socket(p) < 0) {
03703       return XMIT_ERROR;
03704    }
03705 
03706    if (p->socket.type == AST_TRANSPORT_UDP) {
03707       res = ast_sendto(p->socket.fd, ast_str_buffer(data), ast_str_strlen(data), 0, dst);
03708    } else if (p->socket.tcptls_session) {
03709       res = sip_tcptls_write(p->socket.tcptls_session, ast_str_buffer(data), ast_str_strlen(data));
03710    } else if (p->socket.ws_session) {
03711       if (!(res = ast_websocket_write(p->socket.ws_session, AST_WEBSOCKET_OPCODE_TEXT, ast_str_buffer(data), ast_str_strlen(data)))) {
03712          /* The WebSocket API just returns 0 on success and -1 on failure, while this code expects the payload length to be returned */
03713          res = ast_str_strlen(data);
03714       }
03715    } else {
03716       ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
03717       return XMIT_ERROR;
03718    }
03719 
03720    if (res == -1) {
03721       switch (errno) {
03722       case EBADF:    /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
03723       case EHOSTUNREACH:   /* Host can't be reached */
03724       case ENETDOWN:    /* Interface down */
03725       case ENETUNREACH: /* Network failure */
03726       case ECONNREFUSED:      /* ICMP port unreachable */
03727          res = XMIT_ERROR; /* Don't bother with trying to transmit again */
03728       }
03729    }
03730    if (res != ast_str_strlen(data)) {
03731       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));
03732    }
03733 
03734    return res;
03735 }
03736 
03737 /*! \brief Build a Via header for a request */
03738 static void build_via(struct sip_pvt *p)
03739 {
03740    /* Work around buggy UNIDEN UIP200 firmware */
03741    const char *rport = (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) || ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)) ? ";rport" : "";
03742 
03743    /* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
03744    snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s;branch=z9hG4bK%08x%s",
03745        get_transport_pvt(p),
03746        ast_sockaddr_stringify_remote(&p->ourip),
03747        (unsigned)p->branch, rport);
03748 }
03749 
03750 /*! \brief NAT fix - decide which IP address to use for Asterisk server?
03751  *
03752  * Using the localaddr structure built up with localnet statements in sip.conf
03753  * apply it to their address to see if we need to substitute our
03754  * externaddr or can get away with our internal bindaddr
03755  * 'us' is always overwritten.
03756  */
03757 static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p)
03758 {
03759    struct ast_sockaddr theirs;
03760 
03761    /* Set want_remap to non-zero if we want to remap 'us' to an externally
03762     * reachable IP address and port. This is done if:
03763     * 1. we have a localaddr list (containing 'internal' addresses marked
03764     *    as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
03765     *    and AST_SENSE_ALLOW on 'external' ones);
03766     * 2. externaddr is set, so we know what to use as the
03767     *    externally visible address;
03768     * 3. the remote address, 'them', is external;
03769     * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
03770     *    when passed to ast_apply_ha() so it does need to be remapped.
03771     *    This fourth condition is checked later.
03772     */
03773    int want_remap = 0;
03774 
03775    ast_sockaddr_copy(us, &internip); /* starting guess for the internal address */
03776    /* now ask the system what would it use to talk to 'them' */
03777    ast_ouraddrfor(them, us);
03778    ast_sockaddr_copy(&theirs, them);
03779 
03780    if (ast_sockaddr_is_ipv6(&theirs) && !ast_sockaddr_is_ipv4_mapped(&theirs)) {
03781       if (localaddr && !ast_sockaddr_isnull(&externaddr) && !ast_sockaddr_is_any(&bindaddr)) {
03782          ast_log(LOG_WARNING, "Address remapping activated in sip.conf "
03783             "but we're using IPv6, which doesn't need it. Please "
03784             "remove \"localnet\" and/or \"externaddr\" settings.\n");
03785       }
03786    } else {
03787       want_remap = localaddr &&
03788          !ast_sockaddr_isnull(&externaddr) &&
03789          ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
03790    }
03791 
03792    if (want_remap &&
03793        (!sip_cfg.matchexternaddrlocally || !ast_apply_ha(localaddr, us)) ) {
03794       /* if we used externhost, see if it is time to refresh the info */
03795       if (externexpire && time(NULL) >= externexpire) {
03796          if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
03797             ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
03798          }
03799          externexpire = time(NULL) + externrefresh;
03800       }
03801       if (!ast_sockaddr_isnull(&externaddr)) {
03802          ast_sockaddr_copy(us, &externaddr);
03803          switch (p->socket.type) {
03804          case AST_TRANSPORT_TCP:
03805             if (!externtcpport && ast_sockaddr_port(&externaddr)) {
03806                /* for consistency, default to the externaddr port */
03807                externtcpport = ast_sockaddr_port(&externaddr);
03808             }
03809             ast_sockaddr_set_port(us, externtcpport);
03810             break;
03811          case AST_TRANSPORT_TLS:
03812             ast_sockaddr_set_port(us, externtlsport);
03813             break;
03814          case AST_TRANSPORT_UDP:
03815             if (!ast_sockaddr_port(&externaddr)) {
03816                ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
03817             }
03818             break;
03819          default:
03820             break;
03821          }
03822       }
03823       ast_debug(1, "Target address %s is not local, substituting externaddr\n",
03824            ast_sockaddr_stringify(them));
03825    } else {
03826       /* no remapping, but we bind to a specific address, so use it. */
03827       switch (p->socket.type) {
03828       case AST_TRANSPORT_TCP:
03829          if (!ast_sockaddr_is_any(&sip_tcp_desc.local_address)) {
03830             ast_sockaddr_copy(us,
03831                     &sip_tcp_desc.local_address);
03832          } else {
03833             ast_sockaddr_set_port(us,
03834                         ast_sockaddr_port(&sip_tcp_desc.local_address));
03835          }
03836          break;
03837       case AST_TRANSPORT_TLS:
03838          if (!ast_sockaddr_is_any(&sip_tls_desc.local_address)) {
03839             ast_sockaddr_copy(us,
03840                     &sip_tls_desc.local_address);
03841          } else {
03842             ast_sockaddr_set_port(us,
03843                         ast_sockaddr_port(&sip_tls_desc.local_address));
03844          }
03845          break;
03846       case AST_TRANSPORT_UDP:
03847          /* fall through on purpose */
03848       default:
03849          if (!ast_sockaddr_is_any(&bindaddr)) {
03850             ast_sockaddr_copy(us, &bindaddr);
03851          }
03852          if (!ast_sockaddr_port(us)) {
03853             ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
03854          }
03855       }
03856    }
03857    ast_debug(3, "Setting AST_TRANSPORT_%s with address %s\n", sip_get_transport(p->socket.type), ast_sockaddr_stringify(us));
03858 }
03859 
03860 /*! \brief Append to SIP dialog history with arg list  */
03861 static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
03862 {
03863    char buf[80], *c = buf; /* max history length */
03864    struct sip_history *hist;
03865    int l;
03866 
03867    vsnprintf(buf, sizeof(buf), fmt, ap);
03868    strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
03869    l = strlen(buf) + 1;
03870    if (!(hist = ast_calloc(1, sizeof(*hist) + l))) {
03871       return;
03872    }
03873    if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
03874       ast_free(hist);
03875       return;
03876    }
03877    memcpy(hist->event, buf, l);
03878    if (p->history_entries == MAX_HISTORY_ENTRIES) {
03879       struct sip_history *oldest;
03880       oldest = AST_LIST_REMOVE_HEAD(p->history, list);
03881       p->history_entries--;
03882       ast_free(oldest);
03883    }
03884    AST_LIST_INSERT_TAIL(p->history, hist, list);
03885    p->history_entries++;
03886 }
03887 
03888 /*! \brief Append to SIP dialog history with arg list  */
03889 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03890 {
03891    va_list ap;
03892 
03893    if (!p) {
03894       return;
03895    }
03896 
03897    if (!p->do_history && !recordhistory && !dumphistory) {
03898       return;
03899    }
03900 
03901    va_start(ap, fmt);
03902    append_history_va(p, fmt, ap);
03903    va_end(ap);
03904 
03905    return;
03906 }
03907 
03908 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
03909 static int retrans_pkt(const void *data)
03910 {
03911    struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
03912    int reschedule = DEFAULT_RETRANS;
03913    int xmitres = 0;
03914    /* how many ms until retrans timeout is reached */
03915    int64_t diff = pkt->retrans_stop_time - ast_tvdiff_ms(ast_tvnow(), pkt->time_sent);
03916 
03917    /* Do not retransmit if time out is reached. This will be negative if the time between
03918     * the first transmission and now is larger than our timeout period. This is a fail safe
03919     * check in case the scheduler gets behind or the clock is changed. */
03920    if ((diff <= 0) || (diff > pkt->retrans_stop_time)) {
03921       pkt->retrans_stop = 1;
03922    }
03923 
03924    /* Lock channel PVT */
03925    sip_pvt_lock(pkt->owner);
03926 
03927    if (!pkt->retrans_stop) {
03928       pkt->retrans++;
03929       if (!pkt->timer_t1) {   /* Re-schedule using timer_a and timer_t1 */
03930          if (sipdebug) {
03931             ast_debug(4, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n",
03932                pkt->retransid,
03933                sip_methods[pkt->method].text,
03934                pkt->method);
03935          }
03936       } else {
03937          int siptimer_a;
03938 
03939          if (sipdebug) {
03940             ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n",
03941                pkt->retransid,
03942                pkt->retrans,
03943                sip_methods[pkt->method].text,
03944                pkt->method);
03945          }
03946          if (!pkt->timer_a) {
03947             pkt->timer_a = 2 ;
03948          } else {
03949             pkt->timer_a = 2 * pkt->timer_a;
03950          }
03951 
03952          /* For non-invites, a maximum of 4 secs */
03953          siptimer_a = pkt->timer_t1 * pkt->timer_a;   /* Double each time */
03954          if (pkt->method != SIP_INVITE && siptimer_a > 4000) {
03955             siptimer_a = 4000;
03956          }
03957 
03958          /* Reschedule re-transmit */
03959          reschedule = siptimer_a;
03960          ast_debug(4, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n",
03961             pkt->retrans + 1,
03962             siptimer_a,
03963             pkt->timer_t1,
03964             pkt->retransid);
03965       }
03966 
03967       if (sip_debug_test_pvt(pkt->owner)) {
03968          const struct ast_sockaddr *dst = sip_real_dst(pkt->owner);
03969          ast_verbose("Retransmitting #%d (%s) to %s:\n%s\n---\n",
03970             pkt->retrans, sip_nat_mode(pkt->owner),
03971             ast_sockaddr_stringify(dst),
03972             ast_str_buffer(pkt->data));
03973       }
03974 
03975       append_history(pkt->owner, "ReTx", "%d %s", reschedule, ast_str_buffer(pkt->data));
03976       xmitres = __sip_xmit(pkt->owner, pkt->data);
03977 
03978       /* If there was no error during the network transmission, schedule the next retransmission,
03979        * but if the next retransmission is going to be beyond our timeout period, mark the packet's
03980        * stop_retrans value and set the next retransmit to be the exact time of timeout.  This will
03981        * allow any responses to the packet to be processed before the packet is destroyed on the next
03982        * call to this function by the scheduler. */
03983       if (xmitres != XMIT_ERROR) {
03984          if (reschedule >= diff) {
03985             pkt->retrans_stop = 1;
03986             reschedule = diff;
03987          }
03988          sip_pvt_unlock(pkt->owner);
03989          return  reschedule;
03990       }
03991    }
03992 
03993    /* At this point, either the packet's retransmission timed out, or there was a
03994     * transmission error, either way destroy the scheduler item and this packet. */
03995 
03996    pkt->retransid = -1; /* Kill this scheduler item */
03997 
03998    if (pkt->method != SIP_OPTIONS && xmitres == 0) {
03999       if (pkt->is_fatal || sipdebug) { /* Tell us if it's critical or if we're debugging */
04000          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"
04001             "Packet timed out after %dms with no response\n",
04002             pkt->owner->callid,
04003             pkt->seqno,
04004             pkt->is_fatal ? "Critical" : "Non-critical",
04005             pkt->is_resp ? "Response" : "Request",
04006             (int) ast_tvdiff_ms(ast_tvnow(), pkt->time_sent));
04007       }
04008    } else if (pkt->method == SIP_OPTIONS && sipdebug) {
04009       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);
04010    }
04011 
04012    if (xmitres == XMIT_ERROR) {
04013       ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
04014       append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
04015    } else {
04016       append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
04017    }
04018 
04019    if (pkt->is_fatal) {
04020       while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
04021          sip_pvt_unlock(pkt->owner);   /* SIP_PVT, not channel */
04022          usleep(1);
04023          sip_pvt_lock(pkt->owner);
04024       }
04025       if (pkt->owner->owner && !ast_channel_hangupcause(pkt->owner->owner)) {
04026          ast_channel_hangupcause_set(pkt->owner->owner, AST_CAUSE_NO_USER_RESPONSE);
04027       }
04028       if (pkt->owner->owner) {
04029          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);
04030 
04031          if (pkt->is_resp &&
04032             (pkt->response_code >= 200) &&
04033             (pkt->response_code < 300) &&
04034             pkt->owner->pendinginvite &&
04035             ast_test_flag(&pkt->owner->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
04036             /* This is a timeout of the 2XX response to a pending INVITE.  In this case terminate the INVITE
04037              * transaction just as if we received the ACK, but immediately hangup with a BYE (sip_hangup
04038              * will send the BYE as long as the dialog is not set as "alreadygone")
04039              * RFC 3261 section 13.3.1.4.
04040              * "If the server retransmits the 2xx response for 64*T1 seconds without receiving
04041              * an ACK, the dialog is confirmed, but the session SHOULD be terminated.  This is
04042              * accomplished with a BYE, as described in Section 15." */
04043             pkt->owner->invitestate = INV_TERMINATED;
04044             pkt->owner->pendinginvite = 0;
04045          } else {
04046             /* there is nothing left to do, mark the dialog as gone */
04047             sip_alreadygone(pkt->owner);
04048          }
04049          ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_NO_USER_RESPONSE);
04050          ast_channel_unlock(pkt->owner->owner);
04051       } else {
04052          /* If no channel owner, destroy now */
04053 
04054          /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
04055          if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
04056             pvt_set_needdestroy(pkt->owner, "no response to critical packet");
04057             sip_alreadygone(pkt->owner);
04058             append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
04059          }
04060       }
04061    } else if (pkt->owner->pendinginvite == pkt->seqno) {
04062           ast_log(LOG_WARNING, "Timeout on %s on non-critical invite transaction.\n", pkt->owner->callid);
04063           pkt->owner->invitestate = INV_TERMINATED;
04064           pkt->owner->pendinginvite = 0;
04065           check_pendings(pkt->owner);
04066    }
04067 
04068    if (pkt->method == SIP_BYE) {
04069       /* We're not getting answers on SIP BYE's.  Tear down the call anyway. */
04070       sip_alreadygone(pkt->owner);
04071       if (pkt->owner->owner) {
04072          ast_channel_unlock(pkt->owner->owner);
04073       }
04074       append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
04075       pvt_set_needdestroy(pkt->owner, "no response to BYE");
04076    }
04077 
04078    /* Remove the packet */
04079    for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
04080       if (cur == pkt) {
04081          UNLINK(cur, pkt->owner->packets, prev);
04082          sip_pvt_unlock(pkt->owner);
04083          if (pkt->owner) {
04084             pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
04085          }
04086          if (pkt->data) {
04087             ast_free(pkt->data);
04088          }
04089          pkt->data = NULL;
04090          ast_free(pkt);
04091          return 0;
04092       }
04093    }
04094    /* error case */
04095    ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
04096    sip_pvt_unlock(pkt->owner);
04097    return 0;
04098 }
04099 
04100 /*!
04101  * \internal
04102  * \brief Transmit packet with retransmits
04103  * \return 0 on success, -1 on failure to allocate packet
04104  */
04105 static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, uint32_t seqno, int resp, struct ast_str *data, int fatal, int sipmethod)
04106 {
04107    struct sip_pkt *pkt = NULL;
04108    int siptimer_a = DEFAULT_RETRANS;
04109    int xmitres = 0;
04110    unsigned respid;
04111 
04112    if (sipmethod == SIP_INVITE) {
04113       /* Note this is a pending invite */
04114       p->pendinginvite = seqno;
04115    }
04116 
04117    /* If the transport is something reliable (TCP or TLS) then don't really send this reliably */
04118    /* I removed the code from retrans_pkt that does the same thing so it doesn't get loaded into the scheduler */
04119    /*! \todo According to the RFC some packets need to be retransmitted even if its TCP, so this needs to get revisited */
04120    if (!(p->socket.type & AST_TRANSPORT_UDP)) {
04121       xmitres = __sip_xmit(p, data);   /* Send packet */
04122       if (xmitres == XMIT_ERROR) {  /* Serious network trouble, no need to try again */
04123          append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
04124          return AST_FAILURE;
04125       } else {
04126          return AST_SUCCESS;
04127       }
04128    }
04129 
04130    if (!(pkt = ast_calloc(1, sizeof(*pkt)))) {
04131       return AST_FAILURE;
04132    }
04133    /* copy data, add a terminator and save length */
04134    if (!(pkt->data = ast_str_create(ast_str_strlen(data)))) {
04135       ast_free(pkt);
04136       return AST_FAILURE;
04137    }
04138    ast_str_set(&pkt->data, 0, "%s%s", ast_str_buffer(data), "\0");
04139    /* copy other parameters from the caller */
04140    pkt->method = sipmethod;
04141    pkt->seqno = seqno;
04142    pkt->is_resp = resp;
04143    pkt->is_fatal = fatal;
04144    pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
04145    pkt->next = p->packets;
04146    p->packets = pkt; /* Add it to the queue */
04147    if (resp) {
04148       /* Parse out the response code */
04149       if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
04150          pkt->response_code = respid;
04151       }
04152    }
04153    pkt->timer_t1 = p->timer_t1;  /* Set SIP timer T1 */
04154    pkt->retransid = -1;
04155    if (pkt->timer_t1) {
04156       siptimer_a = pkt->timer_t1;
04157    }
04158 
04159    pkt->time_sent = ast_tvnow(); /* time packet was sent */
04160    pkt->retrans_stop_time = 64 * (pkt->timer_t1 ? pkt->timer_t1 : DEFAULT_TIMER_T1); /* time in ms after pkt->time_sent to stop retransmission */
04161 
04162    /* Schedule retransmission */
04163    AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
04164    if (sipdebug) {
04165       ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id  #%d\n", pkt->retransid);
04166    }
04167 
04168    xmitres = __sip_xmit(pkt->owner, pkt->data); /* Send packet */
04169 
04170    if (xmitres == XMIT_ERROR) {  /* Serious network trouble, no need to try again */
04171       append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
04172       ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
04173       AST_SCHED_DEL(sched, pkt->retransid);
04174       p->packets = pkt->next;
04175       pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
04176       ast_free(pkt->data);
04177       ast_free(pkt);
04178       return AST_FAILURE;
04179    } else {
04180       /* This is odd, but since the retrans timer starts at 500ms and the do_monitor thread
04181        * only wakes up every 1000ms by default, we have to poke the thread here to make
04182        * sure it successfully detects this must be retransmitted in less time than
04183        * it usually sleeps for. Otherwise it might not retransmit this packet for 1000ms. */
04184       if (monitor_thread != AST_PTHREADT_NULL) {
04185          pthread_kill(monitor_thread, SIGURG);
04186       }
04187       return AST_SUCCESS;
04188    }
04189 }
04190 
04191 /*! \brief Kill a SIP dialog (called only by the scheduler)
04192  * The scheduler has a reference to this dialog when p->autokillid != -1,
04193  * and we are called using that reference. So if the event is not
04194  * rescheduled, we need to call dialog_unref().
04195  */
04196 static int __sip_autodestruct(const void *data)
04197 {
04198    struct sip_pvt *p = (struct sip_pvt *)data;
04199    struct ast_channel *owner;
04200 
04201    /* If this is a subscription, tell the phone that we got a timeout */
04202    if (p->subscribed && p->subscribed != MWI_NOTIFICATION && p->subscribed != CALL_COMPLETION) {
04203       struct state_notify_data data = { 0, };
04204       data.state = AST_EXTENSION_DEACTIVATED;
04205 
04206       transmit_state_notify(p, &data, 1, TRUE); /* Send last notification */
04207       p->subscribed = NONE;
04208       append_history(p, "Subscribestatus", "timeout");
04209       ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
04210       return 10000;  /* Reschedule this destruction so that we know that it's gone */
04211    }
04212 
04213    /* If there are packets still waiting for delivery, delay the destruction */
04214    if (p->packets) {
04215       if (!p->needdestroy) {
04216          char method_str[31];
04217          ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
04218          append_history(p, "ReliableXmit", "timeout");
04219          if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
04220             if (p->ongoing_reinvite || method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
04221                pvt_set_needdestroy(p, "autodestruct");
04222             }
04223          }
04224          return 10000;
04225       } else {
04226          /* They've had their chance to respond. Time to bail */
04227          __sip_pretend_ack(p);
04228       }
04229    }
04230 
04231    /* Reset schedule ID */
04232    p->autokillid = -1;
04233 
04234    /*
04235     * Lock both the pvt and the channel safely so that we can queue up a frame.
04236     */
04237    owner = sip_pvt_lock_full(p);
04238    if (owner) {
04239       ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner %s in place (Method: %s). Rescheduling destruction for 10000 ms\n", p->callid, ast_channel_name(owner), sip_methods[p->method].text);
04240       ast_queue_hangup_with_cause(owner, AST_CAUSE_PROTOCOL_ERROR);
04241       ast_channel_unlock(owner);
04242       ast_channel_unref(owner);
04243       sip_pvt_unlock(p);
04244       return 10000;
04245    } else if (p->refer && !p->alreadygone) {
04246       ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
04247       stop_media_flows(p);
04248       transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
04249       append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
04250       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
04251    } else {
04252       append_history(p, "AutoDestroy", "%s", p->callid);
04253       ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
04254       sip_pvt_unlock(p);
04255       dialog_unlink_all(p); /* once it's unlinked and unrefd everywhere, it'll be freed automagically */
04256       sip_pvt_lock(p);
04257       /* dialog_unref(p, "unref dialog-- no other matching conditions"); -- unlink all now should finish off the dialog's references and free it. */
04258       /* sip_destroy(p); */      /* Go ahead and destroy dialog. All attempts to recover is done */
04259       /* sip_destroy also absorbs the reference */
04260    }
04261 
04262    sip_pvt_unlock(p);
04263 
04264    dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
04265 
04266    return 0;
04267 }
04268 
04269 /*! \brief Schedule final destruction of SIP dialog.  This can not be canceled.
04270  *  This function is used to keep a dialog around for a period of time in order
04271  *  to properly respond to any retransmits. */
04272 void sip_scheddestroy_final(struct sip_pvt *p, int ms)
04273 {
04274    if (p->final_destruction_scheduled) {
04275       return; /* already set final destruction */
04276    }
04277 
04278    sip_scheddestroy(p, ms);
04279    if (p->autokillid != -1) {
04280       p->final_destruction_scheduled = 1;
04281    }
04282 }
04283 
04284 /*! \brief Schedule destruction of SIP dialog */
04285 void sip_scheddestroy(struct sip_pvt *p, int ms)
04286 {
04287    if (p->final_destruction_scheduled) {
04288       return; /* already set final destruction */
04289    }
04290 
04291    if (ms < 0) {
04292       if (p->timer_t1 == 0) {
04293          p->timer_t1 = global_t1;   /* Set timer T1 if not set (RFC 3261) */
04294       }
04295       if (p->timer_b == 0) {
04296          p->timer_b = global_timer_b;  /* Set timer B if not set (RFC 3261) */
04297       }
04298       ms = p->timer_t1 * 64;
04299    }
04300    if (sip_debug_test_pvt(p)) {
04301       ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
04302    }
04303    if (sip_cancel_destroy(p)) {
04304       ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
04305    }
04306 
04307    if (p->do_history) {
04308       append_history(p, "SchedDestroy", "%d ms", ms);
04309    }
04310    p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
04311 
04312    if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0) {
04313       stop_session_timer(p);
04314    }
04315 }
04316 
04317 /*! \brief Cancel destruction of SIP dialog.
04318  * Be careful as this also absorbs the reference - if you call it
04319  * from within the scheduler, this might be the last reference.
04320  */
04321 int sip_cancel_destroy(struct sip_pvt *p)
04322 {
04323    if (p->final_destruction_scheduled) {
04324       return 0;
04325    }
04326 
04327    if (p->autokillid > -1) {
04328       append_history(p, "CancelDestroy", "");
04329       AST_SCHED_DEL_UNREF(sched, p->autokillid, dialog_unref(p, "remove ref for autokillid"));
04330    }
04331    return 0;
04332 }
04333 
04334 /*! \brief Acknowledges receipt of a packet and stops retransmission
04335  * called with p locked*/
04336 int __sip_ack(struct sip_pvt *p, uint32_t seqno, int resp, int sipmethod)
04337 {
04338    struct sip_pkt *cur, *prev = NULL;
04339    const char *msg = "Not Found";   /* used only for debugging */
04340    int res = FALSE;
04341 
04342    /* If we have an outbound proxy for this dialog, then delete it now since
04343      the rest of the requests in this dialog needs to follow the routing.
04344      If obforcing is set, we will keep the outbound proxy during the whole
04345      dialog, regardless of what the SIP rfc says
04346    */
04347    if (p->outboundproxy && !p->outboundproxy->force) {
04348       ref_proxy(p, NULL);
04349    }
04350 
04351    for (cur = p->packets; cur; prev = cur, cur = cur->next) {
04352       if (cur->seqno != seqno || cur->is_resp != resp) {
04353          continue;
04354       }
04355       if (cur->is_resp || cur->method == sipmethod) {
04356          res = TRUE;
04357          msg = "Found";
04358          if (!resp && (seqno == p->pendinginvite)) {
04359             ast_debug(1, "Acked pending invite %u\n", p->pendinginvite);
04360             p->pendinginvite = 0;
04361          }
04362          if (cur->retransid > -1) {
04363             if (sipdebug)
04364                ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
04365          }
04366          /* This odd section is designed to thwart a
04367           * race condition in the packet scheduler. There are
04368           * two conditions under which deleting the packet from the
04369           * scheduler can fail.
04370           *
04371           * 1. The packet has been removed from the scheduler because retransmission
04372           * is being attempted. The problem is that if the packet is currently attempting
04373           * retransmission and we are at this point in the code, then that MUST mean
04374           * that retrans_pkt is waiting on p's lock. Therefore we will relinquish the
04375           * lock temporarily to allow retransmission.
04376           *
04377           * 2. The packet has reached its maximum number of retransmissions and has
04378           * been permanently removed from the packet scheduler. If this is the case, then
04379           * the packet's retransid will be set to -1. The atomicity of the setting and checking
04380           * of the retransid to -1 is ensured since in both cases p's lock is held.
04381           */
04382          while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
04383             sip_pvt_unlock(p);
04384             usleep(1);
04385             sip_pvt_lock(p);
04386          }
04387          UNLINK(cur, p->packets, prev);
04388          dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
04389          if (cur->data) {
04390             ast_free(cur->data);
04391          }
04392          ast_free(cur);
04393          break;
04394       }
04395    }
04396    ast_debug(1, "Stopping retransmission on '%s' of %s %u: Match %s\n",
04397       p->callid, resp ? "Response" : "Request", seqno, msg);
04398    return res;
04399 }
04400 
04401 /*! \brief Pretend to ack all packets
04402  * called with p locked */
04403 void __sip_pretend_ack(struct sip_pvt *p)
04404 {
04405    struct sip_pkt *cur = NULL;
04406 
04407    while (p->packets) {
04408       int method;
04409       if (cur == p->packets) {
04410          ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
04411          return;
04412       }
04413       cur = p->packets;
04414       method = (cur->method) ? cur->method : find_sip_method(ast_str_buffer(cur->data));
04415       __sip_ack(p, cur->seqno, cur->is_resp, method);
04416    }
04417 }
04418 
04419 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
04420 int __sip_semi_ack(struct sip_pvt *p, uint32_t seqno, int resp, int sipmethod)
04421 {
04422    struct sip_pkt *cur;
04423    int res = FALSE;
04424 
04425    for (cur = p->packets; cur; cur = cur->next) {
04426       if (cur->seqno == seqno && cur->is_resp == resp &&
04427          (cur->is_resp || method_match(sipmethod, ast_str_buffer(cur->data)))) {
04428          /* this is our baby */
04429          if (cur->retransid > -1) {
04430             if (sipdebug)
04431                ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
04432          }
04433          AST_SCHED_DEL(sched, cur->retransid);
04434          res = TRUE;
04435          break;
04436       }
04437    }
04438    ast_debug(1, "(Provisional) Stopping retransmission (but retaining packet) on '%s' %s %u: %s\n", p->callid, resp ? "Response" : "Request", seqno, res == -1 ? "Not Found" : "Found");
04439    return res;
04440 }
04441 
04442 
04443 /*! \brief Copy SIP request, parse it */
04444 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
04445 {
04446    copy_request(dst, src);
04447    parse_request(dst);
04448 }
04449 
04450 /*! \brief add a blank line if no body */
04451 static void add_blank(struct sip_request *req)
04452 {
04453    if (!req->lines) {
04454       /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
04455       ast_str_append(&req->data, 0, "\r\n");
04456    }
04457 }
04458 
04459 static int send_provisional_keepalive_full(struct sip_pvt *pvt, int with_sdp)
04460 {
04461    const char *msg = NULL;
04462    struct ast_channel *chan;
04463    int res = 0;
04464    int old_sched_id = pvt->provisional_keepalive_sched_id;
04465 
04466    chan = sip_pvt_lock_full(pvt);
04467    /* Check that nothing has changed while we were waiting for the lock */
04468    if (old_sched_id != pvt->provisional_keepalive_sched_id) {
04469       /* Keepalive has been cancelled or rescheduled, clean up and leave */
04470       if (chan) {
04471          ast_channel_unlock(chan);
04472          chan = ast_channel_unref(chan);
04473       }
04474       sip_pvt_unlock(pvt);
04475       dialog_unref(pvt, "dialog ref for provisional keepalive");
04476       return 0;
04477    }
04478 
04479    if (!pvt->last_provisional || !strncasecmp(pvt->last_provisional, "100", 3)) {
04480       msg = "183 Session Progress";
04481    }
04482 
04483    if (pvt->invitestate < INV_COMPLETED) {
04484       if (with_sdp) {
04485          transmit_response_with_sdp(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq, XMIT_UNRELIABLE, FALSE, FALSE);
04486       } else {
04487          transmit_response(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq);
04488       }
04489       res = PROVIS_KEEPALIVE_TIMEOUT;
04490    }
04491 
04492    if (chan) {
04493       ast_channel_unlock(chan);
04494       chan = ast_channel_unref(chan);
04495    }
04496 
04497    if (!res) {
04498       pvt->provisional_keepalive_sched_id = -1;
04499    }
04500 
04501    sip_pvt_unlock(pvt);
04502 
04503    if (!res) {
04504       dialog_unref(pvt, "dialog ref for provisional keepalive");
04505    }
04506    return res;
04507 }
04508 
04509 static int send_provisional_keepalive(const void *data)
04510 {
04511    struct sip_pvt *pvt = (struct sip_pvt *) data;
04512 
04513    return send_provisional_keepalive_full(pvt, 0);
04514 }
04515 
04516 static int send_provisional_keepalive_with_sdp(const void *data)
04517 {
04518    struct sip_pvt *pvt = (void *) data;
04519 
04520    return send_provisional_keepalive_full(pvt, 1);
04521 }
04522 
04523 static void update_provisional_keepalive(struct sip_pvt *pvt, int with_sdp)
04524 {
04525    AST_SCHED_DEL_UNREF(sched, pvt->provisional_keepalive_sched_id, dialog_unref(pvt, "when you delete the provisional_keepalive_sched_id, you should dec the refcount for the stored dialog ptr"));
04526 
04527    pvt->provisional_keepalive_sched_id = ast_sched_add(sched, PROVIS_KEEPALIVE_TIMEOUT,
04528       with_sdp ? send_provisional_keepalive_with_sdp : send_provisional_keepalive, dialog_ref(pvt, "Increment refcount to pass dialog pointer to sched callback"));
04529 }
04530 
04531 static void add_required_respheader(struct sip_request *req)
04532 {
04533    struct ast_str *str;
04534    int i;
04535 
04536    if (!req->reqsipoptions) {
04537       return;
04538    }
04539 
04540    str = ast_str_create(32);
04541 
04542    for (i = 0; i < ARRAY_LEN(sip_options); ++i) {
04543       if (!(req->reqsipoptions & sip_options[i].id)) {
04544          continue;
04545       }
04546       if (ast_str_strlen(str) > 0) {
04547          ast_str_append(&str, 0, ", ");
04548       }
04549       ast_str_append(&str, 0, "%s", sip_options[i].text);
04550    }
04551 
04552    if (ast_str_strlen(str) > 0) {
04553       add_header(req, "Require", ast_str_buffer(str));
04554    }
04555 
04556    ast_free(str);
04557 }
04558 
04559 /*! \brief Transmit response on SIP request*/
04560 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno)
04561 {
04562    int res;
04563 
04564    finalize_content(req);
04565    add_blank(req);
04566    if (sip_debug_test_pvt(p)) {
04567       const struct ast_sockaddr *dst = sip_real_dst(p);
04568 
04569       ast_verbose("\n<--- %sTransmitting (%s) to %s --->\n%s\n<------------>\n",
04570          reliable ? "Reliably " : "", sip_nat_mode(p),
04571          ast_sockaddr_stringify(dst),
04572          ast_str_buffer(req->data));
04573    }
04574    if (p->do_history) {
04575       struct sip_request tmp = { .rlpart1 = 0, };
04576       parse_copy(&tmp, req);
04577       append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", ast_str_buffer(tmp.data), sip_get_header(&tmp, "CSeq"),
04578          (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? REQ_OFFSET_TO_STR(&tmp, rlpart2) : sip_methods[tmp.method].text);
04579       deinit_req(&tmp);
04580    }
04581 
04582    /* If we are sending a final response to an INVITE, stop retransmitting provisional responses */
04583    if (p->initreq.method == SIP_INVITE && reliable == XMIT_CRITICAL) {
04584       AST_SCHED_DEL_UNREF(sched, p->provisional_keepalive_sched_id, dialog_unref(p, "when you delete the provisional_keepalive_sched_id, you should dec the refcount for the stored dialog ptr"));
04585    }
04586 
04587    res = (reliable) ?
04588        __sip_reliable_xmit(p, seqno, 1, req->data, (reliable == XMIT_CRITICAL), req->method) :
04589       __sip_xmit(p, req->data);
04590    deinit_req(req);
04591    if (res > 0) {
04592       return 0;
04593    }
04594    return res;
04595 }
04596 
04597 /*!
04598  * \internal
04599  * \brief Send SIP Request to the other part of the dialogue
04600  * \return see \ref __sip_xmit
04601  */
04602 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno)
04603 {
04604    int res;
04605 
04606    /* If we have an outbound proxy, reset peer address
04607       Only do this once.
04608    */
04609    if (p->outboundproxy) {
04610       p->sa = p->outboundproxy->ip;
04611    }
04612 
04613    finalize_content(req);
04614    add_blank(req);
04615    if (sip_debug_test_pvt(p)) {
04616       if (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT)) {
04617          ast_verbose("%sTransmitting (NAT) to %s:\n%s\n---\n", reliable ? "Reliably " : "", ast_sockaddr_stringify(&p->recv), ast_str_buffer(req->data));
04618       } else {
04619          ast_verbose("%sTransmitting (no NAT) to %s:\n%s\n---\n", reliable ? "Reliably " : "", ast_sockaddr_stringify(&p->sa), ast_str_buffer(req->data));
04620       }
04621    }
04622    if (p->do_history) {
04623       struct sip_request tmp = { .rlpart1 = 0, };
04624       parse_copy(&tmp, req);
04625       append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", ast_str_buffer(tmp.data), sip_get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
04626       deinit_req(&tmp);
04627    }
04628    res = (reliable) ?
04629       __sip_reliable_xmit(p, seqno, 0, req->data, (reliable == XMIT_CRITICAL), req->method) :
04630       __sip_xmit(p, req->data);
04631    deinit_req(req);
04632    return res;
04633 }
04634 
04635 static void enable_dsp_detect(struct sip_pvt *p)
04636 {
04637    int features = 0;
04638 
04639    if (p->dsp) {
04640       return;
04641    }
04642 
04643    if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
04644        (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
04645       if (p->rtp) {
04646          ast_rtp_instance_dtmf_mode_set(p->rtp, AST_RTP_DTMF_MODE_INBAND);
04647       }
04648       features |= DSP_FEATURE_DIGIT_DETECT;
04649    }
04650 
04651    if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
04652       features |= DSP_FEATURE_FAX_DETECT;
04653    }
04654 
04655    if (!features) {
04656       return;
04657    }
04658 
04659    if (!(p->dsp = ast_dsp_new())) {
04660       return;
04661    }
04662 
04663    ast_dsp_set_features(p->dsp, features);
04664    if (global_relaxdtmf) {
04665       ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
04666    }
04667 }
04668 
04669 static void disable_dsp_detect(struct sip_pvt *p)
04670 {
04671    if (p->dsp) {
04672       ast_dsp_free(p->dsp);
04673       p->dsp = NULL;
04674    }
04675 }
04676 
04677 /*! \brief Set an option on a SIP dialog */
04678 static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen)
04679 {
04680    int res = -1;
04681    struct sip_pvt *p = ast_channel_tech_pvt(chan);
04682 
04683         if (!p) {
04684       ast_log(LOG_ERROR, "Attempt to Ref a null pointer.  sip private structure is gone!\n");
04685       return -1;
04686         }
04687 
04688    sip_pvt_lock(p);
04689 
04690    switch (option) {
04691    case AST_OPTION_FORMAT_READ:
04692       if (p->rtp) {
04693          res = ast_rtp_instance_set_read_format(p->rtp, *(struct ast_format **) data);
04694       }
04695       break;
04696    case AST_OPTION_FORMAT_WRITE:
04697       if (p->rtp) {
04698          res = ast_rtp_instance_set_write_format(p->rtp, *(struct ast_format **) data);
04699       }
04700       break;
04701    case AST_OPTION_DIGIT_DETECT:
04702       if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
04703           (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
04704          char *cp = (char *) data;
04705 
04706          ast_debug(1, "%sabling digit detection on %s\n", *cp ? "En" : "Dis", ast_channel_name(chan));
04707          if (*cp) {
04708             enable_dsp_detect(p);
04709          } else {
04710             disable_dsp_detect(p);
04711          }
04712          res = 0;
04713       }
04714       break;
04715    case AST_OPTION_SECURE_SIGNALING:
04716       p->req_secure_signaling = *(unsigned int *) data;
04717       res = 0;
04718       break;
04719    case AST_OPTION_SECURE_MEDIA:
04720       ast_set2_flag(&p->flags[1], *(unsigned int *) data, SIP_PAGE2_USE_SRTP);
04721       res = 0;
04722       break;
04723    default:
04724       break;
04725    }
04726 
04727    sip_pvt_unlock(p);
04728 
04729    return res;
04730 }
04731 
04732 /*! \brief Query an option on a SIP dialog */
04733 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
04734 {
04735    int res = -1;
04736    enum ast_t38_state state = T38_STATE_UNAVAILABLE;
04737    struct sip_pvt *p = (struct sip_pvt *) ast_channel_tech_pvt(chan);
04738    char *cp;
04739 
04740    sip_pvt_lock(p);
04741 
04742    switch (option) {
04743    case AST_OPTION_T38_STATE:
04744       /* Make sure we got an ast_t38_state enum passed in */
04745       if (*datalen != sizeof(enum ast_t38_state)) {
04746          ast_log(LOG_ERROR, "Invalid datalen for AST_OPTION_T38_STATE option. Expected %d, got %d\n", (int)sizeof(enum ast_t38_state), *datalen);
04747          break;
04748       }
04749 
04750       /* Now if T38 support is enabled we need to look and see what the current state is to get what we want to report back */
04751       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
04752          switch (p->t38.state) {
04753          case T38_LOCAL_REINVITE:
04754          case T38_PEER_REINVITE:
04755             state = T38_STATE_NEGOTIATING;
04756             break;
04757          case T38_ENABLED:
04758             state = T38_STATE_NEGOTIATED;
04759             break;
04760          case T38_REJECTED:
04761             state = T38_STATE_REJECTED;
04762             break;
04763          default:
04764             state = T38_STATE_UNKNOWN;
04765          }
04766       }
04767 
04768       *((enum ast_t38_state *) data) = state;
04769       res = 0;
04770 
04771       break;
04772    case AST_OPTION_DIGIT_DETECT:
04773       cp = (char *) data;
04774       *cp = p->dsp ? 1 : 0;
04775       ast_debug(1, "Reporting digit detection %sabled on %s\n", *cp ? "en" : "dis", ast_channel_name(chan));
04776       break;
04777    case AST_OPTION_SECURE_SIGNALING:
04778       *((unsigned int *) data) = p->req_secure_signaling;
04779       res = 0;
04780       break;
04781    case AST_OPTION_SECURE_MEDIA:
04782       *((unsigned int *) data) = ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP) ? 1 : 0;
04783       res = 0;
04784       break;
04785    case AST_OPTION_DEVICE_NAME:
04786       if (p && p->outgoing_call) {
04787          cp = (char *) data;
04788          ast_copy_string(cp, p->dialstring, *datalen);
04789          res = 0;
04790       }
04791       /* We purposely break with a return of -1 in the
04792        * implied else case here
04793        */
04794       break;
04795    default:
04796       break;
04797    }
04798 
04799    sip_pvt_unlock(p);
04800 
04801    return res;
04802 }
04803 
04804 /*! \brief Locate closing quote in a string, skipping escaped quotes.
04805  * optionally with a limit on the search.
04806  * start must be past the first quote.
04807  */
04808 const char *find_closing_quote(const char *start, const char *lim)
04809 {
04810    char last_char = '\0';
04811    const char *s;
04812    for (s = start; *s && s != lim; last_char = *s++) {
04813       if (*s == '"' && last_char != '\\')
04814          break;
04815    }
04816    return s;
04817 }
04818 
04819 /*! \brief Send message with Access-URL header, if this is an HTML URL only! */
04820 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
04821 {
04822    struct sip_pvt *p = ast_channel_tech_pvt(chan);
04823 
04824    if (subclass != AST_HTML_URL)
04825       return -1;
04826 
04827    ast_string_field_build(p, url, "<%s>;mode=active", data);
04828 
04829    if (sip_debug_test_pvt(p))
04830       ast_debug(1, "Send URL %s, state = %u!\n", data, ast_channel_state(chan));
04831 
04832    switch (ast_channel_state(chan)) {
04833    case AST_STATE_RING:
04834       transmit_response(p, "100 Trying", &p->initreq);
04835       break;
04836    case AST_STATE_RINGING:
04837       transmit_response(p, "180 Ringing", &p->initreq);
04838       break;
04839    case AST_STATE_UP:
04840       if (!p->pendinginvite) {      /* We are up, and have no outstanding invite */
04841          transmit_reinvite_with_sdp(p, FALSE, FALSE);
04842       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
04843          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
04844       }
04845       break;
04846    default:
04847       ast_log(LOG_WARNING, "Don't know how to send URI when state is %u!\n", ast_channel_state(chan));
04848    }
04849 
04850    return 0;
04851 }
04852 
04853 /*! \brief Deliver SIP call ID for the call */
04854 static const char *sip_get_callid(struct ast_channel *chan)
04855 {
04856    return ast_channel_tech_pvt(chan) ? ((struct sip_pvt *) ast_channel_tech_pvt(chan))->callid : "";
04857 }
04858 
04859 /*!
04860  * \internal
04861  * \brief Send SIP MESSAGE text within a call
04862  * \note Called from PBX core sendtext() application
04863  */
04864 static int sip_sendtext(struct ast_channel *ast, const char *text)
04865 {
04866    struct sip_pvt *dialog = ast_channel_tech_pvt(ast);
04867    int debug;
04868 
04869    if (!dialog) {
04870       return -1;
04871    }
04872    /* NOT ast_strlen_zero, because a zero-length message is specifically
04873     * allowed by RFC 3428 (See section 10, Examples) */
04874    if (!text) {
04875       return 0;
04876    }
04877    if(!is_method_allowed(&dialog->allowed_methods, SIP_MESSAGE)) {
04878       ast_debug(2, "Trying to send MESSAGE to device that does not support it.\n");
04879       return 0;
04880    }
04881 
04882    debug = sip_debug_test_pvt(dialog);
04883    if (debug) {
04884       ast_verbose("Sending text %s on %s\n", text, ast_channel_name(ast));
04885    }
04886 
04887    /* Setup to send text message */
04888    sip_pvt_lock(dialog);
04889    destroy_msg_headers(dialog);
04890    ast_string_field_set(dialog, msg_body, text);
04891    transmit_message(dialog, 0, 0);
04892    sip_pvt_unlock(dialog);
04893    return 0;
04894 }
04895 
04896 /*! \brief Update peer object in realtime storage
04897    If the Asterisk system name is set in asterisk.conf, we will use
04898    that name and store that in the "regserver" field in the sippeers
04899    table to facilitate multi-server setups.
04900 */
04901 static void realtime_update_peer(const char *peername, struct ast_sockaddr *addr, const char *defaultuser, const char *fullcontact, const char *useragent, int expirey, unsigned short deprecated_username, int lastms, const char *path)
04902 {
04903    char port[10];
04904    char ipaddr[INET6_ADDRSTRLEN];
04905    char regseconds[20];
04906    char *tablename = NULL;
04907    char str_lastms[20];
04908 
04909    const char *sysname = ast_config_AST_SYSTEM_NAME;
04910    char *syslabel = NULL;
04911 
04912    time_t nowtime = time(NULL) + expirey;
04913    const char *fc = fullcontact ? "fullcontact" : NULL;
04914 
04915    int realtimeregs = ast_check_realtime("sipregs");
04916 
04917    tablename = realtimeregs ? "sipregs" : "sippeers";
04918 
04919    snprintf(str_lastms, sizeof(str_lastms), "%d", lastms);
04920    snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);  /* Expiration time */
04921    ast_copy_string(ipaddr, ast_sockaddr_isnull(addr) ? "" : ast_sockaddr_stringify_addr(addr), sizeof(ipaddr));
04922    ast_copy_string(port, ast_sockaddr_port(addr) ? ast_sockaddr_stringify_port(addr) : "", sizeof(port));
04923 
04924    if (ast_strlen_zero(sysname)) {  /* No system name, disable this */
04925       sysname = NULL;
04926    } else if (sip_cfg.rtsave_sysname) {
04927       syslabel = "regserver";
04928    }
04929 
04930    /* XXX IMPORTANT: Anytime you add a new parameter to be updated, you
04931          *  must also add it to contrib/scripts/asterisk.ldap-schema,
04932          *  contrib/scripts/asterisk.ldif,
04933          *  and to configs/res_ldap.conf.sample as described in
04934          *  bugs 15156 and 15895
04935          */
04936 
04937    /* This is ugly, we need something better ;-) */
04938    if (sip_cfg.rtsave_path) {
04939       if (fc) {
04940          ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04941             "port", port, "regseconds", regseconds,
04942             deprecated_username ? "username" : "defaultuser", defaultuser,
04943             "useragent", useragent, "lastms", str_lastms,
04944             "path", path,        /* Path data can be NULL */
04945             fc, fullcontact, syslabel, sysname, SENTINEL); /* note fc and syslabel _can_ be NULL */
04946       } else {
04947          ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04948             "port", port, "regseconds", regseconds,
04949             "useragent", useragent, "lastms", str_lastms,
04950             deprecated_username ? "username" : "defaultuser", defaultuser,
04951             "path", path,        /* Path data can be NULL */
04952             syslabel, sysname, SENTINEL); /* note syslabel _can_ be NULL */
04953       }
04954    } else {
04955       if (fc) {
04956          ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04957             "port", port, "regseconds", regseconds,
04958             deprecated_username ? "username" : "defaultuser", defaultuser,
04959             "useragent", useragent, "lastms", str_lastms,
04960             fc, fullcontact, syslabel, sysname, SENTINEL); /* note fc and syslabel _can_ be NULL */
04961       } else {
04962          ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04963             "port", port, "regseconds", regseconds,
04964             "useragent", useragent, "lastms", str_lastms,
04965             deprecated_username ? "username" : "defaultuser", defaultuser,
04966             syslabel, sysname, SENTINEL); /* note syslabel _can_ be NULL */
04967       }
04968    }
04969 }
04970 
04971 /*! \brief Automatically add peer extension to dial plan */
04972 static void register_peer_exten(struct sip_peer *peer, int onoff)
04973 {
04974    char multi[256];
04975    char *stringp, *ext, *context;
04976    struct pbx_find_info q = { .stacklen = 0 };
04977 
04978    /* XXX note that sip_cfg.regcontext is both a global 'enable' flag and
04979     * the name of the global regexten context, if not specified
04980     * individually.
04981     */
04982    if (ast_strlen_zero(sip_cfg.regcontext))
04983       return;
04984 
04985    ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
04986    stringp = multi;
04987    while ((ext = strsep(&stringp, "&"))) {
04988       if ((context = strchr(ext, '@'))) {
04989          *context++ = '\0';   /* split ext@context */
04990          if (!ast_context_find(context)) {
04991             ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
04992             continue;
04993          }
04994       } else {
04995          context = sip_cfg.regcontext;
04996       }
04997       if (onoff) {
04998          if (!ast_exists_extension(NULL, context, ext, 1, NULL)) {
04999             ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
05000                 ast_strdup(peer->name), ast_free_ptr, "SIP");
05001          }
05002       } else if (pbx_find_extension(NULL, NULL, &q, context, ext, 1, NULL, "", E_MATCH)) {
05003          ast_context_remove_extension(context, ext, 1, NULL);
05004       }
05005    }
05006 }
05007 
05008 /*! Destroy mailbox subscriptions */
05009 static void destroy_mailbox(struct sip_mailbox *mailbox)
05010 {
05011    if (mailbox->event_sub) {
05012       mailbox->event_sub = stasis_unsubscribe(mailbox->event_sub);
05013    }
05014    ast_free(mailbox);
05015 }
05016 
05017 /*! Destroy all peer-related mailbox subscriptions */
05018 static void clear_peer_mailboxes(struct sip_peer *peer)
05019 {
05020    struct sip_mailbox *mailbox;
05021 
05022    while ((mailbox = AST_LIST_REMOVE_HEAD(&peer->mailboxes, entry)))
05023       destroy_mailbox(mailbox);
05024 }
05025 
05026 static void sip_destroy_peer_fn(void *peer)
05027 {
05028    sip_destroy_peer(peer);
05029 }
05030 
05031 /*! \brief Destroy peer object from memory */
05032 static void sip_destroy_peer(struct sip_peer *peer)
05033 {
05034    ast_debug(3, "Destroying SIP peer %s\n", peer->name);
05035 
05036    /*
05037     * Remove any mailbox event subscriptions for this peer before
05038     * we destroy anything.  An event subscription callback may be
05039     * happening right now.
05040     */
05041    clear_peer_mailboxes(peer);
05042 
05043    if (peer->outboundproxy) {
05044       ao2_ref(peer->outboundproxy, -1);
05045       peer->outboundproxy = NULL;
05046    }
05047 
05048    /* Delete it, it needs to disappear */
05049    if (peer->call) {
05050       dialog_unlink_all(peer->call);
05051       peer->call = dialog_unref(peer->call, "peer->call is being unset");
05052    }
05053 
05054    if (peer->mwipvt) {  /* We have an active subscription, delete it */
05055       dialog_unlink_all(peer->mwipvt);
05056       peer->mwipvt = dialog_unref(peer->mwipvt, "unreffing peer->mwipvt");
05057    }
05058 
05059    if (peer->chanvars) {
05060       ast_variables_destroy(peer->chanvars);
05061       peer->chanvars = NULL;
05062    }
05063    sip_route_clear(&peer->path);
05064 
05065    register_peer_exten(peer, FALSE);
05066    ast_free_acl_list(peer->acl);
05067    ast_free_acl_list(peer->directmediaacl);
05068    if (peer->selfdestruct)
05069       ast_atomic_fetchadd_int(&apeerobjs, -1);
05070    else if (!ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->is_realtime) {
05071       ast_atomic_fetchadd_int(&rpeerobjs, -1);
05072       ast_debug(3, "-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
05073    } else
05074       ast_atomic_fetchadd_int(&speerobjs, -1);
05075    if (peer->auth) {
05076       ao2_t_ref(peer->auth, -1, "Removing peer authentication");
05077       peer->auth = NULL;
05078    }
05079 
05080    if (peer->socket.tcptls_session) {
05081       ao2_ref(peer->socket.tcptls_session, -1);
05082       peer->socket.tcptls_session = NULL;
05083    } else if (peer->socket.ws_session) {
05084       ast_websocket_unref(peer->socket.ws_session);
05085       peer->socket.ws_session = NULL;
05086    }
05087 
05088    peer->named_callgroups = ast_unref_namedgroups(peer->named_callgroups);
05089    peer->named_pickupgroups = ast_unref_namedgroups(peer->named_pickupgroups);
05090 
05091    ast_cc_config_params_destroy(peer->cc_params);
05092 
05093    ast_string_field_free_memory(peer);
05094 
05095    ao2_cleanup(peer->caps);
05096 
05097    ast_rtp_dtls_cfg_free(&peer->dtls_cfg);
05098 
05099    ast_endpoint_shutdown(peer->endpoint);
05100    peer->endpoint = NULL;
05101 }
05102 
05103 /*! \brief Update peer data in database (if used) */
05104 static void update_peer(struct sip_peer *p, int expire)
05105 {
05106    int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
05107    if (sip_cfg.peer_rtupdate && (p->is_realtime || rtcachefriends)) {
05108       struct ast_str *r = sip_route_list(&p->path, 0, 0);
05109       if (r) {
05110          realtime_update_peer(p->name, &p->addr, p->username,
05111             p->fullcontact, p->useragent, expire, p->deprecated_username,
05112             p->lastms, ast_str_buffer(r));
05113          ast_free(r);
05114       }
05115    }
05116 }
05117 
05118 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *cfg)
05119 {
05120    struct ast_variable *var = NULL;
05121    struct ast_flags flags = {0};
05122    char *cat = NULL;
05123    const char *insecure;
05124    while ((cat = ast_category_browse(cfg, cat))) {
05125       insecure = ast_variable_retrieve(cfg, cat, "insecure");
05126       set_insecure_flags(&flags, insecure, -1);
05127       if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
05128          var = ast_category_root(cfg, cat);
05129          break;
05130       }
05131    }
05132    return var;
05133 }
05134 
05135 static struct ast_variable *get_insecure_variable_from_sippeers(const char *column, const char *value)
05136 {
05137    struct ast_config *peerlist;
05138    struct ast_variable *var = NULL;
05139    if ((peerlist = ast_load_realtime_multientry("sippeers", column, value, "insecure LIKE", "%port%", SENTINEL))) {
05140       if ((var = get_insecure_variable_from_config(peerlist))) {
05141          /* Must clone, because var will get freed along with
05142           * peerlist. */
05143          var = ast_variables_dup(var);
05144       }
05145       ast_config_destroy(peerlist);
05146    }
05147    return var;
05148 }
05149 
05150 /* Yes.. the only column that makes sense to pass is "ipaddr", but for
05151  * consistency's sake, we require the column name to be passed. As extra
05152  * argument, we take a pointer to var. We already got the info, so we better
05153  * return it and save the caller a query. If return value is nonzero, then *var
05154  * is nonzero too (and the other way around). */
05155 static struct ast_variable *get_insecure_variable_from_sipregs(const char *column, const char *value, struct ast_variable **var)
05156 {
05157    struct ast_variable *varregs = NULL;
05158    struct ast_config *regs, *peers;
05159    char *regscat;
05160    const char *regname;
05161 
05162    if (!(regs = ast_load_realtime_multientry("sipregs", column, value, SENTINEL))) {
05163       return NULL;
05164    }
05165 
05166    /* Load *all* peers that are probably insecure=port */
05167    if (!(peers = ast_load_realtime_multientry("sippeers", "insecure LIKE", "%port%", SENTINEL))) {
05168       ast_config_destroy(regs);
05169       return NULL;
05170    }
05171 
05172    /* Loop over the sipregs that match IP address and attempt to find an
05173     * insecure=port match to it in sippeers. */
05174    regscat = NULL;
05175    while ((regscat = ast_category_browse(regs, regscat)) && (regname = ast_variable_retrieve(regs, regscat, "name"))) {
05176       char *peerscat;
05177       const char *peername;
05178 
05179       peerscat = NULL;
05180       while ((peerscat = ast_category_browse(peers, peerscat)) && (peername = ast_variable_retrieve(peers, peerscat, "name"))) {
05181          if (!strcasecmp(regname, peername)) {
05182             /* Ensure that it really is insecure=port and
05183              * not something else. */
05184             const char *insecure = ast_variable_retrieve(peers, peerscat, "insecure");
05185             struct ast_flags flags = {0};
05186             set_insecure_flags(&flags, insecure, -1);
05187             if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
05188                /* ENOMEM checks till the bitter end. */
05189                if ((varregs = ast_variables_dup(ast_category_root(regs, regscat)))) {
05190                   if (!(*var = ast_variables_dup(ast_category_root(peers, peerscat)))) {
05191                      ast_variables_destroy(varregs);
05192                      varregs = NULL;
05193                   }
05194                }
05195                goto done;
05196             }
05197          }
05198       }
05199    }
05200 
05201 done:
05202    ast_config_destroy(regs);
05203    ast_config_destroy(peers);
05204    return varregs;
05205 }
05206 
05207 static const char *get_name_from_variable(const struct ast_variable *var)
05208 {
05209    /* Don't expect this to return non-NULL. Both NULL and empty
05210     * values can cause the option to get removed from the variable
05211     * list. This is called on ast_variables gotten from both
05212     * ast_load_realtime and ast_load_realtime_multientry.
05213     * - ast_load_realtime removes options with empty values
05214     * - ast_load_realtime_multientry does not!
05215     * For consistent behaviour, we check for the empty name and
05216     * return NULL instead. */
05217    const struct ast_variable *tmp;
05218    for (tmp = var; tmp; tmp = tmp->next) {
05219       if (!strcasecmp(tmp->name, "name")) {
05220          if (!ast_strlen_zero(tmp->value)) {
05221             return tmp->value;
05222          }
05223          break;
05224       }
05225    }
05226    return NULL;
05227 }
05228 
05229 /* If varregs is NULL, we don't use sipregs.
05230  * Using empty if-bodies instead of goto's while avoiding unnecessary indents */
05231 static int realtime_peer_by_name(const char *const *name, struct ast_sockaddr *addr, const char *ipaddr, struct ast_variable **var, struct ast_variable **varregs)
05232 {
05233    /* Peer by name and host=dynamic */
05234    if ((*var =