Sat Jul 12 2014 16:02:16

Asterisk developer's documentation


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 /*!
00096  * \page sip_tcp_tls SIP TCP and TLS support
00097  *
00098  * \par tcpfixes TCP implementation changes needed
00099  * \todo Fix TCP/TLS handling in dialplan, SRV records, transfers and much more
00100  * \todo Save TCP/TLS sessions in registry
00101  * If someone registers a SIPS uri, this forces us to set up a TLS connection back.
00102  * \todo Add TCP/TLS information to function SIPPEER and SIPCHANINFO
00103  * \todo If tcpenable=yes, we must open a TCP socket on the same address as the IP for UDP.
00104  *    The tcpbindaddr config option should only be used to open ADDITIONAL ports
00105  *    So we should propably go back to
00106  *    bindaddr= the default address to bind to. If tcpenable=yes, then bind this to both udp and TCP
00107  *          if tlsenable=yes, open TLS port (provided we also have cert)
00108  *    tcpbindaddr = extra address for additional TCP connections
00109  *    tlsbindaddr = extra address for additional TCP/TLS connections
00110  *    udpbindaddr = extra address for additional UDP connections
00111  *       These three options should take multiple IP/port pairs
00112  * Note: Since opening additional listen sockets is a *new* feature we do not have today
00113  *    the XXXbindaddr options needs to be disabled until we have support for it
00114  *
00115  * \todo re-evaluate the transport= setting in sip.conf. This is right now not well
00116  *    thought of. If a device in sip.conf contacts us via TCP, we should not switch transport,
00117  * even if udp is the configured first transport.
00118  *
00119  * \todo Be prepared for one outbound and another incoming socket per pvt. This applies
00120  *       specially to communication with other peers (proxies).
00121  * \todo We need to test TCP sessions with SIP proxies and in regards
00122  *       to the SIP outbound specs.
00123  * \todo ;transport=tls was deprecated in RFC3261 and should not be used at all. See section 26.2.2.
00124  *
00125  * \todo If the message is smaller than the given Content-length, the request should get a 400 Bad request
00126  *       message. If it's a response, it should be dropped. (RFC 3261, Section 18.3)
00127  * \todo Since we have had multidomain support in Asterisk for quite a while, we need to support
00128  *       multiple domains in our TLS implementation, meaning one socket and one cert per domain
00129  * \todo Selection of transport for a request needs to be done after we've parsed all route headers,
00130  *  also considering outbound proxy options.
00131  *    First request: Outboundproxy, routes, (reg contact or URI. If URI doesn't have port:  DNS naptr, srv, AAA)
00132  *    Intermediate requests: Outboundproxy(only when forced), routes, contact/uri
00133  * DNS naptr support is crucial. A SIP uri might lead to a TLS connection.
00134  * Also note that due to outbound proxy settings, a SIPS uri might have to be sent on UDP (not to recommend though)
00135  * \todo Default transports are set to UDP, which cause the wrong behaviour when contacting remote
00136  * devices directly from the dialplan. UDP is only a fallback if no other method works,
00137  * in order to be compatible with RFC2543 (SIP/1.0) devices. For transactions that exceed the
00138  * MTU (like INIVTE with video, audio and RTT)  TCP should be preferred.
00139  *
00140  * When dialling unconfigured peers (with no port number)  or devices in external domains
00141  * NAPTR records MUST be consulted to find configured transport. If they are not found,
00142  * SRV records for both TCP and UDP should be checked. If there's a record for TCP, use that.
00143  * If there's no record for TCP, then use UDP as a last resort. If there's no SRV records,
00144  * \note this only applies if there's no outbound proxy configured for the session. If an outbound
00145  * proxy is configured, these procedures might apply for locating the proxy and determining
00146  * the transport to use for communication with the proxy.
00147  * \par Other bugs to fix ----
00148  * __set_address_from_contact(const char *fullcontact, struct sockaddr_in *sin, int tcp)
00149  * - sets TLS port as default for all TCP connections, unless other port is given in contact.
00150  * parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
00151  * - assumes that the contact the UA registers is using the same transport as the REGISTER request, which is
00152  *   a bad guess.
00153  *      - Does not save any information about TCP/TLS connected devices, which is a severe BUG, as discussed on the mailing list.
00154  * get_destination(struct sip_pvt *p, struct sip_request *oreq)
00155  * - Doesn't store the information that we got an incoming SIPS request in the channel, so that
00156  *   we can require a secure signalling path OUT of Asterisk (on SIP or IAX2). Possibly, the call should
00157  *   fail on in-secure signalling paths if there's no override in our configuration. At least, provide a
00158  *   channel variable in the dialplan.
00159  * get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
00160  * - As above, if we have a SIPS: uri in the refer-to header
00161  * - Does not check transport in refer_to uri.
00162  */
00163 
00164 /*** MODULEINFO
00165    <use type="module">res_crypto</use>
00166    <use type="module">res_http_websocket</use>
00167    <depend>chan_local</depend>
00168    <support_level>core</support_level>
00169  ***/
00170 
00171 /*!  \page sip_session_timers SIP Session Timers in Asterisk Chan_sip
00172 
00173    The SIP Session-Timers is an extension of the SIP protocol that allows end-points and proxies to
00174    refresh a session periodically. The sessions are kept alive by sending a RE-INVITE or UPDATE
00175    request at a negotiated interval. If a session refresh fails then all the entities that support Session-
00176    Timers clear their internal session state. In addition, UAs generate a BYE request in order to clear
00177    the state in the proxies and the remote UA (this is done for the benefit of SIP entities in the path
00178    that do not support Session-Timers).
00179 
00180    The Session-Timers can be configured on a system-wide, per-user, or per-peer basis. The peruser/
00181    per-peer settings override the global settings. The following new parameters have been
00182    added to the sip.conf file.
00183       session-timers=["accept", "originate", "refuse"]
00184       session-expires=[integer]
00185       session-minse=[integer]
00186       session-refresher=["uas", "uac"]
00187 
00188    The session-timers parameter in sip.conf defines the mode of operation of SIP session-timers feature in
00189    Asterisk. The Asterisk can be configured in one of the following three modes:
00190 
00191    1. Accept :: In the "accept" mode, the Asterisk server honors session-timers requests
00192       made by remote end-points. A remote end-point can request Asterisk to engage
00193       session-timers by either sending it an INVITE request with a "Supported: timer"
00194       header in it or by responding to Asterisk's INVITE with a 200 OK that contains
00195       Session-Expires: header in it. In this mode, the Asterisk server does not
00196       request session-timers from remote end-points. This is the default mode.
00197    2. Originate :: In the "originate" mode, the Asterisk server requests the remote
00198       end-points to activate session-timers in addition to honoring such requests
00199       made by the remote end-pints. In order to get as much protection as possible
00200       against hanging SIP channels due to network or end-point failures, Asterisk
00201       resends periodic re-INVITEs even if a remote end-point does not support
00202       the session-timers feature.
00203    3. Refuse :: In the "refuse" mode, Asterisk acts as if it does not support session-
00204       timers for inbound or outbound requests. If a remote end-point requests
00205       session-timers in a dialog, then Asterisk ignores that request unless it's
00206       noted as a requirement (Require: header), in which case the INVITE is
00207       rejected with a 420 Bad Extension response.
00208 
00209 */
00210 
00211 #include "asterisk.h"
00212 
00213 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 417677 $")
00214 
00215 #include <signal.h>
00216 #include <sys/signal.h>
00217 #include <regex.h>
00218 #include <inttypes.h>
00219 
00220 #include "asterisk/network.h"
00221 #include "asterisk/paths.h"   /* need ast_config_AST_SYSTEM_NAME */
00222 #include "asterisk/lock.h"
00223 #include "asterisk/config.h"
00224 #include "asterisk/module.h"
00225 #include "asterisk/pbx.h"
00226 #include "asterisk/sched.h"
00227 #include "asterisk/io.h"
00228 #include "asterisk/rtp_engine.h"
00229 #include "asterisk/udptl.h"
00230 #include "asterisk/acl.h"
00231 #include "asterisk/manager.h"
00232 #include "asterisk/callerid.h"
00233 #include "asterisk/cli.h"
00234 #include "asterisk/musiconhold.h"
00235 #include "asterisk/dsp.h"
00236 #include "asterisk/features.h"
00237 #include "asterisk/srv.h"
00238 #include "asterisk/astdb.h"
00239 #include "asterisk/causes.h"
00240 #include "asterisk/utils.h"
00241 #include "asterisk/file.h"
00242 #include "asterisk/astobj2.h"
00243 #include "asterisk/dnsmgr.h"
00244 #include "asterisk/devicestate.h"
00245 #include "asterisk/monitor.h"
00246 #include "asterisk/netsock2.h"
00247 #include "asterisk/localtime.h"
00248 #include "asterisk/abstract_jb.h"
00249 #include "asterisk/threadstorage.h"
00250 #include "asterisk/translate.h"
00251 #include "asterisk/ast_version.h"
00252 #include "asterisk/event.h"
00253 #include "asterisk/cel.h"
00254 #include "asterisk/data.h"
00255 #include "asterisk/aoc.h"
00256 #include "asterisk/message.h"
00257 #include "sip/include/sip.h"
00258 #include "sip/include/globals.h"
00259 #include "sip/include/config_parser.h"
00260 #include "sip/include/reqresp_parser.h"
00261 #include "sip/include/sip_utils.h"
00262 #include "sip/include/srtp.h"
00263 #include "sip/include/sdp_crypto.h"
00264 #include "asterisk/ccss.h"
00265 #include "asterisk/xml.h"
00266 #include "sip/include/dialog.h"
00267 #include "sip/include/dialplan_functions.h"
00268 #include "sip/include/security_events.h"
00269 #include "asterisk/sip_api.h"
00270 
00271 /*** DOCUMENTATION
00272    <application name="SIPDtmfMode" language="en_US">
00273       <synopsis>
00274          Change the dtmfmode for a SIP call.
00275       </synopsis>
00276       <syntax>
00277          <parameter name="mode" required="true">
00278             <enumlist>
00279                <enum name="inband" />
00280                <enum name="info" />
00281                <enum name="rfc2833" />
00282             </enumlist>
00283          </parameter>
00284       </syntax>
00285       <description>
00286          <para>Changes the dtmfmode for a SIP call.</para>
00287       </description>
00288    </application>
00289    <application name="SIPAddHeader" language="en_US">
00290       <synopsis>
00291          Add a SIP header to the outbound call.
00292       </synopsis>
00293       <syntax argsep=":">
00294          <parameter name="Header" required="true" />
00295          <parameter name="Content" required="true" />
00296       </syntax>
00297       <description>
00298          <para>Adds a header to a SIP call placed with DIAL.</para>
00299          <para>Remember to use the X-header if you are adding non-standard SIP
00300          headers, like <literal>X-Asterisk-Accountcode:</literal>. Use this with care.
00301          Adding the wrong headers may jeopardize the SIP dialog.</para>
00302          <para>Always returns <literal>0</literal>.</para>
00303       </description>
00304    </application>
00305    <application name="SIPRemoveHeader" language="en_US">
00306       <synopsis>
00307          Remove SIP headers previously added with SIPAddHeader
00308       </synopsis>
00309       <syntax>
00310          <parameter name="Header" required="false" />
00311       </syntax>
00312       <description>
00313          <para>SIPRemoveHeader() allows you to remove headers which were previously
00314          added with SIPAddHeader(). If no parameter is supplied, all previously added
00315          headers will be removed. If a parameter is supplied, only the matching headers
00316          will be removed.</para>
00317          <para>For example you have added these 2 headers:</para>
00318          <para>SIPAddHeader(P-Asserted-Identity: sip:foo@bar);</para>
00319          <para>SIPAddHeader(P-Preferred-Identity: sip:bar@foo);</para>
00320          <para></para>
00321          <para>// remove all headers</para>
00322          <para>SIPRemoveHeader();</para>
00323          <para>// remove all P- headers</para>
00324          <para>SIPRemoveHeader(P-);</para>
00325          <para>// remove only the PAI header (note the : at the end)</para>
00326          <para>SIPRemoveHeader(P-Asserted-Identity:);</para>
00327          <para></para>
00328          <para>Always returns <literal>0</literal>.</para>
00329       </description>
00330    </application>
00331    <application name="SIPSendCustomINFO" language="en_US">
00332       <synopsis>
00333          Send a custom INFO frame on specified channels.
00334       </synopsis>
00335       <syntax>
00336          <parameter name="Data" required="true" />
00337          <parameter name="UserAgent" required="false" />
00338       </syntax>
00339       <description>
00340          <para>SIPSendCustomINFO() allows you to send a custom INFO message on all
00341          active SIP channels or on channels with the specified User Agent. This
00342          application is only available if TEST_FRAMEWORK is defined.</para>
00343       </description>
00344    </application>
00345    <function name="SIP_HEADER" language="en_US">
00346       <synopsis>
00347          Gets the specified SIP header from an incoming INVITE message.
00348       </synopsis>
00349       <syntax>
00350          <parameter name="name" required="true" />
00351          <parameter name="number">
00352             <para>If not specified, defaults to <literal>1</literal>.</para>
00353          </parameter>
00354       </syntax>
00355       <description>
00356          <para>Since there are several headers (such as Via) which can occur multiple
00357          times, SIP_HEADER takes an optional second argument to specify which header with
00358          that name to retrieve. Headers start at offset <literal>1</literal>.</para>
00359          <para>Please observe that contents of the SDP (an attachment to the 
00360          SIP request) can't be accessed with this function.</para>
00361       </description>
00362    </function>
00363    <function name="SIPPEER" language="en_US">
00364       <synopsis>
00365          Gets SIP peer information.
00366       </synopsis>
00367       <syntax>
00368          <parameter name="peername" required="true" />
00369          <parameter name="item">
00370             <enumlist>
00371                <enum name="ip">
00372                   <para>(default) The IP address.</para>
00373                </enum>
00374                <enum name="port">
00375                   <para>The port number.</para>
00376                </enum>
00377                <enum name="mailbox">
00378                   <para>The configured mailbox.</para>
00379                </enum>
00380                <enum name="context">
00381                   <para>The configured context.</para>
00382                </enum>
00383                <enum name="expire">
00384                   <para>The epoch time of the next expire.</para>
00385                </enum>
00386                <enum name="dynamic">
00387                   <para>Is it dynamic? (yes/no).</para>
00388                </enum>
00389                <enum name="callerid_name">
00390                   <para>The configured Caller ID name.</para>
00391                </enum>
00392                <enum name="callerid_num">
00393                   <para>The configured Caller ID number.</para>
00394                </enum>
00395                <enum name="callgroup">
00396                   <para>The configured Callgroup.</para>
00397                </enum>
00398                <enum name="pickupgroup">
00399                   <para>The configured Pickupgroup.</para>
00400                </enum>
00401                <enum name="namedcallgroup">
00402                   <para>The configured Named Callgroup.</para>
00403                </enum>
00404                <enum name="namedpickupgroup">
00405                   <para>The configured Named Pickupgroup.</para>
00406                </enum>
00407                <enum name="codecs">
00408                   <para>The configured codecs.</para>
00409                </enum>
00410                <enum name="status">
00411                   <para>Status (if qualify=yes).</para>
00412                </enum>
00413                <enum name="regexten">
00414                   <para>Extension activated at registration.</para>
00415                </enum>
00416                <enum name="limit">
00417                   <para>Call limit (call-limit).</para>
00418                </enum>
00419                <enum name="busylevel">
00420                   <para>Configured call level for signalling busy.</para>
00421                </enum>
00422                <enum name="curcalls">
00423                   <para>Current amount of calls. Only available if call-limit is set.</para>
00424                </enum>
00425                <enum name="language">
00426                   <para>Default language for peer.</para>
00427                </enum>
00428                <enum name="accountcode">
00429                   <para>Account code for this peer.</para>
00430                </enum>
00431                <enum name="useragent">
00432                   <para>Current user agent header used by peer.</para>
00433                </enum>
00434                <enum name="maxforwards">
00435                   <para>The value used for SIP loop prevention in outbound requests</para>
00436                </enum>
00437                <enum name="chanvar[name]">
00438                   <para>A channel variable configured with setvar for this peer.</para>
00439                </enum>
00440                <enum name="codec[x]">
00441                   <para>Preferred codec index number <replaceable>x</replaceable> (beginning with zero).</para>
00442                </enum>
00443             </enumlist>
00444          </parameter>
00445       </syntax>
00446       <description></description>
00447    </function>
00448    <function name="SIPCHANINFO" language="en_US">
00449       <synopsis>
00450          Gets the specified SIP parameter from the current channel.
00451       </synopsis>
00452       <syntax>
00453          <parameter name="item" required="true">
00454             <enumlist>
00455                <enum name="peerip">
00456                   <para>The IP address of the peer.</para>
00457                </enum>
00458                <enum name="recvip">
00459                   <para>The source IP address of the peer.</para>
00460                </enum>
00461                <enum name="from">
00462                   <para>The SIP URI from the <literal>From:</literal> header.</para>
00463                </enum>
00464                <enum name="uri">
00465                   <para>The SIP URI from the <literal>Contact:</literal> header.</para>
00466                </enum>
00467                <enum name="useragent">
00468                   <para>The Useragent header used by the peer.</para>
00469                </enum>
00470                <enum name="peername">
00471                   <para>The name of the peer.</para>
00472                </enum>
00473                <enum name="t38passthrough">
00474                   <para><literal>1</literal> if T38 is offered or enabled in this channel,
00475                   otherwise <literal>0</literal>.</para>
00476                </enum>
00477             </enumlist>
00478          </parameter>
00479       </syntax>
00480       <description></description>
00481    </function>
00482    <function name="CHECKSIPDOMAIN" language="en_US">
00483       <synopsis>
00484          Checks if domain is a local domain.
00485       </synopsis>
00486       <syntax>
00487          <parameter name="domain" required="true" />
00488       </syntax>
00489       <description>
00490          <para>This function checks if the <replaceable>domain</replaceable> in the argument is configured
00491          as a local SIP domain that this Asterisk server is configured to handle.
00492          Returns the domain name if it is locally handled, otherwise an empty string.
00493          Check the <literal>domain=</literal> configuration in <filename>sip.conf</filename>.</para>
00494       </description>
00495    </function>
00496    <manager name="SIPpeers" language="en_US">
00497       <synopsis>
00498          List SIP peers (text format).
00499       </synopsis>
00500       <syntax>
00501          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00502       </syntax>
00503       <description>
00504          <para>Lists SIP peers in text format with details on current status.
00505          <literal>Peerlist</literal> will follow as separate events, followed by a final event called
00506          <literal>PeerlistComplete</literal>.</para>
00507       </description>
00508    </manager>
00509    <manager name="SIPshowpeer" language="en_US">
00510       <synopsis>
00511          show SIP peer (text format).
00512       </synopsis>
00513       <syntax>
00514          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00515          <parameter name="Peer" required="true">
00516             <para>The peer name you want to check.</para>
00517          </parameter>
00518       </syntax>
00519       <description>
00520          <para>Show one SIP peer with details on current status.</para>
00521       </description>
00522    </manager>
00523    <manager name="SIPqualifypeer" language="en_US">
00524       <synopsis>
00525          Qualify SIP peers.
00526       </synopsis>
00527       <syntax>
00528          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00529          <parameter name="Peer" required="true">
00530             <para>The peer name you want to qualify.</para>
00531          </parameter>
00532       </syntax>
00533       <description>
00534          <para>Qualify a SIP peer.</para>
00535       </description>
00536    </manager>
00537    <manager name="SIPshowregistry" language="en_US">
00538       <synopsis>
00539          Show SIP registrations (text format).
00540       </synopsis>
00541       <syntax>
00542          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00543       </syntax>
00544       <description>
00545          <para>Lists all registration requests and status. Registrations will follow as separate
00546          events followed by a final event called <literal>RegistrationsComplete</literal>.</para>
00547       </description>
00548    </manager>
00549    <manager name="SIPnotify" language="en_US">
00550       <synopsis>
00551          Send a SIP notify.
00552       </synopsis>
00553       <syntax>
00554          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00555          <parameter name="Channel" required="true">
00556             <para>Peer to receive the notify.</para>
00557          </parameter>
00558          <parameter name="Variable" required="true">
00559             <para>At least one variable pair must be specified.
00560             <replaceable>name</replaceable>=<replaceable>value</replaceable></para>
00561          </parameter>
00562       </syntax>
00563       <description>
00564          <para>Sends a SIP Notify event.</para>
00565          <para>All parameters for this event must be specified in the body of this request
00566          via multiple <literal>Variable: name=value</literal> sequences.</para>
00567       </description>
00568    </manager>
00569    <manager name="SIPpeerstatus" language="en_US">
00570       <synopsis>
00571          Show the status of one or all of the sip peers.
00572       </synopsis>
00573       <syntax>
00574          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00575          <parameter name="Peer" required="false">
00576             <para>The peer name you want to check.</para>
00577          </parameter>
00578       </syntax>
00579       <description>
00580          <para>Retrieves the status of one or all of the sip peers.  If no peer name is specified, status
00581          for all of the sip peers will be retrieved.</para>
00582       </description>
00583    </manager>
00584    <info name="SIPMessageFromInfo" language="en_US" tech="SIP">
00585       <para>The <literal>from</literal> parameter can be a configured peer name
00586       or in the form of "display-name" &lt;URI&gt;.</para>
00587    </info>
00588    <info name="SIPMessageToInfo" language="en_US" tech="SIP">
00589       <para>Specifying a prefix of <literal>sip:</literal> will send the
00590       message as a SIP MESSAGE request.</para>
00591    </info>
00592  ***/
00593 
00594 static int min_expiry = DEFAULT_MIN_EXPIRY;        /*!< Minimum accepted registration time */
00595 static int max_expiry = DEFAULT_MAX_EXPIRY;        /*!< Maximum accepted registration time */
00596 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
00597 static int min_subexpiry = DEFAULT_MIN_EXPIRY;     /*!< Minimum accepted subscription time */
00598 static int max_subexpiry = DEFAULT_MAX_EXPIRY;     /*!< Maximum accepted subscription time */
00599 static int mwi_expiry = DEFAULT_MWI_EXPIRY;
00600 
00601 static int unauth_sessions = 0;
00602 static int authlimit = DEFAULT_AUTHLIMIT;
00603 static int authtimeout = DEFAULT_AUTHTIMEOUT;
00604 
00605 /*! \brief Global jitterbuffer configuration - by default, jb is disabled
00606  *  \note Values shown here match the defaults shown in sip.conf.sample */
00607 static struct ast_jb_conf default_jbconf =
00608 {
00609    .flags = 0,
00610    .max_size = 200,
00611    .resync_threshold = 1000,
00612    .impl = "fixed",
00613    .target_extra = 40,
00614 };
00615 static struct ast_jb_conf global_jbconf;                /*!< Global jitterbuffer configuration */
00616 
00617 static const char config[] = "sip.conf";                /*!< Main configuration file */
00618 static const char notify_config[] = "sip_notify.conf";  /*!< Configuration file for sending Notify with CLI commands to reconfigure or reboot phones */
00619 
00620 /*! \brief Readable descriptions of device states.
00621  *  \note Should be aligned to above table as index */
00622 static const struct invstate2stringtable {
00623    const enum invitestates state;
00624    const char *desc;
00625 } invitestate2string[] = {
00626    {INV_NONE,              "None"  },
00627    {INV_CALLING,           "Calling (Trying)"},
00628    {INV_PROCEEDING,        "Proceeding "},
00629    {INV_EARLY_MEDIA,       "Early media"},
00630    {INV_COMPLETED,         "Completed (done)"},
00631    {INV_CONFIRMED,         "Confirmed (up)"},
00632    {INV_TERMINATED,        "Done"},
00633    {INV_CANCELLED,         "Cancelled"}
00634 };
00635 
00636 /*! \brief Subscription types that we support. We support
00637  * - dialoginfo updates (really device status, not dialog info as was the original intent of the standard)
00638  * - SIMPLE presence used for device status
00639  * - Voicemail notification subscriptions
00640  */
00641 static const struct cfsubscription_types {
00642    enum subscriptiontype type;
00643    const char * const event;
00644    const char * const mediatype;
00645    const char * const text;
00646 } subscription_types[] = {
00647    { NONE,        "-",        "unknown",               "unknown" },
00648    /* RFC 4235: SIP Dialog event package */
00649    { DIALOG_INFO_XML, "dialog",   "application/dialog-info+xml", "dialog-info+xml" },
00650    { CPIM_PIDF_XML,   "presence", "application/cpim-pidf+xml",   "cpim-pidf+xml" },  /* RFC 3863 */
00651    { PIDF_XML,        "presence", "application/pidf+xml",        "pidf+xml" },       /* RFC 3863 */
00652    { XPIDF_XML,       "presence", "application/xpidf+xml",       "xpidf+xml" },       /* Pre-RFC 3863 with MS additions */
00653    { MWI_NOTIFICATION,  "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
00654 };
00655 
00656 /*! \brief The core structure to setup dialogs. We parse incoming messages by using
00657  *  structure and then route the messages according to the type.
00658  *
00659  *  \note Note that sip_methods[i].id == i must hold or the code breaks
00660  */
00661 static const struct  cfsip_methods {
00662    enum sipmethod id;
00663    int need_rtp;     /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
00664    char * const text;
00665    enum can_create_dialog can_create;
00666 } sip_methods[] = {
00667    { SIP_UNKNOWN,   RTP,    "-UNKNOWN-",CAN_CREATE_DIALOG },
00668    { SIP_RESPONSE,  NO_RTP, "SIP/2.0",  CAN_NOT_CREATE_DIALOG },
00669    { SIP_REGISTER,  NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
00670    { SIP_OPTIONS,   NO_RTP, "OPTIONS",  CAN_CREATE_DIALOG },
00671    { SIP_NOTIFY,    NO_RTP, "NOTIFY",   CAN_CREATE_DIALOG },
00672    { SIP_INVITE,    RTP,    "INVITE",   CAN_CREATE_DIALOG },
00673    { SIP_ACK,       NO_RTP, "ACK",      CAN_NOT_CREATE_DIALOG },
00674    { SIP_PRACK,     NO_RTP, "PRACK",    CAN_NOT_CREATE_DIALOG },
00675    { SIP_BYE,       NO_RTP, "BYE",      CAN_NOT_CREATE_DIALOG },
00676    { SIP_REFER,     NO_RTP, "REFER",    CAN_CREATE_DIALOG },
00677    { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE",CAN_CREATE_DIALOG },
00678    { SIP_MESSAGE,   NO_RTP, "MESSAGE",  CAN_CREATE_DIALOG },
00679    { SIP_UPDATE,    NO_RTP, "UPDATE",   CAN_NOT_CREATE_DIALOG },
00680    { SIP_INFO,      NO_RTP, "INFO",     CAN_NOT_CREATE_DIALOG },
00681    { SIP_CANCEL,    NO_RTP, "CANCEL",   CAN_NOT_CREATE_DIALOG },
00682    { SIP_PUBLISH,   NO_RTP, "PUBLISH",  CAN_CREATE_DIALOG },
00683    { SIP_PING,      NO_RTP, "PING",     CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
00684 };
00685 
00686 /*! \brief Diversion header reasons
00687  *
00688  * The core defines a bunch of constants used to define
00689  * redirecting reasons. This provides a translation table
00690  * between those and the strings which may be present in
00691  * a SIP Diversion header
00692  */
00693 static const struct sip_reasons {
00694    enum AST_REDIRECTING_REASON code;
00695    char * const text;
00696 } sip_reason_table[] = {
00697    { AST_REDIRECTING_REASON_UNKNOWN, "unknown" },
00698    { AST_REDIRECTING_REASON_USER_BUSY, "user-busy" },
00699    { AST_REDIRECTING_REASON_NO_ANSWER, "no-answer" },
00700    { AST_REDIRECTING_REASON_UNAVAILABLE, "unavailable" },
00701    { AST_REDIRECTING_REASON_UNCONDITIONAL, "unconditional" },
00702    { AST_REDIRECTING_REASON_TIME_OF_DAY, "time-of-day" },
00703    { AST_REDIRECTING_REASON_DO_NOT_DISTURB, "do-not-disturb" },
00704    { AST_REDIRECTING_REASON_DEFLECTION, "deflection" },
00705    { AST_REDIRECTING_REASON_FOLLOW_ME, "follow-me" },
00706    { AST_REDIRECTING_REASON_OUT_OF_ORDER, "out-of-service" },
00707    { AST_REDIRECTING_REASON_AWAY, "away" },
00708    { AST_REDIRECTING_REASON_CALL_FWD_DTE, "unknown"},
00709    { AST_REDIRECTING_REASON_SEND_TO_VM, "send_to_vm"},
00710 };
00711 
00712 
00713 /*! \name DefaultSettings
00714    Default setttings are used as a channel setting and as a default when
00715    configuring devices
00716 */
00717 /*@{*/
00718 static char default_language[MAX_LANGUAGE];      /*!< Default language setting for new channels */
00719 static char default_callerid[AST_MAX_EXTENSION]; /*!< Default caller ID for sip messages */
00720 static char default_mwi_from[80];                /*!< Default caller ID for MWI updates */
00721 static char default_fromdomain[AST_MAX_EXTENSION]; /*!< Default domain on outound messages */
00722 static int default_fromdomainport;                 /*!< Default domain port on outbound messages */
00723 static char default_notifymime[AST_MAX_EXTENSION]; /*!< Default MIME media type for MWI notify messages */
00724 static char default_vmexten[AST_MAX_EXTENSION];    /*!< Default From Username on MWI updates */
00725 static int default_qualify;                        /*!< Default Qualify= setting */
00726 static int default_keepalive;                      /*!< Default keepalive= setting */
00727 static char default_mohinterpret[MAX_MUSICCLASS];  /*!< Global setting for moh class to use when put on hold */
00728 static char default_mohsuggest[MAX_MUSICCLASS];    /*!< Global setting for moh class to suggest when putting
00729                                                     *   a bridged channel on hold */
00730 static char default_parkinglot[AST_MAX_CONTEXT];   /*!< Parkinglot */
00731 static char default_engine[256];                   /*!< Default RTP engine */
00732 static int default_maxcallbitrate;                 /*!< Maximum bitrate for call */
00733 static struct ast_codec_pref default_prefs;        /*!< Default codec prefs */
00734 static char default_zone[MAX_TONEZONE_COUNTRY];        /*!< Default tone zone for channels created from the SIP driver */
00735 static unsigned int default_transports;            /*!< Default Transports (enum sip_transport) that are acceptable */
00736 static unsigned int default_primary_transport;     /*!< Default primary Transport (enum sip_transport) for outbound connections to devices */
00737 /*@}*/
00738 
00739 static struct sip_settings sip_cfg;    /*!< SIP configuration data.
00740                \note in the future we could have multiple of these (per domain, per device group etc) */
00741 
00742 /*!< use this macro when ast_uri_decode is dependent on pedantic checking to be on. */
00743 #define SIP_PEDANTIC_DECODE(str) \
00744    if (sip_cfg.pedanticsipchecking && !ast_strlen_zero(str)) { \
00745       ast_uri_decode(str, ast_uri_sip_user); \
00746    }  \
00747 
00748 static unsigned int chan_idx;       /*!< used in naming sip channel */
00749 static int global_match_auth_username;    /*!< Match auth username if available instead of From: Default off. */
00750 
00751 static int global_relaxdtmf;        /*!< Relax DTMF */
00752 static int global_prematuremediafilter;   /*!< Enable/disable premature frames in a call (causing 183 early media) */
00753 static int global_rtptimeout;       /*!< Time out call if no RTP */
00754 static int global_rtpholdtimeout;   /*!< Time out call if no RTP during hold */
00755 static int global_rtpkeepalive;     /*!< Send RTP keepalives */
00756 static int global_reg_timeout;      /*!< Global time between attempts for outbound registrations */
00757 static int global_regattempts_max;  /*!< Registration attempts before giving up */
00758 static int global_reg_retry_403;    /*!< Treat 403 responses to registrations as 401 responses */
00759 static int global_shrinkcallerid;   /*!< enable or disable shrinking of caller id  */
00760 static int global_callcounter;      /*!< Enable call counters for all devices. This is currently enabled by setting the peer
00761                                      *   call-limit to INT_MAX. When we remove the call-limit from the code, we can make it
00762                                      *   with just a boolean flag in the device structure */
00763 static unsigned int global_tos_sip;      /*!< IP type of service for SIP packets */
00764 static unsigned int global_tos_audio;    /*!< IP type of service for audio RTP packets */
00765 static unsigned int global_tos_video;    /*!< IP type of service for video RTP packets */
00766 static unsigned int global_tos_text;     /*!< IP type of service for text RTP packets */
00767 static unsigned int global_cos_sip;      /*!< 802.1p class of service for SIP packets */
00768 static unsigned int global_cos_audio;    /*!< 802.1p class of service for audio RTP packets */
00769 static unsigned int global_cos_video;    /*!< 802.1p class of service for video RTP packets */
00770 static unsigned int global_cos_text;     /*!< 802.1p class of service for text RTP packets */
00771 static unsigned int recordhistory;       /*!< Record SIP history. Off by default */
00772 static unsigned int dumphistory;         /*!< Dump history to verbose before destroying SIP dialog */
00773 static char global_useragent[AST_MAX_EXTENSION];    /*!< Useragent for the SIP channel */
00774 static char global_sdpsession[AST_MAX_EXTENSION];   /*!< SDP session name for the SIP channel */
00775 static char global_sdpowner[AST_MAX_EXTENSION];     /*!< SDP owner name for the SIP channel */
00776 static int global_authfailureevents;     /*!< Whether we send authentication failure manager events or not. Default no. */
00777 static int global_t1;           /*!< T1 time */
00778 static int global_t1min;        /*!< T1 roundtrip time minimum */
00779 static int global_timer_b;      /*!< Timer B - RFC 3261 Section 17.1.1.2 */
00780 static unsigned int global_autoframing; /*!< Turn autoframing on or off. */
00781 static int global_qualifyfreq;          /*!< Qualify frequency */
00782 static int global_qualify_gap;          /*!< Time between our group of peer pokes */
00783 static int global_qualify_peers;        /*!< Number of peers to poke at a given time */
00784 
00785 static enum st_mode global_st_mode;           /*!< Mode of operation for Session-Timers           */
00786 static enum st_refresher_param global_st_refresher; /*!< Session-Timer refresher                        */
00787 static int global_min_se;                     /*!< Lowest threshold for session refresh interval  */
00788 static int global_max_se;                     /*!< Highest threshold for session refresh interval */
00789 
00790 static int global_store_sip_cause;    /*!< Whether the MASTER_CHANNEL(HASH(SIP_CAUSE,[chan_name])) var should be set */
00791 
00792 static int global_dynamic_exclude_static = 0; /*!< Exclude static peers from contact registrations */
00793 static unsigned char global_refer_addheaders; /*!< Add extra headers to outgoing REFER */
00794 /*@}*/
00795 
00796 /*!
00797  * We use libxml2 in order to parse XML that may appear in the body of a SIP message. Currently,
00798  * the only usage is for parsing PIDF bodies of incoming PUBLISH requests in the call-completion
00799  * event package. This variable is set at module load time and may be checked at runtime to determine
00800  * if XML parsing support was found.
00801  */
00802 static int can_parse_xml;
00803 
00804 /*! \name Object counters @{
00805  *  \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
00806  *  should be used to modify these values. */
00807 static int speerobjs = 0;     /*!< Static peers */
00808 static int rpeerobjs = 0;     /*!< Realtime peers */
00809 static int apeerobjs = 0;     /*!< Autocreated peer objects */
00810 static int regobjs = 0;       /*!< Registry objects */
00811 /* }@ */
00812 
00813 static struct ast_flags global_flags[3] = {{0}};  /*!< global SIP_ flags */
00814 static unsigned int global_t38_maxdatagram;                /*!< global T.38 FaxMaxDatagram override */
00815 
00816 static struct ast_event_sub *network_change_event_subscription; /*!< subscription id for network change events */
00817 static struct ast_event_sub *acl_change_event_subscription; /*!< subscription id for named ACL system change events */
00818 static int network_change_event_sched_id = -1;
00819 
00820 static char used_context[AST_MAX_CONTEXT];        /*!< name of automatically created context for unloading */
00821 
00822 AST_MUTEX_DEFINE_STATIC(netlock);
00823 
00824 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
00825    when it's doing something critical. */
00826 AST_MUTEX_DEFINE_STATIC(monlock);
00827 
00828 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
00829 
00830 /*! \brief This is the thread for the monitor which checks for input on the channels
00831    which are not currently in use.  */
00832 static pthread_t monitor_thread = AST_PTHREADT_NULL;
00833 
00834 static int sip_reloading = FALSE;                       /*!< Flag for avoiding multiple reloads at the same time */
00835 static enum channelreloadreason sip_reloadreason;       /*!< Reason for last reload/load of configuration */
00836 
00837 struct ast_sched_context *sched;     /*!< The scheduling context */
00838 static struct io_context *io;           /*!< The IO context */
00839 static int *sipsock_read_id;            /*!< ID of IO entry for sipsock FD */
00840 struct sip_pkt;
00841 static AST_LIST_HEAD_STATIC(domain_list, domain);    /*!< The SIP domain list */
00842 
00843 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
00844 
00845 static enum sip_debug_e sipdebug;
00846 
00847 /*! \brief extra debugging for 'text' related events.
00848  *  At the moment this is set together with sip_debug_console.
00849  *  \note It should either go away or be implemented properly.
00850  */
00851 static int sipdebug_text;
00852 
00853 static const struct _map_x_s referstatusstrings[] = {
00854    { REFER_IDLE,      "<none>" },
00855    { REFER_SENT,      "Request sent" },
00856    { REFER_RECEIVED,  "Request received" },
00857    { REFER_CONFIRMED, "Confirmed" },
00858    { REFER_ACCEPTED,  "Accepted" },
00859    { REFER_RINGING,   "Target ringing" },
00860    { REFER_200OK,     "Done" },
00861    { REFER_FAILED,    "Failed" },
00862    { REFER_NOAUTH,    "Failed - auth failure" },
00863    { -1,               NULL} /* terminator */
00864 };
00865 
00866 /* --- Hash tables of various objects --------*/
00867 #ifdef LOW_MEMORY
00868 static const int HASH_PEER_SIZE = 17;
00869 static const int HASH_DIALOG_SIZE = 17;
00870 #else
00871 static const int HASH_PEER_SIZE = 563; /*!< Size of peer hash table, prime number preferred! */
00872 static const int HASH_DIALOG_SIZE = 563;
00873 #endif
00874 
00875 static const struct {
00876    enum ast_cc_service_type service;
00877    const char *service_string;
00878 } sip_cc_service_map [] = {
00879    [AST_CC_NONE] = { AST_CC_NONE, "" },
00880    [AST_CC_CCBS] = { AST_CC_CCBS, "BS" },
00881    [AST_CC_CCNR] = { AST_CC_CCNR, "NR" },
00882    [AST_CC_CCNL] = { AST_CC_CCNL, "NL" },
00883 };
00884 
00885 static enum ast_cc_service_type service_string_to_service_type(const char * const service_string)
00886 {
00887    enum ast_cc_service_type service;
00888    for (service = AST_CC_CCBS; service <= AST_CC_CCNL; ++service) {
00889       if (!strcasecmp(service_string, sip_cc_service_map[service].service_string)) {
00890          return service;
00891       }
00892    }
00893    return AST_CC_NONE;
00894 }
00895 
00896 static const struct {
00897    enum sip_cc_notify_state state;
00898    const char *state_string;
00899 } sip_cc_notify_state_map [] = {
00900    [CC_QUEUED] = {CC_QUEUED, "cc-state: queued"},
00901    [CC_READY] = {CC_READY, "cc-state: ready"},
00902 };
00903 
00904 AST_LIST_HEAD_STATIC(epa_static_data_list, epa_backend);
00905 
00906 static int sip_epa_register(const struct epa_static_data *static_data)
00907 {
00908    struct epa_backend *backend = ast_calloc(1, sizeof(*backend));
00909 
00910    if (!backend) {
00911       return -1;
00912    }
00913 
00914    backend->static_data = static_data;
00915 
00916    AST_LIST_LOCK(&epa_static_data_list);
00917    AST_LIST_INSERT_TAIL(&epa_static_data_list, backend, next);
00918    AST_LIST_UNLOCK(&epa_static_data_list);
00919    return 0;
00920 }
00921 
00922 static void sip_epa_unregister_all(void)
00923 {
00924    struct epa_backend *backend;
00925 
00926    AST_LIST_LOCK(&epa_static_data_list);
00927    while ((backend = AST_LIST_REMOVE_HEAD(&epa_static_data_list, next))) {
00928       ast_free(backend);
00929    }
00930    AST_LIST_UNLOCK(&epa_static_data_list);
00931 }
00932 
00933 static void cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry);
00934 
00935 static void cc_epa_destructor(void *data)
00936 {
00937    struct sip_epa_entry *epa_entry = data;
00938    struct cc_epa_entry *cc_entry = epa_entry->instance_data;
00939    ast_free(cc_entry);
00940 }
00941 
00942 static const struct epa_static_data cc_epa_static_data  = {
00943    .event = CALL_COMPLETION,
00944    .name = "call-completion",
00945    .handle_error = cc_handle_publish_error,
00946    .destructor = cc_epa_destructor,
00947 };
00948 
00949 static const struct epa_static_data *find_static_data(const char * const event_package)
00950 {
00951    const struct epa_backend *backend = NULL;
00952 
00953    AST_LIST_LOCK(&epa_static_data_list);
00954    AST_LIST_TRAVERSE(&epa_static_data_list, backend, next) {
00955       if (!strcmp(backend->static_data->name, event_package)) {
00956          break;
00957       }
00958    }
00959    AST_LIST_UNLOCK(&epa_static_data_list);
00960    return backend ? backend->static_data : NULL;
00961 }
00962 
00963 static struct sip_epa_entry *create_epa_entry (const char * const event_package, const char * const destination)
00964 {
00965    struct sip_epa_entry *epa_entry;
00966    const struct epa_static_data *static_data;
00967 
00968    if (!(static_data = find_static_data(event_package))) {
00969       return NULL;
00970    }
00971 
00972    if (!(epa_entry = ao2_t_alloc(sizeof(*epa_entry), static_data->destructor, "Allocate new EPA entry"))) {
00973       return NULL;
00974    }
00975 
00976    epa_entry->static_data = static_data;
00977    ast_copy_string(epa_entry->destination, destination, sizeof(epa_entry->destination));
00978    return epa_entry;
00979 }
00980 
00981 /*!
00982  * Used to create new entity IDs by ESCs.
00983  */
00984 static int esc_etag_counter;
00985 static const int DEFAULT_PUBLISH_EXPIRES = 3600;
00986 
00987 #ifdef HAVE_LIBXML2
00988 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);
00989 
00990 static const struct sip_esc_publish_callbacks cc_esc_publish_callbacks = {
00991    .initial_handler = cc_esc_publish_handler,
00992    .modify_handler = cc_esc_publish_handler,
00993 };
00994 #endif
00995 
00996 /*!
00997  * \brief The Event State Compositors
00998  *
00999  * An Event State Compositor is an entity which
01000  * accepts PUBLISH requests and acts appropriately
01001  * based on these requests.
01002  *
01003  * The actual event_state_compositor structure is simply
01004  * an ao2_container of sip_esc_entrys. When an incoming
01005  * PUBLISH is received, we can match the appropriate sip_esc_entry
01006  * using the entity ID of the incoming PUBLISH.
01007  */
01008 static struct event_state_compositor {
01009    enum subscriptiontype event;
01010    const char * name;
01011    const struct sip_esc_publish_callbacks *callbacks;
01012    struct ao2_container *compositor;
01013 } event_state_compositors [] = {
01014 #ifdef HAVE_LIBXML2
01015    {CALL_COMPLETION, "call-completion", &cc_esc_publish_callbacks},
01016 #endif
01017 };
01018 
01019 static const int ESC_MAX_BUCKETS = 37;
01020 
01021 static void esc_entry_destructor(void *obj)
01022 {
01023    struct sip_esc_entry *esc_entry = obj;
01024    if (esc_entry->sched_id > -1) {
01025       AST_SCHED_DEL(sched, esc_entry->sched_id);
01026    }
01027 }
01028 
01029 static int esc_hash_fn(const void *obj, const int flags)
01030 {
01031    const struct sip_esc_entry *entry = obj;
01032    return ast_str_hash(entry->entity_tag);
01033 }
01034 
01035 static int esc_cmp_fn(void *obj, void *arg, int flags)
01036 {
01037    struct sip_esc_entry *entry1 = obj;
01038    struct sip_esc_entry *entry2 = arg;
01039 
01040    return (!strcmp(entry1->entity_tag, entry2->entity_tag)) ? (CMP_MATCH | CMP_STOP) : 0;
01041 }
01042 
01043 static struct event_state_compositor *get_esc(const char * const event_package) {
01044    int i;
01045    for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
01046       if (!strcasecmp(event_package, event_state_compositors[i].name)) {
01047          return &event_state_compositors[i];
01048       }
01049    }
01050    return NULL;
01051 }
01052 
01053 static struct sip_esc_entry *get_esc_entry(const char * entity_tag, struct event_state_compositor *esc) {
01054    struct sip_esc_entry *entry;
01055    struct sip_esc_entry finder;
01056 
01057    ast_copy_string(finder.entity_tag, entity_tag, sizeof(finder.entity_tag));
01058 
01059    entry = ao2_find(esc->compositor, &finder, OBJ_POINTER);
01060 
01061    return entry;
01062 }
01063 
01064 static int publish_expire(const void *data)
01065 {
01066    struct sip_esc_entry *esc_entry = (struct sip_esc_entry *) data;
01067    struct event_state_compositor *esc = get_esc(esc_entry->event);
01068 
01069    ast_assert(esc != NULL);
01070 
01071    ao2_unlink(esc->compositor, esc_entry);
01072    ao2_ref(esc_entry, -1);
01073    return 0;
01074 }
01075 
01076 static void create_new_sip_etag(struct sip_esc_entry *esc_entry, int is_linked)
01077 {
01078    int new_etag = ast_atomic_fetchadd_int(&esc_etag_counter, +1);
01079    struct event_state_compositor *esc = get_esc(esc_entry->event);
01080 
01081    ast_assert(esc != NULL);
01082    if (is_linked) {
01083       ao2_unlink(esc->compositor, esc_entry);
01084    }
01085    snprintf(esc_entry->entity_tag, sizeof(esc_entry->entity_tag), "%d", new_etag);
01086    ao2_link(esc->compositor, esc_entry);
01087 }
01088 
01089 static struct sip_esc_entry *create_esc_entry(struct event_state_compositor *esc, struct sip_request *req, const int expires)
01090 {
01091    struct sip_esc_entry *esc_entry;
01092    int expires_ms;
01093 
01094    if (!(esc_entry = ao2_alloc(sizeof(*esc_entry), esc_entry_destructor))) {
01095       return NULL;
01096    }
01097 
01098    esc_entry->event = esc->name;
01099 
01100    expires_ms = expires * 1000;
01101    /* Bump refcount for scheduler */
01102    ao2_ref(esc_entry, +1);
01103    esc_entry->sched_id = ast_sched_add(sched, expires_ms, publish_expire, esc_entry);
01104 
01105    /* Note: This links the esc_entry into the ESC properly */
01106    create_new_sip_etag(esc_entry, 0);
01107 
01108    return esc_entry;
01109 }
01110 
01111 static int initialize_escs(void)
01112 {
01113    int i, res = 0;
01114    for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
01115       if (!((event_state_compositors[i].compositor) =
01116                ao2_container_alloc(ESC_MAX_BUCKETS, esc_hash_fn, esc_cmp_fn))) {
01117          res = -1;
01118       }
01119    }
01120    return res;
01121 }
01122 
01123 static void destroy_escs(void)
01124 {
01125    int i;
01126    for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
01127       ao2_ref(event_state_compositors[i].compositor, -1);
01128    }
01129 }
01130 
01131 struct state_notify_data {
01132    int state;
01133    struct ao2_container *device_state_info;
01134    int presence_state;
01135    const char *presence_subtype;
01136    const char *presence_message;
01137 };
01138 
01139 /*!
01140  * \details
01141  * Here we implement the container for dialogs which are in the
01142  * dialog_needdestroy state to iterate only through the dialogs
01143  * unlink them instead of iterate through all dialogs
01144  */
01145 struct ao2_container *dialogs_needdestroy;
01146 
01147 /*!
01148  * \details
01149  * Here we implement the container for dialogs which have rtp
01150  * traffic and rtptimeout, rtpholdtimeout or rtpkeepalive
01151  * set. We use this container instead the whole dialog list.
01152  */
01153 struct ao2_container *dialogs_rtpcheck;
01154 
01155 /*!
01156  * \details
01157  * Here we implement the container for dialogs (sip_pvt), defining
01158  * generic wrapper functions to ease the transition from the current
01159  * implementation (a single linked list) to a different container.
01160  * In addition to a reference to the container, we need functions to lock/unlock
01161  * the container and individual items, and functions to add/remove
01162  * references to the individual items.
01163  */
01164 static struct ao2_container *dialogs;
01165 #define sip_pvt_lock(x) ao2_lock(x)
01166 #define sip_pvt_trylock(x) ao2_trylock(x)
01167 #define sip_pvt_unlock(x) ao2_unlock(x)
01168 
01169 /*! \brief  The table of TCP threads */
01170 static struct ao2_container *threadt;
01171 
01172 /*! \brief  The peer list: Users, Peers and Friends */
01173 static struct ao2_container *peers;
01174 static struct ao2_container *peers_by_ip;
01175 
01176 /*! \brief  A bogus peer, to be used when authentication should fail */
01177 static struct sip_peer *bogus_peer;
01178 /*! \brief  We can recognise the bogus peer by this invalid MD5 hash */
01179 #define BOGUS_PEER_MD5SECRET "intentionally_invalid_md5_string"
01180 
01181 /*! \brief  The register list: Other SIP proxies we register with and receive calls from */
01182 static struct ast_register_list {
01183    ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
01184    int recheck;
01185 } regl;
01186 
01187 /*! \brief  The MWI subscription list */
01188 static struct ast_subscription_mwi_list {
01189    ASTOBJ_CONTAINER_COMPONENTS(struct sip_subscription_mwi);
01190 } submwil;
01191 static int temp_pvt_init(void *);
01192 static void temp_pvt_cleanup(void *);
01193 
01194 /*! \brief A per-thread temporary pvt structure */
01195 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
01196 
01197 /*! \brief A per-thread buffer for transport to string conversion */
01198 AST_THREADSTORAGE(sip_transport_str_buf);
01199 
01200 /*! \brief Size of the SIP transport buffer */
01201 #define SIP_TRANSPORT_STR_BUFSIZE 128
01202 
01203 /*! \brief Authentication container for realm authentication */
01204 static struct sip_auth_container *authl = NULL;
01205 /*! \brief Global authentication container protection while adjusting the references. */
01206 AST_MUTEX_DEFINE_STATIC(authl_lock);
01207 
01208 /* --- Sockets and networking --------------*/
01209 
01210 /*! \brief Main socket for UDP SIP communication.
01211  *
01212  * sipsock is shared between the SIP manager thread (which handles reload
01213  * requests), the udp io handler (sipsock_read()) and the user routines that
01214  * issue udp writes (using __sip_xmit()).
01215  * The socket is -1 only when opening fails (this is a permanent condition),
01216  * or when we are handling a reload() that changes its address (this is
01217  * a transient situation during which we might have a harmless race, see
01218  * below). Because the conditions for the race to be possible are extremely
01219  * rare, we don't want to pay the cost of locking on every I/O.
01220  * Rather, we remember that when the race may occur, communication is
01221  * bound to fail anyways, so we just live with this event and let
01222  * the protocol handle this above us.
01223  */
01224 static int sipsock  = -1;
01225 
01226 struct ast_sockaddr bindaddr; /*!< UDP: The address we bind to */
01227 
01228 /*! \brief our (internal) default address/port to put in SIP/SDP messages
01229  *  internip is initialized picking a suitable address from one of the
01230  * interfaces, and the same port number we bind to. It is used as the
01231  * default address/port in SIP messages, and as the default address
01232  * (but not port) in SDP messages.
01233  */
01234 static struct ast_sockaddr internip;
01235 
01236 /*! \brief our external IP address/port for SIP sessions.
01237  * externaddr.sin_addr is only set when we know we might be behind
01238  * a NAT, and this is done using a variety of (mutually exclusive)
01239  * ways from the config file:
01240  *
01241  * + with "externaddr = host[:port]" we specify the address/port explicitly.
01242  *   The address is looked up only once when (re)loading the config file;
01243  *
01244  * + with "externhost = host[:port]" we do a similar thing, but the
01245  *   hostname is stored in externhost, and the hostname->IP mapping
01246  *   is refreshed every 'externrefresh' seconds;
01247  *
01248  * Other variables (externhost, externexpire, externrefresh) are used
01249  * to support the above functions.
01250  */
01251 static struct ast_sockaddr externaddr;      /*!< External IP address if we are behind NAT */
01252 static struct ast_sockaddr media_address; /*!< External RTP IP address if we are behind NAT */
01253 
01254 static char externhost[MAXHOSTNAMELEN];   /*!< External host name */
01255 static time_t externexpire;             /*!< Expiration counter for re-resolving external host name in dynamic DNS */
01256 static int externrefresh = 10;          /*!< Refresh timer for DNS-based external address (dyndns) */
01257 static uint16_t externtcpport;          /*!< external tcp port */
01258 static uint16_t externtlsport;          /*!< external tls port */
01259 
01260 /*! \brief  List of local networks
01261  * We store "localnet" addresses from the config file into an access list,
01262  * marked as 'DENY', so the call to ast_apply_ha() will return
01263  * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
01264  * (i.e. presumably public) addresses.
01265  */
01266 static struct ast_ha *localaddr;    /*!< List of local networks, on the same side of NAT as this Asterisk */
01267 
01268 static int ourport_tcp;             /*!< The port used for TCP connections */
01269 static int ourport_tls;             /*!< The port used for TCP/TLS connections */
01270 static struct ast_sockaddr debugaddr;
01271 
01272 static struct ast_config *notify_types = NULL;    /*!< The list of manual NOTIFY types we know how to send */
01273 
01274 /*! some list management macros. */
01275 
01276 #define UNLINK(element, head, prev) do {  \
01277    if (prev)            \
01278       (prev)->next = (element)->next;  \
01279    else              \
01280       (head) = (element)->next;  \
01281    } while (0)
01282 
01283 struct show_peers_context;
01284 
01285 /*---------------------------- Forward declarations of functions in chan_sip.c */
01286 /* Note: This is added to help splitting up chan_sip.c into several files
01287    in coming releases. */
01288 
01289 /*--- PBX interface functions */
01290 static struct ast_channel *sip_request_call(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, const char *dest, int *cause);
01291 static int sip_devicestate(const char *data);
01292 static int sip_sendtext(struct ast_channel *ast, const char *text);
01293 static int sip_call(struct ast_channel *ast, const char *dest, int timeout);
01294 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
01295 static int sip_hangup(struct ast_channel *ast);
01296 static int sip_answer(struct ast_channel *ast);
01297 static struct ast_frame *sip_read(struct ast_channel *ast);
01298 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
01299 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
01300 static int sip_transfer(struct ast_channel *ast, const char *dest);
01301 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
01302 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
01303 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
01304 static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen);
01305 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
01306 static const char *sip_get_callid(struct ast_channel *chan);
01307 
01308 static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr);
01309 static int sip_standard_port(enum sip_transport type, int port);
01310 static int sip_prepare_socket(struct sip_pvt *p);
01311 static int get_address_family_filter(unsigned int transport);
01312 
01313 /*--- Transmitting responses and requests */
01314 static int sipsock_read(int *id, int fd, short events, void *ignore);
01315 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data);
01316 static int __sip_reliable_xmit(struct sip_pvt *p, uint32_t seqno, int resp, struct ast_str *data, int fatal, int sipmethod);
01317 static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp);
01318 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
01319 static int retrans_pkt(const void *data);
01320 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);
01321 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01322 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01323 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01324 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);
01325 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
01326 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);
01327 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
01328 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
01329 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable);
01330 static int transmit_request(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch);
01331 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch);
01332 static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri);
01333 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri);
01334 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
01335 static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded);
01336 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
01337 static int transmit_info_with_vidupdate(struct sip_pvt *p);
01338 static int transmit_message(struct sip_pvt *p, int init, int auth);
01339 static int transmit_refer(struct sip_pvt *p, const char *dest);
01340 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
01341 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
01342 static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state);
01343 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
01344 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno);
01345 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno);
01346 static void copy_request(struct sip_request *dst, const struct sip_request *src);
01347 static void receive_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
01348 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward);
01349 static int sip_send_mwi_to_peer(struct sip_peer *peer, int cache_only);
01350 
01351 /* Misc dialog routines */
01352 static int __sip_autodestruct(const void *data);
01353 static void *registry_unref(struct sip_registry *reg, char *tag);
01354 static int update_call_counter(struct sip_pvt *fup, int event);
01355 static int auto_congest(const void *arg);
01356 static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method);
01357 static void free_old_route(struct sip_route *route);
01358 static void list_route(struct sip_route *route);
01359 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards, int resp);
01360 static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
01361                      struct sip_request *req, const char *uri);
01362 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
01363 static void check_pendings(struct sip_pvt *p);
01364 static void *sip_park_thread(void *stuff);
01365 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, uint32_t seqno, const char *park_exten, const char *park_context);
01366 
01367 static void *sip_pickup_thread(void *stuff);
01368 static int sip_pickup(struct ast_channel *chan);
01369 
01370 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
01371 static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method);
01372 
01373 /*--- Codec handling / SDP */
01374 static void try_suggested_sip_codec(struct sip_pvt *p);
01375 static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
01376 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
01377 static int find_sdp(struct sip_request *req);
01378 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
01379 static int process_sdp_o(const char *o, struct sip_pvt *p);
01380 static int process_sdp_c(const char *c, struct ast_sockaddr *addr);
01381 static int process_sdp_a_sendonly(const char *a, int *sendonly);
01382 static int process_sdp_a_ice(const char *a, struct sip_pvt *p, struct ast_rtp_instance *instance);
01383 static int process_sdp_a_dtls(const char *a, struct sip_pvt *p, struct ast_rtp_instance *instance);
01384 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec);
01385 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec);
01386 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);
01387 static int process_sdp_a_image(const char *a, struct sip_pvt *p);
01388 static void add_ice_to_sdp(struct ast_rtp_instance *instance, struct ast_str **a_buf);
01389 static void add_dtls_to_sdp(struct ast_rtp_instance *instance, struct ast_str **a_buf);
01390 static void start_ice(struct ast_rtp_instance *instance, int offer);
01391 static void add_codec_to_sdp(const struct sip_pvt *p, struct ast_format *codec,
01392               struct ast_str **m_buf, struct ast_str **a_buf,
01393               int debug, int *min_packet_size);
01394 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
01395             struct ast_str **m_buf, struct ast_str **a_buf,
01396             int debug);
01397 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
01398 static void do_setnat(struct sip_pvt *p);
01399 static void stop_media_flows(struct sip_pvt *p);
01400 
01401 /*--- Authentication stuff */
01402 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
01403 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
01404 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
01405                 const char *secret, const char *md5secret, int sipmethod,
01406                 const char *uri, enum xmittype reliable);
01407 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
01408                      int sipmethod, const char *uri, enum xmittype reliable,
01409                      struct ast_sockaddr *addr, struct sip_peer **authpeer);
01410 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr);
01411 
01412 /*--- Domain handling */
01413 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
01414 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
01415 static void clear_sip_domains(void);
01416 
01417 /*--- SIP realm authentication */
01418 static void add_realm_authentication(struct sip_auth_container **credentials, const char *configuration, int lineno);
01419 static struct sip_auth *find_realm_authentication(struct sip_auth_container *credentials, const char *realm);
01420 
01421 /*--- Misc functions */
01422 static int check_rtp_timeout(struct sip_pvt *dialog, time_t t);
01423 static int reload_config(enum channelreloadreason reason);
01424 static void add_diversion(struct sip_request *req, struct sip_pvt *pvt);
01425 static int expire_register(const void *data);
01426 static void *do_monitor(void *data);
01427 static int restart_monitor(void);
01428 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
01429 static struct ast_variable *copy_vars(struct ast_variable *src);
01430 static int dialog_find_multiple(void *obj, void *arg, int flags);
01431 static struct ast_channel *sip_pvt_lock_full(struct sip_pvt *pvt);
01432 /* static int sip_addrcmp(char *name, struct sockaddr_in *sin);   Support for peer matching */
01433 static int sip_refer_alloc(struct sip_pvt *p);
01434 static int sip_notify_alloc(struct sip_pvt *p);
01435 static void ast_quiet_chan(struct ast_channel *chan);
01436 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
01437 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
01438 static void set_peer_nat(const struct sip_pvt *p, struct sip_peer *peer);
01439 static void check_for_nat(const struct ast_sockaddr *them, struct sip_pvt *p);
01440 
01441 /*--- Device monitoring and Device/extension state/event handling */
01442 static int extensionstate_update(const char *context, const char *exten, struct state_notify_data *data, struct sip_pvt *p, int force);
01443 static int cb_extensionstate(char *context, char *exten, struct ast_state_cb_info *info, void *data);
01444 static int sip_poke_noanswer(const void *data);
01445 static int sip_poke_peer(struct sip_peer *peer, int force);
01446 static void sip_poke_all_peers(void);
01447 static void sip_peer_hold(struct sip_pvt *p, int hold);
01448 static void mwi_event_cb(const struct ast_event *, void *);
01449 static void network_change_event_cb(const struct ast_event *, void *);
01450 static void acl_change_event_cb(const struct ast_event *event, void *userdata);
01451 static void sip_keepalive_all_peers(void);
01452 
01453 /*--- Applications, functions, CLI and manager command helpers */
01454 static const char *sip_nat_mode(const struct sip_pvt *p);
01455 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01456 static char *transfermode2str(enum transfermodes mode) attribute_const;
01457 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
01458 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01459 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01460 static struct sip_peer *_sip_show_peers_one(int fd, struct mansession *s, struct show_peers_context *cont, struct sip_peer *peer);
01461 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01462 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01463 static void  print_group(int fd, ast_group_t group, int crlf);
01464 static void  print_named_groups(int fd, struct ast_namedgroups *groups, int crlf);
01465 static const char *dtmfmode2str(int mode) attribute_const;
01466 static int str2dtmfmode(const char *str) attribute_unused;
01467 static const char *insecure2str(int mode) attribute_const;
01468 static const char *allowoverlap2str(int mode) attribute_const;
01469 static void cleanup_stale_contexts(char *new, char *old);
01470 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
01471 static const char *domain_mode_to_text(const enum domain_mode mode);
01472 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01473 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01474 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01475 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01476 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01477 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01478 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01479 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01480 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01481 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
01482 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
01483 static char *complete_sip_peer(const char *word, int state, int flags2);
01484 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
01485 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
01486 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
01487 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
01488 static char *complete_sip_notify(const char *line, const char *word, int pos, int state);
01489 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01490 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01491 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01492 static char *sip_do_debug_ip(int fd, const char *arg);
01493 static char *sip_do_debug_peer(int fd, const char *arg);
01494 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01495 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01496 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01497 static int sip_dtmfmode(struct ast_channel *chan, const char *data);
01498 static int sip_addheader(struct ast_channel *chan, const char *data);
01499 static int sip_do_reload(enum channelreloadreason reason);
01500 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01501 static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
01502                   const char *name, int flag, int family);
01503 static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
01504                   const char *name, int flag);
01505 static int ast_sockaddr_resolve_first_transport(struct ast_sockaddr *addr,
01506                   const char *name, int flag, unsigned int transport);
01507 
01508 /*--- Debugging
01509    Functions for enabling debug per IP or fully, or enabling history logging for
01510    a SIP dialog
01511 */
01512 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to debuglog at end of dialog, before destroying data */
01513 static inline int sip_debug_test_addr(const struct ast_sockaddr *addr);
01514 static inline int sip_debug_test_pvt(struct sip_pvt *p);
01515 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
01516 static void sip_dump_history(struct sip_pvt *dialog);
01517 
01518 /*--- Device object handling */
01519 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
01520 static int update_call_counter(struct sip_pvt *fup, int event);
01521 static void sip_destroy_peer(struct sip_peer *peer);
01522 static void sip_destroy_peer_fn(void *peer);
01523 static void set_peer_defaults(struct sip_peer *peer);
01524 static struct sip_peer *temp_peer(const char *name);
01525 static void register_peer_exten(struct sip_peer *peer, int onoff);
01526 static int sip_poke_peer_s(const void *data);
01527 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
01528 static void reg_source_db(struct sip_peer *peer);
01529 static void destroy_association(struct sip_peer *peer);
01530 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
01531 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
01532 static void set_socket_transport(struct sip_socket *socket, int transport);
01533 static int peer_ipcmp_cb_full(void *obj, void *arg, void *data, int flags);
01534 
01535 /* Realtime device support */
01536 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);
01537 static void update_peer(struct sip_peer *p, int expire);
01538 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
01539 static const char *get_name_from_variable(const struct ast_variable *var);
01540 static struct sip_peer *realtime_peer(const char *peername, struct ast_sockaddr *sin, char *callbackexten, int devstate_only, int which_objects);
01541 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01542 
01543 /*--- Internal UA client handling (outbound registrations) */
01544 static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p);
01545 static void sip_registry_destroy(struct sip_registry *reg);
01546 static int sip_register(const char *value, int lineno);
01547 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
01548 static int sip_reregister(const void *data);
01549 static int __sip_do_register(struct sip_registry *r);
01550 static int sip_reg_timeout(const void *data);
01551 static void sip_send_all_registers(void);
01552 static int sip_reinvite_retry(const void *data);
01553 
01554 /*--- Parsing SIP requests and responses */
01555 static int determine_firstline_parts(struct sip_request *req);
01556 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
01557 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
01558 static int find_sip_method(const char *msg);
01559 static unsigned int parse_allowed_methods(struct sip_request *req);
01560 static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req);
01561 static int parse_request(struct sip_request *req);
01562 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
01563 static int method_match(enum sipmethod id, const char *name);
01564 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
01565 static void parse_oli(struct sip_request *req, struct ast_channel *chan);
01566 static const char *find_alias(const char *name, const char *_default);
01567 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
01568 static void lws2sws(struct ast_str *msgbuf);
01569 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
01570 static char *remove_uri_parameters(char *uri);
01571 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
01572 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
01573 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
01574 static int set_address_from_contact(struct sip_pvt *pvt);
01575 static void check_via(struct sip_pvt *p, const struct sip_request *req);
01576 static int get_rpid(struct sip_pvt *p, struct sip_request *oreq);
01577 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason);
01578 static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id);
01579 static int transmit_state_notify(struct sip_pvt *p, struct state_notify_data *data, int full, int timeout);
01580 static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen);
01581 static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen);
01582 static int get_domain(const char *str, char *domain, int len);
01583 static void get_realm(struct sip_pvt *p, const struct sip_request *req);
01584 static char *get_content(struct sip_request *req);
01585 
01586 /*-- TCP connection handling ---*/
01587 static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session);
01588 static void *sip_tcp_worker_fn(void *);
01589 
01590 /*--- Constructing requests and responses */
01591 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
01592 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
01593 static void deinit_req(struct sip_request *req);
01594 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, uint32_t seqno, int newbranch);
01595 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri);
01596 static int init_resp(struct sip_request *resp, const char *msg);
01597 static inline int resp_needs_contact(const char *msg, enum sipmethod method);
01598 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
01599 static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p);
01600 static void build_via(struct sip_pvt *p);
01601 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
01602 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog);
01603 static char *generate_random_string(char *buf, size_t size);
01604 static void build_callid_pvt(struct sip_pvt *pvt);
01605 static void change_callid_pvt(struct sip_pvt *pvt, const char *callid);
01606 static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain);
01607 static void build_localtag_registry(struct sip_registry *reg);
01608 static void make_our_tag(struct sip_pvt *pvt);
01609 static int add_header(struct sip_request *req, const char *var, const char *value);
01610 static int add_max_forwards(struct sip_pvt *dialog, struct sip_request *req);
01611 static int add_content(struct sip_request *req, const char *line);
01612 static int finalize_content(struct sip_request *req);
01613 static void destroy_msg_headers(struct sip_pvt *pvt);
01614 static int add_text(struct sip_request *req, struct sip_pvt *p);
01615 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
01616 static int add_rpid(struct sip_request *req, struct sip_pvt *p);
01617 static int add_vidupdate(struct sip_request *req);
01618 static void add_route(struct sip_request *req, struct sip_route *route);
01619 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
01620 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
01621 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
01622 static void set_destination(struct sip_pvt *p, char *uri);
01623 static void add_date(struct sip_request *req);
01624 static void add_expires(struct sip_request *req, int expires);
01625 static void build_contact(struct sip_pvt *p);
01626 
01627 /*------Request handling functions */
01628 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock);
01629 static int handle_request_update(struct sip_pvt *p, struct sip_request *req);
01630 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);
01631 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, uint32_t seqno, int *nounlock);
01632 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
01633 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *sin, const char *e);
01634 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
01635 static int handle_request_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
01636 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
01637 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
01638 static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
01639 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, int *nounlock);
01640 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
01641 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, uint32_t seqno, int *nounlock);
01642 
01643 /*------Response handling functions */
01644 static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01645 static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01646 static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01647 static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01648 static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01649 static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01650 static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01651 
01652 /*------ SRTP Support -------- */
01653 static int setup_srtp(struct sip_srtp **srtp);
01654 static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct sip_srtp **srtp, const char *a);
01655 
01656 /*------ T38 Support --------- */
01657 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
01658 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
01659 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
01660 static void change_t38_state(struct sip_pvt *p, int state);
01661 
01662 /*------ Session-Timers functions --------- */
01663 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
01664 static int  proc_session_timer(const void *vp);
01665 static void stop_session_timer(struct sip_pvt *p);
01666 static void start_session_timer(struct sip_pvt *p);
01667 static void restart_session_timer(struct sip_pvt *p);
01668 static const char *strefresherparam2str(enum st_refresher r);
01669 static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher_param *const p_ref);
01670 static int parse_minse(const char *p_hdrval, int *const p_interval);
01671 static int st_get_se(struct sip_pvt *, int max);
01672 static enum st_refresher st_get_refresher(struct sip_pvt *);
01673 static enum st_mode st_get_mode(struct sip_pvt *, int no_cached);
01674 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
01675 
01676 /*------- RTP Glue functions -------- */
01677 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);
01678 
01679 /*!--- SIP MWI Subscription support */
01680 static int sip_subscribe_mwi(const char *value, int lineno);
01681 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi);
01682 static void sip_send_all_mwi_subscriptions(void);
01683 static int sip_subscribe_mwi_do(const void *data);
01684 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
01685 
01686 /*! \brief Definition of this channel for PBX channel registration */
01687 struct ast_channel_tech sip_tech = {
01688    .type = "SIP",
01689    .description = "Session Initiation Protocol (SIP)",
01690    .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
01691    .requester = sip_request_call,         /* called with chan unlocked */
01692    .devicestate = sip_devicestate,        /* called with chan unlocked (not chan-specific) */
01693    .call = sip_call,       /* called with chan locked */
01694    .send_html = sip_sendhtml,
01695    .hangup = sip_hangup,         /* called with chan locked */
01696    .answer = sip_answer,         /* called with chan locked */
01697    .read = sip_read,       /* called with chan locked */
01698    .write = sip_write,        /* called with chan locked */
01699    .write_video = sip_write,     /* called with chan locked */
01700    .write_text = sip_write,
01701    .indicate = sip_indicate,     /* called with chan locked */
01702    .transfer = sip_transfer,     /* called with chan locked */
01703    .fixup = sip_fixup,        /* called with chan locked */
01704    .send_digit_begin = sip_senddigit_begin,  /* called with chan unlocked */
01705    .send_digit_end = sip_senddigit_end,
01706    .bridge = ast_rtp_instance_bridge,        /* XXX chan unlocked ? */
01707    .early_bridge = ast_rtp_instance_early_bridge,
01708    .send_text = sip_sendtext,    /* called with chan locked */
01709    .func_channel_read = sip_acf_channel_read,
01710    .setoption = sip_setoption,
01711    .queryoption = sip_queryoption,
01712    .get_pvt_uniqueid = sip_get_callid,
01713 };
01714 
01715 /*! \brief This version of the sip channel tech has no send_digit_begin
01716  * callback so that the core knows that the channel does not want
01717  * DTMF BEGIN frames.
01718  * The struct is initialized just before registering the channel driver,
01719  * and is for use with channels using SIP INFO DTMF.
01720  */
01721 struct ast_channel_tech sip_tech_info;
01722 
01723 /*------- CC Support -------- */
01724 static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan);
01725 static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent);
01726 static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent);
01727 static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason);
01728 static int sip_cc_agent_status_request(struct ast_cc_agent *agent);
01729 static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent);
01730 static int sip_cc_agent_recall(struct ast_cc_agent *agent);
01731 static void sip_cc_agent_destructor(struct ast_cc_agent *agent);
01732 
01733 static struct ast_cc_agent_callbacks sip_cc_agent_callbacks = {
01734    .type = "SIP",
01735    .init = sip_cc_agent_init,
01736    .start_offer_timer = sip_cc_agent_start_offer_timer,
01737    .stop_offer_timer = sip_cc_agent_stop_offer_timer,
01738    .respond = sip_cc_agent_respond,
01739    .status_request = sip_cc_agent_status_request,
01740    .start_monitoring = sip_cc_agent_start_monitoring,
01741    .callee_available = sip_cc_agent_recall,
01742    .destructor = sip_cc_agent_destructor,
01743 };
01744 
01745 static int find_by_notify_uri_helper(void *obj, void *arg, int flags)
01746 {
01747    struct ast_cc_agent *agent = obj;
01748    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01749    const char *uri = arg;
01750 
01751    return !sip_uri_cmp(agent_pvt->notify_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
01752 }
01753 
01754 static struct ast_cc_agent *find_sip_cc_agent_by_notify_uri(const char * const uri)
01755 {
01756    struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_notify_uri_helper, (char *)uri, "SIP");
01757    return agent;
01758 }
01759 
01760 static int find_by_subscribe_uri_helper(void *obj, void *arg, int flags)
01761 {
01762    struct ast_cc_agent *agent = obj;
01763    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01764    const char *uri = arg;
01765 
01766    return !sip_uri_cmp(agent_pvt->subscribe_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
01767 }
01768 
01769 static struct ast_cc_agent *find_sip_cc_agent_by_subscribe_uri(const char * const uri)
01770 {
01771    struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_subscribe_uri_helper, (char *)uri, "SIP");
01772    return agent;
01773 }
01774 
01775 static int find_by_callid_helper(void *obj, void *arg, int flags)
01776 {
01777    struct ast_cc_agent *agent = obj;
01778    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01779    struct sip_pvt *call_pvt = arg;
01780 
01781    return !strcmp(agent_pvt->original_callid, call_pvt->callid) ? CMP_MATCH | CMP_STOP : 0;
01782 }
01783 
01784 static struct ast_cc_agent *find_sip_cc_agent_by_original_callid(struct sip_pvt *pvt)
01785 {
01786    struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_callid_helper, pvt, "SIP");
01787    return agent;
01788 }
01789 
01790 static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan)
01791 {
01792    struct sip_cc_agent_pvt *agent_pvt = ast_calloc(1, sizeof(*agent_pvt));
01793    struct sip_pvt *call_pvt = ast_channel_tech_pvt(chan);
01794 
01795    if (!agent_pvt) {
01796       return -1;
01797    }
01798 
01799    ast_assert(!strcmp(ast_channel_tech(chan)->type, "SIP"));
01800 
01801    ast_copy_string(agent_pvt->original_callid, call_pvt->callid, sizeof(agent_pvt->original_callid));
01802    ast_copy_string(agent_pvt->original_exten, call_pvt->exten, sizeof(agent_pvt->original_exten));
01803    agent_pvt->offer_timer_id = -1;
01804    agent->private_data = agent_pvt;
01805    sip_pvt_lock(call_pvt);
01806    ast_set_flag(&call_pvt->flags[0], SIP_OFFER_CC);
01807    sip_pvt_unlock(call_pvt);
01808    return 0;
01809 }
01810 
01811 static int sip_offer_timer_expire(const void *data)
01812 {
01813    struct ast_cc_agent *agent = (struct ast_cc_agent *) data;
01814    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01815 
01816    agent_pvt->offer_timer_id = -1;
01817 
01818    return ast_cc_failed(agent->core_id, "SIP agent %s's offer timer expired", agent->device_name);
01819 }
01820 
01821 static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent)
01822 {
01823    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01824    int when;
01825 
01826    when = ast_get_cc_offer_timer(agent->cc_params) * 1000;
01827    agent_pvt->offer_timer_id = ast_sched_add(sched, when, sip_offer_timer_expire, agent);
01828    return 0;
01829 }
01830 
01831 static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent)
01832 {
01833    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01834 
01835    AST_SCHED_DEL(sched, agent_pvt->offer_timer_id);
01836    return 0;
01837 }
01838 
01839 static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason)
01840 {
01841    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01842 
01843    sip_pvt_lock(agent_pvt->subscribe_pvt);
01844    ast_set_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
01845    if (reason == AST_CC_AGENT_RESPONSE_SUCCESS || !ast_strlen_zero(agent_pvt->notify_uri)) {
01846       /* The second half of this if statement may be a bit hard to grasp,
01847        * so here's an explanation. When a subscription comes into
01848        * chan_sip, as long as it is not malformed, it will be passed
01849        * to the CC core. If the core senses an out-of-order state transition,
01850        * then the core will call this callback with the "reason" set to a
01851        * failure condition.
01852        * However, an out-of-order state transition will occur during a resubscription
01853        * for CC. In such a case, we can see that we have already generated a notify_uri
01854        * and so we can detect that this isn't a *real* failure. Rather, it is just
01855        * something the core doesn't recognize as a legitimate SIP state transition.
01856        * Thus we respond with happiness and flowers.
01857        */
01858       transmit_response(agent_pvt->subscribe_pvt, "200 OK", &agent_pvt->subscribe_pvt->initreq);
01859       transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_QUEUED);
01860    } else {
01861       transmit_response(agent_pvt->subscribe_pvt, "500 Internal Error", &agent_pvt->subscribe_pvt->initreq);
01862    }
01863    sip_pvt_unlock(agent_pvt->subscribe_pvt);
01864    agent_pvt->is_available = TRUE;
01865 }
01866 
01867 static int sip_cc_agent_status_request(struct ast_cc_agent *agent)
01868 {
01869    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01870    enum ast_device_state state = agent_pvt->is_available ? AST_DEVICE_NOT_INUSE : AST_DEVICE_INUSE;
01871    return ast_cc_agent_status_response(agent->core_id, state);
01872 }
01873 
01874 static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent)
01875 {
01876    /* To start monitoring just means to wait for an incoming PUBLISH
01877     * to tell us that the caller has become available again. No special
01878     * action is needed
01879     */
01880    return 0;
01881 }
01882 
01883 static int sip_cc_agent_recall(struct ast_cc_agent *agent)
01884 {
01885    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01886    /* If we have received a PUBLISH beforehand stating that the caller in question
01887     * is not available, we can save ourself a bit of effort here and just report
01888     * the caller as busy
01889     */
01890    if (!agent_pvt->is_available) {
01891       return ast_cc_agent_caller_busy(agent->core_id, "Caller %s is busy, reporting to the core",
01892             agent->device_name);
01893    }
01894    /* Otherwise, we transmit a NOTIFY to the caller and await either
01895     * a PUBLISH or an INVITE
01896     */
01897    sip_pvt_lock(agent_pvt->subscribe_pvt);
01898    transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_READY);
01899    sip_pvt_unlock(agent_pvt->subscribe_pvt);
01900    return 0;
01901 }
01902 
01903 static void sip_cc_agent_destructor(struct ast_cc_agent *agent)
01904 {
01905    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01906 
01907    if (!agent_pvt) {
01908       /* The agent constructor probably failed. */
01909       return;
01910    }
01911 
01912    sip_cc_agent_stop_offer_timer(agent);
01913    if (agent_pvt->subscribe_pvt) {
01914       sip_pvt_lock(agent_pvt->subscribe_pvt);
01915       if (!ast_test_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
01916          /* If we haven't sent a 200 OK for the SUBSCRIBE dialog yet, then we need to send a response letting
01917           * the subscriber know something went wrong
01918           */
01919          transmit_response(agent_pvt->subscribe_pvt, "500 Internal Server Error", &agent_pvt->subscribe_pvt->initreq);
01920       }
01921       sip_pvt_unlock(agent_pvt->subscribe_pvt);
01922       agent_pvt->subscribe_pvt = dialog_unref(agent_pvt->subscribe_pvt, "SIP CC agent destructor: Remove ref to subscription");
01923    }
01924    ast_free(agent_pvt);
01925 }
01926 
01927 struct ao2_container *sip_monitor_instances;
01928 
01929 static int sip_monitor_instance_hash_fn(const void *obj, const int flags)
01930 {
01931    const struct sip_monitor_instance *monitor_instance = obj;
01932    return monitor_instance->core_id;
01933 }
01934 
01935 static int sip_monitor_instance_cmp_fn(void *obj, void *arg, int flags)
01936 {
01937    struct sip_monitor_instance *monitor_instance1 = obj;
01938    struct sip_monitor_instance *monitor_instance2 = arg;
01939 
01940    return monitor_instance1->core_id == monitor_instance2->core_id ? CMP_MATCH | CMP_STOP : 0;
01941 }
01942 
01943 static void sip_monitor_instance_destructor(void *data)
01944 {
01945    struct sip_monitor_instance *monitor_instance = data;
01946    if (monitor_instance->subscription_pvt) {
01947       sip_pvt_lock(monitor_instance->subscription_pvt);
01948       monitor_instance->subscription_pvt->expiry = 0;
01949       transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 0, monitor_instance->subscribe_uri);
01950       sip_pvt_unlock(monitor_instance->subscription_pvt);
01951       dialog_unref(monitor_instance->subscription_pvt, "Unref monitor instance ref of subscription pvt");
01952    }
01953    if (monitor_instance->suspension_entry) {
01954       monitor_instance->suspension_entry->body[0] = '\0';
01955       transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_REMOVE ,monitor_instance->notify_uri);
01956       ao2_t_ref(monitor_instance->suspension_entry, -1, "Decrementing suspension entry refcount in sip_monitor_instance_destructor");
01957    }
01958    ast_string_field_free_memory(monitor_instance);
01959 }
01960 
01961 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)
01962 {
01963    struct sip_monitor_instance *monitor_instance = ao2_alloc(sizeof(*monitor_instance), sip_monitor_instance_destructor);
01964 
01965    if (!monitor_instance) {
01966       return NULL;
01967    }
01968 
01969    if (ast_string_field_init(monitor_instance, 256)) {
01970       ao2_ref(monitor_instance, -1);
01971       return NULL;
01972    }
01973 
01974    ast_string_field_set(monitor_instance, subscribe_uri, subscribe_uri);
01975    ast_string_field_set(monitor_instance, peername, peername);
01976    ast_string_field_set(monitor_instance, device_name, device_name);
01977    monitor_instance->core_id = core_id;
01978    ao2_link(sip_monitor_instances, monitor_instance);
01979    return monitor_instance;
01980 }
01981 
01982 static int find_sip_monitor_instance_by_subscription_pvt(void *obj, void *arg, int flags)
01983 {
01984    struct sip_monitor_instance *monitor_instance = obj;
01985    return monitor_instance->subscription_pvt == arg ? CMP_MATCH | CMP_STOP : 0;
01986 }
01987 
01988 static int find_sip_monitor_instance_by_suspension_entry(void *obj, void *arg, int flags)
01989 {
01990    struct sip_monitor_instance *monitor_instance = obj;
01991    return monitor_instance->suspension_entry == arg ? CMP_MATCH | CMP_STOP : 0;
01992 }
01993 
01994 static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id);
01995 static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor);
01996 static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor);
01997 static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id);
01998 static void sip_cc_monitor_destructor(void *private_data);
01999 
02000 static struct ast_cc_monitor_callbacks sip_cc_monitor_callbacks = {
02001    .type = "SIP",
02002    .request_cc = sip_cc_monitor_request_cc,
02003    .suspend = sip_cc_monitor_suspend,
02004    .unsuspend = sip_cc_monitor_unsuspend,
02005    .cancel_available_timer = sip_cc_monitor_cancel_available_timer,
02006    .destructor = sip_cc_monitor_destructor,
02007 };
02008 
02009 static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id)
02010 {
02011    struct sip_monitor_instance *monitor_instance = monitor->private_data;
02012    enum ast_cc_service_type service = monitor->service_offered;
02013    int when;
02014 
02015    if (!monitor_instance) {
02016       return -1;
02017    }
02018 
02019    if (!(monitor_instance->subscription_pvt = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL, NULL))) {
02020       return -1;
02021    }
02022 
02023    when = service == AST_CC_CCBS ? ast_get_ccbs_available_timer(monitor->interface->config_params) :
02024       ast_get_ccnr_available_timer(monitor->interface->config_params);
02025 
02026    sip_pvt_lock(monitor_instance->subscription_pvt);
02027    ast_set_flag(&monitor_instance->subscription_pvt->flags[0], SIP_OUTGOING);
02028    create_addr(monitor_instance->subscription_pvt, monitor_instance->peername, 0, 1);
02029    ast_sip_ouraddrfor(&monitor_instance->subscription_pvt->sa, &monitor_instance->subscription_pvt->ourip, monitor_instance->subscription_pvt);
02030    monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
02031    monitor_instance->subscription_pvt->expiry = when;
02032 
02033    transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 2, monitor_instance->subscribe_uri);
02034    sip_pvt_unlock(monitor_instance->subscription_pvt);
02035 
02036    ao2_t_ref(monitor, +1, "Adding a ref to the monitor for the scheduler");
02037    *available_timer_id = ast_sched_add(sched, when * 1000, ast_cc_available_timer_expire, monitor);
02038    return 0;
02039 }
02040 
02041 static int construct_pidf_body(enum sip_cc_publish_state state, char *pidf_body, size_t size, const char *presentity)
02042 {
02043    struct ast_str *body = ast_str_alloca(size);
02044    char tuple_id[32];
02045 
02046    generate_random_string(tuple_id, sizeof(tuple_id));
02047 
02048    /* We'll make this a bare-bones pidf body. In state_notify_build_xml, the PIDF
02049     * body gets a lot more extra junk that isn't necessary, so we'll leave it out here.
02050     */
02051    ast_str_append(&body, 0, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
02052    /* XXX The entity attribute is currently set to the peer name associated with the
02053     * dialog. This is because we currently only call this function for call-completion
02054     * PUBLISH bodies. In such cases, the entity is completely disregarded. For other
02055     * event packages, it may be crucial to have a proper URI as the presentity so this
02056     * should be revisited as support is expanded.
02057     */
02058    ast_str_append(&body, 0, "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" entity=\"%s\">\n", presentity);
02059    ast_str_append(&body, 0, "<tuple id=\"%s\">\n", tuple_id);
02060    ast_str_append(&body, 0, "<status><basic>%s</basic></status>\n", state == CC_OPEN ? "open" : "closed");
02061    ast_str_append(&body, 0, "</tuple>\n");
02062    ast_str_append(&body, 0, "</presence>\n");
02063    ast_copy_string(pidf_body, ast_str_buffer(body), size);
02064    return 0;
02065 }
02066 
02067 static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor)
02068 {
02069    struct sip_monitor_instance *monitor_instance = monitor->private_data;
02070    enum sip_publish_type publish_type;
02071    struct cc_epa_entry *cc_entry;
02072 
02073    if (!monitor_instance) {
02074       return -1;
02075    }
02076 
02077    if (!monitor_instance->suspension_entry) {
02078       /* We haven't yet allocated the suspension entry, so let's give it a shot */
02079       if (!(monitor_instance->suspension_entry = create_epa_entry("call-completion", monitor_instance->peername))) {
02080          ast_log(LOG_WARNING, "Unable to allocate sip EPA entry for call-completion\n");
02081          ao2_ref(monitor_instance, -1);
02082          return -1;
02083       }
02084       if (!(cc_entry = ast_calloc(1, sizeof(*cc_entry)))) {
02085          ast_log(LOG_WARNING, "Unable to allocate space for instance data of EPA entry for call-completion\n");
02086          ao2_ref(monitor_instance, -1);
02087          return -1;
02088       }
02089       cc_entry->core_id = monitor->core_id;
02090       monitor_instance->suspension_entry->instance_data = cc_entry;
02091       publish_type = SIP_PUBLISH_INITIAL;
02092    } else {
02093       publish_type = SIP_PUBLISH_MODIFY;
02094       cc_entry = monitor_instance->suspension_entry->instance_data;
02095    }
02096 
02097    cc_entry->current_state = CC_CLOSED;
02098 
02099    if (ast_strlen_zero(monitor_instance->notify_uri)) {
02100       /* If we have no set notify_uri, then what this means is that we have
02101        * not received a NOTIFY from this destination stating that he is
02102        * currently available.
02103        *
02104        * This situation can arise when the core calls the suspend callbacks
02105        * of multiple destinations. If one of the other destinations aside
02106        * from this one notified Asterisk that he is available, then there
02107        * is no reason to take any suspension action on this device. Rather,
02108        * we should return now and if we receive a NOTIFY while monitoring
02109        * is still "suspended" then we can immediately respond with the
02110        * proper PUBLISH to let this endpoint know what is going on.
02111        */
02112       return 0;
02113    }
02114    construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
02115    return transmit_publish(monitor_instance->suspension_entry, publish_type, monitor_instance->notify_uri);
02116 }
02117 
02118 static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor)
02119 {
02120    struct sip_monitor_instance *monitor_instance = monitor->private_data;
02121    struct cc_epa_entry *cc_entry;
02122 
02123    if (!monitor_instance) {
02124       return -1;
02125    }
02126 
02127    ast_assert(monitor_instance->suspension_entry != NULL);
02128 
02129    cc_entry = monitor_instance->suspension_entry->instance_data;
02130    cc_entry->current_state = CC_OPEN;
02131    if (ast_strlen_zero(monitor_instance->notify_uri)) {
02132       /* This means we are being asked to unsuspend a call leg we never
02133        * sent a PUBLISH on. As such, there is no reason to send another
02134        * PUBLISH at this point either. We can just return instead.
02135        */
02136       return 0;
02137    }
02138    construct_pidf_body(CC_OPEN, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
02139    return transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_MODIFY, monitor_instance->notify_uri);
02140 }
02141 
02142 static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id)
02143 {
02144    if (*sched_id != -1) {
02145       AST_SCHED_DEL(sched, *sched_id);
02146       ao2_t_ref(monitor, -1, "Removing scheduler's reference to the monitor");
02147    }
02148    return 0;
02149 }
02150 
02151 static void sip_cc_monitor_destructor(void *private_data)
02152 {
02153    struct sip_monitor_instance *monitor_instance = private_data;
02154    ao2_unlink(sip_monitor_instances, monitor_instance);
02155    ast_module_unref(ast_module_info->self);
02156 }
02157 
02158 static int sip_get_cc_information(struct sip_request *req, char *subscribe_uri, size_t size, enum ast_cc_service_type *service)
02159 {
02160    char *call_info = ast_strdupa(sip_get_header(req, "Call-Info"));
02161    char *uri;
02162    char *purpose;
02163    char *service_str;
02164    static const char cc_purpose[] = "purpose=call-completion";
02165    static const int cc_purpose_len = sizeof(cc_purpose) - 1;
02166 
02167    if (ast_strlen_zero(call_info)) {
02168       /* No Call-Info present. Definitely no CC offer */
02169       return -1;
02170    }
02171 
02172    uri = strsep(&call_info, ";");
02173 
02174    while ((purpose = strsep(&call_info, ";"))) {
02175       if (!strncmp(purpose, cc_purpose, cc_purpose_len)) {
02176          break;
02177       }
02178    }
02179    if (!purpose) {
02180       /* We didn't find the appropriate purpose= parameter. Oh well */
02181       return -1;
02182    }
02183 
02184    /* Okay, call-completion has been offered. Let's figure out what type of service this is */
02185    while ((service_str = strsep(&call_info, ";"))) {
02186       if (!strncmp(service_str, "m=", 2)) {
02187          break;
02188       }
02189    }
02190    if (!service_str) {
02191       /* So they didn't offer a particular service, We'll just go with CCBS since it really
02192        * doesn't matter anyway
02193        */
02194       service_str = "BS";
02195    } else {
02196       /* We already determined that there is an "m=" so no need to check
02197        * the result of this strsep
02198        */
02199       strsep(&service_str, "=");
02200    }
02201 
02202    if ((*service = service_string_to_service_type(service_str)) == AST_CC_NONE) {
02203       /* Invalid service offered */
02204       return -1;
02205    }
02206 
02207    ast_copy_string(subscribe_uri, get_in_brackets(uri), size);
02208 
02209    return 0;
02210 }
02211 
02212 /*
02213  * \brief Determine what, if any, CC has been offered and queue a CC frame if possible
02214  *
02215  * After taking care of some formalities to be sure that this call is eligible for CC,
02216  * we first try to see if we can make use of native CC. We grab the information from
02217  * the passed-in sip_request (which is always a response to an INVITE). If we can
02218  * use native CC monitoring for the call, then so be it.
02219  *
02220  * If native cc monitoring is not possible or not supported, then we will instead attempt
02221  * to use generic monitoring. Falling back to generic from a failed attempt at using native
02222  * monitoring will only work if the monitor policy of the endpoint is "always"
02223  *
02224  * \param pvt The current dialog. Contains CC parameters for the endpoint
02225  * \param req The response to the INVITE we want to inspect
02226  * \param service The service to use if generic monitoring is to be used. For native
02227  * monitoring, we get the service from the SIP response itself
02228  */
02229 static void sip_handle_cc(struct sip_pvt *pvt, struct sip_request *req, enum ast_cc_service_type service)
02230 {
02231    enum ast_cc_monitor_policies monitor_policy = ast_get_cc_monitor_policy(pvt->cc_params);
02232    int core_id;
02233    char interface_name[AST_CHANNEL_NAME];
02234 
02235    if (monitor_policy == AST_CC_MONITOR_NEVER) {
02236       /* Don't bother, just return */
02237       return;
02238    }
02239 
02240    if ((core_id = ast_cc_get_current_core_id(pvt->owner)) == -1) {
02241       /* For some reason, CC is invalid, so don't try it! */
02242       return;
02243    }
02244 
02245    ast_channel_get_device_name(pvt->owner, interface_name, sizeof(interface_name));
02246 
02247    if (monitor_policy == AST_CC_MONITOR_ALWAYS || monitor_policy == AST_CC_MONITOR_NATIVE) {
02248       char subscribe_uri[SIPBUFSIZE];
02249       char device_name[AST_CHANNEL_NAME];
02250       enum ast_cc_service_type offered_service;
02251       struct sip_monitor_instance *monitor_instance;
02252       if (sip_get_cc_information(req, subscribe_uri, sizeof(subscribe_uri), &offered_service)) {
02253          /* If CC isn't being offered to us, or for some reason the CC offer is
02254           * not formatted correctly, then it may still be possible to use generic
02255           * call completion since the monitor policy may be "always"
02256           */
02257          goto generic;
02258       }
02259       ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
02260       if (!(monitor_instance = sip_monitor_instance_init(core_id, subscribe_uri, pvt->peername, device_name))) {
02261          /* Same deal. We can try using generic still */
02262          goto generic;
02263       }
02264       /* We bump the refcount of chan_sip because once we queue this frame, the CC core
02265        * will have a reference to callbacks in this module. We decrement the module
02266        * refcount once the monitor destructor is called
02267        */
02268       ast_module_ref(ast_module_info->self);
02269       ast_queue_cc_frame(pvt->owner, "SIP", pvt->dialstring, offered_service, monitor_instance);
02270       ao2_ref(monitor_instance, -1);
02271       return;
02272    }
02273 
02274 generic:
02275    if (monitor_policy == AST_CC_MONITOR_GENERIC || monitor_policy == AST_CC_MONITOR_ALWAYS) {
02276       ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE, interface_name, service, NULL);
02277    }
02278 }
02279 
02280 /*! \brief Working TLS connection configuration */
02281 static struct ast_tls_config sip_tls_cfg;
02282 
02283 /*! \brief Default TLS connection configuration */
02284 static struct ast_tls_config default_tls_cfg;
02285 
02286 /*! \brief The TCP server definition */
02287 static struct ast_tcptls_session_args sip_tcp_desc = {
02288    .accept_fd = -1,
02289    .master = AST_PTHREADT_NULL,
02290    .tls_cfg = NULL,
02291    .poll_timeout = -1,
02292    .name = "SIP TCP server",
02293    .accept_fn = ast_tcptls_server_root,
02294    .worker_fn = sip_tcp_worker_fn,
02295 };
02296 
02297 /*! \brief The TCP/TLS server definition */
02298 static struct ast_tcptls_session_args sip_tls_desc = {
02299    .accept_fd = -1,
02300    .master = AST_PTHREADT_NULL,
02301    .tls_cfg = &sip_tls_cfg,
02302    .poll_timeout = -1,
02303    .name = "SIP TLS server",
02304    .accept_fn = ast_tcptls_server_root,
02305    .worker_fn = sip_tcp_worker_fn,
02306 };
02307 
02308 /*! \brief Append to SIP dialog history
02309    \return Always returns 0 */
02310 #define append_history(p, event, fmt , args... )   append_history_full(p, "%-15s " fmt, event, ## args)
02311 
02312 struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, const char *tag, char *file, int line, const char *func)
02313 {
02314    if (p)
02315 #ifdef REF_DEBUG
02316       __ao2_ref_debug(p, 1, tag, file, line, func);
02317 #else
02318       ao2_ref(p, 1);
02319 #endif
02320    else
02321       ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
02322    return p;
02323 }
02324 
02325 struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, const char *tag, char *file, int line, const char *func)
02326 {
02327    if (p)
02328 #ifdef REF_DEBUG
02329       __ao2_ref_debug(p, -1, tag, file, line, func);
02330 #else
02331       ao2_ref(p, -1);
02332 #endif
02333    return NULL;
02334 }
02335 
02336 /*! \brief map from an integer value to a string.
02337  * If no match is found, return errorstring
02338  */
02339 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
02340 {
02341    const struct _map_x_s *cur;
02342 
02343    for (cur = table; cur->s; cur++) {
02344       if (cur->x == x) {
02345          return cur->s;
02346       }
02347    }
02348    return errorstring;
02349 }
02350 
02351 /*! \brief map from a string to an integer value, case insensitive.
02352  * If no match is found, return errorvalue.
02353  */
02354 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
02355 {
02356    const struct _map_x_s *cur;
02357 
02358    for (cur = table; cur->s; cur++) {
02359       if (!strcasecmp(cur->s, s)) {
02360          return cur->x;
02361       }
02362    }
02363    return errorvalue;
02364 }
02365 
02366 static enum AST_REDIRECTING_REASON sip_reason_str_to_code(const char *text)
02367 {
02368    enum AST_REDIRECTING_REASON ast = AST_REDIRECTING_REASON_UNKNOWN;
02369    int i;
02370 
02371    for (i = 0; i < ARRAY_LEN(sip_reason_table); ++i) {
02372       if (!strcasecmp(text, sip_reason_table[i].text)) {
02373          ast = sip_reason_table[i].code;
02374          break;
02375       }
02376    }
02377 
02378    return ast;
02379 }
02380 
02381 static const char *sip_reason_code_to_str(enum AST_REDIRECTING_REASON code)
02382 {
02383    if (code >= 0 && code < ARRAY_LEN(sip_reason_table)) {
02384       return sip_reason_table[code].text;
02385    }
02386 
02387    return "unknown";
02388 }
02389 
02390 /*!
02391  * \brief generic function for determining if a correct transport is being
02392  * used to contact a peer
02393  *
02394  * this is done as a macro so that the "tmpl" var can be passed either a
02395  * sip_request or a sip_peer
02396  */
02397 #define check_request_transport(peer, tmpl) ({ \
02398    int ret = 0; \
02399    if (peer->socket.type == tmpl->socket.type) \
02400       ; \
02401    else if (!(peer->transports & tmpl->socket.type)) {\
02402       ast_log(LOG_ERROR, \
02403          "'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
02404          sip_get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
02405          ); \
02406       ret = 1; \
02407    } else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
02408       ast_log(LOG_WARNING, \
02409          "peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
02410          peer->name, sip_get_transport(tmpl->socket.type) \
02411       ); \
02412    } else { \
02413       ast_debug(1, \
02414          "peer '%s' has contacted us over %s even though we prefer %s.\n", \
02415          peer->name, sip_get_transport(tmpl->socket.type), sip_get_transport(peer->socket.type) \
02416       ); \
02417    }\
02418    (ret); \
02419 })
02420 
02421 /*! \brief
02422  * duplicate a list of channel variables, \return the copy.
02423  */
02424 static struct ast_variable *copy_vars(struct ast_variable *src)
02425 {
02426    struct ast_variable *res = NULL, *tmp, *v = NULL;
02427 
02428    for (v = src ; v ; v = v->next) {
02429       if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
02430          tmp->next = res;
02431          res = tmp;
02432       }
02433    }
02434    return res;
02435 }
02436 
02437 static void tcptls_packet_destructor(void *obj)
02438 {
02439    struct tcptls_packet *packet = obj;
02440 
02441    ast_free(packet->data);
02442 }
02443 
02444 static void sip_tcptls_client_args_destructor(void *obj)
02445 {
02446    struct ast_tcptls_session_args *args = obj;
02447    if (args->tls_cfg) {
02448       ast_free(args->tls_cfg->certfile);
02449       ast_free(args->tls_cfg->pvtfile);
02450       ast_free(args->tls_cfg->cipher);
02451       ast_free(args->tls_cfg->cafile);
02452       ast_free(args->tls_cfg->capath);
02453 
02454       ast_ssl_teardown(args->tls_cfg);
02455    }
02456    ast_free(args->tls_cfg);
02457    ast_free((char *) args->name);
02458 }
02459 
02460 static void sip_threadinfo_destructor(void *obj)
02461 {
02462    struct sip_threadinfo *th = obj;
02463    struct tcptls_packet *packet;
02464 
02465    if (th->alert_pipe[1] > -1) {
02466       close(th->alert_pipe[0]);
02467    }
02468    if (th->alert_pipe[1] > -1) {
02469       close(th->alert_pipe[1]);
02470    }
02471    th->alert_pipe[0] = th->alert_pipe[1] = -1;
02472 
02473    while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
02474       ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
02475    }
02476 
02477    if (th->tcptls_session) {
02478       ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
02479    }
02480 }
02481 
02482 /*! \brief creates a sip_threadinfo object and links it into the threadt table. */
02483 static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
02484 {
02485    struct sip_threadinfo *th;
02486 
02487    if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
02488       return NULL;
02489    }
02490 
02491    th->alert_pipe[0] = th->alert_pipe[1] = -1;
02492 
02493    if (pipe(th->alert_pipe) == -1) {
02494       ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
02495       ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
02496       return NULL;
02497    }
02498    ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
02499    th->tcptls_session = tcptls_session;
02500    th->type = transport ? transport : (tcptls_session->ssl ? SIP_TRANSPORT_TLS: SIP_TRANSPORT_TCP);
02501    ao2_t_link(threadt, th, "Adding new tcptls helper thread");
02502    ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
02503    return th;
02504 }
02505 
02506 /*! \brief used to indicate to a tcptls thread that data is ready to be written */
02507 static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
02508 {
02509    int res = len;
02510    struct sip_threadinfo *th = NULL;
02511    struct tcptls_packet *packet = NULL;
02512    struct sip_threadinfo tmp = {
02513       .tcptls_session = tcptls_session,
02514    };
02515    enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
02516 
02517    if (!tcptls_session) {
02518       return XMIT_ERROR;
02519    }
02520 
02521    ao2_lock(tcptls_session);
02522 
02523    if ((tcptls_session->fd == -1) ||
02524       !(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
02525       !(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
02526       !(packet->data = ast_str_create(len))) {
02527       goto tcptls_write_setup_error;
02528    }
02529 
02530    /* goto tcptls_write_error should _NOT_ be used beyond this point */
02531    ast_str_set(&packet->data, 0, "%s", (char *) buf);
02532    packet->len = len;
02533 
02534    /* alert tcptls thread handler that there is a packet to be sent.
02535     * must lock the thread info object to guarantee control of the
02536     * packet queue */
02537    ao2_lock(th);
02538    if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
02539       ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
02540       ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
02541       packet = NULL;
02542       res = XMIT_ERROR;
02543    } else { /* it is safe to queue the frame after issuing the alert when we hold the threadinfo lock */
02544       AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
02545    }
02546    ao2_unlock(th);
02547 
02548    ao2_unlock(tcptls_session);
02549    ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
02550    return res;
02551 
02552 tcptls_write_setup_error:
02553    if (th) {
02554       ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
02555    }
02556    if (packet) {
02557       ao2_t_ref(packet, -1, "could not allocate packet's data");
02558    }
02559    ao2_unlock(tcptls_session);
02560 
02561    return XMIT_ERROR;
02562 }
02563 
02564 /*! \brief SIP TCP connection handler */
02565 static void *sip_tcp_worker_fn(void *data)
02566 {
02567    struct ast_tcptls_session_instance *tcptls_session = data;
02568 
02569    return _sip_tcp_helper_thread(tcptls_session);
02570 }
02571 
02572 /*! \brief SIP WebSocket connection handler */
02573 static void sip_websocket_callback(struct ast_websocket *session, struct ast_variable *parameters, struct ast_variable *headers)
02574 {
02575    int res;
02576 
02577    if (ast_websocket_set_nonblock(session)) {
02578       goto end;
02579    }
02580 
02581    if (ast_websocket_set_timeout(session, sip_cfg.websocket_write_timeout)) {
02582       goto end;
02583    }
02584 
02585    while ((res = ast_wait_for_input(ast_websocket_fd(session), -1)) > 0) {
02586       char *payload;
02587       uint64_t payload_len;
02588       enum ast_websocket_opcode opcode;
02589       int fragmented;
02590 
02591       if (ast_websocket_read(session, &payload, &payload_len, &opcode, &fragmented)) {
02592          /* We err on the side of caution and terminate the session if any error occurs */
02593          break;
02594       }
02595 
02596       if (opcode == AST_WEBSOCKET_OPCODE_TEXT || opcode == AST_WEBSOCKET_OPCODE_BINARY) {
02597          struct sip_request req = { 0, };
02598 
02599          if (!(req.data = ast_str_create(payload_len + 1))) {
02600             goto end;
02601          }
02602 
02603          if (ast_str_set(&req.data, -1, "%s", payload) == AST_DYNSTR_BUILD_FAILED) {
02604             deinit_req(&req);
02605             goto end;
02606          }
02607 
02608          req.socket.fd = ast_websocket_fd(session);
02609          set_socket_transport(&req.socket, ast_websocket_is_secure(session) ? SIP_TRANSPORT_WSS : SIP_TRANSPORT_WS);
02610          req.socket.ws_session = session;
02611 
02612          handle_request_do(&req, ast_websocket_remote_address(session));
02613          deinit_req(&req);
02614 
02615       } else if (opcode == AST_WEBSOCKET_OPCODE_CLOSE) {
02616          break;
02617       }
02618    }
02619 
02620 end:
02621    ast_websocket_unref(session);
02622 }
02623 
02624 /*! \brief Check if the authtimeout has expired.
02625  * \param start the time when the session started
02626  *
02627  * \retval 0 the timeout has expired
02628  * \retval -1 error
02629  * \return the number of milliseconds until the timeout will expire
02630  */
02631 static int sip_check_authtimeout(time_t start)
02632 {
02633    int timeout;
02634    time_t now;
02635    if(time(&now) == -1) {
02636       ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
02637       return -1;
02638    }
02639 
02640    timeout = (authtimeout - (now - start)) * 1000;
02641    if (timeout < 0) {
02642       /* we have timed out */
02643       return 0;
02644    }
02645 
02646    return timeout;
02647 }
02648 
02649 /*!
02650  * \brief Read a SIP request or response from a TLS connection
02651  *
02652  * Because TLS operations are hidden from view via a FILE handle, the
02653  * logic for reading data is a bit complex, and we have to make periodic
02654  * checks to be sure we aren't taking too long to perform the necessary
02655  * action.
02656  *
02657  * \todo XXX This should be altered in the future not to use a FILE pointer
02658  *
02659  * \param req The request structure to fill in
02660  * \param tcptls_session The TLS connection on which the data is being received
02661  * \param authenticated A flag indicating whether authentication has occurred yet.
02662  *        This is only relevant in a server role.
02663  * \param start The time at which we started attempting to read data. Used in
02664  *        determining if there has been a timeout.
02665  * \param me Thread info. Used as a means of determining if the session needs to be stoppped.
02666  * \retval -1 Failed to read data
02667  * \retval 0 Succeeded in reading data
02668  */
02669 static int sip_tls_read(struct sip_request *req, struct sip_request *reqcpy, struct ast_tcptls_session_instance *tcptls_session,
02670          int authenticated, time_t start, struct sip_threadinfo *me)
02671 {
02672    int res, content_length, after_poll = 1, need_poll = 1;
02673    size_t datalen = ast_str_strlen(req->data);
02674    char buf[1024] = "";
02675    int timeout = -1;
02676  
02677    /* Read in headers one line at a time */
02678    while (datalen < 4 || strncmp(REQ_OFFSET_TO_STR(req, data->used - 4), "\r\n\r\n", 4)) {
02679       if (!tcptls_session->client && !authenticated) {
02680          if ((timeout = sip_check_authtimeout(start)) < 0) {
02681             ast_debug(2, "SIP TLS server failed to determine authentication timeout\n");
02682             return -1;
02683          }
02684 
02685          if (timeout == 0) {
02686             ast_debug(2, "SIP TLS server timed out\n");
02687             return -1;
02688          }
02689       } else {
02690          timeout = -1;
02691       }
02692 
02693       /* special polling behavior is required for TLS
02694        * sockets because of the buffering done in the
02695        * TLS layer */
02696       if (need_poll) {
02697          need_poll = 0;
02698          after_poll = 1;
02699          res = ast_wait_for_input(tcptls_session->fd, timeout);
02700          if (res < 0) {
02701             ast_debug(2, "SIP TLS server :: ast_wait_for_input returned %d\n", res);
02702             return -1;
02703          } else if (res == 0) {
02704             /* timeout */
02705             ast_debug(2, "SIP TLS server timed out\n");
02706             return -1;
02707          }
02708       }
02709 
02710       ao2_lock(tcptls_session);
02711       if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
02712          ao2_unlock(tcptls_session);
02713          if (after_poll) {
02714             return -1;
02715          } else {
02716             need_poll = 1;
02717             continue;
02718          }
02719       }
02720       ao2_unlock(tcptls_session);
02721       after_poll = 0;
02722       if (me->stop) {
02723          return -1;
02724       }
02725       ast_str_append(&req->data, 0, "%s", buf);
02726 
02727       datalen = ast_str_strlen(req->data);
02728       if (datalen > SIP_MAX_PACKET_SIZE) {
02729          ast_log(LOG_WARNING, "Rejecting TLS packet from '%s' because way too large: %zu\n",
02730             ast_sockaddr_stringify(&tcptls_session->remote_address), datalen);
02731          return -1;
02732       }
02733    }
02734    copy_request(reqcpy, req);
02735    parse_request(reqcpy);
02736    /* In order to know how much to read, we need the content-length header */
02737    if (sscanf(sip_get_header(reqcpy, "Content-Length"), "%30d", &content_length)) {
02738       while (content_length > 0) {
02739          size_t bytes_read;
02740          if (!tcptls_session->client && !authenticated) {
02741             if ((timeout = sip_check_authtimeout(start)) < 0) {
02742                return -1;
02743             }
02744 
02745             if (timeout == 0) {
02746                ast_debug(2, "SIP TLS server timed out\n");
02747                return -1;
02748             }
02749          } else {
02750             timeout = -1;
02751          }
02752 
02753          if (need_poll) {
02754             need_poll = 0;
02755             after_poll = 1;
02756             res = ast_wait_for_input(tcptls_session->fd, timeout);
02757             if (res < 0) {
02758                ast_debug(2, "SIP TLS server :: ast_wait_for_input returned %d\n", res);
02759                return -1;
02760             } else if (res == 0) {
02761                /* timeout */
02762                ast_debug(2, "SIP TLS server timed out\n");
02763                return -1;
02764             }
02765          }
02766 
02767          ao2_lock(tcptls_session);
02768          if (!(bytes_read = fread(buf, 1, MIN(sizeof(buf) - 1, content_length), tcptls_session->f))) {
02769             ao2_unlock(tcptls_session);
02770             if (after_poll) {
02771                return -1;
02772             } else {
02773                need_poll = 1;
02774                continue;
02775             }
02776          }
02777          buf[bytes_read] = '\0';
02778          ao2_unlock(tcptls_session);
02779          after_poll = 0;
02780          if (me->stop) {
02781             return -1;
02782          }
02783          content_length -= strlen(buf);
02784          ast_str_append(&req->data, 0, "%s", buf);
02785       
02786          datalen = ast_str_strlen(req->data);
02787          if (datalen > SIP_MAX_PACKET_SIZE) {
02788             ast_log(LOG_WARNING, "Rejecting TLS packet from '%s' because way too large: %zu\n",
02789                ast_sockaddr_stringify(&tcptls_session->remote_address), datalen);
02790             return -1;
02791          }
02792       }
02793    }
02794    /*! \todo XXX If there's no Content-Length or if the content-length and what
02795                we receive is not the same - we should generate an error */
02796    return 0;
02797 }
02798 
02799 /*!
02800  * \brief Indication of a TCP message's integrity
02801  */
02802 enum message_integrity {
02803    /*!
02804     * The message has an error in it with
02805     * regards to its Content-Length header
02806     */
02807    MESSAGE_INVALID,
02808    /*!
02809     * The message is incomplete
02810     */
02811    MESSAGE_FRAGMENT,
02812    /*!
02813     * The data contains a complete message
02814     * plus a fragment of another.
02815     */
02816    MESSAGE_FRAGMENT_COMPLETE,
02817    /*!
02818     * The message is complete
02819     */
02820    MESSAGE_COMPLETE,
02821 };
02822 
02823 /*!
02824  * \brief
02825  * Get the content length from an unparsed SIP message
02826  *
02827  * \param message The unparsed SIP message headers
02828  * \return The value of the Content-Length header or -1 if message is invalid
02829  */
02830 static int read_raw_content_length(const char *message)
02831 {
02832    char *content_length_str;
02833    int content_length = -1;
02834 
02835    struct ast_str *msg_copy;
02836    char *msg;
02837 
02838    /* Using a ast_str because lws2sws takes one of those */
02839    if (!(msg_copy = ast_str_create(strlen(message) + 1))) {
02840       return -1;
02841    }
02842    ast_str_set(&msg_copy, 0, "%s", message);
02843 
02844    if (sip_cfg.pedanticsipchecking) {
02845       lws2sws(msg_copy);
02846    }
02847 
02848    msg = ast_str_buffer(msg_copy);
02849 
02850    /* Let's find a Content-Length header */
02851    if ((content_length_str = strcasestr(msg, "\nContent-Length:"))) {
02852       content_length_str += sizeof("\nContent-Length:") - 1;
02853    } else if ((content_length_str = strcasestr(msg, "\nl:"))) {
02854       content_length_str += sizeof("\nl:") - 1;
02855    } else {
02856       /* RFC 3261 18.3
02857        * "In the case of stream-oriented transports such as TCP, the Content-
02858        *  Length header field indicates the size of the body.  The Content-
02859        *  Length header field MUST be used with stream oriented transports."
02860        */
02861       goto done;
02862    }
02863 
02864    /* Double-check that this is a complete header */
02865    if (!strchr(content_length_str, '\n')) {
02866       goto done;
02867    }
02868 
02869    if (sscanf(content_length_str, "%30d", &content_length) != 1) {
02870       content_length = -1;
02871    }
02872 
02873 done:
02874    ast_free(msg_copy);
02875    return content_length;
02876 }
02877 
02878 /*!
02879  * \brief Check that a message received over TCP is a full message
02880  *
02881  * This will take the information read in and then determine if
02882  * 1) The message is a full SIP request
02883  * 2) The message is a partial SIP request
02884  * 3) The message contains a full SIP request along with another partial request
02885  * \param data The unparsed incoming SIP message.
02886  * \param request The resulting request with extra fragments removed.
02887  * \param overflow If the message contains more than a full request, this is the remainder of the message
02888  * \return The resulting integrity of the message
02889  */
02890 static enum message_integrity check_message_integrity(struct ast_str **request, struct ast_str **overflow)
02891 {
02892    char *message = ast_str_buffer(*request);
02893    char *body;
02894    int content_length;
02895    int message_len = ast_str_strlen(*request);
02896    int body_len;
02897 
02898    /* Important pieces to search for in a SIP request are \r\n\r\n. This
02899     * marks either
02900     * 1) The division between the headers and body
02901     * 2) The end of the SIP request
02902     */
02903    body = strstr(message, "\r\n\r\n");
02904    if (!body) {
02905       /* This is clearly a partial message since we haven't reached an end
02906        * yet.
02907        */
02908       return MESSAGE_FRAGMENT;
02909    }
02910    body += sizeof("\r\n\r\n") - 1;
02911    body_len = message_len - (body - message);
02912 
02913    body[-1] = '\0';
02914    content_length = read_raw_content_length(message);
02915    body[-1] = '\n';
02916 
02917    if (content_length < 0) {
02918       return MESSAGE_INVALID;
02919    } else if (content_length == 0) {
02920       /* We've definitely received an entire message. We need
02921        * to check if there's also a fragment of another message
02922        * in addition.
02923        */
02924       if (body_len == 0) {
02925          return MESSAGE_COMPLETE;
02926       } else {
02927          ast_str_append(overflow, 0, "%s", body);
02928          ast_str_truncate(*request, message_len - body_len);
02929          return MESSAGE_FRAGMENT_COMPLETE;
02930       }
02931    }
02932    /* Positive content length. Let's see what sort of
02933     * message body we're dealing with.
02934     */
02935    if (body_len < content_length) {
02936       /* We don't have the full message body yet */
02937       return MESSAGE_FRAGMENT;
02938    } else if (body_len > content_length) {
02939       /* We have the full message plus a fragment of a further
02940        * message
02941        */
02942       ast_str_append(overflow, 0, "%s", body + content_length);
02943       ast_str_truncate(*request, message_len - (body_len - content_length));
02944       return MESSAGE_FRAGMENT_COMPLETE;
02945    } else {
02946       /* Yay! Full message with no extra content */
02947       return MESSAGE_COMPLETE;
02948    }
02949 }
02950 
02951 /*!
02952  * \brief Read SIP request or response from a TCP connection
02953  *
02954  * \param req The request structure to be filled in
02955  * \param tcptls_session The TCP connection from which to read
02956  * \retval -1 Failed to read data
02957  * \retval 0 Successfully read data
02958  */
02959 static int sip_tcp_read(struct sip_request *req, struct ast_tcptls_session_instance *tcptls_session,
02960       int authenticated, time_t start)
02961 {
02962    enum message_integrity message_integrity = MESSAGE_FRAGMENT;
02963 
02964    while (message_integrity == MESSAGE_FRAGMENT) {
02965       size_t datalen;
02966 
02967       if (ast_str_strlen(tcptls_session->overflow_buf) == 0) {
02968          char readbuf[4097];
02969          int timeout;
02970          int res;
02971          if (!tcptls_session->client && !authenticated) {
02972             if ((timeout = sip_check_authtimeout(start)) < 0) {
02973                return -1;
02974             }
02975 
02976             if (timeout == 0) {
02977                ast_debug(2, "SIP TCP server timed out\n");
02978                return -1;
02979             }
02980          } else {
02981             timeout = -1;
02982          }
02983          res = ast_wait_for_input(tcptls_session->fd, timeout);
02984          if (res < 0) {
02985             ast_debug(2, "SIP TCP server :: ast_wait_for_input returned %d\n", res);
02986             return -1;
02987          } else if (res == 0) {
02988             ast_debug(2, "SIP TCP server timed out\n");
02989             return -1;
02990          }
02991 
02992          res = recv(tcptls_session->fd, readbuf, sizeof(readbuf) - 1, 0);
02993          if (res < 0) {
02994             ast_debug(2, "SIP TCP server error when receiving data\n");
02995             return -1;
02996          } else if (res == 0) {
02997             ast_debug(2, "SIP TCP server has shut down\n");
02998             return -1;
02999          }
03000          readbuf[res] = '\0';
03001          ast_str_append(&req->data, 0, "%s", readbuf);
03002       } else {
03003          ast_str_append(&req->data, 0, "%s", ast_str_buffer(tcptls_session->overflow_buf));
03004          ast_str_reset(tcptls_session->overflow_buf);
03005       }
03006       
03007       datalen = ast_str_strlen(req->data);
03008       if (datalen > SIP_MAX_PACKET_SIZE) {
03009          ast_log(LOG_WARNING, "Rejecting TCP packet from '%s' because way too large: %zu\n",
03010             ast_sockaddr_stringify(&tcptls_session->remote_address), datalen);
03011          return -1;
03012       }
03013 
03014       message_integrity = check_message_integrity(&req->data, &tcptls_session->overflow_buf);
03015    }
03016 
03017    return 0;
03018 }
03019 
03020 /*! \brief SIP TCP thread management function
03021    This function reads from the socket, parses the packet into a request
03022 */
03023 static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session)
03024 {
03025    int res, timeout = -1, authenticated = 0, flags;
03026    time_t start;
03027    struct sip_request req = { 0, } , reqcpy = { 0, };
03028    struct sip_threadinfo *me = NULL;
03029    char buf[1024] = "";
03030    struct pollfd fds[2] = { { 0 }, { 0 }, };
03031    struct ast_tcptls_session_args *ca = NULL;
03032 
03033    /* If this is a server session, then the connection has already been
03034     * setup. Check if the authlimit has been reached and if not create the
03035     * threadinfo object so we can access this thread for writing.
03036     *
03037     * if this is a client connection more work must be done.
03038     * 1. We own the parent session args for a client connection.  This pointer needs
03039     *    to be held on to so we can decrement it's ref count on thread destruction.
03040     * 2. The threadinfo object was created before this thread was launched, however
03041     *    it must be found within the threadt table.
03042     * 3. Last, the tcptls_session must be started.
03043     */
03044    if (!tcptls_session->client) {
03045       if (ast_atomic_fetchadd_int(&unauth_sessions, +1) >= authlimit) {
03046          /* unauth_sessions is decremented in the cleanup code */
03047          goto cleanup;
03048       }
03049 
03050       if ((flags = fcntl(tcptls_session->fd, F_GETFL)) == -1) {
03051          ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
03052          goto cleanup;
03053       }
03054 
03055       flags |= O_NONBLOCK;
03056       if (fcntl(tcptls_session->fd, F_SETFL, flags) == -1) {
03057          ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
03058          goto cleanup;
03059       }
03060 
03061       if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? SIP_TRANSPORT_TLS : SIP_TRANSPORT_TCP))) {
03062          goto cleanup;
03063       }
03064       ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
03065    } else {
03066       struct sip_threadinfo tmp = {
03067          .tcptls_session = tcptls_session,
03068       };
03069 
03070       if ((!(ca = tcptls_session->parent)) ||
03071          (!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
03072          (!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
03073          goto cleanup;
03074       }
03075    }
03076 
03077    flags = 1;
03078    if (setsockopt(tcptls_session->fd, SOL_SOCKET, SO_KEEPALIVE, &flags, sizeof(flags))) {
03079       ast_log(LOG_ERROR, "error enabling TCP keep-alives on sip socket: %s\n", strerror(errno));
03080       goto cleanup;
03081    }
03082 
03083    me->threadid = pthread_self();
03084    ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "TLS" : "TCP");
03085 
03086    /* set up pollfd to watch for reads on both the socket and the alert_pipe */
03087    fds[0].fd = tcptls_session->fd;
03088    fds[1].fd = me->alert_pipe[0];
03089    fds[0].events = fds[1].events = POLLIN | POLLPRI;
03090 
03091    if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
03092       goto cleanup;
03093    }
03094    if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET))) {
03095       goto cleanup;
03096    }
03097 
03098    if(time(&start) == -1) {
03099       ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
03100       goto cleanup;
03101    }
03102 
03103    /*
03104     * We cannot let the stream exclusively wait for data to arrive.
03105     * We have to wake up the task to send outgoing messages.
03106     */
03107    ast_tcptls_stream_set_exclusive_input(tcptls_session->stream_cookie, 0);
03108 
03109    ast_tcptls_stream_set_timeout_sequence(tcptls_session->stream_cookie, ast_tvnow(),
03110       tcptls_session->client ? -1 : (authtimeout * 1000));
03111 
03112    for (;;) {
03113       struct ast_str *str_save;
03114 
03115       if (!tcptls_session->client && req.authenticated && !authenticated) {
03116          authenticated = 1;
03117          ast_tcptls_stream_set_timeout_disable(tcptls_session->stream_cookie);
03118          ast_atomic_fetchadd_int(&unauth_sessions, -1);
03119       }
03120 
03121       /* calculate the timeout for unauthenticated server sessions */
03122       if (!tcptls_session->client && !authenticated ) {
03123          if ((timeout = sip_check_authtimeout(start)) < 0) {
03124             goto cleanup;
03125          }
03126 
03127          if (timeout == 0) {
03128             ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "TLS": "TCP");
03129             goto cleanup;
03130          }
03131       } else {
03132          timeout = -1;
03133       }
03134 
03135       if (ast_str_strlen(tcptls_session->overflow_buf) == 0) {
03136          res = ast_poll(fds, 2, timeout); /* polls for both socket and alert_pipe */
03137          if (res < 0) {
03138             ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "TLS": "TCP", res);
03139             goto cleanup;
03140          } else if (res == 0) {
03141             /* timeout */
03142             ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "TLS": "TCP");
03143             goto cleanup;
03144          }
03145       }
03146 
03147       /* 
03148        * handle the socket event, check for both reads from the socket fd or TCP overflow buffer,
03149        * and writes from alert_pipe fd.
03150        */
03151       if (fds[0].revents || (ast_str_strlen(tcptls_session->overflow_buf) > 0)) { /* there is data on the socket to be read */
03152          fds[0].revents = 0;
03153 
03154          /* clear request structure */
03155          str_save = req.data;
03156          memset(&req, 0, sizeof(req));
03157          req.data = str_save;
03158          ast_str_reset(req.data);
03159 
03160          str_save = reqcpy.data;
03161          memset(&reqcpy, 0, sizeof(reqcpy));
03162          reqcpy.data = str_save;
03163          ast_str_reset(reqcpy.data);
03164 
03165          memset(buf, 0, sizeof(buf));
03166 
03167          if (tcptls_session->ssl) {
03168             set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
03169             req.socket.port = htons(ourport_tls);
03170          } else {
03171             set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
03172             req.socket.port = htons(ourport_tcp);
03173          }
03174          req.socket.fd = tcptls_session->fd;
03175          if (tcptls_session->ssl) {
03176             res = sip_tls_read(&req, &reqcpy, tcptls_session, authenticated, start, me);
03177          } else {
03178             res = sip_tcp_read(&req, tcptls_session, authenticated, start);
03179          }
03180 
03181          if (res < 0) {
03182             goto cleanup;
03183          }
03184 
03185          req.socket.tcptls_session = tcptls_session;
03186          req.socket.ws_session = NULL;
03187          handle_request_do(&req, &tcptls_session->remote_address);
03188       }
03189 
03190       if (fds[1].revents) { /* alert_pipe indicates there is data in the send queue to be sent */
03191          enum sip_tcptls_alert alert;
03192          struct tcptls_packet *packet;
03193 
03194          fds[1].revents = 0;
03195 
03196          if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
03197             ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
03198             continue;
03199          }
03200 
03201          switch (alert) {
03202          case TCPTLS_ALERT_STOP:
03203             goto cleanup;
03204          case TCPTLS_ALERT_DATA:
03205             ao2_lock(me);
03206             if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
03207                ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty\n");
03208             }
03209             ao2_unlock(me);
03210 
03211             if (packet) {
03212                if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
03213                   ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
03214                }
03215                ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
03216             }
03217             break;
03218          default:
03219             ast_log(LOG_ERROR, "Unknown tcptls thread alert '%u'\n", alert);
03220          }
03221       }
03222    }
03223 
03224    ast_debug(2, "Shutting down thread for %s server\n", tcptls_session->ssl ? "TLS" : "TCP");
03225 
03226 cleanup:
03227    if (tcptls_session && !tcptls_session->client && !authenticated) {
03228       ast_atomic_fetchadd_int(&unauth_sessions, -1);
03229    }
03230 
03231    if (me) {
03232       ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
03233       ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
03234    }
03235    deinit_req(&reqcpy);
03236    deinit_req(&req);
03237 
03238    /* if client, we own the parent session arguments and must decrement ref */
03239    if (ca) {
03240       ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
03241    }
03242 
03243    if (tcptls_session) {
03244       ao2_lock(tcptls_session);
03245       ast_tcptls_close_session_file(tcptls_session);
03246       tcptls_session->parent = NULL;
03247       ao2_unlock(tcptls_session);
03248 
03249       ao2_ref(tcptls_session, -1);
03250       tcptls_session = NULL;
03251    }
03252    return NULL;
03253 }
03254 
03255 #ifdef REF_DEBUG
03256 struct sip_peer *_ref_peer(struct sip_peer *peer, char *tag, char *file, int line, const char *func)
03257 {
03258    if (peer)
03259       __ao2_ref_debug(peer, 1, tag, file, line, func);
03260    else
03261       ast_log(LOG_ERROR, "Attempt to Ref a null peer pointer\n");
03262    return peer;
03263 }
03264 
03265 void *_unref_peer(struct sip_peer *peer, char *tag, char *file, int line, const char *func)
03266 {
03267    if (peer)
03268       __ao2_ref_debug(peer, -1, tag, file, line, func);
03269    return NULL;
03270 }
03271 #else
03272 /*!
03273  * helper functions to unreference various types of objects.
03274  * By handling them this way, we don't have to declare the
03275  * destructor on each call, which removes the chance of errors.
03276  */
03277 void *sip_unref_peer(struct sip_peer *peer, char *tag)
03278 {
03279    ao2_t_ref(peer, -1, tag);
03280    return NULL;
03281 }
03282 
03283 struct sip_peer *sip_ref_peer(struct sip_peer *peer, char *tag)
03284 {
03285    ao2_t_ref(peer, 1, tag);
03286    return peer;
03287 }
03288 #endif /* REF_DEBUG */
03289 
03290 static void peer_sched_cleanup(struct sip_peer *peer)
03291 {
03292    if (peer->pokeexpire != -1) {
03293       AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
03294             sip_unref_peer(peer, "removing poke peer ref"));
03295    }
03296    if (peer->expire != -1) {
03297       AST_SCHED_DEL_UNREF(sched, peer->expire,
03298             sip_unref_peer(peer, "remove register expire ref"));
03299    }
03300    if (peer->keepalivesend != -1) {
03301       AST_SCHED_DEL_UNREF(sched, peer->keepalivesend,
03302                 sip_unref_peer(peer, "remove keepalive peer ref"));
03303    }
03304 }
03305 
03306 typedef enum {
03307    SIP_PEERS_MARKED,
03308    SIP_PEERS_ALL,
03309 } peer_unlink_flag_t;
03310 
03311 /* this func is used with ao2_callback to unlink/delete all marked or linked
03312    peers, depending on arg */
03313 static int match_and_cleanup_peer_sched(void *peerobj, void *arg, int flags)
03314 {
03315    struct sip_peer *peer = peerobj;
03316    peer_unlink_flag_t which = *(peer_unlink_flag_t *)arg;
03317 
03318    if (which == SIP_PEERS_ALL || peer->the_mark) {
03319       peer_sched_cleanup(peer);
03320       if (peer->dnsmgr) {
03321          ast_dnsmgr_release(peer->dnsmgr);
03322          peer->dnsmgr = NULL;
03323          sip_unref_peer(peer, "Release peer from dnsmgr");
03324       }
03325       return CMP_MATCH;
03326    }
03327    return 0;
03328 }
03329 
03330 static void unlink_peers_from_tables(peer_unlink_flag_t flag)
03331 {
03332    ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
03333       match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
03334    ao2_t_callback(peers_by_ip, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
03335       match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
03336 }
03337 
03338 /* \brief Unlink all marked peers from ao2 containers */
03339 static void unlink_marked_peers_from_tables(void)
03340 {
03341    unlink_peers_from_tables(SIP_PEERS_MARKED);
03342 }
03343 
03344 static void unlink_all_peers_from_tables(void)
03345 {
03346    unlink_peers_from_tables(SIP_PEERS_ALL);
03347 }
03348 
03349 /* \brief Unlink single peer from all ao2 containers */
03350 static void unlink_peer_from_tables(struct sip_peer *peer)
03351 {
03352    ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
03353    if (!ast_sockaddr_isnull(&peer->addr)) {
03354       ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
03355    }
03356 }
03357 
03358 /*! \brief maintain proper refcounts for a sip_pvt's outboundproxy
03359  *
03360  * This function sets pvt's outboundproxy pointer to the one referenced
03361  * by the proxy parameter. Because proxy may be a refcounted object, and
03362  * because pvt's old outboundproxy may also be a refcounted object, we need
03363  * to maintain the proper refcounts.
03364  *
03365  * \param pvt The sip_pvt for which we wish to set the outboundproxy
03366  * \param proxy The sip_proxy which we will point pvt towards.
03367  * \return Returns void
03368  */
03369 static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
03370 {
03371    struct sip_proxy *old_obproxy = pvt->outboundproxy;
03372    /* The sip_cfg.outboundproxy is statically allocated, and so
03373     * we don't ever need to adjust refcounts for it
03374     */
03375    if (proxy && proxy != &sip_cfg.outboundproxy) {
03376       ao2_ref(proxy, +1);
03377    }
03378    pvt->outboundproxy = proxy;
03379    if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
03380       ao2_ref(old_obproxy, -1);
03381    }
03382 }
03383 
03384 /*!
03385  * \brief Unlink a dialog from the dialogs container, as well as any other places
03386  * that it may be currently stored.
03387  *
03388  * \note A reference to the dialog must be held before calling this function, and this
03389  * function does not release that reference.
03390  */
03391 void dialog_unlink_all(struct sip_pvt *dialog)
03392 {
03393    struct sip_pkt *cp;
03394    struct ast_channel *owner;
03395 
03396    dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
03397 
03398    ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
03399    ao2_t_unlink(dialogs_needdestroy, dialog, "unlinking dialog_needdestroy via ao2_unlink");
03400    ao2_t_unlink(dialogs_rtpcheck, dialog, "unlinking dialog_rtpcheck via ao2_unlink");
03401 
03402    /* Unlink us from the owner (channel) if we have one */
03403    owner = sip_pvt_lock_full(dialog);
03404    if (owner) {
03405       ast_debug(1, "Detaching from channel %s\n", ast_channel_name(owner));
03406       ast_channel_tech_pvt_set(owner, dialog_unref(ast_channel_tech_pvt(owner), "resetting channel dialog ptr in unlink_all"));
03407       ast_channel_unlock(owner);
03408       ast_channel_unref(owner);
03409       dialog->owner = NULL;
03410    }
03411    sip_pvt_unlock(dialog);
03412 
03413    if (dialog->registry) {
03414       if (dialog->registry->call == dialog) {
03415          dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
03416       }
03417       dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
03418    }
03419    if (dialog->stateid != -1) {
03420       ast_extension_state_del(dialog->stateid, cb_extensionstate);
03421       dialog->stateid = -1;
03422    }
03423    /* Remove link from peer to subscription of MWI */
03424    if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog) {
03425       dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
03426    }
03427    if (dialog->relatedpeer && dialog->relatedpeer->call == dialog) {
03428       dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
03429    }
03430 
03431    /* remove all current packets in this dialog */
03432    while((cp = dialog->packets)) {
03433       dialog->packets = dialog->packets->next;
03434       AST_SCHED_DEL(sched, cp->retransid);
03435       dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
03436       if (cp->data) {
03437          ast_free(cp->data);
03438       }
03439       ast_free(cp);
03440    }
03441 
03442    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"));
03443 
03444    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"));
03445    
03446    if (dialog->autokillid > -1) {
03447       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"));
03448    }
03449 
03450    if (dialog->request_queue_sched_id > -1) {
03451       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"));
03452    }
03453 
03454    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"));
03455 
03456    if (dialog->t38id > -1) {
03457       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"));
03458    }
03459 
03460    if (dialog->stimer) {
03461       stop_session_timer(dialog);
03462    }
03463 
03464    dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
03465 }
03466 
03467 void *registry_unref(struct sip_registry *reg, char *tag)
03468 {
03469    ast_debug(3, "SIP Registry %s: refcount now %u\n", reg->hostname, reg->refcount - 1);
03470    ASTOBJ_UNREF(reg, sip_registry_destroy);
03471    return NULL;
03472 }
03473 
03474 /*! \brief Add object reference to SIP registry */
03475 static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
03476 {
03477    ast_debug(3, "SIP Registry %s: refcount now %u\n", reg->hostname, reg->refcount + 1);
03478    return ASTOBJ_REF(reg); /* Add pointer to registry in packet */
03479 }
03480 
03481 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
03482 static struct ast_udptl_protocol sip_udptl = {
03483    .type = "SIP",
03484    .get_udptl_info = sip_get_udptl_peer,
03485    .set_udptl_peer = sip_set_udptl_peer,
03486 };
03487 
03488 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03489    __attribute__((format(printf, 2, 3)));
03490 
03491 
03492 /*! \brief Convert transfer status to string */
03493 static const char *referstatus2str(enum referstatus rstatus)
03494 {
03495    return map_x_s(referstatusstrings, rstatus, "");
03496 }
03497 
03498 static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
03499 {
03500    if (pvt->final_destruction_scheduled) {
03501       return; /* This is already scheduled for final destruction, let the scheduler take care of it. */
03502    }
03503    append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
03504    if (!pvt->needdestroy) {
03505       pvt->needdestroy = 1;
03506       ao2_t_link(dialogs_needdestroy, pvt, "link pvt into dialogs_needdestroy container");
03507    }
03508 }
03509 
03510 /*! \brief Initialize the initital request packet in the pvt structure.
03511    This packet is used for creating replies and future requests in
03512    a dialog */
03513 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
03514 {
03515    if (p->initreq.headers) {
03516       ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
03517    } else {
03518       ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
03519    }
03520    /* Use this as the basis */
03521    copy_request(&p->initreq, req);
03522    parse_request(&p->initreq);
03523    if (req->debug) {
03524       ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
03525    }
03526 }
03527 
03528 /*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
03529 static void sip_alreadygone(struct sip_pvt *dialog)
03530 {
03531    ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
03532    dialog->alreadygone = 1;
03533 }
03534 
03535 /*! Resolve DNS srv name or host name in a sip_proxy structure */
03536 static int proxy_update(struct sip_proxy *proxy)
03537 {
03538    /* if it's actually an IP address and not a name,
03539            there's no need for a managed lookup */
03540    if (!ast_sockaddr_parse(&proxy->ip, proxy->name, 0)) {
03541       /* Ok, not an IP address, then let's check if it's a domain or host */
03542       /* XXX Todo - if we have proxy port, don't do SRV */
03543       proxy->ip.ss.ss_family = get_address_family_filter(SIP_TRANSPORT_UDP); /* Filter address family */
03544       if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
03545             ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
03546             return FALSE;
03547       }
03548 
03549    }
03550 
03551    ast_sockaddr_set_port(&proxy->ip, proxy->port);
03552 
03553    proxy->last_dnsupdate = time(NULL);
03554    return TRUE;
03555 }
03556 
03557 /*! \brief Parse proxy string and return an ao2_alloc'd proxy. If dest is
03558  *         non-NULL, no allocation is performed and dest is used instead.
03559  *         On error NULL is returned. */
03560 static struct sip_proxy *proxy_from_config(const char *proxy, int sipconf_lineno, struct sip_proxy *dest)
03561 {
03562    char *mutable_proxy, *sep, *name;
03563    int allocated = 0;
03564 
03565    if (!dest) {
03566       dest = ao2_alloc(sizeof(struct sip_proxy), NULL);
03567       if (!dest) {
03568          ast_log(LOG_WARNING, "Unable to allocate config storage for proxy\n");
03569          return NULL;
03570       }
03571       allocated = 1;
03572    }
03573 
03574    /* Format is: [transport://]name[:port][,force] */
03575    mutable_proxy = ast_skip_blanks(ast_strdupa(proxy));
03576    sep = strchr(mutable_proxy, ',');
03577    if (sep) {
03578       *sep++ = '\0';
03579       dest->force = !strncasecmp(ast_skip_blanks(sep), "force", 5);
03580    } else {
03581       dest->force = FALSE;
03582    }
03583 
03584    sip_parse_host(mutable_proxy, sipconf_lineno, &name, &dest->port, &dest->transport);
03585 
03586    /* Check that there is a name at all */
03587    if (ast_strlen_zero(name)) {
03588       if (allocated) {
03589          ao2_ref(dest, -1);
03590       } else {
03591          dest->name[0] = '\0';
03592       }
03593       return NULL;
03594    }
03595    ast_copy_string(dest->name, name, sizeof(dest->name));
03596 
03597    /* Resolve host immediately */
03598    proxy_update(dest);
03599 
03600    return dest;
03601 }
03602 
03603 /*! \brief converts ascii port to int representation. If no
03604  *  pt buffer is provided or the pt has errors when being converted
03605  *  to an int value, the port provided as the standard is used.
03606  */
03607 unsigned int port_str2int(const char *pt, unsigned int standard)
03608 {
03609    int port = standard;
03610    if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
03611       port = standard;
03612    }
03613 
03614    return port;
03615 }
03616 
03617 /*! \brief Get default outbound proxy or global proxy */
03618 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
03619 {
03620    if (dialog && dialog->options && dialog->options->outboundproxy) {
03621       if (sipdebug) {
03622          ast_debug(1, "OBPROXY: Applying dialplan set OBproxy to this call\n");
03623       }
03624       append_history(dialog, "OBproxy", "Using dialplan obproxy %s", dialog->options->outboundproxy->name);
03625       return dialog->options->outboundproxy;
03626    }
03627    if (peer && peer->outboundproxy) {
03628       if (sipdebug) {
03629          ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
03630       }
03631       append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
03632       return peer->outboundproxy;
03633    }
03634    if (sip_cfg.outboundproxy.name[0]) {
03635       if (sipdebug) {
03636          ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
03637       }
03638       append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
03639       return &sip_cfg.outboundproxy;
03640    }
03641    if (sipdebug) {
03642       ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
03643    }
03644    return NULL;
03645 }
03646 
03647 /*! \brief returns true if 'name' (with optional trailing whitespace)
03648  * matches the sip method 'id'.
03649  * Strictly speaking, SIP methods are case SENSITIVE, but we do
03650  * a case-insensitive comparison to be more tolerant.
03651  * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
03652  */
03653 static int method_match(enum sipmethod id, const char *name)
03654 {
03655    int len = strlen(sip_methods[id].text);
03656    int l_name = name ? strlen(name) : 0;
03657    /* true if the string is long enough, and ends with whitespace, and matches */
03658    return (l_name >= len && name && name[len] < 33 &&
03659       !strncasecmp(sip_methods[id].text, name, len));
03660 }
03661 
03662 /*! \brief  find_sip_method: Find SIP method from header */
03663 static int find_sip_method(const char *msg)
03664 {
03665    int i, res = 0;
03666    
03667    if (ast_strlen_zero(msg)) {
03668       return 0;
03669    }
03670    for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
03671       if (method_match(i, msg)) {
03672          res = sip_methods[i].id;
03673       }
03674    }
03675    return res;
03676 }
03677 
03678 /*! \brief See if we pass debug IP filter */
03679 static inline int sip_debug_test_addr(const struct ast_sockaddr *addr)
03680 {
03681    /* Can't debug if sipdebug is not enabled */
03682    if (!sipdebug) {
03683       return 0;
03684    }
03685 
03686    /* A null debug_addr means we'll debug any address */
03687    if (ast_sockaddr_isnull(&debugaddr)) {
03688       return 1;
03689    }
03690 
03691    /* If no port was specified for a debug address, just compare the
03692     * addresses, otherwise compare the address and port
03693     */
03694    if (ast_sockaddr_port(&debugaddr)) {
03695       return !ast_sockaddr_cmp(&debugaddr, addr);
03696    } else {
03697       return !ast_sockaddr_cmp_addr(&debugaddr, addr);
03698    }
03699 }
03700 
03701 /*! \brief The real destination address for a write */
03702 static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p)
03703 {
03704    if (p->outboundproxy) {
03705       return &p->outboundproxy->ip;
03706    }
03707 
03708    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;
03709 }
03710 
03711 /*! \brief Display SIP nat mode */
03712 static const char *sip_nat_mode(const struct sip_pvt *p)
03713 {
03714    return ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) ? "NAT" : "no NAT";
03715 }
03716 
03717 /*! \brief Test PVT for debugging output */
03718 static inline int sip_debug_test_pvt(struct sip_pvt *p)
03719 {
03720    if (!sipdebug) {
03721       return 0;
03722    }
03723    return sip_debug_test_addr(sip_real_dst(p));
03724 }
03725 
03726 /*! \brief Return int representing a bit field of transport types found in const char *transport */
03727 static int get_transport_str2enum(const char *transport)
03728 {
03729    int res = 0;
03730 
03731    if (ast_strlen_zero(transport)) {
03732       return res;
03733    }
03734 
03735    if (!strcasecmp(transport, "udp")) {
03736       res |= SIP_TRANSPORT_UDP;
03737    }
03738    if (!strcasecmp(transport, "tcp")) {
03739       res |= SIP_TRANSPORT_TCP;
03740    }
03741    if (!strcasecmp(transport, "tls")) {
03742       res |= SIP_TRANSPORT_TLS;
03743    }
03744    if (!strcasecmp(transport, "ws")) {
03745       res |= SIP_TRANSPORT_WS;
03746    }
03747    if (!strcasecmp(transport, "wss")) {
03748       res |= SIP_TRANSPORT_WSS;
03749    }
03750 
03751    return res;
03752 }
03753 
03754 /*! \brief Return configuration of transports for a device */
03755 static inline const char *get_transport_list(unsigned int transports)
03756 {
03757    char *buf;
03758 
03759    if (!transports) {
03760       return "UNKNOWN";
03761    }
03762 
03763    if (!(buf = ast_threadstorage_get(&sip_transport_str_buf, SIP_TRANSPORT_STR_BUFSIZE))) {
03764       return "";
03765    }
03766 
03767    memset(buf, 0, SIP_TRANSPORT_STR_BUFSIZE);
03768 
03769    if (transports & SIP_TRANSPORT_UDP) {
03770       strncat(buf, "UDP,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
03771    }
03772    if (transports & SIP_TRANSPORT_TCP) {
03773       strncat(buf, "TCP,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
03774    }
03775    if (transports & SIP_TRANSPORT_TLS) {
03776       strncat(buf, "TLS,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
03777    }
03778    if (transports & SIP_TRANSPORT_WS) {
03779       strncat(buf, "WS,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
03780    }
03781    if (transports & SIP_TRANSPORT_WSS) {
03782       strncat(buf, "WSS,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
03783    }
03784 
03785    /* Remove the trailing ',' if present */
03786    if (strlen(buf)) {
03787       buf[strlen(buf) - 1] = 0;
03788    }
03789 
03790    return buf;
03791 }
03792 
03793 /*! \brief Return transport as string */
03794 const char *sip_get_transport(enum sip_transport t)
03795 {
03796    switch (t) {
03797    case SIP_TRANSPORT_UDP:
03798       return "UDP";
03799    case SIP_TRANSPORT_TCP:
03800       return "TCP";
03801    case SIP_TRANSPORT_TLS:
03802       return "TLS";
03803    case SIP_TRANSPORT_WS:
03804    case SIP_TRANSPORT_WSS:
03805       return "WS";
03806    }
03807 
03808    return "UNKNOWN";
03809 }
03810 
03811 /*! \brief Return protocol string for srv dns query */
03812 static inline const char *get_srv_protocol(enum sip_transport t)
03813 {
03814    switch (t) {
03815    case SIP_TRANSPORT_UDP:
03816       return "udp";
03817    case SIP_TRANSPORT_WS:
03818       return "ws";
03819    case SIP_TRANSPORT_TLS:
03820    case SIP_TRANSPORT_TCP:
03821       return "tcp";
03822    case SIP_TRANSPORT_WSS:
03823       return "wss";
03824    }
03825 
03826    return "udp";
03827 }
03828 
03829 /*! \brief Return service string for srv dns query */
03830 static inline const char *get_srv_service(enum sip_transport t)
03831 {
03832    switch (t) {
03833    case SIP_TRANSPORT_TCP:
03834    case SIP_TRANSPORT_UDP:
03835    case SIP_TRANSPORT_WS:
03836       return "sip";
03837    case SIP_TRANSPORT_TLS:
03838    case SIP_TRANSPORT_WSS:
03839       return "sips";
03840    }
03841    return "sip";
03842 }
03843 
03844 /*! \brief Return transport of dialog.
03845    \note this is based on a false assumption. We don't always use the
03846    outbound proxy for all requests in a dialog. It depends on the
03847    "force" parameter. The FIRST request is always sent to the ob proxy.
03848    \todo Fix this function to work correctly
03849 */
03850 static inline const char *get_transport_pvt(struct sip_pvt *p)
03851 {
03852    if (p->outboundproxy && p->outboundproxy->transport) {
03853       set_socket_transport(&p->socket, p->outboundproxy->transport);
03854    }
03855 
03856    return sip_get_transport(p->socket.type);
03857 }
03858 
03859 /*!
03860  * \internal
03861  * \brief Transmit SIP message
03862  *
03863  * \details
03864  * Sends a SIP request or response on a given socket (in the pvt)
03865  * \note
03866  * Called by retrans_pkt, send_request, send_response and __sip_reliable_xmit
03867  *
03868  * \return length of transmitted message, XMIT_ERROR on known network failures -1 on other failures.
03869  */
03870 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data)
03871 {
03872    int res = 0;
03873    const struct ast_sockaddr *dst = sip_real_dst(p);
03874 
03875    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));
03876 
03877    if (sip_prepare_socket(p) < 0) {
03878       return XMIT_ERROR;
03879    }
03880 
03881    if (p->socket.type == SIP_TRANSPORT_UDP) {
03882       res = ast_sendto(p->socket.fd, ast_str_buffer(data), ast_str_strlen(data), 0, dst);
03883    } else if (p->socket.tcptls_session) {
03884       res = sip_tcptls_write(p->socket.tcptls_session, ast_str_buffer(data), ast_str_strlen(data));
03885    } else if (p->socket.ws_session) {
03886       if (!(res = ast_websocket_write(p->socket.ws_session, AST_WEBSOCKET_OPCODE_TEXT, ast_str_buffer(data), ast_str_strlen(data)))) {
03887          /* The WebSocket API just returns 0 on success and -1 on failure, while this code expects the payload length to be returned */
03888          res = ast_str_strlen(data);
03889       }
03890    } else {
03891       ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
03892       return XMIT_ERROR;
03893    }
03894 
03895    if (res == -1) {
03896       switch (errno) {
03897       case EBADF:    /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
03898       case EHOSTUNREACH:   /* Host can't be reached */
03899       case ENETDOWN:    /* Interface down */
03900       case ENETUNREACH: /* Network failure */
03901       case ECONNREFUSED:      /* ICMP port unreachable */
03902          res = XMIT_ERROR; /* Don't bother with trying to transmit again */
03903       }
03904    }
03905    if (res != ast_str_strlen(data)) {
03906       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));
03907    }
03908 
03909    return res;
03910 }
03911 
03912 /*! \brief Build a Via header for a request */
03913 static void build_via(struct sip_pvt *p)
03914 {
03915    /* Work around buggy UNIDEN UIP200 firmware */
03916    const char *rport = (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) || ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)) ? ";rport" : "";
03917 
03918    /* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
03919    snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s;branch=z9hG4bK%08x%s",
03920        get_transport_pvt(p),
03921        ast_sockaddr_stringify_remote(&p->ourip),
03922        (unsigned)p->branch, rport);
03923 }
03924 
03925 /*! \brief NAT fix - decide which IP address to use for Asterisk server?
03926  *
03927  * Using the localaddr structure built up with localnet statements in sip.conf
03928  * apply it to their address to see if we need to substitute our
03929  * externaddr or can get away with our internal bindaddr
03930  * 'us' is always overwritten.
03931  */
03932 static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p)
03933 {
03934    struct ast_sockaddr theirs;
03935 
03936    /* Set want_remap to non-zero if we want to remap 'us' to an externally
03937     * reachable IP address and port. This is done if:
03938     * 1. we have a localaddr list (containing 'internal' addresses marked
03939     *    as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
03940     *    and AST_SENSE_ALLOW on 'external' ones);
03941     * 2. externaddr is set, so we know what to use as the
03942     *    externally visible address;
03943     * 3. the remote address, 'them', is external;
03944     * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
03945     *    when passed to ast_apply_ha() so it does need to be remapped.
03946     *    This fourth condition is checked later.
03947     */
03948    int want_remap = 0;
03949 
03950    ast_sockaddr_copy(us, &internip); /* starting guess for the internal address */
03951    /* now ask the system what would it use to talk to 'them' */
03952    ast_ouraddrfor(them, us);
03953    ast_sockaddr_copy(&theirs, them);
03954 
03955    if (ast_sockaddr_is_ipv6(&theirs)) {
03956       if (localaddr && !ast_sockaddr_isnull(&externaddr) && !ast_sockaddr_is_any(&bindaddr)) {
03957          ast_log(LOG_WARNING, "Address remapping activated in sip.conf "
03958             "but we're using IPv6, which doesn't need it. Please "
03959             "remove \"localnet\" and/or \"externaddr\" settings.\n");
03960       }
03961    } else {
03962       want_remap = localaddr &&
03963          !ast_sockaddr_isnull(&externaddr) &&
03964          ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
03965    }
03966 
03967    if (want_remap &&
03968        (!sip_cfg.matchexternaddrlocally || !ast_apply_ha(localaddr, us)) ) {
03969       /* if we used externhost, see if it is time to refresh the info */
03970       if (externexpire && time(NULL) >= externexpire) {
03971          if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
03972             ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
03973          }
03974          externexpire = time(NULL) + externrefresh;
03975       }
03976       if (!ast_sockaddr_isnull(&externaddr)) {
03977          ast_sockaddr_copy(us, &externaddr);
03978          switch (p->socket.type) {
03979          case SIP_TRANSPORT_TCP:
03980             if (!externtcpport && ast_sockaddr_port(&externaddr)) {
03981                /* for consistency, default to the externaddr port */
03982                externtcpport = ast_sockaddr_port(&externaddr);
03983             }
03984             ast_sockaddr_set_port(us, externtcpport);
03985             break;
03986          case SIP_TRANSPORT_TLS:
03987             ast_sockaddr_set_port(us, externtlsport);
03988             break;
03989          case SIP_TRANSPORT_UDP:
03990             if (!ast_sockaddr_port(&externaddr)) {
03991                ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
03992             }
03993             break;
03994          default:
03995             break;
03996          }
03997       }
03998       ast_debug(1, "Target address %s is not local, substituting externaddr\n",
03999            ast_sockaddr_stringify(them));
04000    } else {
04001       /* no remapping, but we bind to a specific address, so use it. */
04002       switch (p->socket.type) {
04003       case SIP_TRANSPORT_TCP:
04004          if (!ast_sockaddr_is_any(&sip_tcp_desc.local_address)) {
04005             ast_sockaddr_copy(us,
04006                     &sip_tcp_desc.local_address);
04007          } else {
04008             ast_sockaddr_set_port(us,
04009                         ast_sockaddr_port(&sip_tcp_desc.local_address));
04010          }
04011          break;
04012       case SIP_TRANSPORT_TLS:
04013          if (!ast_sockaddr_is_any(&sip_tls_desc.local_address)) {
04014             ast_sockaddr_copy(us,
04015                     &sip_tls_desc.local_address);
04016          } else {
04017             ast_sockaddr_set_port(us,
04018                         ast_sockaddr_port(&sip_tls_desc.local_address));
04019          }
04020          break;
04021       case SIP_TRANSPORT_UDP:
04022          /* fall through on purpose */
04023       default:
04024          if (!ast_sockaddr_is_any(&bindaddr)) {
04025             ast_sockaddr_copy(us, &bindaddr);
04026          }
04027          if (!ast_sockaddr_port(us)) {
04028             ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
04029          }
04030       }
04031    }
04032    ast_debug(3, "Setting SIP_TRANSPORT_%s with address %s\n", sip_get_transport(p->socket.type), ast_sockaddr_stringify(us));
04033 }
04034 
04035 /*! \brief Append to SIP dialog history with arg list  */
04036 static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
04037 {
04038    char buf[80], *c = buf; /* max history length */
04039    struct sip_history *hist;
04040    int l;
04041 
04042    vsnprintf(buf, sizeof(buf), fmt, ap);
04043    strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
04044    l = strlen(buf) + 1;
04045    if (!(hist = ast_calloc(1, sizeof(*hist) + l))) {
04046       return;
04047    }
04048    if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
04049       ast_free(hist);
04050       return;
04051    }
04052    memcpy(hist->event, buf, l);
04053    if (p->history_entries == MAX_HISTORY_ENTRIES) {
04054       struct sip_history *oldest;
04055       oldest = AST_LIST_REMOVE_HEAD(p->history, list);
04056       p->history_entries--;
04057       ast_free(oldest);
04058    }
04059    AST_LIST_INSERT_TAIL(p->history, hist, list);
04060    p->history_entries++;
04061 }
04062 
04063 /*! \brief Append to SIP dialog history with arg list  */
04064 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
04065 {
04066    va_list ap;
04067 
04068    if (!p) {
04069       return;
04070    }
04071 
04072    if (!p->do_history && !recordhistory && !dumphistory) {
04073       return;
04074    }
04075 
04076    va_start(ap, fmt);
04077    append_history_va(p, fmt, ap);
04078    va_end(ap);
04079 
04080    return;
04081 }
04082 
04083 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
04084 static int retrans_pkt(const void *data)
04085 {
04086    struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
04087    int reschedule = DEFAULT_RETRANS;
04088    int xmitres = 0;
04089    /* how many ms until retrans timeout is reached */
04090    int64_t diff = pkt->retrans_stop_time - ast_tvdiff_ms(ast_tvnow(), pkt->time_sent);
04091 
04092    /* Do not retransmit if time out is reached. This will be negative if the time between
04093     * the first transmission and now is larger than our timeout period. This is a fail safe
04094     * check in case the scheduler gets behind or the clock is changed. */
04095    if ((diff <= 0) || (diff > pkt->retrans_stop_time)) {
04096       pkt->retrans_stop = 1;
04097    }
04098 
04099    /* Lock channel PVT */
04100    sip_pvt_lock(pkt->owner);
04101 
04102    if (!pkt->retrans_stop) {
04103       pkt->retrans++;
04104       if (!pkt->timer_t1) {   /* Re-schedule using timer_a and timer_t1 */
04105          if (sipdebug) {
04106             ast_debug(4, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n",
04107                pkt->retransid,
04108                sip_methods[pkt->method].text,
04109                pkt->method);
04110          }
04111       } else {
04112          int siptimer_a;
04113 
04114          if (sipdebug) {
04115             ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n",
04116                pkt->retransid,
04117                pkt->retrans,
04118                sip_methods[pkt->method].text,
04119                pkt->method);
04120          }
04121          if (!pkt->timer_a) {
04122             pkt->timer_a = 2 ;
04123          } else {
04124             pkt->timer_a = 2 * pkt->timer_a;
04125          }
04126 
04127          /* For non-invites, a maximum of 4 secs */
04128          siptimer_a = pkt->timer_t1 * pkt->timer_a;   /* Double each time */
04129          if (pkt->method != SIP_INVITE && siptimer_a > 4000) {
04130             siptimer_a = 4000;
04131          }
04132 
04133          /* Reschedule re-transmit */
04134          reschedule = siptimer_a;
04135          ast_debug(4, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n",
04136             pkt->retrans + 1,
04137             siptimer_a,
04138             pkt->timer_t1,
04139             pkt->retransid);
04140       }
04141 
04142       if (sip_debug_test_pvt(pkt->owner)) {
04143          const struct ast_sockaddr *dst = sip_real_dst(pkt->owner);
04144          ast_verbose("Retransmitting #%d (%s) to %s:\n%s\n---\n",
04145             pkt->retrans, sip_nat_mode(pkt->owner),
04146             ast_sockaddr_stringify(dst),
04147             ast_str_buffer(pkt->data));
04148       }
04149 
04150       append_history(pkt->owner, "ReTx", "%d %s", reschedule, ast_str_buffer(pkt->data));
04151       xmitres = __sip_xmit(pkt->owner, pkt->data);
04152 
04153       /* If there was no error during the network transmission, schedule the next retransmission,
04154        * but if the next retransmission is going to be beyond our timeout period, mark the packet's
04155        * stop_retrans value and set the next retransmit to be the exact time of timeout.  This will
04156        * allow any responses to the packet to be processed before the packet is destroyed on the next
04157        * call to this function by the scheduler. */
04158       if (xmitres != XMIT_ERROR) {
04159          if (reschedule >= diff) {
04160             pkt->retrans_stop = 1;
04161             reschedule = diff;
04162          }
04163          sip_pvt_unlock(pkt->owner);
04164          return  reschedule;
04165       }
04166    }
04167 
04168    /* At this point, either the packet's retransmission timed out, or there was a
04169     * transmission error, either way destroy the scheduler item and this packet. */
04170 
04171    pkt->retransid = -1; /* Kill this scheduler item */
04172 
04173    if (pkt->method != SIP_OPTIONS && xmitres == 0) {
04174       if (pkt->is_fatal || sipdebug) { /* Tell us if it's critical or if we're debugging */
04175          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"
04176             "Packet timed out after %dms with no response\n",
04177             pkt->owner->callid,
04178             pkt->seqno,
04179             pkt->is_fatal ? "Critical" : "Non-critical",
04180             pkt->is_resp ? "Response" : "Request",
04181             (int) ast_tvdiff_ms(ast_tvnow(), pkt->time_sent));
04182       }
04183    } else if (pkt->method == SIP_OPTIONS && sipdebug) {
04184       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);
04185    }
04186 
04187    if (xmitres == XMIT_ERROR) {
04188       ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
04189       append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
04190    } else {
04191       append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
04192    }
04193 
04194    if (pkt->is_fatal) {
04195       while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
04196          sip_pvt_unlock(pkt->owner);   /* SIP_PVT, not channel */
04197          usleep(1);
04198          sip_pvt_lock(pkt->owner);
04199       }
04200       if (pkt->owner->owner && !ast_channel_hangupcause(pkt->owner->owner)) {
04201          ast_channel_hangupcause_set(pkt->owner->owner, AST_CAUSE_NO_USER_RESPONSE);
04202       }
04203       if (pkt->owner->owner) {
04204          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);
04205 
04206          if (pkt->is_resp &&
04207             (pkt->response_code >= 200) &&
04208             (pkt->response_code < 300) &&
04209             pkt->owner->pendinginvite &&
04210             ast_test_flag(&pkt->owner->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
04211             /* This is a timeout of the 2XX response to a pending INVITE.  In this case terminate the INVITE
04212              * transaction just as if we received the ACK, but immediately hangup with a BYE (sip_hangup
04213              * will send the BYE as long as the dialog is not set as "alreadygone")
04214              * RFC 3261 section 13.3.1.4.
04215              * "If the server retransmits the 2xx response for 64*T1 seconds without receiving
04216              * an ACK, the dialog is confirmed, but the session SHOULD be terminated.  This is
04217              * accomplished with a BYE, as described in Section 15." */
04218             pkt->owner->invitestate = INV_TERMINATED;
04219             pkt->owner->pendinginvite = 0;
04220          } else {
04221             /* there is nothing left to do, mark the dialog as gone */
04222             sip_alreadygone(pkt->owner);
04223          }
04224          ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_NO_USER_RESPONSE);
04225          ast_channel_unlock(pkt->owner->owner);
04226       } else {
04227          /* If no channel owner, destroy now */
04228 
04229          /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
04230          if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
04231             pvt_set_needdestroy(pkt->owner, "no response to critical packet");
04232             sip_alreadygone(pkt->owner);
04233             append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
04234          }
04235       }
04236    }
04237 
04238    if (pkt->method == SIP_BYE) {
04239       /* We're not getting answers on SIP BYE's.  Tear down the call anyway. */
04240       sip_alreadygone(pkt->owner);
04241       if (pkt->owner->owner) {
04242          ast_channel_unlock(pkt->owner->owner);
04243       }
04244       append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
04245       pvt_set_needdestroy(pkt->owner, "no response to BYE");
04246    }
04247 
04248    /* Remove the packet */
04249    for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
04250       if (cur == pkt) {
04251          UNLINK(cur, pkt->owner->packets, prev);
04252          sip_pvt_unlock(pkt->owner);
04253          if (pkt->owner) {
04254             pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
04255          }
04256          if (pkt->data) {
04257             ast_free(pkt->data);
04258          }
04259          pkt->data = NULL;
04260          ast_free(pkt);
04261          return 0;
04262       }
04263    }
04264    /* error case */
04265    ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
04266    sip_pvt_unlock(pkt->owner);
04267    return 0;
04268 }
04269 
04270 /*!
04271  * \internal
04272  * \brief Transmit packet with retransmits
04273  * \return 0 on success, -1 on failure to allocate packet
04274  */
04275 static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, uint32_t seqno, int resp, struct ast_str *data, int fatal, int sipmethod)
04276 {
04277    struct sip_pkt *pkt = NULL;
04278    int siptimer_a = DEFAULT_RETRANS;
04279    int xmitres = 0;
04280    unsigned respid;
04281 
04282    if (sipmethod == SIP_INVITE) {
04283       /* Note this is a pending invite */
04284       p->pendinginvite = seqno;
04285    }
04286 
04287    /* If the transport is something reliable (TCP or TLS) then don't really send this reliably */
04288    /* I removed the code from retrans_pkt that does the same thing so it doesn't get loaded into the scheduler */
04289    /*! \todo According to the RFC some packets need to be retransmitted even if its TCP, so this needs to get revisited */
04290    if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
04291       xmitres = __sip_xmit(p, data);   /* Send packet */
04292       if (xmitres == XMIT_ERROR) {  /* Serious network trouble, no need to try again */
04293          append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
04294          return AST_FAILURE;
04295       } else {
04296          return AST_SUCCESS;
04297       }
04298    }
04299 
04300    if (!(pkt = ast_calloc(1, sizeof(*pkt)))) {
04301       return AST_FAILURE;
04302    }
04303    /* copy data, add a terminator and save length */
04304    if (!(pkt->data = ast_str_create(ast_str_strlen(data)))) {
04305       ast_free(pkt);
04306       return AST_FAILURE;
04307    }
04308    ast_str_set(&pkt->data, 0, "%s%s", ast_str_buffer(data), "\0");
04309    /* copy other parameters from the caller */
04310    pkt->method = sipmethod;
04311    pkt->seqno = seqno;
04312    pkt->is_resp = resp;
04313    pkt->is_fatal = fatal;
04314    pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
04315    pkt->next = p->packets;
04316    p->packets = pkt; /* Add it to the queue */
04317    if (resp) {
04318       /* Parse out the response code */
04319       if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
04320          pkt->response_code = respid;
04321       }
04322    }
04323    pkt->timer_t1 = p->timer_t1;  /* Set SIP timer T1 */
04324    pkt->retransid = -1;
04325    if (pkt->timer_t1) {
04326       siptimer_a = pkt->timer_t1;
04327    }
04328 
04329    pkt->time_sent = ast_tvnow(); /* time packet was sent */
04330    pkt->retrans_stop_time = 64 * (pkt->timer_t1 ? pkt->timer_t1 : DEFAULT_TIMER_T1); /* time in ms after pkt->time_sent to stop retransmission */
04331 
04332    /* Schedule retransmission */
04333    AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
04334    if (sipdebug) {
04335       ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id  #%d\n", pkt->retransid);
04336    }
04337 
04338    xmitres = __sip_xmit(pkt->owner, pkt->data); /* Send packet */
04339 
04340    if (xmitres == XMIT_ERROR) {  /* Serious network trouble, no need to try again */
04341       append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
04342       ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
04343       AST_SCHED_DEL(sched, pkt->retransid);
04344       p->packets = pkt->next;
04345       pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
04346       ast_free(pkt->data);
04347       ast_free(pkt);
04348       return AST_FAILURE;
04349    } else {
04350       /* This is odd, but since the retrans timer starts at 500ms and the do_monitor thread
04351        * only wakes up every 1000ms by default, we have to poke the thread here to make
04352        * sure it successfully detects this must be retransmitted in less time than
04353        * it usually sleeps for. Otherwise it might not retransmit this packet for 1000ms. */
04354       if (monitor_thread != AST_PTHREADT_NULL) {
04355          pthread_kill(monitor_thread, SIGURG);
04356       }
04357       return AST_SUCCESS;
04358    }
04359 }
04360 
04361 /*! \brief Kill a SIP dialog (called only by the scheduler)
04362  * The scheduler has a reference to this dialog when p->autokillid != -1,
04363  * and we are called using that reference. So if the event is not
04364  * rescheduled, we need to call dialog_unref().
04365  */
04366 static int __sip_autodestruct(const void *data)
04367 {
04368    struct sip_pvt *p = (struct sip_pvt *)data;
04369    struct ast_channel *owner;
04370 
04371    /* If this is a subscription, tell the phone that we got a timeout */
04372    if (p->subscribed && p->subscribed != MWI_NOTIFICATION && p->subscribed != CALL_COMPLETION) {
04373       struct state_notify_data data = { 0, };
04374       data.state = AST_EXTENSION_DEACTIVATED;
04375 
04376       transmit_state_notify(p, &data, 1, TRUE); /* Send last notification */
04377       p->subscribed = NONE;
04378       append_history(p, "Subscribestatus", "timeout");
04379       ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
04380       return 10000;  /* Reschedule this destruction so that we know that it's gone */
04381    }
04382 
04383    /* If there are packets still waiting for delivery, delay the destruction */
04384    if (p->packets) {
04385       if (!p->needdestroy) {
04386          char method_str[31];
04387          ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
04388          append_history(p, "ReliableXmit", "timeout");
04389          if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
04390             if (p->ongoing_reinvite || method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
04391                pvt_set_needdestroy(p, "autodestruct");
04392             }
04393          }
04394          return 10000;
04395       } else {
04396          /* They've had their chance to respond. Time to bail */
04397          __sip_pretend_ack(p);
04398       }
04399    }
04400 
04401    /* Reset schedule ID */
04402    p->autokillid = -1;
04403 
04404    /*
04405     * Lock both the pvt and the channel safely so that we can queue up a frame.
04406     */
04407    owner = sip_pvt_lock_full(p);
04408    if (owner) {
04409       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);
04410       ast_queue_hangup_with_cause(owner, AST_CAUSE_PROTOCOL_ERROR);
04411       ast_channel_unlock(owner);
04412       ast_channel_unref(owner);
04413       sip_pvt_unlock(p);
04414       return 10000;
04415    } else if (p->refer && !p->alreadygone) {
04416       ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
04417       stop_media_flows(p);
04418       transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
04419       append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
04420       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
04421    } else {
04422       append_history(p, "AutoDestroy", "%s", p->callid);
04423       ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
04424       sip_pvt_unlock(p);
04425       dialog_unlink_all(p); /* once it's unlinked and unrefd everywhere, it'll be freed automagically */
04426       sip_pvt_lock(p);
04427       /* dialog_unref(p, "unref dialog-- no other matching conditions"); -- unlink all now should finish off the dialog's references and free it. */
04428       /* sip_destroy(p); */      /* Go ahead and destroy dialog. All attempts to recover is done */
04429       /* sip_destroy also absorbs the reference */
04430    }
04431 
04432    sip_pvt_unlock(p);
04433 
04434    dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
04435 
04436    return 0;
04437 }
04438 
04439 /*! \brief Schedule final destruction of SIP dialog.  This can not be canceled.
04440  *  This function is used to keep a dialog around for a period of time in order
04441  *  to properly respond to any retransmits. */
04442 void sip_scheddestroy_final(struct sip_pvt *p, int ms)
04443 {
04444    if (p->final_destruction_scheduled) {
04445       return; /* already set final destruction */
04446    }
04447 
04448    sip_scheddestroy(p, ms);
04449    if (p->autokillid != -1) {
04450       p->final_destruction_scheduled = 1;
04451    }
04452 }
04453 
04454 /*! \brief Schedule destruction of SIP dialog */
04455 void sip_scheddestroy(struct sip_pvt *p, int ms)
04456 {
04457    if (p->final_destruction_scheduled) {
04458       return; /* already set final destruction */
04459    }
04460 
04461    if (ms < 0) {
04462       if (p->timer_t1 == 0) {
04463          p->timer_t1 = global_t1;   /* Set timer T1 if not set (RFC 3261) */
04464       }
04465       if (p->timer_b == 0) {
04466          p->timer_b = global_timer_b;  /* Set timer B if not set (RFC 3261) */
04467       }
04468       ms = p->timer_t1 * 64;
04469    }
04470    if (sip_debug_test_pvt(p)) {
04471       ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
04472    }
04473    if (sip_cancel_destroy(p)) {
04474       ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
04475    }
04476 
04477    if (p->do_history) {
04478       append_history(p, "SchedDestroy", "%d ms", ms);
04479    }
04480    p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
04481 
04482    if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0) {
04483       stop_session_timer(p);
04484    }
04485 }
04486 
04487 /*! \brief Cancel destruction of SIP dialog.
04488  * Be careful as this also absorbs the reference - if you call it
04489  * from within the scheduler, this might be the last reference.
04490  */
04491 int sip_cancel_destroy(struct sip_pvt *p)
04492 {
04493    if (p->final_destruction_scheduled) {
04494       return 0;
04495    }
04496 
04497    if (p->autokillid > -1) {
04498       append_history(p, "CancelDestroy", "");
04499       AST_SCHED_DEL_UNREF(sched, p->autokillid, dialog_unref(p, "remove ref for autokillid"));
04500    }
04501    return 0;
04502 }
04503 
04504 /*! \brief Acknowledges receipt of a packet and stops retransmission
04505  * called with p locked*/
04506 int __sip_ack(struct sip_pvt *p, uint32_t seqno, int resp, int sipmethod)
04507 {
04508    struct sip_pkt *cur, *prev = NULL;
04509    const char *msg = "Not Found";   /* used only for debugging */
04510    int res = FALSE;
04511 
04512    /* If we have an outbound proxy for this dialog, then delete it now since
04513      the rest of the requests in this dialog needs to follow the routing.
04514      If obforcing is set, we will keep the outbound proxy during the whole
04515      dialog, regardless of what the SIP rfc says
04516    */
04517    if (p->outboundproxy && !p->outboundproxy->force){
04518       ref_proxy(p, NULL);
04519    }
04520 
04521    for (cur = p->packets; cur; prev = cur, cur = cur->next) {
04522       if (cur->seqno != seqno || cur->is_resp != resp) {
04523          continue;
04524       }
04525       if (cur->is_resp || cur->method == sipmethod) {
04526          res = TRUE;
04527          msg = "Found";
04528          if (!resp && (seqno == p->pendinginvite)) {
04529             ast_debug(1, "Acked pending invite %u\n", p->pendinginvite);
04530             p->pendinginvite = 0;
04531          }
04532          if (cur->retransid > -1) {
04533             if (sipdebug)
04534                ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
04535          }
04536          /* This odd section is designed to thwart a
04537           * race condition in the packet scheduler. There are
04538           * two conditions under which deleting the packet from the
04539           * scheduler can fail.
04540           *
04541           * 1. The packet has been removed from the scheduler because retransmission
04542           * is being attempted. The problem is that if the packet is currently attempting
04543           * retransmission and we are at this point in the code, then that MUST mean
04544           * that retrans_pkt is waiting on p's lock. Therefore we will relinquish the
04545           * lock temporarily to allow retransmission.
04546           *
04547           * 2. The packet has reached its maximum number of retransmissions and has
04548           * been permanently removed from the packet scheduler. If this is the case, then
04549           * the packet's retransid will be set to -1. The atomicity of the setting and checking
04550           * of the retransid to -1 is ensured since in both cases p's lock is held.
04551           */
04552          while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
04553             sip_pvt_unlock(p);
04554             usleep(1);
04555             sip_pvt_lock(p);
04556          }
04557          UNLINK(cur, p->packets, prev);
04558          dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
04559          if (cur->data) {
04560             ast_free(cur->data);
04561          }
04562          ast_free(cur);
04563          break;
04564       }
04565    }
04566    ast_debug(1, "Stopping retransmission on '%s' of %s %u: Match %s\n",
04567       p->callid, resp ? "Response" : "Request", seqno, msg);
04568    return res;
04569 }
04570 
04571 /*! \brief Pretend to ack all packets
04572  * called with p locked */
04573 void __sip_pretend_ack(struct sip_pvt *p)
04574 {
04575    struct sip_pkt *cur = NULL;
04576 
04577    while (p->packets) {
04578       int method;
04579       if (cur == p->packets) {
04580          ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
04581          return;
04582       }
04583       cur = p->packets;
04584       method = (cur->method) ? cur->method : find_sip_method(ast_str_buffer(cur->data));
04585       __sip_ack(p, cur->seqno, cur->is_resp, method);
04586    }
04587 }
04588 
04589 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
04590 int __sip_semi_ack(struct sip_pvt *p, uint32_t seqno, int resp, int sipmethod)
04591 {
04592    struct sip_pkt *cur;
04593    int res = FALSE;
04594 
04595    for (cur = p->packets; cur; cur = cur->next) {
04596       if (cur->seqno == seqno && cur->is_resp == resp &&
04597          (cur->is_resp || method_match(sipmethod, ast_str_buffer(cur->data)))) {
04598          /* this is our baby */
04599          if (cur->retransid > -1) {
04600             if (sipdebug)
04601                ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
04602          }
04603          AST_SCHED_DEL(sched, cur->retransid);
04604          res = TRUE;
04605          break;
04606       }
04607    }
04608    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");
04609    return res;
04610 }
04611 
04612 
04613 /*! \brief Copy SIP request, parse it */
04614 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
04615 {
04616    copy_request(dst, src);
04617    parse_request(dst);
04618 }
04619 
04620 /*! \brief add a blank line if no body */
04621 static void add_blank(struct sip_request *req)
04622 {
04623    if (!req->lines) {
04624       /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
04625       ast_str_append(&req->data, 0, "\r\n");
04626    }
04627 }
04628 
04629 static int send_provisional_keepalive_full(struct sip_pvt *pvt, int with_sdp)
04630 {
04631    const char *msg = NULL;
04632    struct ast_channel *chan;
04633    int res = 0;
04634    int old_sched_id = pvt->provisional_keepalive_sched_id;
04635 
04636    chan = sip_pvt_lock_full(pvt);
04637    /* Check that nothing has changed while we were waiting for the lock */
04638    if (old_sched_id != pvt->provisional_keepalive_sched_id) {
04639       /* Keepalive has been cancelled or rescheduled, clean up and leave */
04640       if (chan) {
04641          ast_channel_unlock(chan);
04642          chan = ast_channel_unref(chan);
04643       }
04644       sip_pvt_unlock(pvt);
04645       dialog_unref(pvt, "dialog ref for provisional keepalive");
04646       return 0;
04647    }
04648 
04649    if (!pvt->last_provisional || !strncasecmp(pvt->last_provisional, "100", 3)) {
04650       msg = "183 Session Progress";
04651    }
04652 
04653    if (pvt->invitestate < INV_COMPLETED) {
04654       if (with_sdp) {
04655          transmit_response_with_sdp(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq, XMIT_UNRELIABLE, FALSE, FALSE);
04656       } else {
04657          transmit_response(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq);
04658       }
04659       res = PROVIS_KEEPALIVE_TIMEOUT;
04660    }
04661 
04662    if (chan) {
04663       ast_channel_unlock(chan);
04664       chan = ast_channel_unref(chan);
04665    }
04666 
04667    if (!res) {
04668       pvt->provisional_keepalive_sched_id = -1;
04669    }
04670 
04671    sip_pvt_unlock(pvt);
04672 
04673    if (!res) {
04674       dialog_unref(pvt, "dialog ref for provisional keepalive");
04675    }
04676    return res;
04677 }
04678 
04679 static int send_provisional_keepalive(const void *data)
04680 {
04681    struct sip_pvt *pvt = (struct sip_pvt *) data;
04682 
04683    return send_provisional_keepalive_full(pvt, 0);
04684 }
04685 
04686 static int send_provisional_keepalive_with_sdp(const void *data)
04687 {
04688    struct sip_pvt *pvt = (void *) data;
04689 
04690    return send_provisional_keepalive_full(pvt, 1);
04691 }
04692 
04693 static void update_provisional_keepalive(struct sip_pvt *pvt, int with_sdp)
04694 {
04695    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"));
04696 
04697    pvt->provisional_keepalive_sched_id = ast_sched_add(sched, PROVIS_KEEPALIVE_TIMEOUT,
04698       with_sdp ? send_provisional_keepalive_with_sdp : send_provisional_keepalive, dialog_ref(pvt, "Increment refcount to pass dialog pointer to sched callback"));
04699 }
04700 
04701 static void add_required_respheader(struct sip_request *req)
04702 {
04703    struct ast_str *str;
04704    int i;
04705 
04706    if (!req->reqsipoptions) {
04707       return;
04708    }
04709 
04710    str = ast_str_create(32);
04711 
04712    for (i = 0; i < ARRAY_LEN(sip_options); ++i) {
04713       if (!(req->reqsipoptions & sip_options[i].id)) {
04714          continue;
04715       }
04716       if (ast_str_strlen(str) > 0) {
04717          ast_str_append(&str, 0, ", ");
04718       }
04719       ast_str_append(&str, 0, "%s", sip_options[i].text);
04720    }
04721 
04722    if (ast_str_strlen(str) > 0) {
04723       add_header(req, "Require", ast_str_buffer(str));
04724    }
04725 
04726    ast_free(str);
04727 }
04728 
04729 /*! \brief Transmit response on SIP request*/
04730 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno)
04731 {
04732    int res;
04733 
04734    finalize_content(req);
04735    add_blank(req);
04736    if (sip_debug_test_pvt(p)) {
04737       const struct ast_sockaddr *dst = sip_real_dst(p);
04738 
04739       ast_verbose("\n<--- %sTransmitting (%s) to %s --->\n%s\n<------------>\n",
04740          reliable ? "Reliably " : "", sip_nat_mode(p),
04741          ast_sockaddr_stringify(dst),
04742          ast_str_buffer(req->data));
04743    }
04744    if (p->do_history) {
04745       struct sip_request tmp = { .rlpart1 = 0, };
04746       parse_copy(&tmp, req);
04747       append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", ast_str_buffer(tmp.data), sip_get_header(&tmp, "CSeq"),
04748          (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? REQ_OFFSET_TO_STR(&tmp, rlpart2) : sip_methods[tmp.method].text);
04749       deinit_req(&tmp);
04750    }
04751 
04752    /* If we are sending a final response to an INVITE, stop retransmitting provisional responses */
04753    if (p->initreq.method == SIP_INVITE && reliable == XMIT_CRITICAL) {
04754       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"));
04755    }
04756 
04757    res = (reliable) ?
04758        __sip_reliable_xmit(p, seqno, 1, req->data, (reliable == XMIT_CRITICAL), req->method) :
04759       __sip_xmit(p, req->data);
04760    deinit_req(req);
04761    if (res > 0) {
04762       return 0;
04763    }
04764    return res;
04765 }
04766 
04767 /*!
04768  * \internal
04769  * \brief Send SIP Request to the other part of the dialogue
04770  * \return see \ref __sip_xmit
04771  */
04772 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno)
04773 {
04774    int res;
04775 
04776    /* If we have an outbound proxy, reset peer address
04777       Only do this once.
04778    */
04779    if (p->outboundproxy) {
04780       p->sa = p->outboundproxy->ip;
04781    }
04782 
04783    finalize_content(req);
04784    add_blank(req);
04785    if (sip_debug_test_pvt(p)) {
04786       if (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT)) {
04787          ast_verbose("%sTransmitting (NAT) to %s:\n%s\n---\n", reliable ? "Reliably " : "", ast_sockaddr_stringify(&p->recv), ast_str_buffer(req->data));
04788       } else {
04789          ast_verbose("%sTransmitting (no NAT) to %s:\n%s\n---\n", reliable ? "Reliably " : "", ast_sockaddr_stringify(&p->sa), ast_str_buffer(req->data));
04790       }
04791    }
04792    if (p->do_history) {
04793       struct sip_request tmp = { .rlpart1 = 0, };
04794       parse_copy(&tmp, req);
04795       append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", ast_str_buffer(tmp.data), sip_get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
04796       deinit_req(&tmp);
04797    }
04798    res = (reliable) ?
04799       __sip_reliable_xmit(p, seqno, 0, req->data, (reliable == XMIT_CRITICAL), req->method) :
04800       __sip_xmit(p, req->data);
04801    deinit_req(req);
04802    return res;
04803 }
04804 
04805 static void enable_dsp_detect(struct sip_pvt *p)
04806 {
04807    int features = 0;
04808 
04809    if (p->dsp) {
04810       return;
04811    }
04812 
04813    if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
04814        (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
04815       if (p->rtp) {
04816          ast_rtp_instance_dtmf_mode_set(p->rtp, AST_RTP_DTMF_MODE_INBAND);
04817       }
04818       features |= DSP_FEATURE_DIGIT_DETECT;
04819    }
04820 
04821    if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
04822       features |= DSP_FEATURE_FAX_DETECT;
04823    }
04824 
04825    if (!features) {
04826       return;
04827    }
04828 
04829    if (!(p->dsp = ast_dsp_new())) {
04830       return;
04831    }
04832 
04833    ast_dsp_set_features(p->dsp, features);
04834    if (global_relaxdtmf) {
04835       ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
04836    }
04837 }
04838 
04839 static void disable_dsp_detect(struct sip_pvt *p)
04840 {
04841    if (p->dsp) {
04842       ast_dsp_free(p->dsp);
04843       p->dsp = NULL;
04844    }
04845 }
04846 
04847 /*! \brief Set an option on a SIP dialog */
04848 static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen)
04849 {
04850    int res = -1;
04851    struct sip_pvt *p = ast_channel_tech_pvt(chan);
04852 
04853         if (!p) {
04854       ast_log(LOG_ERROR, "Attempt to Ref a null pointer.  sip private structure is gone!\n");
04855       return -1;
04856         }
04857 
04858    sip_pvt_lock(p);
04859 
04860    switch (option) {
04861    case AST_OPTION_FORMAT_READ:
04862       if (p->rtp) {
04863          res = ast_rtp_instance_set_read_format(p->rtp, (struct ast_format *) data);
04864       }
04865       break;
04866    case AST_OPTION_FORMAT_WRITE:
04867       if (p->rtp) {
04868          res = ast_rtp_instance_set_write_format(p->rtp, (struct ast_format *) data);
04869       }
04870       break;
04871    case AST_OPTION_MAKE_COMPATIBLE:
04872       if (p->rtp) {
04873          res = ast_rtp_instance_make_compatible(chan, p->rtp, (struct ast_channel *) data);
04874       }
04875       break;
04876    case AST_OPTION_DIGIT_DETECT:
04877       if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
04878           (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
04879          char *cp = (char *) data;
04880 
04881          ast_debug(1, "%sabling digit detection on %s\n", *cp ? "En" : "Dis", ast_channel_name(chan));
04882          if (*cp) {
04883             enable_dsp_detect(p);
04884          } else {
04885             disable_dsp_detect(p);
04886          }
04887          res = 0;
04888       }
04889       break;
04890    case AST_OPTION_SECURE_SIGNALING:
04891       p->req_secure_signaling = *(unsigned int *) data;
04892       res = 0;
04893       break;
04894    case AST_OPTION_SECURE_MEDIA:
04895       ast_set2_flag(&p->flags[1], *(unsigned int *) data, SIP_PAGE2_USE_SRTP);
04896       res = 0;
04897       break;
04898    default:
04899       break;
04900    }
04901 
04902    sip_pvt_unlock(p);
04903 
04904    return res;
04905 }
04906 
04907 /*! \brief Query an option on a SIP dialog */
04908 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
04909 {
04910    int res = -1;
04911    enum ast_t38_state state = T38_STATE_UNAVAILABLE;
04912    struct sip_pvt *p = (struct sip_pvt *) ast_channel_tech_pvt(chan);
04913    char *cp;
04914 
04915    sip_pvt_lock(p);
04916 
04917    switch (option) {
04918    case AST_OPTION_T38_STATE:
04919       /* Make sure we got an ast_t38_state enum passed in */
04920       if (*datalen != sizeof(enum ast_t38_state)) {
04921          ast_log(LOG_ERROR, "Invalid datalen for AST_OPTION_T38_STATE option. Expected %d, got %d\n", (int)sizeof(enum ast_t38_state), *datalen);
04922          break;
04923       }
04924 
04925       /* 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 */
04926       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
04927          switch (p->t38.state) {
04928          case T38_LOCAL_REINVITE:
04929          case T38_PEER_REINVITE:
04930             state = T38_STATE_NEGOTIATING;
04931             break;
04932          case T38_ENABLED:
04933             state = T38_STATE_NEGOTIATED;
04934             break;
04935          case T38_REJECTED:
04936             state = T38_STATE_REJECTED;
04937             break;
04938          default:
04939             state = T38_STATE_UNKNOWN;
04940          }
04941       }
04942 
04943       *((enum ast_t38_state *) data) = state;
04944       res = 0;
04945 
04946       break;
04947    case AST_OPTION_DIGIT_DETECT:
04948       cp = (char *) data;
04949       *cp = p->dsp ? 1 : 0;
04950       ast_debug(1, "Reporting digit detection %sabled on %s\n", *cp ? "en" : "dis", ast_channel_name(chan));
04951       break;
04952    case AST_OPTION_SECURE_SIGNALING:
04953       *((unsigned int *) data) = p->req_secure_signaling;
04954       res = 0;
04955       break;
04956    case AST_OPTION_SECURE_MEDIA:
04957       *((unsigned int *) data) = ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP) ? 1 : 0;
04958       res = 0;
04959       break;
04960    case AST_OPTION_DEVICE_NAME:
04961       if (p && p->outgoing_call) {
04962          cp = (char *) data;
04963          ast_copy_string(cp, p->dialstring, *datalen);
04964          res = 0;
04965       }
04966       /* We purposely break with a return of -1 in the
04967        * implied else case here
04968        */
04969       break;
04970    default:
04971       break;
04972    }
04973 
04974    sip_pvt_unlock(p);
04975 
04976    return res;
04977 }
04978 
04979 /*! \brief Locate closing quote in a string, skipping escaped quotes.
04980  * optionally with a limit on the search.
04981  * start must be past the first quote.
04982  */
04983 const char *find_closing_quote(const char *start, const char *lim)
04984 {
04985    char last_char = '\0';
04986    const char *s;
04987    for (s = start; *s && s != lim; last_char = *s++) {
04988       if (*s == '"' && last_char != '\\')
04989          break;
04990    }
04991    return s;
04992 }
04993 
04994 /*! \brief Send message with Access-URL header, if this is an HTML URL only! */
04995 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
04996 {
04997    struct sip_pvt *p = ast_channel_tech_pvt(chan);
04998 
04999    if (subclass != AST_HTML_URL)
05000       return -1;
05001 
05002    ast_string_field_build(p, url, "<%s>;mode=active", data);
05003 
05004    if (sip_debug_test_pvt(p))
05005       ast_debug(1, "Send URL %s, state = %u!\n", data, ast_channel_state(chan));
05006 
05007    switch (ast_channel_state(chan)) {
05008    case AST_STATE_RING:
05009       transmit_response(p, "100 Trying", &p->initreq);
05010       break;
05011    case AST_STATE_RINGING:
05012       transmit_response(p, "180 Ringing", &p->initreq);
05013       break;
05014    case AST_STATE_UP:
05015       if (!p->pendinginvite) {      /* We are up, and have no outstanding invite */
05016          transmit_reinvite_with_sdp(p, FALSE, FALSE);
05017       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
05018          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
05019       }
05020       break;
05021    default:
05022       ast_log(LOG_WARNING, "Don't know how to send URI when state is %u!\n", ast_channel_state(chan));
05023    }
05024 
05025    return 0;
05026 }
05027 
05028 /*! \brief Deliver SIP call ID for the call */
05029 static const char *sip_get_callid(struct ast_channel *chan)
05030 {
05031    return ast_channel_tech_pvt(chan) ? ((struct sip_pvt *) ast_channel_tech_pvt(chan))->callid : "";
05032 }
05033 
05034 /*!
05035  * \internal
05036  * \brief Send SIP MESSAGE text within a call
05037  * \note Called from PBX core sendtext() application
05038  */
05039 static int sip_sendtext(struct ast_channel *ast, const char *text)
05040 {
05041    struct sip_pvt *dialog = ast_channel_tech_pvt(ast);
05042    int debug;
05043 
05044    if (!dialog) {
05045       return -1;
05046    }
05047    /* NOT ast_strlen_zero, because a zero-length message is specifically
05048     * allowed by RFC 3428 (See section 10, Examples) */
05049    if (!text) {
05050       return 0;
05051    }
05052    if(!is_method_allowed(&dialog->allowed_methods, SIP_MESSAGE)) {
05053       ast_debug(2, "Trying to send MESSAGE to device that does not support it.\n");
05054       return 0;
05055    }
05056 
05057    debug = sip_debug_test_pvt(dialog);
05058    if (debug) {
05059       ast_verbose("Sending text %s on %s\n", text, ast_channel_name(ast));
05060    }
05061 
05062    /* Setup to send text message */
05063    sip_pvt_lock(dialog);
05064    destroy_msg_headers(dialog);
05065    ast_string_field_set(dialog, msg_body, text);
05066    transmit_message(dialog, 0, 0);
05067    sip_pvt_unlock(dialog);
05068    return 0;
05069 }
05070 
05071 /*! \brief Update peer object in realtime storage
05072    If the Asterisk system name is set in asterisk.conf, we will use
05073    that name and store that in the "regserver" field in the sippeers
05074    table to facilitate multi-server setups.
05075 */
05076 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)
05077 {
05078    char port[10];
05079    char ipaddr[INET6_ADDRSTRLEN];
05080    char regseconds[20];
05081    char *tablename = NULL;
05082    char str_lastms[20];
05083 
05084    const char *sysname = ast_config_AST_SYSTEM_NAME;
05085    char *syslabel = NULL;
05086 
05087    time_t nowtime = time(NULL) + expirey;
05088    const char *fc = fullcontact ? "fullcontact" : NULL;
05089 
05090    int realtimeregs = ast_check_realtime("sipregs");
05091 
05092    tablename = realtimeregs ? "sipregs" : "sippeers";
05093 
05094    snprintf(str_lastms, sizeof(str_lastms), "%d", lastms);
05095    snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);  /* Expiration time */
05096    ast_copy_string(ipaddr, ast_sockaddr_isnull(addr) ? "" : ast_sockaddr_stringify_addr(addr), sizeof(ipaddr));
05097    ast_copy_string(port, ast_sockaddr_port(addr) ? ast_sockaddr_stringify_port(addr) : "", sizeof(port));
05098 
05099    if (ast_strlen_zero(sysname)) /* No system name, disable this */
05100       sysname = NULL;
05101    else if (sip_cfg.rtsave_sysname)
05102       syslabel = "regserver";
05103 
05104    /* XXX IMPORTANT: Anytime you add a new parameter to be updated, you
05105          *  must also add it to contrib/scripts/asterisk.ldap-schema,
05106          *  contrib/scripts/asterisk.ldif,
05107          *  and to configs/res_ldap.conf.sample as described in
05108          *  bugs 15156 and 15895
05109          */
05110    if (fc) {
05111       ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
05112          "port", port, "regseconds", regseconds,
05113          deprecated_username ? "username" : "defaultuser", defaultuser,
05114          "useragent", useragent, "lastms", str_lastms,
05115          fc, fullcontact, syslabel, sysname, SENTINEL); /* note fc and syslabel _can_ be NULL */
05116    } else {
05117       ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
05118          "port", port, "regseconds", regseconds,
05119          "useragent", useragent, "lastms", str_lastms,
05120          deprecated_username ? "username" : "defaultuser", defaultuser,
05121          syslabel, sysname, SENTINEL); /* note syslabel _can_ be NULL */
05122    }
05123 }
05124 
05125 /*! \brief Automatically add peer extension to dial plan */
05126 static void register_peer_exten(struct sip_peer *peer, int onoff)
05127 {
05128    char multi[256];
05129    char *stringp, *ext, *context;
05130    struct pbx_find_info q = { .stacklen = 0 };
05131 
05132    /* XXX note that sip_cfg.regcontext is both a global 'enable' flag and
05133     * the name of the global regexten context, if not specified
05134     * individually.
05135     */
05136    if (ast_strlen_zero(sip_cfg.regcontext))
05137       return;
05138 
05139    ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
05140    stringp = multi;
05141    while ((ext = strsep(&stringp, "&"))) {
05142       if ((context = strchr(ext, '@'))) {
05143          *context++ = '\0';   /* split ext@context */
05144          if (!ast_context_find(context)) {
05145             ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
05146             continue;
05147          }
05148       } else {
05149          context = sip_cfg.regcontext;
05150       }
05151       if (onoff) {
05152          if (!ast_exists_extension(NULL, context, ext, 1, NULL)) {
05153             ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
05154                 ast_strdup(peer->name), ast_free_ptr, "SIP");
05155          }
05156       } else if (pbx_find_extension(NULL, NULL, &q, context, ext, 1, NULL, "", E_MATCH)) {
05157          ast_context_remove_extension(context, ext, 1, NULL);
05158       }
05159    }
05160 }
05161 
05162 /*! Destroy mailbox subscriptions */
05163 static void destroy_mailbox(struct sip_mailbox *mailbox)
05164 {
05165    if (mailbox->event_sub)
05166       ast_event_unsubscribe(mailbox->event_sub);
05167    ast_free(mailbox);
05168 }
05169 
05170 /*! Destroy all peer-related mailbox subscriptions */
05171 static void clear_peer_mailboxes(struct sip_peer *peer)
05172 {
05173    struct sip_mailbox *mailbox;
05174 
05175    while ((mailbox = AST_LIST_REMOVE_HEAD(&peer->mailboxes, entry)))
05176       destroy_mailbox(mailbox);
05177 }
05178 
05179 static void sip_destroy_peer_fn(void *peer)
05180 {
05181    sip_destroy_peer(peer);
05182 }
05183 
05184 /*! \brief Destroy peer object from memory */
05185 static void sip_destroy_peer(struct sip_peer *peer)
05186 {
05187    ast_debug(3, "Destroying SIP peer %s\n", peer->name);
05188 
05189    /*
05190     * Remove any mailbox event subscriptions for this peer before
05191     * we destroy anything.  An event subscription callback may be
05192     * happening right now.
05193     */
05194    clear_peer_mailboxes(peer);
05195 
05196    if (peer->outboundproxy) {
05197       ao2_ref(peer->outboundproxy, -1);
05198       peer->outboundproxy = NULL;
05199    }
05200 
05201    /* Delete it, it needs to disappear */
05202    if (peer->call) {
05203       dialog_unlink_all(peer->call);
05204       peer->call = dialog_unref(peer->call, "peer->call is being unset");
05205    }
05206 
05207    if (peer->mwipvt) {  /* We have an active subscription, delete it */
05208       dialog_unlink_all(peer->mwipvt);
05209       peer->mwipvt = dialog_unref(peer->mwipvt, "unreffing peer->mwipvt");
05210    }
05211 
05212    if (peer->chanvars) {
05213       ast_variables_destroy(peer->chanvars);
05214       peer->chanvars = NULL;
05215    }
05216 
05217    register_peer_exten(peer, FALSE);
05218    ast_free_acl_list(peer->acl);
05219    ast_free_acl_list(peer->directmediaacl);
05220    if (peer->selfdestruct)
05221       ast_atomic_fetchadd_int(&apeerobjs, -1);
05222    else if (!ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->is_realtime) {
05223       ast_atomic_fetchadd_int(&rpeerobjs, -1);
05224       ast_debug(3, "-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
05225    } else
05226       ast_atomic_fetchadd_int(&speerobjs, -1);
05227    if (peer->auth) {
05228       ao2_t_ref(peer->auth, -1, "Removing peer authentication");
05229       peer->auth = NULL;
05230    }
05231 
05232    if (peer->socket.tcptls_session) {
05233       ao2_ref(peer->socket.tcptls_session, -1);
05234       peer->socket.tcptls_session = NULL;
05235    } else if (peer->socket.ws_session) {
05236       ast_websocket_unref(peer->socket.ws_session);
05237       peer->socket.ws_session = NULL;
05238    }
05239 
05240    peer->named_callgroups = ast_unref_namedgroups(peer->named_callgroups);
05241    peer->named_pickupgroups = ast_unref_namedgroups(peer->named_pickupgroups);
05242 
05243    ast_cc_config_params_destroy(peer->cc_params);
05244 
05245    ast_string_field_free_memory(peer);
05246 
05247    peer->caps = ast_format_cap_destroy(peer->caps);
05248 
05249    ast_rtp_dtls_cfg_free(&peer->dtls_cfg);
05250 }
05251 
05252 /*! \brief Update peer data in database (if used) */
05253 static void update_peer(struct sip_peer *p, int expire)
05254 {
05255    int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
05256    if (sip_cfg.peer_rtupdate &&
05257        (p->is_realtime || rtcachefriends)) {
05258       realtime_update_peer(p->name, &p->addr, p->username, p->fullcontact, p->useragent, expire, p->deprecated_username, p->lastms);
05259    }
05260 }
05261 
05262 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *cfg)
05263 {
05264    struct ast_variable *var = NULL;
05265    struct ast_flags flags = {0};
05266    char *cat = NULL;
05267    const char *insecure;
05268    while ((cat = ast_category_browse(cfg, cat))) {
05269       insecure = ast_variable_retrieve(cfg, cat, "insecure");
05270       set_insecure_flags(&flags, insecure, -1);
05271       if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
05272          var = ast_category_root(cfg, cat);
05273          break;
05274       }
05275    }
05276    return var;
05277 }
05278 
05279 static struct ast_variable *get_insecure_variable_from_sippeers(const char *column, const char *value)
05280 {
05281    struct ast_config *peerlist;
05282    struct ast_variable *var = NULL;
05283    if ((peerlist = ast_load_realtime_multientry("sippeers", column, value, "insecure LIKE", "%port%", SENTINEL))) {
05284       if ((var = get_insecure_variable_from_config(peerlist))) {
05285          /* Must clone, because var will get freed along with
05286           * peerlist. */
05287          var = ast_variables_dup(var);
05288       }
05289       ast_config_destroy(peerlist);
05290    }
05291    return var;
05292 }
05293 
05294 /* Yes.. the only column that makes sense to pass is "ipaddr", but for
05295  * consistency's sake, we require the column name to be passed. As extra
05296  * argument, we take a pointer to var. We already got the info, so we better
05297  * return it and save the caller a query. If return value is nonzero, then *var
05298  * is nonzero too (and the other way around). */
05299 static struct ast_variable *get_insecure_variable_from_sipregs(const char *column, const char *value, struct ast_variable **var)
05300 {
05301    struct ast_variable *varregs = NULL;
05302    struct ast_config *regs, *peers;
05303    char *regscat;
05304    const char *regname;
05305 
05306    if (!(regs = ast_load_realtime_multientry("sipregs", column, value, SENTINEL))) {
05307       return NULL;
05308    }
05309 
05310    /* Load *all* peers that are probably insecure=port */
05311    if (!(peers = ast_load_realtime_multientry("sippeers", "insecure LIKE", "%port%", SENTINEL))) {
05312       ast_config_destroy(regs);
05313       return NULL;
05314    }
05315 
05316    /* Loop over the sipregs that match IP address and attempt to find an
05317     * insecure=port match to it in sippeers. */
05318    regscat = NULL;
05319    while ((regscat = ast_category_browse(regs, regscat)) && (regname = ast_variable_retrieve(regs, regscat, "name"))) {
05320       char *peerscat;
05321       const char *peername;
05322 
05323       peerscat = NULL;
05324       while ((peerscat = ast_category_browse(peers, peerscat)) && (peername = ast_variable_retrieve(peers, peerscat, "name"))) {
05325          if (!strcasecmp(regname, peername)) {
05326             /* Ensure that it really is insecure=port and
05327              * not something else. */
05328             const char *insecure = ast_variable_retrieve(peers, peerscat, "insecure");
05329             struct ast_flags flags = {0};
05330             set_insecure_flags(&flags, insecure, -1);
05331             if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
05332                /* ENOMEM checks till the bitter end. */
05333                if ((varregs = ast_variables_dup(ast_category_root(regs, regscat)))) {
05334                   if (!(*var = ast_variables_dup(ast_category_root(peers, peerscat)))) {
05335                      ast_variables_destroy(varregs);
05336                      varregs = NULL;
05337                   }
05338                }
05339                goto done;
05340             }
05341          }
05342       }
05343    }
05344 
05345 done:
05346    ast_config_destroy(regs);
05347    ast_config_destroy(peers);
05348    return varregs;
05349 }
05350 
05351 static const char *get_name_from_variable(const struct ast_variable *var)
05352 {
05353    /* Don't expect this to return non-NULL. Both NULL and empty
05354     * values can cause the option to get removed from the variable
05355     * list. This is called on ast_variables gotten from both
05356     * ast_load_realtime and ast_load_realtime_multientry.
05357     * - ast_load_realtime removes options with empty values
05358     * - ast_load_realtime_multientry does not!
05359     * For consistent behaviour, we check for the empty name and
05360     * return NULL instead. */
05361    const struct ast_variable *tmp;
05362    for (tmp = var; tmp; tmp = tmp->next) {
05363       if (!strcasecmp(tmp->name, "name")) {
05364          if (!ast_strlen_zero(tmp->value)) {
05365             return tmp->value;
05366          }
05367          break;
05368       }
05369    }
05370    return NULL;
05371 }
05372 
05373 /* If varregs is NULL, we don't use sipregs.
05374  * Using empty if-bodies instead of goto's while avoiding unnecessary indents */
05375 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)
05376 {
05377    /* Peer by name and host=dynamic */
05378    if ((*var = ast_load_realtime("sippeers", "name", *name, "host", "dynamic", SENTINEL))) {
05379       ;
05380    /* Peer by name and host=IP */
05381    } else if (addr && !(*var = ast_load_realtime("sippeers", "name", *name, "host", ipaddr, SENTINEL))) {
05382       ;
05383    /* Peer by name and host=HOSTNAME */
05384    } else if ((*var = ast_load_realtime("sippeers", "name", *name, SENTINEL))) {
05385       /*!\note
05386        * If this one loaded something, then we need to ensure that the host
05387        * field matched.  The only reason why we can't have this as a criteria
05388        * is because we only have the IP address and the host field might be
05389        * set as a name (and the reverse PTR might not match).
05390        */
05391       if (addr) {
05392          struct ast_variable *tmp;
05393          for (tmp = *var; tmp; tmp = tmp->next) {
05394             if (!strcasecmp(tmp->name, "host")) {
05395                struct ast_sockaddr *addrs = NULL;
05396 
05397                if (ast_sockaddr_resolve(&addrs,
05398                          tmp->value,
05399                          PARSE_PORT_FORBID,
05400                          get_address_family_filter(SIP_TRANSPORT_UDP)) <= 0 ||
05401                          ast_sockaddr_cmp(&addrs[0], addr)) {
05402                   /* No match */
05403                   ast_variables_destroy(*var);
05404                   *var = NULL;
05405                }
05406                ast_free(addrs);
05407                break;
05408             }
05409          }
05410       }
05411    }
05412 
05413    /* Did we find anything? */
05414    if (*var) {
05415       if (varregs) {
05416          *varregs = ast_load_realtime("sipregs", "name", *name, SENTINEL);
05417       }
05418       return 1;
05419    }
05420    return 0;
05421 }
05422 
05423 /* Another little helper function for backwards compatibility: this
05424  * checks/fetches the sippeer that belongs to the sipreg. If none is
05425  * found, we free the sipreg and return false. This way we can do the
05426  * check inside the if-condition below. In the old code, not finding
05427  * the sippeer also had it continue look for another match, so we do
05428  * the same. */
05429 static struct ast_variable *realtime_peer_get_sippeer_helper(const char **name, struct ast_variable **varregs) {
05430    struct ast_variable *var = NULL;
05431    const char *old_name = *name;
05432    *name = get_name_from_variable(*varregs);
05433    if (!*name || !(var = ast_load_realtime("sippeers", "name", *name, SENTINEL))) {
05434       if (!*name) {
05435          ast_log(LOG_WARNING, "Found sipreg but it has no name\n");
05436       }
05437       ast_variables_destroy(*varregs);
05438       *varregs = NULL;
05439       *name = old_name;
05440    }
05441    return var;
05442 }
05443 
05444 /* If varregs is NULL, we don't use sipregs. If we return true, then *name is
05445  * set. Using empty if-bodies instead of goto's while avoiding unnecessary
05446  * indents. */
05447 static int realtime_peer_by_addr(const char **name, struct ast_sockaddr *addr, const char *ipaddr, const char *callbackexten, struct ast_variable **var, struct ast_variable **varregs)
05448 {
05449    char portstring[6]; /* up to 5 digits plus null terminator */
05450    ast_copy_string(portstring, ast_sockaddr_stringify_port(addr), sizeof(portstring));
05451 
05452    /* We're not finding this peer by this name anymore. Reset it. */
05453    *name = NULL;
05454 
05455    /* First check for fixed IP hosts with matching callbackextensions, if specified */
05456    if (!ast_strlen_zero(callbackexten) && (*var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, "callbackextension", callbackexten, SENTINEL))) {
05457       ;
05458    /* Check for fixed IP hosts */
05459    } else if ((*var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, SENTINEL))) {
05460       ;
05461    /* Check for registered hosts (in sipregs) */
05462    } else if (varregs && (*varregs = ast_load_realtime("sipregs", "ipaddr", ipaddr, "port", portstring, SENTINEL)) &&
05463          (*var = realtime_peer_get_sippeer_helper(name, varregs))) {
05464       ;
05465    /* Check for registered hosts (in sippeers) */
05466    } else if (!varregs && (*var = ast_load_realtime("sippeers", "ipaddr", ipaddr, "port", portstring, SENTINEL))) {
05467       ;
05468    /* We couldn't match on ipaddress and port, so we need to check if port is insecure */
05469    } else if ((*var = get_insecure_variable_from_sippeers("host", ipaddr))) {
05470       ;
05471    /* Same as above, but try the IP address field (in sipregs)
05472     * Observe that it fetches the name/var at the same time, without the
05473     * realtime_peer_get_sippeer_helper. Also note that it is quite inefficient.
05474     * Avoid sipregs if possible. */
05475    } else if (varregs && (*varregs = get_insecure_variable_from_sipregs("ipaddr", ipaddr, var))) {
05476       ;
05477    /* Same as above, but try the IP address field (in sippeers) */
05478    } else if (!varregs && (*var = get_insecure_variable_from_sippeers("ipaddr", ipaddr))) {
05479       ;
05480    }
05481 
05482    /* Nothing found? */
05483    if (!*var) {
05484       return 0;
05485    }
05486 
05487    /* Check peer name. It must not be empty. There may exist a
05488     * different match that does have a name, but it's too late for
05489     * that now. */
05490    if (!*name && !(*name = get_name_from_variable(*var))) {
05491       ast_log(LOG_WARNING, "Found peer for IP %s but it has no name\n", ipaddr);
05492       ast_variables_destroy(*var);
05493       *var = NULL;
05494       if (varregs && *varregs) {
05495          ast_variables_destroy(*varregs);
05496          *varregs = NULL;
05497       }
05498       return 0;
05499    }
05500 
05501    /* Make sure varregs is populated if var is. The inverse,
05502     * ensuring that var is set when varregs is, is taken
05503     * care of by realtime_peer_get_sippeer_helper(). */
05504    if (varregs && !*varregs) {
05505       *varregs = ast_load_realtime("sipregs", "name", *name, SENTINEL);
05506    }
05507    return 1;
05508 }
05509 
05510 static int register_realtime_peers_with_callbackextens(void)
05511 {
05512    struct ast_config *cfg;
05513    char *cat = NULL;
05514 
05515    if (!(ast_check_realtime("sippeers"))) {
05516       return 0;
05517    }
05518 
05519    /* This is hacky. We want name to be the cat, so it is the first property */
05520    if (!(cfg = ast_load_realtime_multientry("sippeers", "name LIKE", "%", "callbackextension LIKE", "%", SENTINEL))) {
05521       return -1;
05522    }
05523 
05524    while ((cat = ast_category_browse(cfg, cat))) {
05525       struct sip_peer *peer;
05526       struct ast_variable *var = ast_category_root(cfg, cat);
05527 
05528       if (!(peer = build_peer(cat, var, NULL, TRUE, FALSE))) {
05529          continue;
05530       }
05531       ast_log(LOG_NOTICE, "Created realtime peer '%s' for registration\n", peer->name);
05532 
05533       peer->is_realtime = 1;
05534       sip_unref_peer(peer, "register_realtime_peers: Done registering releasing");
05535    }
05536 
05537    ast_config_destroy(cfg);
05538 
05539    return 0;
05540 }
05541 
05542 /*! \brief  realtime_peer: Get peer from realtime storage
05543  * Checks the "sippeers" realtime family from extconfig.conf
05544  * Checks the "sipregs" realtime family from extconfig.conf if it's configured.
05545  * This returns a pointer to a peer and because we use build_peer, we can rest
05546  * assured that the refcount is bumped.
05547  * 
05548  * \note This is never called with both newpeername and addr at the same time.
05549  * If you do, be prepared to get a peer with a different name than newpeername.
05550  */
05551 static struct sip_peer *realtime_peer(const char *newpeername, struct ast_sockaddr *addr, char *callbackexten, int devstate_only, int which_objects)
05552 {
05553    struct sip_peer *peer = NULL;
05554    struct ast_variable *var = NULL;
05555    struct ast_variable *varregs = NULL;
05556    char ipaddr[INET6_ADDRSTRLEN];
05557    int realtimeregs = ast_check_realtime("sipregs");
05558 
05559    if (addr) {
05560       ast_copy_string(ipaddr, ast_sockaddr_stringify_addr(addr), sizeof(ipaddr));
05561    } else {
05562       ipaddr[0] = '\0';
05563    }
05564 
05565    if (newpeername && realtime_peer_by_name(&newpeername, addr, ipaddr, &var, realtimeregs ? &varregs : NULL)) {
05566       ;
05567    } else if (addr && realtime_peer_by_addr(&newpeername, addr, ipaddr, callbackexten, &var, realtimeregs ? &varregs : NULL)) {
05568       ;
05569    } else {
05570       return NULL;
05571    }
05572 
05573    /* If we're looking for users, don't return peers (although this check
05574     * should probably be done in realtime_peer_by_* instead...) */
05575    if (which_objects == FINDUSERS) {
05576       struct ast_variable *tmp;
05577       for (tmp = var; tmp; tmp = tmp->next) {
05578          if (!strcasecmp(tmp->name, "type") && (!strcasecmp(tmp->value, "peer"))) {
05579             goto cleanup;
05580          }
05581       }
05582    }
05583 
05584    /* Peer found in realtime, now build it in memory */
05585    peer = build_peer(newpeername, var, varregs, TRUE, devstate_only);
05586    if (!peer) {
05587       goto cleanup;
05588    }
05589 
05590    /* Previous versions of Asterisk did not require the type field to be
05591     * set for real time peers.  This statement preserves that behavior. */
05592    if  (peer->type == 0) {
05593       if (which_objects == FINDUSERS) {
05594          peer->type = SIP_TYPE_USER;
05595       } else if (which_objects == FINDPEERS) {
05596          peer->type = SIP_TYPE_PEER;
05597       } else {
05598          peer->type = SIP_TYPE_PEER | SIP_TYPE_USER;
05599       }
05600    }
05601 
05602    ast_debug(3, "-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);
05603 
05604    if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && !devstate_only) {
05605       /* Cache peer */
05606       ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
05607       if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
05608          AST_SCHED_REPLACE_UNREF(peer->expire, sched, sip_cfg.rtautoclear * 1000, expire_register, peer,
05609                sip_unref_peer(_data, "remove registration ref"),
05610                sip_unref_peer(peer, "remove registration ref"),
05611                sip_ref_peer(peer, "add registration ref"));
05612       }
05613       ao2_t_link(peers, peer, "link peer into peers table");
05614       if (!ast_sockaddr_isnull(&peer->addr)) {
05615          ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
05616       }
05617    }
05618    peer->is_realtime = 1;
05619 
05620 cleanup:
05621    ast_variables_destroy(var);
05622    ast_variables_destroy(varregs);
05623    return peer;
05624 }
05625 
05626 /* Function to assist finding peers by name only */
05627 static int find_by_name(void *obj, void *arg, void *data, int flags)
05628 {
05629    struct sip_peer *search = obj, *match = arg;
05630    int *which_objects = data;
05631 
05632    /* Usernames in SIP uri's are case sensitive. Domains are not */
05633    if (strcmp(search->name, match->name)) {
05634       return 0;
05635    }
05636 
05637    switch (*which_objects) {
05638    case FINDUSERS:
05639       if (!(search->type & SIP_TYPE_USER)) {
05640          return 0;
05641       }
05642       break;
05643    case FINDPEERS:
05644       if (!(search->type & SIP_TYPE_PEER)) {
05645          return 0;
05646       }
05647       break;
05648    case FINDALLDEVICES:
05649       break;
05650    }
05651 
05652    return CMP_MATCH | CMP_STOP;
05653 }
05654 
05655 static struct sip_peer *sip_find_peer_full(const char *peer, struct ast_sockaddr *addr, char *callbackexten, int realtime, int which_objects, int devstate_only, int transport)
05656 {
05657    struct sip_peer *p = NULL;
05658    struct sip_peer tmp_peer;
05659 
05660    if (peer) {
05661       ast_copy_string(tmp_peer.name, peer, sizeof(tmp_peer.name));
05662       p = ao2_t_callback_data(peers, OBJ_POINTER, find_by_name, &tmp_peer, &which_objects, "ao2_find in peers table");
05663    } else if (addr) { /* search by addr? */
05664       ast_sockaddr_copy(&tmp_peer.addr, addr);
05665       tmp_peer.flags[0].flags = 0;
05666       tmp_peer.transports = transport;
05667       p = ao2_t_callback_data(peers_by_ip, OBJ_POINTER, peer_ipcmp_cb_full, &tmp_peer, callbackexten, "ao2_find in peers_by_ip table");
05668       if (!p) {
05669          ast_set_flag(&tmp_peer.flags[0], SIP_INSECURE_PORT);
05670          p = ao2_t_callback_data(peers_by_ip, OBJ_POINTER, peer_ipcmp_cb_full, &tmp_peer, callbackexten, "ao2_find in peers_by_ip table 2");
05671          if (p) {
05672             return p;
05673          }
05674       }
05675    }
05676 
05677    if (!p && (realtime || devstate_only)) {
05678       /* realtime_peer will return a peer with matching callbackexten if possible, otherwise one matching
05679        * without the callbackexten */
05680       p = realtime_peer(peer, addr, callbackexten, devstate_only, which_objects);
05681       if (p) {
05682          switch (which_objects) {
05683          case FINDUSERS:
05684             if (!(p->type & SIP_TYPE_USER)) {
05685                sip_unref_peer(p, "Wrong type of realtime SIP endpoint");
05686                return NULL;
05687             }
05688             break;
05689          case FINDPEERS:
05690             if (!(p->type & SIP_TYPE_PEER)) {
05691                sip_unref_peer(p, "Wrong type of realtime SIP endpoint");
05692                return NULL;
05693             }
05694             break;
05695          case FINDALLDEVICES:
05696             break;
05697          }
05698       }
05699    }
05700 
05701    return p;
05702 }
05703 
05704 /*!
05705  * \brief Locate device by name or ip address
05706  * \param peer, sin, realtime, devstate_only, transport
05707  * \param which_objects Define which objects should be matched when doing a lookup
05708  *        by name.  Valid options are FINDUSERS, FINDPEERS, or FINDALLDEVICES.
05709  *        Note that this option is not used at all when doing a lookup by IP.
05710  *
05711  * This is used on find matching device on name or ip/port.
05712  * If the device was declared as type=peer, we don't match on peer name on incoming INVITEs.
05713  *
05714  * \note Avoid using this function in new functions if there is a way to avoid it,
05715  * since it might cause a database lookup.
05716  */
05717 struct sip_peer *sip_find_peer(const char *peer, struct ast_sockaddr *addr, int realtime, int which_objects, int devstate_only, int transport)
05718 {
05719    return sip_find_peer_full(peer, addr, NULL, realtime, which_objects, devstate_only, transport);
05720 }
05721 
05722 static struct sip_peer *sip_find_peer_by_ip_and_exten(struct ast_sockaddr *addr, char *callbackexten, int transport)
05723 {
05724    return sip_find_peer_full(NULL, addr, callbackexten, TRUE, FINDPEERS, FALSE, transport);
05725 }
05726 
05727 /*! \brief Set nat mode on the various data sockets */
05728 static void do_setnat(struct sip_pvt *p)
05729 {
05730    const char *mode;
05731    int natflags;
05732 
05733    natflags = ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
05734    mode = natflags ? "On" : "Off";
05735 
05736    if (p->rtp) {
05737       ast_debug(1, "Setting NAT on RTP to %s\n", mode);
05738       ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_NAT, natflags);
05739    }
05740    if (p->vrtp) {
05741       ast_debug(1, "Setting NAT on VRTP to %s\n", mode);
05742       ast_rtp_instance_set_prop(p->vrtp, AST_RTP_PROPERTY_NAT, natflags);
05743    }
05744    if (p->udptl) {
05745       ast_debug(1, "Setting NAT on UDPTL to %s\n", mode);
05746       ast_udptl_setnat(p->udptl, natflags);
05747    }
05748    if (p->trtp) {
05749       ast_debug(1, "Setting NAT on TRTP to %s\n", mode);
05750       ast_rtp_instance_set_prop(p->trtp, AST_RTP_PROPERTY_NAT, natflags);
05751    }
05752 }
05753 
05754 /*! \brief Change the T38 state on a SIP dialog */
05755 static void change_t38_state(struct sip_pvt *p, int state)
05756 {
05757    int old = p->t38.state;
05758    struct ast_channel *chan = p->owner;
05759    struct ast_control_t38_parameters parameters = { .request_response = 0 };
05760 
05761    /* Don't bother changing if we are already in the state wanted */
05762    if (old == state)
05763       return;
05764 
05765    p->t38.state = state;
05766    ast_debug(2, "T38 state changed to %u on channel %s\n", p->t38.state, chan ? ast_channel_name(chan) : "<none>");
05767 
05768    /* If no channel was provided we can't send off a control frame */
05769    if (!chan)
05770       return;
05771 
05772    /* Given the state requested and old state determine what control frame we want to queue up */
05773    switch (state) {
05774    case T38_PEER_REINVITE:
05775       parameters = p->t38.their_parms;
05776       parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05777       parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
05778       ast_udptl_set_tag(p->udptl, "%s", ast_channel_name(chan));
05779       break;
05780    case T38_ENABLED:
05781       parameters = p->t38.their_parms;
05782       parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05783       parameters.request_response = AST_T38_NEGOTIATED;
05784       ast_udptl_set_tag(p->udptl, "%s", ast_channel_name(chan));
05785       break;
05786    case T38_REJECTED:
05787    case T38_DISABLED:
05788       if (old == T38_ENABLED) {
05789          parameters.request_response = AST_T38_TERMINATED;
05790       } else if (old == T38_LOCAL_REINVITE) {
05791          parameters.request_response = AST_T38_REFUSED;
05792       }
05793       break;
05794    case T38_LOCAL_REINVITE:
05795       /* wait until we get a peer response before responding to local reinvite */
05796       break;
05797    }
05798 
05799    /* Woot we got a message, create a control frame and send it on! */
05800    if (parameters.request_response)
05801       ast_queue_control_data(chan, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));
05802 }
05803 
05804 /*! \brief Set the global T38 capabilities on a SIP dialog structure */
05805 static void set_t38_capabilities(struct sip_pvt *p)
05806 {
05807    if (p->udptl) {
05808       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY) {
05809                         ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
05810       } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_FEC) {
05811          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
05812       } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL) {
05813          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
05814       }
05815    }
05816 }
05817 
05818 static void copy_socket_data(struct sip_socket *to_sock, const struct sip_socket *from_sock)
05819 {
05820    if (to_sock->tcptls_session) {
05821       ao2_ref(to_sock->tcptls_session, -1);
05822       to_sock->tcptls_session = NULL;
05823    } else if (to_sock->ws_session) {
05824       ast_websocket_unref(to_sock->ws_session);
05825       to_sock->ws_session = NULL;
05826    }
05827 
05828    if (from_sock->tcptls_session) {
05829       ao2_ref(from_sock->tcptls_session, +1);
05830    } else if (from_sock->ws_session) {
05831       ast_websocket_ref(from_sock->ws_session);
05832    }
05833 
05834    *to_sock = *from_sock;
05835 }
05836 
05837 /*! \brief Initialize DTLS-SRTP support on an RTP instance */
05838 static int dialog_initialize_dtls_srtp(const struct sip_pvt *dialog, struct ast_rtp_instance *rtp, struct sip_srtp **srtp)
05839 {
05840    struct ast_rtp_engine_dtls *dtls;
05841 
05842    if (!dialog->dtls_cfg.enabled) {
05843       return 0;
05844    }
05845 
05846    if (!ast_rtp_engine_srtp_is_registered()) {
05847       ast_log(LOG_ERROR, "No SRTP module loaded, can't setup SRTP session.\n");
05848       return -1;
05849    }
05850 
05851    if (!(dtls = ast_rtp_instance_get_dtls(rtp))) {
05852       ast_log(LOG_ERROR, "No DTLS-SRTP support present on engine for RTP instance '%p', was it compiled with support for it?\n",
05853          rtp);
05854       return -1;
05855    }
05856 
05857    if (dtls->set_configuration(rtp, &dialog->dtls_cfg)) {
05858       ast_log(LOG_ERROR, "Attempted to set an invalid DTLS-SRTP configuration on RTP instance '%p'\n",
05859          rtp);
05860       return -1;
05861    }
05862 
05863    if (!(*srtp = sip_srtp_alloc())) {
05864       ast_log(LOG_ERROR, "Failed to create required SRTP structure on RTP instance '%p'\n",
05865          rtp);
05866       return -1;
05867    }
05868 
05869    return 0;
05870 }
05871 
05872 /*! \brief Initialize RTP portion of a dialog
05873  * \return -1 on failure, 0 on success
05874  */
05875 static int dialog_initialize_rtp(struct sip_pvt *dialog)
05876 {
05877    struct ast_sockaddr bindaddr_tmp;
05878    struct ast_rtp_engine_ice *ice;
05879 
05880    if (!sip_methods[dialog->method].need_rtp) {
05881       return 0;
05882    }
05883 
05884    ast_sockaddr_copy(&bindaddr_tmp, &bindaddr);
05885    if (!(dialog->rtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
05886       return -1;
05887    }
05888 
05889    if (!ast_test_flag(&dialog->flags[2], SIP_PAGE3_ICE_SUPPORT) && (ice = ast_rtp_instance_get_ice(dialog->rtp))) {
05890       ice->stop(dialog->rtp);
05891    }
05892 
05893    if (dialog_initialize_dtls_srtp(dialog, dialog->rtp, &dialog->srtp)) {
05894       return -1;
05895    }
05896 
05897    if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) ||
05898          (ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) && (ast_format_cap_has_type(dialog->caps, AST_FORMAT_TYPE_VIDEO)))) {
05899       if (!(dialog->vrtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
05900          return -1;
05901       }
05902 
05903       if (!ast_test_flag(&dialog->flags[2], SIP_PAGE3_ICE_SUPPORT) && (ice = ast_rtp_instance_get_ice(dialog->vrtp))) {
05904          ice->stop(dialog->vrtp);
05905       }
05906 
05907       if (dialog_initialize_dtls_srtp(dialog, dialog->vrtp, &dialog->vsrtp)) {
05908          return -1;
05909       }
05910 
05911       ast_rtp_instance_set_timeout(dialog->vrtp, dialog->rtptimeout);
05912       ast_rtp_instance_set_hold_timeout(dialog->vrtp, dialog->rtpholdtimeout);
05913       ast_rtp_instance_set_keepalive(dialog->vrtp, dialog->rtpkeepalive);
05914 
05915       ast_rtp_instance_set_prop(dialog->vrtp, AST_RTP_PROPERTY_RTCP, 1);
05916       ast_rtp_instance_set_qos(dialog->vrtp, global_tos_video, global_cos_video, "SIP VIDEO");
05917    }
05918 
05919    if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT)) {
05920       if (!(dialog->trtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
05921          return -1;
05922       }
05923 
05924       if (!ast_test_flag(&dialog->flags[2], SIP_PAGE3_ICE_SUPPORT) && (ice = ast_rtp_instance_get_ice(dialog->trtp))) {
05925          ice->stop(dialog->trtp);
05926       }
05927 
05928       if (dialog_initialize_dtls_srtp(dialog, dialog->trtp, &dialog->tsrtp)) {
05929          return -1;
05930       }
05931 
05932       /* Do not timeout text as its not constant*/
05933       ast_rtp_instance_set_keepalive(dialog->trtp, dialog->rtpkeepalive);
05934 
05935       ast_rtp_instance_set_prop(dialog->trtp, AST_RTP_PROPERTY_RTCP, 1);
05936    }
05937 
05938    ast_rtp_instance_set_timeout(dialog->rtp, dialog->rtptimeout);
05939    ast_rtp_instance_set_hold_timeout(dialog->rtp, dialog->rtpholdtimeout);
05940    ast_rtp_instance_set_keepalive(dialog->rtp, dialog->rtpkeepalive);
05941 
05942    ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_RTCP, 1);
05943    ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
05944    ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
05945 
05946    ast_rtp_instance_set_qos(dialog->rtp, global_tos_audio, global_cos_audio, "SIP RTP");
05947 
05948    do_setnat(dialog);
05949 
05950    return 0;
05951 }
05952 
05953 /*! \brief Create address structure from peer reference.
05954  * This function copies data from peer to the dialog, so we don't have to look up the peer
05955  * again from memory or database during the life time of the dialog.
05956  *
05957  * \return -1 on error, 0 on success.
05958  *
05959  */
05960 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
05961 {
05962    struct sip_auth_container *credentials;
05963 
05964    /* this checks that the dialog is contacting the peer on a valid
05965     * transport type based on the peers transport configuration,
05966     * otherwise, this function bails out */
05967    if (dialog->socket.type && check_request_transport(peer, dialog))
05968       return -1;
05969    copy_socket_data(&dialog->socket, &peer->socket);
05970 
05971    if (!(ast_sockaddr_isnull(&peer->addr) && ast_sockaddr_isnull(&peer->defaddr)) &&
05972        (!peer->maxms || ((peer->lastms >= 0)  && (peer->lastms <= peer->maxms)))) {
05973       dialog->sa = ast_sockaddr_isnull(&peer->addr) ? peer->defaddr : peer->addr;
05974       dialog->recv = dialog->sa;
05975    } else
05976       return -1;
05977 
05978    /* XXX TODO: get flags directly from peer only as they are needed using dialog->relatedpeer */
05979    ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
05980    ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
05981    ast_copy_flags(&dialog->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
05982    ast_format_cap_copy(dialog->caps, peer->caps);
05983    dialog->prefs = peer->prefs;
05984    dialog->amaflags = peer->amaflags;
05985 
05986    ast_string_field_set(dialog, engine, peer->engine);
05987 
05988    ast_rtp_dtls_cfg_copy(&peer->dtls_cfg, &dialog->dtls_cfg);
05989 
05990    dialog->rtptimeout = peer->rtptimeout;
05991    dialog->rtpholdtimeout = peer->rtpholdtimeout;
05992    dialog->rtpkeepalive = peer->rtpkeepalive;
05993    if (dialog_initialize_rtp(dialog)) {
05994       return -1;
05995    }
05996 
05997    if (dialog->rtp) { /* Audio */
05998       ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
05999       ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
06000       /* Set Frame packetization */
06001       ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(dialog->rtp), dialog->rtp, &dialog->prefs);
06002       dialog->autoframing = peer->autoframing;
06003    }
06004 
06005    /* XXX TODO: get fields directly from peer only as they are needed using dialog->relatedpeer */
06006    ast_string_field_set(dialog, peername, peer->name);
06007    ast_string_field_set(dialog, authname, peer->username);
06008    ast_string_field_set(dialog, username, peer->username);
06009    ast_string_field_set(dialog, peersecret, peer->secret);
06010    ast_string_field_set(dialog, peermd5secret, peer->md5secret);
06011    ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
06012    ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
06013    ast_string_field_set(dialog, tohost, peer->tohost);
06014    ast_string_field_set(dialog, fullcontact, peer->fullcontact);
06015    ast_string_field_set(dialog, accountcode, peer->accountcode);
06016    ast_string_field_set(dialog, context, peer->context);
06017    ast_string_field_set(dialog, cid_num, peer->cid_num);
06018    ast_string_field_set(dialog, cid_name, peer->cid_name);
06019    ast_string_field_set(dialog, cid_tag, peer->cid_tag);
06020    ast_string_field_set(dialog, mwi_from, peer->mwi_from);
06021    if (!ast_strlen_zero(peer->parkinglot)) {
06022       ast_string_field_set(dialog, parkinglot, peer->parkinglot);
06023    }
06024    ast_string_field_set(dialog, engine, peer->engine);
06025    ref_proxy(dialog, obproxy_get(dialog, peer));
06026    dialog->callgroup = peer->callgroup;
06027    dialog->pickupgroup = peer->pickupgroup;
06028    ast_unref_namedgroups(dialog->named_callgroups);
06029    dialog->named_callgroups = ast_ref_namedgroups(peer->named_callgroups);
06030    ast_unref_namedgroups(dialog->named_pickupgroups);
06031    dialog->named_pickupgroups = ast_ref_namedgroups(peer->named_pickupgroups);
06032    ast_copy_string(dialog->zone, peer->zone, sizeof(dialog->zone));
06033    dialog->allowtransfer = peer->allowtransfer;
06034    dialog->jointnoncodeccapability = dialog->noncodeccapability;
06035 
06036    /* Update dialog authorization credentials */
06037    ao2_lock(peer);
06038    credentials = peer->auth;
06039    if (credentials) {
06040       ao2_t_ref(credentials, +1, "Ref peer auth for dialog");
06041    }
06042    ao2_unlock(peer);
06043    ao2_lock(dialog);
06044    if (dialog->peerauth) {
06045       ao2_t_ref(dialog->peerauth, -1, "Unref old dialog peer auth");
06046    }
06047    dialog->peerauth = credentials;
06048    ao2_unlock(dialog);
06049 
06050    dialog->maxcallbitrate = peer->maxcallbitrate;
06051    dialog->disallowed_methods = peer->disallowed_methods;
06052    ast_cc_copy_config_params(dialog->cc_params, peer->cc_params);
06053    if (ast_strlen_zero(dialog->tohost))
06054       ast_string_field_set(dialog, tohost, ast_sockaddr_stringify_host_remote(&dialog->sa));
06055    if (!ast_strlen_zero(peer->fromdomain)) {
06056       ast_string_field_set(dialog, fromdomain, peer->fromdomain);
06057       if (!dialog->initreq.headers) {
06058          char *new_callid;
06059          char *tmpcall = ast_strdupa(dialog->callid);
06060          /* this sure looks to me like we are going to change the callid on this dialog!! */
06061          new_callid = strchr(tmpcall, '@');
06062          if (new_callid) {
06063             int callid_size;
06064 
06065             *new_callid = '\0';
06066 
06067             /* Change the dialog callid. */
06068             callid_size = strlen(tmpcall) + strlen(peer->fromdomain) + 2;
06069             new_callid = ast_alloca(callid_size);
06070             snprintf(new_callid, callid_size, "%s@%s", tmpcall, peer->fromdomain);
06071             change_callid_pvt(dialog, new_callid);
06072          }
06073       }
06074    }
06075    if (!ast_strlen_zero(peer->fromuser))
06076       ast_string_field_set(dialog, fromuser, peer->fromuser);
06077    if (!ast_strlen_zero(peer->language))
06078       ast_string_field_set(dialog, language, peer->language);
06079    /* Set timer T1 to RTT for this peer (if known by qualify=) */
06080    /* Minimum is settable or default to 100 ms */
06081    /* If there is a maxms and lastms from a qualify use that over a manual T1
06082       value. Otherwise, use the peer's T1 value. */
06083    if (peer->maxms && peer->lastms)
06084       dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
06085    else
06086       dialog->timer_t1 = peer->timer_t1;
06087 
06088    /* Set timer B to control transaction timeouts, the peer setting is the default and overrides
06089       the known timer */
06090    if (peer->timer_b)
06091       dialog->timer_b = peer->timer_b;
06092    else
06093       dialog->timer_b = 64 * dialog->timer_t1;
06094 
06095    if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
06096        (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
06097       dialog->noncodeccapability |= AST_RTP_DTMF;
06098    else
06099       dialog->noncodeccapability &= ~AST_RTP_DTMF;
06100 
06101    dialog->directmediaacl = ast_duplicate_acl_list(peer->directmediaacl);
06102 
06103    if (peer->call_limit)
06104       ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
06105    if (!dialog->portinuri)
06106       dialog->portinuri = peer->portinuri;
06107    dialog->chanvars = copy_vars(peer->chanvars);
06108    if (peer->fromdomainport)
06109       dialog->fromdomainport = peer->fromdomainport;
06110    dialog->callingpres = peer->callingpres;
06111 
06112    return 0;
06113 }
06114 
06115 /*! \brief The default sip port for the given transport */
06116 static inline int default_sip_port(enum sip_transport type)
06117 {
06118    return type == SIP_TRANSPORT_TLS ? STANDARD_TLS_PORT : STANDARD_SIP_PORT;
06119 }
06120 
06121 /*! \brief create address structure from device name
06122  *      Or, if peer not found, find it in the global DNS
06123  *      returns TRUE (-1) on failure, FALSE on success */
06124 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog)
06125 {
06126    struct sip_peer *peer;
06127    char *peername, *peername2, *hostn;
06128    char host[MAXHOSTNAMELEN];
06129    char service[MAXHOSTNAMELEN];
06130    int srv_ret = 0;
06131    int tportno;
06132 
06133    AST_DECLARE_APP_ARGS(hostport,
06134       AST_APP_ARG(host);
06135       AST_APP_ARG(port);
06136    );
06137 
06138    peername = ast_strdupa(opeer);
06139    peername2 = ast_strdupa(opeer);
06140    AST_NONSTANDARD_RAW_ARGS(hostport, peername2, ':');
06141 
06142    if (hostport.port)
06143       dialog->portinuri = 1;
06144 
06145    dialog->timer_t1 = global_t1; /* Default SIP retransmission timer T1 (RFC 3261) */
06146    dialog->timer_b = global_timer_b; /* Default SIP transaction timer B (RFC 3261) */
06147    peer = sip_find_peer(peername, NULL, TRUE, FINDPEERS, FALSE, 0);
06148 
06149    if (peer) {
06150       int res;
06151       if (newdialog) {
06152          set_socket_transport(&dialog->socket, 0);
06153       }
06154       res = create_addr_from_peer(dialog, peer);
06155       dialog->relatedpeer = sip_ref_peer(peer, "create_addr: setting dialog's relatedpeer pointer");
06156       sip_unref_peer(peer, "create_addr: unref peer from sip_find_peer hashtab lookup");
06157       return res;
06158    } else if (ast_check_digits(peername)) {
06159       /* Although an IPv4 hostname *could* be represented as a 32-bit integer, it is uncommon and
06160        * it makes dialing SIP/${EXTEN} for a peer that isn't defined resolve to an IP that is
06161        * almost certainly not intended. It is much better to just reject purely numeric hostnames */
06162       ast_log(LOG_WARNING, "Purely numeric hostname (%s), and not a peer--rejecting!\n", peername);
06163       return -1;
06164    } else {
06165       dialog->rtptimeout = global_rtptimeout;
06166       dialog->rtpholdtimeout = global_rtpholdtimeout;
06167       dialog->rtpkeepalive = global_rtpkeepalive;
06168       if (dialog_initialize_rtp(dialog)) {
06169          return -1;
06170       }
06171    }
06172 
06173    ast_string_field_set(dialog, tohost, hostport.host);
06174    dialog->allowed_methods &= ~sip_cfg.disallowed_methods;
06175 
06176    /* Get the outbound proxy information */
06177    ref_proxy(dialog, obproxy_get(dialog, NULL));
06178 
06179    if (addr) {
06180       /* This address should be updated using dnsmgr */
06181       ast_sockaddr_copy(&dialog->sa, addr);
06182    } else {
06183 
06184       /* Let's see if we can find the host in DNS. First try DNS SRV records,
06185          then hostname lookup */
06186       /*! \todo Fix this function. When we ask for SRV, we should check all transports
06187            In the future, we should first check NAPTR to find out transport preference
06188        */
06189       hostn = peername;
06190       /* Section 4.2 of RFC 3263 specifies that if a port number is specified, then
06191        * an A record lookup should be used instead of SRV.
06192        */
06193       if (!hostport.port && sip_cfg.srvlookup) {
06194          snprintf(service, sizeof(service), "_%s._%s.%s", 
06195              get_srv_service(dialog->socket.type),
06196              get_srv_protocol(dialog->socket.type), peername);
06197          if ((srv_ret = ast_get_srv(NULL, host, sizeof(host), &tportno,
06198                      service)) > 0) {
06199             hostn = host;
06200          }
06201       }
06202 
06203       if (ast_sockaddr_resolve_first_transport(&dialog->sa, hostn, 0, dialog->socket.type ? dialog->socket.type : SIP_TRANSPORT_UDP)) {
06204          ast_log(LOG_WARNING, "No such host: %s\n", peername);
06205          return -1;
06206       }
06207 
06208       if (srv_ret > 0) {
06209          ast_sockaddr_set_port(&dialog->sa, tportno);
06210       }
06211    }
06212 
06213    if (!dialog->socket.type)
06214       set_socket_transport(&dialog->socket, SIP_TRANSPORT_UDP);
06215    if (!dialog->socket.port) {
06216       dialog->socket.port = htons(ast_sockaddr_port(&bindaddr));
06217    }
06218 
06219    if (!ast_sockaddr_port(&dialog->sa)) {
06220       ast_sockaddr_set_port(&dialog->sa, default_sip_port(dialog->socket.type));
06221    }
06222    ast_sockaddr_copy(&dialog->recv, &dialog->sa);
06223    return 0;
06224 }
06225 
06226 /*! \brief Scheduled congestion on a call.
06227  * Only called by the scheduler, must return the reference when done.
06228  */
06229 static int auto_congest(const void *arg)
06230 {
06231    struct sip_pvt *p = (struct sip_pvt *)arg;
06232 
06233    sip_pvt_lock(p);
06234    p->initid = -1;   /* event gone, will not be rescheduled */
06235    if (p->owner) {
06236       /* XXX fails on possible deadlock */
06237       if (!ast_channel_trylock(p->owner)) {
06238          append_history(p, "Cong", "Auto-congesting (timer)");
06239          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
06240          ast_channel_unlock(p->owner);
06241       }
06242 
06243       /* Give the channel a chance to act before we proceed with destruction */
06244       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06245    }
06246    sip_pvt_unlock(p);
06247    dialog_unref(p, "unreffing arg passed into auto_congest callback (p->initid)");
06248    return 0;
06249 }
06250 
06251 
06252 /*! \brief Initiate SIP call from PBX
06253  *      used from the dial() application      */
06254 static int sip_call(struct ast_channel *ast, const char *dest, int timeout)
06255 {
06256    int res;
06257    struct sip_pvt *p = ast_channel_tech_pvt(ast);  /* chan is locked, so the reference cannot go away */
06258    struct varshead *headp;
06259    struct ast_var_t *current;
06260    const char *referer = NULL;   /* SIP referrer */
06261    int cc_core_id;
06262    char uri[SIPBUFSIZE] = "";
06263 
06264    if ((ast_channel_state(ast) != AST_STATE_DOWN) && (ast_channel_state(ast) != AST_STATE_RESERVED)) {
06265       ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast_channel_name(ast));
06266       return -1;
06267    }
06268 
06269    if (ast_cc_is_recall(ast, &cc_core_id, "SIP")) {
06270       char device_name[AST_CHANNEL_NAME];
06271       struct ast_cc_monitor *recall_monitor;
06272       struct sip_monitor_instance *monitor_instance;
06273       ast_channel_get_device_name(ast, device_name, sizeof(device_name));
06274       if ((recall_monitor = ast_cc_get_monitor_by_recall_core_id(cc_core_id, device_name))) {
06275          monitor_instance = recall_monitor->private_data;
06276          ast_copy_string(uri, monitor_instance->notify_uri, sizeof(uri));
06277          ao2_t_ref(recall_monitor, -1, "Got the URI we need so unreffing monitor");
06278       }
06279    }
06280 
06281    /* Check whether there is vxml_url, distinctive ring variables */
06282    headp=ast_channel_varshead(ast);
06283    AST_LIST_TRAVERSE(headp, current, entries) {
06284       /* Check whether there is a VXML_URL variable */
06285       if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
06286          p->options->vxml_url = ast_var_value(current);
06287       } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
06288          p->options->uri_options = ast_var_value(current);
06289       } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
06290          /* Check whether there is a variable with a name starting with SIPADDHEADER */
06291          p->options->addsipheaders = 1;
06292       } else if (!strcasecmp(ast_var_name(current), "SIPFROMDOMAIN")) {
06293          ast_string_field_set(p, fromdomain, ast_var_value(current));
06294       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
06295          /* This is a transferred call */
06296          p->options->transfer = 1;
06297       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
06298          /* This is the referrer */
06299          referer = ast_var_value(current);
06300       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
06301          /* We're replacing a call. */
06302          p->options->replaces = ast_var_value(current);
06303       } else if (!strcasecmp(ast_var_name(current), "SIP_MAX_FORWARDS")) {
06304          if (sscanf(ast_var_value(current), "%30d", &(p->maxforwards)) != 1) {
06305             ast_log(LOG_WARNING, "The SIP_MAX_FORWARDS channel variable is not a valid integer.\n");
06306          }
06307       }
06308    }
06309 
06310    /* Check to see if we should try to force encryption */
06311    if (p->req_secure_signaling && p->socket.type != SIP_TRANSPORT_TLS) {
06312       ast_log(LOG_WARNING, "Encrypted signaling is required\n");
06313       ast_channel_hangupcause_set(ast, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
06314       return -1;
06315    }
06316 
06317    if (ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP)) {
06318       if (ast_test_flag(&p->flags[0], SIP_REINVITE)) {
06319          ast_debug(1, "Direct media not possible when using SRTP, ignoring canreinvite setting\n");
06320          ast_clear_flag(&p->flags[0], SIP_REINVITE);
06321       }
06322 
06323       if (p->rtp && !p->srtp && setup_srtp(&p->srtp) < 0) {
06324          ast_log(LOG_WARNING, "SRTP audio setup failed\n");
06325          return -1;
06326       }
06327 
06328       if (p->vrtp && !p->vsrtp && setup_srtp(&p->vsrtp) < 0) {
06329          ast_log(LOG_WARNING, "SRTP video setup failed\n");
06330          return -1;
06331       }
06332 
06333       if (p->trtp && !p->tsrtp && setup_srtp(&p->tsrtp) < 0) {
06334          ast_log(LOG_WARNING, "SRTP text setup failed\n");
06335          return -1;
06336       }
06337    }
06338 
06339    res = 0;
06340    ast_set_flag(&p->flags[0], SIP_OUTGOING);
06341 
06342    /* T.38 re-INVITE FAX detection should never be done for outgoing calls,
06343     * so ensure it is disabled.
06344     */
06345    ast_clear_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38);
06346 
06347    if (p->options->transfer) {
06348       char buf[SIPBUFSIZE/2];
06349 
06350       if (referer) {
06351          if (sipdebug)
06352             ast_debug(3, "Call for %s transferred by %s\n", p->username, referer);
06353          snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
06354       } else
06355          snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
06356       ast_string_field_set(p, cid_name, buf);
06357    }
06358    ast_debug(1, "Outgoing Call for %s\n", p->username);
06359 
06360    res = update_call_counter(p, INC_CALL_RINGING);
06361 
06362    if (res == -1) {
06363       ast_channel_hangupcause_set(ast, AST_CAUSE_USER_BUSY);
06364       return res;
06365    }
06366    p->callingpres = ast_party_id_presentation(&ast_channel_caller(ast)->id);
06367    ast_rtp_instance_available_formats(p->rtp, p->caps, p->prefcaps, p->jointcaps);
06368    p->jointnoncodeccapability = p->noncodeccapability;
06369 
06370    /* If there are no audio formats left to offer, punt */
06371    if (!(ast_format_cap_has_type(p->jointcaps, AST_FORMAT_TYPE_AUDIO))) {
06372       ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
06373       res = -1;
06374    } else {
06375       int xmitres;
06376       struct ast_party_connected_line connected;
06377       struct ast_set_party_connected_line update_connected;
06378 
06379       sip_pvt_lock(p);
06380 
06381       /* Supply initial connected line information if available. */
06382       memset(&update_connected, 0, sizeof(update_connected));
06383       ast_party_connected_line_init(&connected);
06384       if (!ast_strlen_zero(p->cid_num)
06385          || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
06386          update_connected.id.number = 1;
06387          connected.id.number.valid = 1;
06388          connected.id.number.str = (char *) p->cid_num;
06389          connected.id.number.presentation = p->callingpres;
06390       }
06391       if (!ast_strlen_zero(p->cid_name)
06392          || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
06393          update_connected.id.name = 1;
06394          connected.id.name.valid = 1;
06395          connected.id.name.str = (char *) p->cid_name;
06396          connected.id.name.presentation = p->callingpres;
06397       }
06398       if (update_connected.id.number || update_connected.id.name) {
06399          /* Invalidate any earlier private connected id representation */
06400          ast_set_party_id_all(&update_connected.priv);
06401 
06402          connected.id.tag = (char *) p->cid_tag;
06403          connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
06404          ast_channel_queue_connected_line_update(ast, &connected, &update_connected);
06405       }
06406 
06407       xmitres = transmit_invite(p, SIP_INVITE, 1, 2, uri);
06408       if (xmitres == XMIT_ERROR) {
06409          sip_pvt_unlock(p);
06410          return -1;
06411       }
06412       p->invitestate = INV_CALLING;
06413 
06414       /* Initialize auto-congest time */
06415       AST_SCHED_REPLACE_UNREF(p->initid, sched, p->timer_b, auto_congest, p,
06416                         dialog_unref(_data, "dialog ptr dec when SCHED_REPLACE del op succeeded"),
06417                         dialog_unref(p, "dialog ptr dec when SCHED_REPLACE add failed"),
06418                         dialog_ref(p, "dialog ptr inc when SCHED_REPLACE add succeeded") );
06419       sip_pvt_unlock(p);
06420    }
06421    return res;
06422 }
06423 
06424 /*! \brief Destroy registry object
06425    Objects created with the register= statement in static configuration */
06426 static void sip_registry_destroy(struct sip_registry *reg)
06427 {
06428    /* Really delete */
06429    ast_debug(3, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
06430 
06431    if (reg->call) {
06432       /* Clear registry before destroying to ensure
06433          we don't get reentered trying to grab the registry lock */
06434       reg->call->registry = registry_unref(reg->call->registry, "destroy reg->call->registry");
06435       ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
06436       dialog_unlink_all(reg->call);
06437       reg->call = dialog_unref(reg->call, "unref reg->call");
06438       /* reg->call = sip_destroy(reg->call); */
06439    }
06440    AST_SCHED_DEL(sched, reg->expire);
06441    AST_SCHED_DEL(sched, reg->timeout);
06442 
06443    ast_string_field_free_memory(reg);
06444    ast_atomic_fetchadd_int(&regobjs, -1);
06445    ast_free(reg);
06446 }
06447 
06448 /*! \brief Destroy MWI subscription object */
06449 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi)
06450 {
06451    if (mwi->call) {
06452       mwi->call->mwi = NULL;
06453       sip_destroy(mwi->call);
06454    }
06455    
06456    AST_SCHED_DEL(sched, mwi->resub);
06457    ast_string_field_free_memory(mwi);
06458    ast_free(mwi);
06459 }
06460 
06461 /*! \brief Destroy SDP media offer list */
06462 static void offered_media_list_destroy(struct sip_pvt *p)
06463 {
06464    struct offered_media *offer;
06465    while ((offer = AST_LIST_REMOVE_HEAD(&p->offered_media, next))) {
06466       ast_free(offer->decline_m_line);
06467       ast_free(offer);
06468    }
06469 }
06470 
06471 /*! \brief Execute destruction of SIP dialog structure, release memory */
06472 void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
06473 {
06474    struct sip_request *req;
06475 
06476    /* Destroy Session-Timers if allocated */
06477    if (p->stimer) {
06478       p->stimer->quit_flag = 1;
06479       stop_session_timer(p);
06480       ast_free(p->stimer);
06481       p->stimer = NULL;
06482    }
06483 
06484    if (sip_debug_test_pvt(p))
06485       ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
06486 
06487    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
06488       update_call_counter(p, DEC_CALL_LIMIT);
06489       ast_debug(2, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
06490    }
06491 
06492    /* Unlink us from the owner if we have one */
06493    if (p->owner) {
06494       if (lockowner)
06495          ast_channel_lock(p->owner);
06496       ast_debug(1, "Detaching from %s\n", ast_channel_name(p->owner));
06497       ast_channel_tech_pvt_set(p->owner, NULL);
06498       /* Make sure that the channel knows its backend is going away */
06499       ast_channel_softhangup_internal_flag_add(p->owner, AST_SOFTHANGUP_DEV);
06500       if (lockowner)
06501          ast_channel_unlock(p->owner);
06502       /* Give the channel a chance to react before deallocation */
06503       usleep(1);
06504    }
06505 
06506    /* Remove link from peer to subscription of MWI */
06507    if (p->relatedpeer && p->relatedpeer->mwipvt == p)
06508       p->relatedpeer->mwipvt = dialog_unref(p->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
06509    if (p->relatedpeer && p->relatedpeer->call == p)
06510       p->relatedpeer->call = dialog_unref(p->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
06511    
06512    if (p->relatedpeer)
06513       p->relatedpeer = sip_unref_peer(p->relatedpeer,"unsetting a dialog relatedpeer field in sip_destroy");
06514    
06515    if (p->registry) {
06516       if (p->registry->call == p)
06517          p->registry->call = dialog_unref(p->registry->call, "nulling out the registry's call dialog field in unlink_all");
06518       p->registry = registry_unref(p->registry, "delete p->registry");
06519    }
06520    
06521    if (p->mwi) {
06522       p->mwi->call = NULL;
06523       p->mwi = NULL;
06524    }
06525 
06526    if (dumphistory)
06527       sip_dump_history(p);
06528 
06529    if (p->options) {
06530       if (p->options->outboundproxy) {
06531          ao2_ref(p->options->outboundproxy, -1);
06532       }
06533       ast_free(p->options);
06534       p->options = NULL;
06535    }
06536 
06537    if (p->notify) {
06538       ast_variables_destroy(p->notify->headers);
06539       ast_free(p->notify->content);
06540       ast_free(p->notify);
06541       p->notify = NULL;
06542    }
06543    if (p->rtp) {
06544       ast_rtp_instance_destroy(p->rtp);
06545       p->rtp = NULL;
06546    }
06547    if (p->vrtp) {
06548       ast_rtp_instance_destroy(p->vrtp);
06549       p->vrtp = NULL;
06550    }
06551    if (p->trtp) {
06552       ast_rtp_instance_destroy(p->trtp);
06553       p->trtp = NULL;
06554    }
06555    if (p->udptl) {
06556       ast_udptl_destroy(p->udptl);
06557       p->udptl = NULL;
06558    }
06559    if (p->refer) {
06560       if (p->refer->refer_call) {
06561          p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
06562       }
06563       ast_string_field_free_memory(p->refer);
06564       ast_free(p->refer);
06565       p->refer = NULL;
06566    }
06567    if (p->route) {
06568       free_old_route(p->route);
06569       p->route = NULL;
06570    }
06571    deinit_req(&p->initreq);
06572 
06573    /* Clear history */
06574    if (p->history) {
06575       struct sip_history *hist;
06576       while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
06577          ast_free(hist);
06578          p->history_entries--;
06579       }
06580       ast_free(p->history);
06581       p->history = NULL;
06582    }
06583 
06584    while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
06585       ast_free(req);
06586    }
06587 
06588    offered_media_list_destroy(p);
06589 
06590    if (p->chanvars) {
06591       ast_variables_destroy(p->chanvars);
06592       p->chanvars = NULL;
06593    }
06594 
06595    destroy_msg_headers(p);
06596 
06597    if (p->srtp) {
06598       sip_srtp_destroy(p->srtp);
06599       p->srtp = NULL;
06600    }
06601 
06602    if (p->vsrtp) {
06603       sip_srtp_destroy(p->vsrtp);
06604       p->vsrtp = NULL;
06605    }
06606 
06607    if (p->tsrtp) {
06608       sip_srtp_destroy(p->tsrtp);
06609       p->tsrtp = NULL;
06610    }
06611 
06612    if (p->directmediaacl) {
06613       p->directmediaacl = ast_free_acl_list(p->directmediaacl);
06614    }
06615 
06616    ast_string_field_free_memory(p);
06617 
06618    ast_cc_config_params_destroy(p->cc_params);
06619    p->cc_params = NULL;
06620 
06621    if (p->epa_entry) {
06622       ao2_ref(p->epa_entry, -1);
06623       p->epa_entry = NULL;
06624    }
06625 
06626    if (p->socket.tcptls_session) {
06627       ao2_ref(p->socket.tcptls_session, -1);
06628       p->socket.tcptls_session = NULL;
06629    } else if (p->socket.ws_session) {
06630       ast_websocket_unref(p->socket.ws_session);
06631       p->socket.ws_session = NULL;
06632    }
06633 
06634    if (p->peerauth) {
06635       ao2_t_ref(p->peerauth, -1, "Removing active peer authentication");
06636       p->peerauth = NULL;
06637    }
06638 
06639    p->named_callgroups = ast_unref_namedgroups(p->named_callgroups);
06640    p->named_pickupgroups = ast_unref_namedgroups(p->named_pickupgroups);
06641 
06642    p->caps = ast_format_cap_destroy(p->caps);
06643    p->jointcaps = ast_format_cap_destroy(p->jointcaps);
06644    p->peercaps = ast_format_cap_destroy(p->peercaps);
06645    p->redircaps = ast_format_cap_destroy(p->redircaps);
06646    p->prefcaps = ast_format_cap_destroy(p->prefcaps);
06647 
06648    ast_rtp_dtls_cfg_free(&p->dtls_cfg);
06649 
06650    if (p->last_device_state_info) {
06651       ao2_ref(p->last_device_state_info, -1);
06652       p->last_device_state_info = NULL;
06653    }
06654 
06655    /* Lastly, kill the callid associated with the pvt */
06656    if (p->logger_callid) {
06657       ast_callid_unref(p->logger_callid);
06658    }
06659 }
06660 
06661 /*! \brief  update_call_counter: Handle call_limit for SIP devices
06662  * Setting a call-limit will cause calls above the limit not to be accepted.
06663  *
06664  * Remember that for a type=friend, there's one limit for the user and
06665  * another for the peer, not a combined call limit.
06666  * This will cause unexpected behaviour in subscriptions, since a "friend"
06667  * is *two* devices in Asterisk, not one.
06668  *
06669  * Thought: For realtime, we should probably update storage with inuse counter...
06670  *
06671  * \return 0 if call is ok (no call limit, below threshold)
06672  * -1 on rejection of call
06673  *
06674  */
06675 static int update_call_counter(struct sip_pvt *fup, int event)
06676 {
06677    char name[256];
06678    int *inuse = NULL, *call_limit = NULL, *ringing = NULL;
06679    int outgoing = fup->outgoing_call;
06680    struct sip_peer *p = NULL;
06681 
06682    ast_debug(3, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
06683 
06684 
06685    /* Test if we need to check call limits, in order to avoid
06686       realtime lookups if we do not need it */
06687    if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT) && !ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD))
06688       return 0;
06689 
06690    ast_copy_string(name, fup->username, sizeof(name));
06691 
06692    /* Check the list of devices */
06693    if (fup->relatedpeer) {
06694       p = sip_ref_peer(fup->relatedpeer, "ref related peer for update_call_counter");
06695       inuse = &p->inuse;
06696       call_limit = &p->call_limit;
06697       ringing = &p->ringing;
06698       ast_copy_string(name, fup->peername, sizeof(name));
06699    }
06700    if (!p) {
06701       ast_debug(2, "%s is not a local device, no call limit\n", name);
06702       return 0;
06703    }
06704 
06705    switch(event) {
06706    /* incoming and outgoing affects the inuse counter */
06707    case DEC_CALL_LIMIT:
06708       /* Decrement inuse count if applicable */
06709       if (inuse) {
06710          sip_pvt_lock(fup);
06711          ao2_lock(p);
06712          if (*inuse > 0) {
06713             if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
06714                (*inuse)--;
06715                ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
06716             }
06717          } else {
06718             *inuse = 0;
06719          }
06720          ao2_unlock(p);
06721          sip_pvt_unlock(fup);
06722       }
06723 
06724       /* Decrement ringing count if applicable */
06725       if (ringing) {
06726          sip_pvt_lock(fup);
06727          ao2_lock(p);
06728          if (*ringing > 0) {
06729             if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
06730                (*ringing)--;
06731                ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
06732             }
06733          } else {
06734             *ringing = 0;
06735          }
06736          ao2_unlock(p);
06737          sip_pvt_unlock(fup);
06738       }
06739 
06740       /* Decrement onhold count if applicable */
06741       sip_pvt_lock(fup);
06742       ao2_lock(p);
06743       if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && sip_cfg.notifyhold) {
06744          ast_clear_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD);
06745          ao2_unlock(p);
06746          sip_pvt_unlock(fup);
06747          sip_peer_hold(fup, FALSE);
06748       } else {
06749          ao2_unlock(p);
06750          sip_pvt_unlock(fup);
06751       }
06752       if (sipdebug)
06753          ast_debug(2, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
06754       break;
06755 
06756    case INC_CALL_RINGING:
06757    case INC_CALL_LIMIT:
06758       /* If call limit is active and we have reached the limit, reject the call */
06759       if (*call_limit > 0 ) {
06760          if (*inuse >= *call_limit) {
06761             ast_log(LOG_NOTICE, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
06762             sip_unref_peer(p, "update_call_counter: unref peer p, call limit exceeded");
06763             return -1;
06764          }
06765       }
06766       if (ringing && (event == INC_CALL_RINGING)) {
06767          sip_pvt_lock(fup);
06768          ao2_lock(p);
06769          if (!ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
06770             (*ringing)++;
06771             ast_set_flag(&fup->flags[0], SIP_INC_RINGING);
06772          }
06773          ao2_unlock(p);
06774          sip_pvt_unlock(fup);
06775       }
06776       if (inuse) {
06777          sip_pvt_lock(fup);
06778          ao2_lock(p);
06779          if (!ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
06780             (*inuse)++;
06781             ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
06782          }
06783          ao2_unlock(p);
06784          sip_pvt_unlock(fup);
06785       }
06786       if (sipdebug) {
06787          ast_debug(2, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", "peer", name, *inuse, *call_limit);
06788       }
06789       break;
06790 
06791    case DEC_CALL_RINGING:
06792       if (ringing) {
06793          sip_pvt_lock(fup);
06794          ao2_lock(p);
06795          if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
06796             if (*ringing > 0) {
06797                (*ringing)--;
06798             }
06799             ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
06800          }
06801          ao2_unlock(p);
06802          sip_pvt_unlock(fup);
06803       }
06804       break;
06805 
06806    default:
06807       ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
06808    }
06809 
06810    if (p) {
06811       ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", p->name);
06812       sip_unref_peer(p, "update_call_counter: sip_unref_peer from call counter");
06813    }
06814    return 0;
06815 }
06816 
06817 
06818 static void sip_destroy_fn(void *p)
06819 {
06820    sip_destroy(p);
06821 }
06822 
06823 /*! \brief Destroy SIP call structure.
06824  * Make it return NULL so the caller can do things like
06825  * foo = sip_destroy(foo);
06826  * and reduce the chance of bugs due to dangling pointers.
06827  */
06828 struct sip_pvt *sip_destroy(struct sip_pvt *p)
06829 {
06830    ast_debug(3, "Destroying SIP dialog %s\n", p->callid);
06831    __sip_destroy(p, TRUE, TRUE);
06832    return NULL;
06833 }
06834 
06835 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
06836 int hangup_sip2cause(int cause)
06837 {
06838    /* Possible values taken from causes.h */
06839 
06840    switch(cause) {
06841       case 401:   /* Unauthorized */
06842          return AST_CAUSE_CALL_REJECTED;
06843       case 403:   /* Not found */
06844          return AST_CAUSE_CALL_REJECTED;
06845       case 404:   /* Not found */
06846          return AST_CAUSE_UNALLOCATED;
06847       case 405:   /* Method not allowed */
06848          return AST_CAUSE_INTERWORKING;
06849       case 407:   /* Proxy authentication required */
06850          return AST_CAUSE_CALL_REJECTED;
06851       case 408:   /* No reaction */
06852          return AST_CAUSE_NO_USER_RESPONSE;
06853       case 409:   /* Conflict */
06854          return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
06855       case 410:   /* Gone */
06856          return AST_CAUSE_NUMBER_CHANGED;
06857       case 411:   /* Length required */
06858          return AST_CAUSE_INTERWORKING;
06859       case 413:   /* Request entity too large */
06860          return AST_CAUSE_INTERWORKING;
06861       case 414:   /* Request URI too large */
06862          return AST_CAUSE_INTERWORKING;
06863       case 415:   /* Unsupported media type */
06864          return AST_CAUSE_INTERWORKING;
06865       case 420:   /* Bad extension */
06866          return AST_CAUSE_NO_ROUTE_DESTINATION;
06867       case 480:   /* No answer */
06868          return AST_CAUSE_NO_ANSWER;
06869       case 481:   /* No answer */
06870          return AST_CAUSE_INTERWORKING;
06871       case 482:   /* Loop detected */
06872          return AST_CAUSE_INTERWORKING;
06873       case 483:   /* Too many hops */
06874          return AST_CAUSE_NO_ANSWER;
06875       case 484:   /* Address incomplete */
06876          return AST_CAUSE_INVALID_NUMBER_FORMAT;
06877       case 485:   /* Ambiguous */
06878          return AST_CAUSE_UNALLOCATED;
06879       case 486:   /* Busy everywhere */
06880          return AST_CAUSE_BUSY;
06881       case 487:   /* Request terminated */
06882          return AST_CAUSE_INTERWORKING;
06883       case 488:   /* No codecs approved */
06884          return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
06885       case 491:   /* Request pending */
06886          return AST_CAUSE_INTERWORKING;
06887       case 493:   /* Undecipherable */
06888          return AST_CAUSE_INTERWORKING;
06889       case 500:   /* Server internal failure */
06890          return AST_CAUSE_FAILURE;
06891       case 501:   /* Call rejected */
06892          return AST_CAUSE_FACILITY_REJECTED;
06893       case 502:
06894          return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
06895       case 503:   /* Service unavailable */
06896          return AST_CAUSE_CONGESTION;
06897       case 504:   /* Gateway timeout */
06898          return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
06899       case 505:   /* SIP version not supported */
06900          return AST_CAUSE_INTERWORKING;
06901       case 600:   /* Busy everywhere */
06902          return AST_CAUSE_USER_BUSY;
06903       case 603:   /* Decline */
06904          return AST_CAUSE_CALL_REJECTED;
06905       case 604:   /* Does not exist anywhere */
06906          return AST_CAUSE_UNALLOCATED;
06907       case 606:   /* Not acceptable */
06908          return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
06909       default:
06910          if (cause < 500 && cause >= 400) {
06911             /* 4xx class error that is unknown - someting wrong with our request */
06912             return AST_CAUSE_INTERWORKING;
06913          } else if (cause < 600 && cause >= 500) {
06914             /* 5xx class error - problem in the remote end */
06915             return AST_CAUSE_CONGESTION;
06916          } else if (cause < 700 && cause >= 600) {
06917             /* 6xx - global errors in the 4xx class */
06918             return AST_CAUSE_INTERWORKING;
06919          }
06920          return AST_CAUSE_NORMAL;
06921    }
06922    /* Never reached */
06923    return 0;
06924 }
06925 
06926 /*! \brief Convert Asterisk hangup causes to SIP codes
06927 \verbatim
06928  Possible values from causes.h
06929         AST_CAUSE_NOTDEFINED    AST_CAUSE_NORMAL        AST_CAUSE_BUSY
06930         AST_CAUSE_FAILURE       AST_CAUSE_CONGESTION    AST_CAUSE_UNALLOCATED
06931 
06932    In addition to these, a lot of PRI codes is defined in causes.h
06933    ...should we take care of them too ?
06934 
06935    Quote RFC 3398
06936 
06937    ISUP Cause value                        SIP response
06938    ----------------                        ------------
06939    1  unallocated number                   404 Not Found
06940    2  no route to network                  404 Not found
06941    3  no route to destination              404 Not found
06942    16 normal call clearing                 --- (*)
06943    17 user busy                            486 Busy here
06944    18 no user responding                   408 Request Timeout
06945    19 no answer from the user              480 Temporarily unavailable
06946    20 subscriber absent                    480 Temporarily unavailable
06947    21 call rejected                        403 Forbidden (+)
06948    22 number changed (w/o diagnostic)      410 Gone
06949    22 number changed (w/ diagnostic)       301 Moved Permanently
06950    23 redirection to new destination       410 Gone
06951    26 non-selected user clearing           404 Not Found (=)
06952    27 destination out of order             502 Bad Gateway
06953    28 address incomplete                   484 Address incomplete
06954    29 facility rejected                    501 Not implemented
06955    31 normal unspecified                   480 Temporarily unavailable
06956 \endverbatim
06957 */
06958 const char *hangup_cause2sip(int cause)
06959 {
06960    switch (cause) {
06961       case AST_CAUSE_UNALLOCATED:      /* 1 */
06962       case AST_CAUSE_NO_ROUTE_DESTINATION:   /* 3 IAX2: Can't find extension in context */
06963       case AST_CAUSE_NO_ROUTE_TRANSIT_NET:   /* 2 */
06964          return "404 Not Found";
06965       case AST_CAUSE_CONGESTION:    /* 34 */
06966       case AST_CAUSE_SWITCH_CONGESTION:   /* 42 */
06967          return "503 Service Unavailable";
06968       case AST_CAUSE_NO_USER_RESPONSE: /* 18 */
06969          return "408 Request Timeout";
06970       case AST_CAUSE_NO_ANSWER:     /* 19 */
06971       case AST_CAUSE_UNREGISTERED:        /* 20 */
06972          return "480 Temporarily unavailable";
06973       case AST_CAUSE_CALL_REJECTED:    /* 21 */
06974          return "403 Forbidden";
06975       case AST_CAUSE_NUMBER_CHANGED:      /* 22 */
06976          return "410 Gone";
06977       case AST_CAUSE_NORMAL_UNSPECIFIED:  /* 31 */
06978          return "480 Temporarily unavailable";
06979       case AST_CAUSE_INVALID_NUMBER_FORMAT:
06980          return "484 Address incomplete";
06981       case AST_CAUSE_USER_BUSY:
06982          return "486 Busy here";
06983       case AST_CAUSE_FAILURE:
06984          return "500 Server internal failure";
06985       case AST_CAUSE_FACILITY_REJECTED:   /* 29 */
06986          return "501 Not Implemented";
06987       case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
06988          return "503 Service Unavailable";
06989       /* Used in chan_iax2 */
06990       case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
06991          return "502 Bad Gateway";
06992       case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */
06993          return "488 Not Acceptable Here";
06994       case AST_CAUSE_INTERWORKING:  /* Unspecified Interworking issues */
06995          return "500 Network error";
06996 
06997       case AST_CAUSE_NOTDEFINED:
06998       default:
06999          ast_debug(1, "AST hangup cause %d (no match found in SIP)\n", cause);
07000          return NULL;
07001    }
07002 
07003    /* Never reached */
07004    return 0;
07005 }
07006 
07007 static int reinvite_timeout(const void *data)
07008 {
07009    struct sip_pvt *dialog = (struct sip_pvt *) data;
07010    struct ast_channel *owner = sip_pvt_lock_full(dialog);
07011    dialog->reinviteid = -1;
07012    check_pendings(dialog);
07013    if (owner) {
07014       ast_channel_unlock(owner);
07015       ast_channel_unref(owner);
07016    }
07017    ao2_unlock(dialog);
07018    dialog_unref(dialog, "unref for reinvite timeout");
07019    return 0;
07020 }
07021 
07022 /*! \brief  sip_hangup: Hangup SIP call
07023  * Part of PBX interface, called from ast_hangup */
07024 static int sip_hangup(struct ast_channel *ast)
07025 {
07026    struct sip_pvt *p = ast_channel_tech_pvt(ast);
07027    int needcancel = FALSE;
07028    int needdestroy = 0;
07029    struct ast_channel *oldowner = ast;
07030 
07031    if (!p) {
07032       ast_debug(1, "Asked to hangup channel that was not connected\n");
07033       return 0;
07034    }
07035    if (ast_channel_hangupcause(ast) == AST_CAUSE_ANSWERED_ELSEWHERE) {
07036       ast_debug(1, "This call was answered elsewhere\n");
07037       append_history(p, "Cancel", "Call answered elsewhere");
07038       p->answered_elsewhere = TRUE;
07039    }
07040 
07041    /* Store hangupcause locally in PVT so we still have it before disconnect */
07042    if (p->owner)
07043       p->hangupcause = ast_channel_hangupcause(p->owner);
07044 
07045    if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
07046       if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
07047          if (sipdebug)
07048             ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
07049          update_call_counter(p, DEC_CALL_LIMIT);
07050       }
07051       ast_debug(4, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
07052       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
07053       ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Really hang up next time */
07054       if (p->owner) {
07055          sip_pvt_lock(p);
07056          oldowner = p->owner;
07057          p->owner = NULL;  /* Owner will be gone after we return, so take it away */
07058          sip_pvt_unlock(p);
07059          ast_channel_tech_pvt_set(oldowner, dialog_unref(ast_channel_tech_pvt(oldowner), "unref oldowner->tech_pvt"));
07060       }
07061       ast_module_unref(ast_module_info->self);
07062       return 0;
07063    }
07064 
07065    ast_debug(1, "Hangup call %s, SIP callid %s\n", ast_channel_name(ast), p->callid);
07066 
07067    sip_pvt_lock(p);
07068    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
07069       if (sipdebug)
07070          ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
07071       update_call_counter(p, DEC_CALL_LIMIT);
07072    }
07073 
07074    /* Determine how to disconnect */
07075    if (p->owner != ast) {
07076       ast_log(LOG_WARNING, "Huh?  We aren't the owner? Can't hangup call.\n");
07077       sip_pvt_unlock(p);
07078       return 0;
07079    }
07080    /* If the call is not UP, we need to send CANCEL instead of BYE */
07081    /* In case of re-invites, the call might be UP even though we have an incomplete invite transaction */
07082    if (p->invitestate < INV_COMPLETED && ast_channel_state(p->owner) != AST_STATE_UP) {
07083       needcancel = TRUE;
07084       ast_debug(4, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast_channel_state(ast)));
07085    }
07086 
07087    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
07088 
07089    append_history(p, needcancel ? "Cancel" : "Hangup", "Cause %s", ast_cause2str(p->hangupcause));
07090 
07091    /* Disconnect */
07092    disable_dsp_detect(p);
07093 
07094    p->owner = NULL;
07095    ast_channel_tech_pvt_set(ast, NULL);
07096 
07097    ast_module_unref(ast_module_info->self);
07098    /* Do not destroy this pvt until we have timeout or
07099       get an answer to the BYE or INVITE/CANCEL
07100       If we get no answer during retransmit period, drop the call anyway.
07101       (Sorry, mother-in-law, you can't deny a hangup by sending
07102       603 declined to BYE...)
07103    */
07104    if (p->alreadygone)
07105       needdestroy = 1;  /* Set destroy flag at end of this function */
07106    else if (p->invitestate != INV_CALLING)
07107       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
07108 
07109    /* Start the process if it's not already started */
07110    if (!p->alreadygone && p->initreq.data && ast_str_strlen(p->initreq.data)) {
07111       if (needcancel) { /* Outgoing call, not up */
07112          if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
07113             /* if we can't send right now, mark it pending */
07114             if (p->invitestate == INV_CALLING) {
07115                /* We can't send anything in CALLING state */
07116                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
07117                /* Do we need a timer here if we don't hear from them at all? Yes we do or else we will get hung dialogs and those are no fun. */
07118                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
07119                append_history(p, "DELAY", "Not sending cancel, waiting for timeout");
07120             } else {
07121                struct sip_pkt *cur;
07122 
07123                for (cur = p->packets; cur; cur = cur->next) {
07124                   __sip_semi_ack(p, cur->seqno, cur->is_resp, cur->method ? cur->method : find_sip_method(ast_str_buffer(cur->data)));
07125                }
07126                p->invitestate = INV_CANCELLED;
07127                /* Send a new request: CANCEL */
07128                transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
07129                /* Actually don't destroy us yet, wait for the 487 on our original
07130                   INVITE, but do set an autodestruct just in case we never get it. */
07131                needdestroy = 0;
07132                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
07133             }
07134          } else { /* Incoming call, not up */
07135             const char *res;
07136             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"));
07137             if (p->hangupcause && (res = hangup_cause2sip(p->hangupcause)))
07138                transmit_response_reliable(p, res, &p->initreq);
07139             else
07140                transmit_response_reliable(p, "603 Declined", &p->initreq);
07141             p->invitestate = INV_TERMINATED;
07142          }
07143       } else { /* Call is in UP state, send BYE */
07144          if (p->stimer->st_active == TRUE) {
07145             stop_session_timer(p);
07146          }
07147 
07148          if (!p->pendinginvite) {
07149             struct ast_channel *bridge = ast_bridged_channel(oldowner);
07150             char quality_buf[AST_MAX_USER_FIELD], *quality;
07151 
07152             /* We need to get the lock on bridge because ast_rtp_instance_set_stats_vars will attempt
07153              * to lock the bridge. This may get hairy...
07154              */
07155             while (bridge && ast_channel_trylock(bridge)) {
07156                sip_pvt_unlock(p);
07157                do {
07158                   CHANNEL_DEADLOCK_AVOIDANCE(oldowner);
07159                } while (sip_pvt_trylock(p));
07160                bridge = ast_bridged_channel(oldowner);
07161             }
07162 
07163             if (p->rtp) {
07164                ast_rtp_instance_set_stats_vars(oldowner, p->rtp);
07165             }
07166 
07167             if (bridge) {
07168                struct sip_pvt *q = ast_channel_tech_pvt(bridge);
07169 
07170                if (IS_SIP_TECH(ast_channel_tech(bridge)) && q && q->rtp) {
07171                   ast_rtp_instance_set_stats_vars(bridge, q->rtp);
07172                }
07173                ast_channel_unlock(bridge);
07174             }
07175 
07176             /*
07177              * The channel variables are set below just to get the AMI
07178              * VarSet event because the channel is being hungup.
07179              */
07180             if (p->rtp && (quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
07181                if (p->do_history) {
07182                   append_history(p, "RTCPaudio", "Quality:%s", quality);
07183                }
07184                pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", quality);
07185             }
07186             if (p->vrtp && (quality = ast_rtp_instance_get_quality(p->vrtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
07187                if (p->do_history) {
07188                   append_history(p, "RTCPvideo", "Quality:%s", quality);
07189                }
07190                pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", quality);
07191             }
07192             if (p->trtp && (quality = ast_rtp_instance_get_quality(p->trtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
07193                if (p->do_history) {
07194                   append_history(p, "RTCPtext", "Quality:%s", quality);
07195                }
07196                pbx_builtin_setvar_helper(oldowner, "RTPTEXTQOS", quality);
07197             }
07198 
07199             /* Send a hangup */
07200             if (ast_channel_state(oldowner) == AST_STATE_UP) {
07201                transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
07202             }
07203 
07204          } else {
07205             /* Note we will need a BYE when this all settles out
07206                but we can't send one while we have "INVITE" outstanding. */
07207             ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
07208             ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE); 
07209             AST_SCHED_DEL_UNREF(sched, p->waitid, dialog_unref(p, "when you delete the waitid sched, you should dec the refcount for the stored dialog ptr"));
07210             if (sip_cancel_destroy(p)) {
07211                ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
07212             }
07213             /* If we have an ongoing reinvite, there is a chance that we have gotten a provisional
07214              * response, but something weird has happened and we will never receive a final response.
07215              * So, just in case, check for pending actions after a bit of time to trigger the pending
07216              * bye that we are setting above */
07217             if (p->ongoing_reinvite && p->reinviteid < 0) {
07218                p->reinviteid = ast_sched_add(sched, 32 * p->timer_t1, reinvite_timeout, dialog_ref(p, "ref for reinvite_timeout"));
07219             }
07220          }
07221       }
07222    }
07223    if (needdestroy) {
07224       pvt_set_needdestroy(p, "hangup");
07225    }
07226    sip_pvt_unlock(p);
07227    dialog_unref(p, "unref ast->tech_pvt");
07228    return 0;
07229 }
07230 
07231 /*! \brief Try setting codec suggested by the SIP_CODEC channel variable */
07232 static void try_suggested_sip_codec(struct sip_pvt *p)
07233 {
07234    struct ast_format fmt;
07235    const char *codec;
07236 
07237    ast_format_clear(&fmt);
07238 
07239    if (p->outgoing_call) {
07240       codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC_OUTBOUND");
07241    } else if (!(codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC_INBOUND"))) {
07242       codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
07243    }
07244 
07245    if (!codec) 
07246       return;
07247 
07248    ast_getformatbyname(codec, &fmt);
07249    if (fmt.id) {
07250       ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
07251       if (ast_format_cap_iscompatible(p->jointcaps, &fmt)) {
07252          ast_format_cap_set(p->jointcaps, &fmt);
07253          ast_format_cap_set(p->caps, &fmt);
07254       } else
07255          ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
07256    } else
07257       ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
07258    return;
07259 }
07260 
07261 /*! \brief  sip_answer: Answer SIP call , send 200 OK on Invite
07262  * Part of PBX interface */
07263 static int sip_answer(struct ast_channel *ast)
07264 {
07265    int res = 0;
07266    struct sip_pvt *p = ast_channel_tech_pvt(ast);
07267    int oldsdp = FALSE;
07268 
07269    if (!p) {
07270       ast_debug(1, "Asked to answer channel %s without tech pvt; ignoring\n",
07271             ast_channel_name(ast));
07272       return res;
07273    }
07274    sip_pvt_lock(p);
07275    if (ast_channel_state(ast) != AST_STATE_UP) {
07276       try_suggested_sip_codec(p);
07277 
07278       if (ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT)) {
07279          oldsdp = TRUE;
07280       }
07281 
07282       ast_setstate(ast, AST_STATE_UP);
07283       ast_debug(1, "SIP answering channel: %s\n", ast_channel_name(ast));
07284       ast_rtp_instance_update_source(p->rtp);
07285       res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL, oldsdp, TRUE);
07286       ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
07287       /* RFC says the session timer starts counting on 200,
07288        * not on INVITE. */
07289       if (p->stimer->st_active == TRUE) {
07290          start_session_timer(p);
07291       }
07292    }
07293    sip_pvt_unlock(p);
07294    return res;
07295 }
07296 
07297 /*! \brief Send frame to media channel (rtp) */
07298 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
07299 {
07300    struct sip_pvt *p = ast_channel_tech_pvt(ast);
07301    int res = 0;
07302 
07303    switch (frame->frametype) {
07304    case AST_FRAME_VOICE:
07305       if (!(ast_format_cap_iscompatible(ast_channel_nativeformats(ast), &frame->subclass.format))) {
07306          char s1[512];
07307          ast_log(LOG_WARNING, "Asked to transmit frame type %s, while native formats is %s read/write = %s/%s\n",
07308             ast_getformatname(&frame->subclass.format),
07309             ast_getformatname_multiple(s1, sizeof(s1), ast_channel_nativeformats(ast)),
07310             ast_getformatname(ast_channel_readformat(ast)),
07311             ast_getformatname(ast_channel_writeformat(ast)));
07312          return 0;
07313       }
07314       if (p) {
07315          sip_pvt_lock(p);
07316          if (p->t38.state == T38_ENABLED) {
07317             /* drop frame, can't sent VOICE frames while in T.38 mode */
07318             sip_pvt_unlock(p);
07319             break;
07320          } else if (p->rtp) {
07321             /* If channel is not up, activate early media session */
07322             if ((ast_channel_state(ast) != AST_STATE_UP) &&
07323                 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
07324                 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
07325                ast_rtp_instance_update_source(p->rtp);
07326                if (!global_prematuremediafilter) {
07327                   p->invitestate = INV_EARLY_MEDIA;
07328                   transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
07329                   ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
07330                }
07331             }
07332             p->lastrtptx = time(NULL);
07333             res = ast_rtp_instance_write(p->rtp, frame);
07334          }
07335          sip_pvt_unlock(p);
07336       }
07337       break;
07338    case AST_FRAME_VIDEO:
07339       if (p) {
07340          sip_pvt_lock(p);
07341          if (p->vrtp) {
07342             /* Activate video early media */
07343             if ((ast_channel_state(ast) != AST_STATE_UP) &&
07344                 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
07345                 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
07346                p->invitestate = INV_EARLY_MEDIA;
07347                transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
07348                ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
07349             }
07350             p->lastrtptx = time(NULL);
07351             res = ast_rtp_instance_write(p->vrtp, frame);
07352          }
07353          sip_pvt_unlock(p);
07354       }
07355       break;
07356    case AST_FRAME_TEXT:
07357       if (p) {
07358          sip_pvt_lock(p);
07359          if (p->red) {
07360             ast_rtp_red_buffer(p->trtp, frame);
07361          } else {
07362             if (p->trtp) {
07363                /* Activate text early media */
07364                if ((ast_channel_state(ast) != AST_STATE_UP) &&
07365                    !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
07366                    !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
07367                   p->invitestate = INV_EARLY_MEDIA;
07368                   transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
07369                   ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
07370                }
07371                p->lastrtptx = time(NULL);
07372                res = ast_rtp_instance_write(p->trtp, frame);
07373             }
07374          }
07375          sip_pvt_unlock(p);
07376       }
07377       break;
07378    case AST_FRAME_IMAGE:
07379       return 0;
07380       break;
07381    case AST_FRAME_MODEM:
07382       if (p) {
07383          sip_pvt_lock(p);
07384          /* UDPTL requires two-way communication, so early media is not needed here.
07385             we simply forget the frames if we get modem frames before the bridge is up.
07386             Fax will re-transmit.
07387          */
07388          if ((ast_channel_state(ast) == AST_STATE_UP) &&
07389              p->udptl &&
07390              (p->t38.state == T38_ENABLED)) {
07391             res = ast_udptl_write(p->udptl, frame);
07392          }
07393          sip_pvt_unlock(p);
07394       }
07395       break;
07396    default:
07397       ast_log(LOG_WARNING, "Can't send %u type frames with SIP write\n", frame->frametype);
07398       return 0;
07399    }
07400 
07401    return res;
07402 }
07403 
07404 /*! \brief  sip_fixup: Fix up a channel:  If a channel is consumed, this is called.
07405         Basically update any ->owner links */
07406 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
07407 {
07408    int ret = -1;
07409    struct sip_pvt *p;
07410 
07411    if (newchan && ast_test_flag(ast_channel_flags(newchan), AST_FLAG_ZOMBIE))
07412       ast_debug(1, "New channel is zombie\n");
07413    if (oldchan && ast_test_flag(ast_channel_flags(oldchan), AST_FLAG_ZOMBIE))
07414       ast_debug(1, "Old channel is zombie\n");
07415 
07416    if (!newchan || !ast_channel_tech_pvt(newchan)) {
07417       if (!newchan)
07418          ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", ast_channel_name(oldchan));
07419       else
07420          ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", ast_channel_name(oldchan));
07421       return -1;
07422    }
07423    p = ast_channel_tech_pvt(newchan);
07424 
07425    sip_pvt_lock(p);
07426    append_history(p, "Masq", "Old channel: %s\n", ast_channel_name(oldchan));
07427    append_history(p, "Masq (cont)", "...new owner: %s\n", ast_channel_name(newchan));
07428    if (p->owner != oldchan)
07429       ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
07430    else {
07431       p->owner = newchan;
07432       /* Re-invite RTP back to Asterisk. Needed if channel is masqueraded out of a native
07433          RTP bridge (i.e., RTP not going through Asterisk): RTP bridge code might not be
07434          able to do this if the masquerade happens before the bridge breaks (e.g., AMI
07435          redirect of both channels). Note that a channel can not be masqueraded *into*
07436          a native bridge. So there is no danger that this breaks a native bridge that
07437          should stay up. */
07438       sip_set_rtp_peer(newchan, NULL, NULL, 0, 0, 0);
07439       ret = 0;
07440    }
07441    ast_debug(3, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, ast_channel_name(p->owner), ast_channel_name(oldchan));
07442 
07443    sip_pvt_unlock(p);
07444    return ret;
07445 }
07446 
07447 static int sip_senddigit_begin(struct ast_channel *ast, char digit)
07448 {
07449    struct sip_pvt *p = ast_channel_tech_pvt(ast);
07450    int res = 0;
07451 
07452    if (!p) {
07453       ast_debug(1, "Asked to begin DTMF digit on channel %s with no pvt; ignoring\n",
07454             ast_channel_name(ast));
07455       return res;
07456    }
07457 
07458    sip_pvt_lock(p);
07459    switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
07460    case SIP_DTMF_INBAND:
07461       res = -1; /* Tell Asterisk to generate inband indications */
07462       break;
07463    case SIP_DTMF_RFC2833:
07464       if (p->rtp)
07465          ast_rtp_instance_dtmf_begin(p->rtp, digit);
07466       break;
07467    default:
07468       break;
07469    }
07470    sip_pvt_unlock(p);
07471 
07472    return res;
07473 }
07474 
07475 /*! \brief Send DTMF character on SIP channel
07476    within one call, we're able to transmit in many methods simultaneously */
07477 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
07478 {
07479    struct sip_pvt *p = ast_channel_tech_pvt(ast);
07480    int res = 0;
07481 
07482    if (!p) {
07483       ast_debug(1, "Asked to end DTMF digit on channel %s with no pvt; ignoring\n",
07484             ast_channel_name(ast));
07485       return res;
07486    }
07487 
07488    sip_pvt_lock(p);
07489    switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
07490    case SIP_DTMF_INFO:
07491    case SIP_DTMF_SHORTINFO:
07492       transmit_info_with_digit(p, digit, duration);
07493       break;
07494    case SIP_DTMF_RFC2833:
07495       if (p->rtp)
07496          ast_rtp_instance_dtmf_end_with_duration(p->rtp, digit, duration);
07497       break;
07498    case SIP_DTMF_INBAND:
07499       res = -1; /* Tell Asterisk to stop inband indications */
07500       break;
07501    }
07502    sip_pvt_unlock(p);
07503 
07504    return res;
07505 }
07506 
07507 /*! \brief Transfer SIP call */
07508 static int sip_transfer(struct ast_channel *ast, const char *dest)
07509 {
07510    struct sip_pvt *p = ast_channel_tech_pvt(ast);
07511    int res;
07512 
07513    if (!p) {
07514       ast_debug(1, "Asked to transfer channel %s with no pvt; ignoring\n",
07515             ast_channel_name(ast));
07516       return -1;
07517    }
07518 
07519    if (dest == NULL) /* functions below do not take a NULL */
07520       dest = "";
07521    sip_pvt_lock(p);
07522    if (ast_channel_state(ast) == AST_STATE_RING)
07523       res = sip_sipredirect(p, dest);
07524    else
07525       res = transmit_refer(p, dest);
07526    sip_pvt_unlock(p);
07527    return res;
07528 }
07529 
07530 /*! \brief Helper function which updates T.38 capability information and triggers a reinvite */
07531 static int interpret_t38_parameters(struct sip_pvt *p, const struct ast_control_t38_parameters *parameters)
07532 {
07533    int res = 0;
07534 
07535    if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) || !p->udptl) {
07536       return -1;
07537    }
07538    switch (parameters->request_response) {
07539    case AST_T38_NEGOTIATED:
07540    case AST_T38_REQUEST_NEGOTIATE:         /* Request T38 */
07541       /* Negotiation can not take place without a valid max_ifp value. */
07542       if (!parameters->max_ifp) {
07543          if (p->t38.state == T38_PEER_REINVITE) {
07544             AST_SCHED_DEL_UNREF(sched, p->t38id, dialog_unref(p, "when you delete the t38id sched, you should dec the refcount for the stored dialog ptr"));
07545             transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
07546          }
07547          change_t38_state(p, T38_REJECTED);
07548          break;
07549       } else if (p->t38.state == T38_PEER_REINVITE) {
07550          AST_SCHED_DEL_UNREF(sched, p->t38id, dialog_unref(p, "when you delete the t38id sched, you should dec the refcount for the stored dialog ptr"));
07551          p->t38.our_parms = *parameters;
07552          /* modify our parameters to conform to the peer's parameters,
07553           * based on the rules in the ITU T.38 recommendation
07554           */
07555          if (!p->t38.their_parms.fill_bit_removal) {
07556             p->t38.our_parms.fill_bit_removal = FALSE;
07557          }
07558          if (!p->t38.their_parms.transcoding_mmr) {
07559             p->t38.our_parms.transcoding_mmr = FALSE;
07560          }
07561          if (!p->t38.their_parms.transcoding_jbig) {
07562             p->t38.our_parms.transcoding_jbig = FALSE;
07563          }
07564          p->t38.our_parms.version = MIN(p->t38.our_parms.version, p->t38.their_parms.version);
07565          p->t38.our_parms.rate_management = p->t38.their_parms.rate_management;
07566          ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
07567          change_t38_state(p, T38_ENABLED);
07568          transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
07569       } else if (p->t38.state != T38_ENABLED) {
07570          p->t38.our_parms = *parameters;
07571          ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
07572          change_t38_state(p, T38_LOCAL_REINVITE);
07573          if (!p->pendinginvite) {
07574             transmit_reinvite_with_sdp(p, TRUE, FALSE);
07575          } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
07576             ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
07577          }
07578       }
07579       break;
07580    case AST_T38_TERMINATED:
07581    case AST_T38_REFUSED:
07582    case AST_T38_REQUEST_TERMINATE:         /* Shutdown T38 */
07583       if (p->t38.state == T38_PEER_REINVITE) {
07584          AST_SCHED_DEL_UNREF(sched, p->t38id, dialog_unref(p, "when you delete the t38id sched, you should dec the refcount for the stored dialog ptr"));
07585          change_t38_state(p, T38_REJECTED);
07586          transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
07587       } else if (p->t38.state == T38_ENABLED)
07588          transmit_reinvite_with_sdp(p, FALSE, FALSE);
07589       break;
07590    case AST_T38_REQUEST_PARMS: {    /* Application wants remote's parameters re-sent */
07591       struct ast_control_t38_parameters parameters = p->t38.their_parms;
07592 
07593       if (p->t38.state == T38_PEER_REINVITE) {
07594          AST_SCHED_DEL_UNREF(sched, p->t38id, dialog_unref(p, "when you delete the t38id sched, you should dec the refcount for the stored dialog ptr"));
07595          parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
07596          parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
07597          if (p->owner) {
07598             ast_queue_control_data(p->owner, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));
07599          }
07600          /* we need to return a positive value here, so that applications that
07601           * send this request can determine conclusively whether it was accepted or not...
07602           * older versions of chan_sip would just silently accept it and return zero.
07603           */
07604          res = AST_T38_REQUEST_PARMS;
07605       }
07606       break;
07607    }
07608    default:
07609       res = -1;
07610       break;
07611    }
07612 
07613    return res;
07614 }
07615 
07616 /*! \internal \brief Create and initialize UDPTL for the specified dialog
07617  * \param p SIP private structure to create UDPTL object for
07618  * \pre p is locked
07619  * \pre p->owner is locked
07620  *
07621  * \note In the case of failure, SIP_PAGE2_T38SUPPORT is cleared on p
07622  *
07623  * \return 0 on success, any other value on failure
07624  */
07625 static int initialize_udptl(struct sip_pvt *p)
07626 {
07627    int natflags = ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
07628 
07629    if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
07630       return 1;
07631    }
07632 
07633    /* If we've already initialized T38, don't take any further action */
07634    if (p->udptl) {
07635       return 0;
07636    }
07637 
07638    /* T38 can be supported by this dialog, create it and set the derived properties */
07639    if ((p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, &bindaddr))) {
07640       if (p->owner) {
07641          ast_channel_set_fd(p->owner, 5, ast_udptl_fd(p->udptl));
07642       }
07643 
07644       ast_udptl_setqos(p->udptl, global_tos_audio, global_cos_audio);
07645       p->t38_maxdatagram = p->relatedpeer ? p->relatedpeer->t38_maxdatagram : global_t38_maxdatagram;
07646       set_t38_capabilities(p);
07647 
07648       ast_debug(1, "Setting NAT on UDPTL to %s\n", natflags ? "On" : "Off");
07649       ast_udptl_setnat(p->udptl, natflags);
07650    } else {
07651       ast_log(AST_LOG_WARNING, "UDPTL creation failed - disabling T38 for this dialog\n");
07652       ast_clear_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT);
07653       return 1;
07654    }
07655 
07656    return 0;
07657 }
07658 
07659 
07660 static int sipinfo_send(
07661       struct ast_channel *chan,
07662       struct ast_variable *headers,
07663       const char *content_type,
07664       const char *content,
07665       const char *useragent_filter)
07666 {
07667    struct sip_pvt *p;
07668    struct ast_variable *var;
07669    struct sip_request req;
07670    int res = -1;
07671 
07672    ast_channel_lock(chan);
07673 
07674    if (ast_channel_tech(chan) != &sip_tech) {
07675       ast_log(LOG_WARNING, "Attempted to send a custom INFO on a non-SIP channel %s\n", ast_channel_name(chan));
07676       ast_channel_unlock(chan);
07677       return res;
07678    }
07679 
07680    p = ast_channel_tech_pvt(chan);
07681    sip_pvt_lock(p);
07682 
07683    if (!(ast_strlen_zero(useragent_filter))) {
07684       int match = (strstr(p->useragent, useragent_filter)) ? 1 : 0;
07685       if (!match) {
07686          goto cleanup;
07687       }
07688    }
07689 
07690    reqprep(&req, p, SIP_INFO, 0, 1);
07691    for (var = headers; var; var = var->next) {
07692       add_header(&req, var->name, var->value);
07693    }
07694    if (!ast_strlen_zero(content) && !ast_strlen_zero(content_type)) {
07695       add_header(&req, "Content-Type", content_type);
07696       add_content(&req, content);
07697    }
07698 
07699    res = send_request(p, &req, XMIT_RELIABLE, p->ocseq);
07700 
07701 cleanup:
07702    sip_pvt_unlock(p);
07703    ast_channel_unlock(chan);
07704    return res;
07705 }
07706 /*! \brief Play indication to user
07707  * With SIP a lot of indications is sent as messages, letting the device play
07708    the indication - busy signal, congestion etc
07709    \return -1 to force ast_indicate to send indication in audio, 0 if SIP can handle the indication by sending a message
07710 */
07711 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
07712 {
07713    struct sip_pvt *p = ast_channel_tech_pvt(ast);
07714    int res = 0;
07715 
07716    if (!p) {
07717       ast_debug(1, "Asked to indicate condition on channel %s with no pvt; ignoring\n",
07718             ast_channel_name(ast));
07719       return res;
07720    }
07721 
07722    sip_pvt_lock(p);
07723    switch(condition) {
07724    case AST_CONTROL_RINGING:
07725       if (ast_channel_state(ast) == AST_STATE_RING) {
07726          p->invitestate = INV_EARLY_MEDIA;
07727          if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
07728              (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {            
07729             /* Send 180 ringing if out-of-band seems reasonable */
07730             transmit_provisional_response(p, "180 Ringing", &p->initreq, 0);
07731             ast_set_flag(&p->flags[0], SIP_RINGING);
07732             if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
07733                break;
07734          } else {
07735             /* Well, if it's not reasonable, just send in-band */
07736          }
07737       }
07738       res = -1;
07739       break;
07740    case AST_CONTROL_BUSY:
07741       if (ast_channel_state(ast) != AST_STATE_UP) {
07742          transmit_response_reliable(p, "486 Busy Here", &p->initreq);
07743          p->invitestate = INV_COMPLETED;
07744          sip_alreadygone(p);
07745          ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
07746          break;
07747       }
07748       res = -1;
07749       break;
07750    case AST_CONTROL_CONGESTION:
07751       if (ast_channel_state(ast) != AST_STATE_UP) {
07752          transmit_response_reliable(p, "503 Service Unavailable", &p->initreq);
07753          p->invitestate = INV_COMPLETED;
07754          sip_alreadygone(p);
07755          ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
07756          break;
07757       }
07758       res = -1;
07759       break;
07760    case AST_CONTROL_INCOMPLETE:
07761       if (ast_channel_state(ast) != AST_STATE_UP) {
07762          switch (ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)) {
07763          case SIP_PAGE2_ALLOWOVERLAP_YES:
07764             transmit_response_reliable(p, "484 Address Incomplete", &p->initreq);
07765             p->invitestate = INV_COMPLETED;
07766             sip_alreadygone(p);
07767             ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
07768             break;
07769          case SIP_PAGE2_ALLOWOVERLAP_DTMF:
07770             /* Just wait for inband DTMF digits */
07771             break;
07772          default:
07773             /* it actually means no support for overlap */
07774             transmit_response_reliable(p, "404 Not Found", &p->initreq);
07775             p->invitestate = INV_COMPLETED;
07776             sip_alreadygone(p);
07777             ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
07778             break;
07779          }
07780       }
07781       break;
07782    case AST_CONTROL_PROCEEDING:
07783       if ((ast_channel_state(ast) != AST_STATE_UP) &&
07784           !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
07785           !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
07786          transmit_response(p, "100 Trying", &p->initreq);
07787          p->invitestate = INV_PROCEEDING;
07788          break;
07789       }
07790       res = -1;
07791       break;
07792    case AST_CONTROL_PROGRESS:
07793       if ((ast_channel_state(ast) != AST_STATE_UP) &&
07794           !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
07795           !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
07796          p->invitestate = INV_EARLY_MEDIA;
07797          transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
07798          ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
07799          break;
07800       }
07801       res = -1;
07802       break;
07803    case AST_CONTROL_HOLD:
07804       ast_rtp_instance_update_source(p->rtp);
07805       ast_moh_start(ast, data, p->mohinterpret);
07806       break;
07807    case AST_CONTROL_UNHOLD:
07808       ast_rtp_instance_update_source(p->rtp);
07809       ast_moh_stop(ast);
07810       break;
07811    case AST_CONTROL_VIDUPDATE:   /* Request a video frame update */
07812       if (p->vrtp && !p->novideo) {
07813          transmit_info_with_vidupdate(p);
07814          /* ast_rtcp_send_h261fur(p->vrtp); */
07815       } else
07816          res = -1;
07817       break;
07818    case AST_CONTROL_T38_PARAMETERS:
07819       res = -1;
07820       if (datalen != sizeof(struct ast_control_t38_parameters)) {
07821          ast_log(LOG_ERROR, "Invalid datalen for AST_CONTROL_T38_PARAMETERS. Expected %d, got %d\n", (int) sizeof(struct ast_control_t38_parameters), (int) datalen);
07822       } else {
07823          const struct ast_control_t38_parameters *parameters = data;
07824          if (!initialize_udptl(p)) {
07825             res = interpret_t38_parameters(p, parameters);
07826          }
07827       }
07828       break;
07829    case AST_CONTROL_SRCUPDATE:
07830       ast_rtp_instance_update_source(p->rtp);
07831       break;
07832    case AST_CONTROL_SRCCHANGE:
07833       ast_rtp_instance_change_source(p->rtp);
07834       break;
07835    case AST_CONTROL_CONNECTED_LINE:
07836       update_connectedline(p, data, datalen);
07837       break;
07838    case AST_CONTROL_REDIRECTING:
07839       update_redirecting(p, data, datalen);
07840       break;
07841    case AST_CONTROL_AOC:
07842       {
07843          struct ast_aoc_decoded *decoded = ast_aoc_decode((struct ast_aoc_encoded *) data, datalen, ast);
07844          if (!decoded) {
07845             ast_log(LOG_ERROR, "Error decoding indicated AOC data\n");
07846             res = -1;
07847             break;
07848          }
07849          switch (ast_aoc_get_msg_type(decoded)) {
07850          case AST_AOC_REQUEST:
07851             if (ast_aoc_get_termination_request(decoded)) {
07852                /* TODO, once there is a way to get AOC-E on hangup, attempt that here
07853                 * before hanging up the channel.*/
07854 
07855                /* The other side has already initiated the hangup. This frame
07856                 * just says they are waiting to get AOC-E before completely tearing
07857                 * the call down.  Since SIP does not support this at the moment go
07858                 * ahead and terminate the call here to avoid an unnecessary timeout. */
07859                ast_debug(1, "AOC-E termination request received on %s. This is not yet supported on sip. Continue with hangup \n", ast_channel_name(p->owner));
07860                ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
07861             }
07862             break;
07863          case AST_AOC_D:
07864          case AST_AOC_E:
07865             if (ast_test_flag(&p->flags[2], SIP_PAGE3_SNOM_AOC)) {
07866                transmit_info_with_aoc(p, decoded);
07867             }
07868             break;
07869          case AST_AOC_S: /* S not supported yet */
07870          default:
07871             break;
07872          }
07873          ast_aoc_destroy_decoded(decoded);
07874       }
07875       break;
07876    case AST_CONTROL_UPDATE_RTP_PEER: /* Absorb this since it is handled by the bridge */
07877       break;
07878    case AST_CONTROL_FLASH: /* We don't currently handle AST_CONTROL_FLASH here, but it is expected, so we don't need to warn either. */
07879       res = -1;
07880       break;
07881    case AST_CONTROL_PVT_CAUSE_CODE: /* these should be handled by the code in channel.c */
07882    case -1:
07883       res = -1;
07884       break;
07885    default:
07886       ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
07887       res = -1;
07888       break;
07889    }
07890    sip_pvt_unlock(p);
07891    return res;
07892 }
07893 
07894 /*!
07895  * \brief Initiate a call in the SIP channel
07896  *
07897  * \note called from sip_request_call (calls from the pbx ) for
07898  * outbound channels and from handle_request_invite for inbound
07899  * channels
07900  *
07901  * \pre i is locked
07902  *
07903  * \return New ast_channel locked.
07904  */
07905 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title, const char *linkedid, struct ast_callid *callid)
07906 {
07907    struct ast_channel *tmp;
07908    struct ast_variable *v = NULL;
07909    struct ast_format fmt;
07910    struct ast_format_cap *what = NULL; /* SHALLOW COPY DO NOT DESTROY! */
07911    int needvideo = 0;
07912    int needtext = 0;
07913    char buf[SIPBUFSIZE];
07914    char *exten;
07915 
07916    {
07917       const char *my_name; /* pick a good name */
07918    
07919       if (title) {
07920          my_name = title;
07921       } else {
07922          my_name = ast_strdupa(i->fromdomain);
07923       }
07924 
07925       sip_pvt_unlock(i);
07926       /* Don't hold a sip pvt lock while we allocate a channel */
07927       tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, i->accountcode, i->exten, i->context, linkedid, i->amaflags, "SIP/%s-%08x", my_name, (unsigned)ast_atomic_fetchadd_int((int *)&chan_idx, +1));
07928    }
07929    if (!tmp) {
07930       ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
07931       sip_pvt_lock(i);
07932       return NULL;
07933    }
07934 
07935    /* If we sent in a callid, bind it to the channel. */
07936    if (callid) {
07937       ast_channel_callid_set(tmp, callid);
07938    }
07939 
07940    ast_channel_lock(tmp);
07941    sip_pvt_lock(i);
07942    ast_channel_cc_params_init(tmp, i->cc_params);
07943    ast_channel_caller(tmp)->id.tag = ast_strdup(i->cid_tag);
07944 
07945    ast_channel_tech_set(tmp, (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INFO || ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO) ? &sip_tech_info : &sip_tech);
07946 
07947    /* Select our native format based on codec preference until we receive
07948       something from another device to the contrary. */
07949    if (!(ast_format_cap_is_empty(i->jointcaps))) { /* The joint capabilities of us and peer */
07950       what = i->jointcaps;
07951    } else if (!(ast_format_cap_is_empty(i->caps))) {     /* Our configured capability for this peer */
07952       what = i->caps;
07953    } else {
07954       what = sip_cfg.caps;
07955    }
07956 
07957    /* Set the native formats */
07958    ast_format_cap_copy(ast_channel_nativeformats(tmp), what);
07959    /* choose and use only the best audio format for our native formats */
07960    ast_codec_choose(&i->prefs, ast_channel_nativeformats(tmp), 1, &fmt); /* get the best audio format */
07961    ast_format_cap_remove_bytype(ast_channel_nativeformats(tmp), AST_FORMAT_TYPE_AUDIO); /* remove only the other audio formats */
07962    ast_format_cap_add(ast_channel_nativeformats(tmp), &fmt); /* add our best choice back */
07963 
07964    ast_debug(3, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, ast_channel_nativeformats(tmp)));
07965    ast_debug(3, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->jointcaps));
07966    ast_debug(3, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->caps));
07967    ast_debug(3, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname(&fmt));
07968    if (!ast_format_cap_is_empty(i->prefcaps)) {
07969       ast_debug(3, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->prefcaps));
07970    }
07971 
07972    /* If we have a prefcodec setting, we have an inbound channel that set a
07973       preferred format for this call. Otherwise, we check the jointcapability
07974       We also check for vrtp. If it's not there, we are not allowed do any video anyway.
07975     */
07976    if (i->vrtp) {
07977       if (ast_test_flag(&i->flags[1], SIP_PAGE2_VIDEOSUPPORT))
07978          needvideo = 1;
07979       else if (!ast_format_cap_is_empty(i->prefcaps))
07980          needvideo = ast_format_cap_has_type(i->prefcaps, AST_FORMAT_TYPE_VIDEO);   /* Outbound call */
07981       else
07982          needvideo = ast_format_cap_has_type(i->jointcaps, AST_FORMAT_TYPE_VIDEO);  /* Inbound call */
07983    }
07984 
07985    if (i->trtp) {
07986       if (!ast_format_cap_is_empty(i->prefcaps))
07987          needtext = ast_format_cap_has_type(i->prefcaps, AST_FORMAT_TYPE_TEXT);  /* Outbound call */
07988       else
07989          needtext = ast_format_cap_has_type(i->jointcaps, AST_FORMAT_TYPE_TEXT); /* Inbound call */
07990    }
07991 
07992    if (needvideo) {
07993       ast_debug(3, "This channel can handle video! HOLLYWOOD next!\n");
07994    } else {
07995       ast_debug(3, "This channel will not be able to handle video.\n");
07996    }
07997 
07998    enable_dsp_detect(i);
07999 
08000    if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
08001        (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
08002       if (i->rtp) {
08003          ast_rtp_instance_dtmf_mode_set(i->rtp, AST_RTP_DTMF_MODE_INBAND);
08004       }
08005    } else if (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) {
08006       if (i->rtp) {
08007          ast_rtp_instance_dtmf_mode_set(i->rtp, AST_RTP_DTMF_MODE_RFC2833);
08008       }
08009    }
08010 
08011    /* Set file descriptors for audio, video, and realtime text.  Since
08012     * UDPTL is created as needed in the lifetime of a dialog, its file
08013     * descriptor is set in initialize_udptl */
08014    if (i->rtp) {
08015       ast_channel_set_fd(tmp, 0, ast_rtp_instance_fd(i->rtp, 0));
08016       ast_channel_set_fd(tmp, 1, ast_rtp_instance_fd(i->rtp, 1));
08017       ast_rtp_instance_set_write_format(i->rtp, &fmt);
08018       ast_rtp_instance_set_read_format(i->rtp, &fmt);
08019    }
08020    if (needvideo && i->vrtp) {
08021       ast_channel_set_fd(tmp, 2, ast_rtp_instance_fd(i->vrtp, 0));
08022       ast_channel_set_fd(tmp, 3, ast_rtp_instance_fd(i->vrtp, 1));
08023    }
08024    if (needtext && i->trtp) {
08025       ast_channel_set_fd(tmp, 4, ast_rtp_instance_fd(i->trtp, 0));
08026    }
08027    if (i->udptl) {
08028       ast_channel_set_fd(tmp, 5, ast_udptl_fd(i->udptl));
08029    }
08030 
08031    if (state == AST_STATE_RING) {
08032       ast_channel_rings_set(tmp, 1);
08033    }
08034    ast_channel_adsicpe_set(tmp, AST_ADSI_UNAVAILABLE);
08035 
08036    ast_format_copy(ast_channel_writeformat(tmp), &fmt);
08037    ast_format_copy(ast_channel_rawwriteformat(tmp), &fmt);
08038 
08039    ast_format_copy(ast_channel_readformat(tmp), &fmt);
08040    ast_format_copy(ast_channel_rawreadformat(tmp), &fmt);
08041 
08042    ast_channel_tech_pvt_set(tmp, dialog_ref(i, "sip_new: set chan->tech_pvt to i"));
08043 
08044    ast_channel_callgroup_set(tmp, i->callgroup);
08045    ast_channel_pickupgroup_set(tmp, i->pickupgroup);
08046 
08047    ast_channel_named_callgroups_set(tmp, i->named_callgroups);
08048    ast_channel_named_pickupgroups_set(tmp, i->named_pickupgroups);
08049 
08050    ast_channel_caller(tmp)->id.name.presentation = i->callingpres;
08051    ast_channel_caller(tmp)->id.number.presentation = i->callingpres;
08052    if (!ast_strlen_zero(i->parkinglot)) {
08053       ast_channel_parkinglot_set(tmp, i->parkinglot);
08054    }
08055    if (!ast_strlen_zero(i->accountcode)) {
08056       ast_channel_accountcode_set(tmp, i->accountcode);
08057    }
08058    if (i->amaflags) {
08059       ast_channel_amaflags_set(tmp, i->amaflags);
08060    }
08061    if (!ast_strlen_zero(i->language)) {
08062       ast_channel_language_set(tmp, i->language);
08063    }
08064    if (!ast_strlen_zero(i->zone)) {
08065       struct ast_tone_zone *zone;
08066       if (!(zone = ast_get_indication_zone(i->zone))) {
08067          ast_log(LOG_ERROR, "Unknown country code '%s' for tonezone. Check indications.conf for available country codes.\n", i->zone);
08068       } 
08069       ast_channel_zone_set(tmp, zone);
08070    }
08071    i->owner = tmp;
08072    ast_module_ref(ast_module_info->self);
08073    ast_channel_context_set(tmp, i->context);
08074    /*Since it is valid to have extensions in the dialplan that have unescaped characters in them
08075     * we should decode the uri before storing it in the channel, but leave it encoded in the sip_pvt
08076     * structure so that there aren't issues when forming URI's
08077     */
08078    exten = ast_strdupa(i->exten);
08079    sip_pvt_unlock(i);
08080    ast_channel_unlock(tmp);
08081    if (!ast_exists_extension(NULL, i->context, i->exten, 1, i->cid_num)) {
08082       ast_uri_decode(exten, ast_uri_sip_user);
08083    }
08084    ast_channel_lock(tmp);
08085    sip_pvt_lock(i);
08086    ast_channel_exten_set(tmp, exten);
08087 
08088    /* Don't use ast_set_callerid() here because it will
08089     * generate an unnecessary NewCallerID event  */
08090    if (!ast_strlen_zero(i->cid_num)) {
08091       ast_channel_caller(tmp)->ani.number.valid = 1;
08092       ast_channel_caller(tmp)->ani.number.str = ast_strdup(i->cid_num);
08093    }
08094    if (!ast_strlen_zero(i->rdnis)) {
08095       ast_channel_redirecting(tmp)->from.number.valid = 1;
08096       ast_channel_redirecting(tmp)->from.number.str = ast_strdup(i->rdnis);
08097    }
08098 
08099    if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s")) {
08100       ast_channel_dialed(tmp)->number.str = ast_strdup(i->exten);
08101    }
08102 
08103    ast_channel_priority_set(tmp, 1);
08104    if (!ast_strlen_zero(i->uri)) {
08105       pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
08106    }
08107    if (!ast_strlen_zero(i->domain)) {
08108       pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
08109    }
08110    if (!ast_strlen_zero(i->callid)) {
08111       pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
08112    }
08113    if (i->rtp) {
08114       ast_jb_configure(tmp, &global_jbconf);
08115    }
08116 
08117    if (!i->relatedpeer) {
08118       ast_set_flag(ast_channel_flags(tmp), AST_FLAG_DISABLE_DEVSTATE_CACHE);
08119    }
08120    /* Set channel variables for this call from configuration */
08121    for (v = i->chanvars ; v ; v = v->next) {
08122       char valuebuf[1024];
08123       pbx_builtin_setvar_helper(tmp, v->name, ast_get_encoded_str(v->value, valuebuf, sizeof(valuebuf)));
08124    }
08125 
08126    if (i->do_history) {
08127       append_history(i, "NewChan", "Channel %s - from %s", ast_channel_name(tmp), i->callid);
08128    }
08129 
08130    /* Inform manager user about new channel and their SIP call ID */
08131    if (sip_cfg.callevents) {
08132       manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
08133          "Channel: %s\r\nUniqueid: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\n",
08134          ast_channel_name(tmp), ast_channel_uniqueid(tmp), "SIP", i->callid, i->fullcontact);
08135    }
08136 
08137    return tmp;
08138 }
08139 
08140 /*! \brief Lookup 'name' in the SDP starting
08141  * at the 'start' line. Returns the matching line, and 'start'
08142  * is updated with the next line number.
08143  */
08144 static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
08145 {
08146    int len = strlen(name);
08147    const char *line;
08148 
08149    while (*start < (req->sdp_start + req->sdp_count)) {
08150       line = REQ_OFFSET_TO_STR(req, line[(*start)++]);
08151       if (!strncasecmp(line, name, len) && line[len] == '=') {
08152          return ast_skip_blanks(line + len + 1);
08153       }
08154    }
08155 
08156    /* if the line was not found, ensure that *start points past the SDP */
08157    (*start)++;
08158 
08159    return "";
08160 }
08161 
08162 /*! \brief Fetches the next valid SDP line between the 'start' line
08163  * (inclusive) and the 'stop' line (exclusive). Returns the type
08164  * ('a', 'c', ...) and matching line in reference 'start' is updated
08165  * with the next line number.
08166  */
08167 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value)
08168 {
08169    char type = '\0';
08170    const char *line = NULL;
08171 
08172    if (stop > (req->sdp_start + req->sdp_count)) {
08173       stop = req->sdp_start + req->sdp_count;
08174    }
08175 
08176    while (*start < stop) {
08177       line = REQ_OFFSET_TO_STR(req, line[(*start)++]);
08178       if (line[1] == '=') {
08179          type = line[0];
08180          *value = ast_skip_blanks(line + 2);
08181          break;
08182       }
08183    }
08184 
08185    return type;
08186 }
08187 
08188 /*! \brief Get a specific line from the message content */
08189 static char *get_content_line(struct sip_request *req, char *name, char delimiter)
08190 {
08191    int i;
08192    int len = strlen(name);
08193    const char *line;
08194 
08195    for (i = 0; i < req->lines; i++) {
08196       line = REQ_OFFSET_TO_STR(req, line[i]);
08197       if (!strncasecmp(line, name, len) && line[len] == delimiter) {
08198          return ast_skip_blanks(line + len + 1);
08199       }
08200    }
08201 
08202    return "";
08203 }
08204 
08205 /*! \brief Structure for conversion between compressed SIP and "normal" SIP headers */
08206 struct cfalias {
08207    const char *fullname;
08208    const char *shortname;
08209 };
08210 static const struct cfalias aliases[] = {
08211    { "Content-Type",           "c" },
08212    { "Content-Encoding",       "e" },
08213    { "From",                   "f" },
08214    { "Call-ID",                "i" },
08215    { "Contact",                "m" },
08216    { "Content-Length",         "l" },
08217    { "Subject",                "s" },
08218    { "To",                     "t" },
08219    { "Supported",              "k" },
08220    { "Refer-To",               "r" },
08221    { "Referred-By",            "b" },
08222    { "Allow-Events",           "u" },
08223    { "Event",                  "o" },
08224    { "Via",                    "v" },
08225    { "Accept-Contact",         "a" },
08226    { "Reject-Contact",         "j" },
08227    { "Request-Disposition",    "d" },
08228    { "Session-Expires",        "x" },
08229    { "Identity",               "y" },
08230    { "Identity-Info",          "n" },
08231 };
08232 
08233 /*! \brief Find compressed SIP alias */
08234 static const char *find_alias(const char *name, const char *_default)
08235 {
08236    int x;
08237 
08238    for (x = 0; x < ARRAY_LEN(aliases); x++) {
08239       if (!strcasecmp(aliases[x].fullname, name))
08240          return aliases[x].shortname;
08241    }
08242 
08243    return _default;
08244 }
08245 
08246 /*! \brief Find full SIP alias */
08247 static const char *find_full_alias(const char *name, const char *_default)
08248 {
08249    int x;
08250 
08251    if (strlen(name) == 1) {
08252       /* We have a short header name to convert. */
08253       for (x = 0; x < ARRAY_LEN(aliases); ++x) {
08254          if (!strcasecmp(aliases[x].shortname, name))
08255             return aliases[x].fullname;
08256       }
08257    }
08258 
08259    return _default;
08260 }
08261 
08262 static const char *__get_header(const struct sip_request *req, const char *name, int *start)
08263 {
08264    /*
08265     * Technically you can place arbitrary whitespace both before and after the ':' in
08266     * a header, although RFC3261 clearly says you shouldn't before, and place just
08267     * one afterwards.  If you shouldn't do it, what absolute idiot decided it was
08268     * a good idea to say you can do it, and if you can do it, why in the hell would.
08269     * you say you shouldn't.
08270     * Anyways, pedanticsipchecking controls whether we allow spaces before ':',
08271     * and we always allow spaces after that for compatibility.
08272     */
08273    const char *sname = find_alias(name, NULL);
08274    int x, len = strlen(name), slen = (sname ? 1 : 0);
08275    for (x = *start; x < req->headers; x++) {
08276       const char *header = REQ_OFFSET_TO_STR(req, header[x]);
08277       int smatch = 0, match = !strncasecmp(header, name, len);
08278       if (slen) {
08279          smatch = !strncasecmp(header, sname, slen);
08280       }
08281       if (match || smatch) {
08282          /* skip name */
08283          const char *r = header + (match ? len : slen );
08284          if (sip_cfg.pedanticsipchecking) {
08285             r = ast_skip_blanks(r);
08286          }
08287 
08288          if (*r == ':') {
08289             *start = x+1;
08290             return ast_skip_blanks(r+1);
08291          }
08292       }
08293    }
08294 
08295    /* Don't return NULL, so sip_get_header is always a valid pointer */
08296    return "";
08297 }
08298 
08299 /*! \brief Get header from SIP request
08300    \return Always return something, so don't check for NULL because it won't happen :-)
08301 */
08302 const char *sip_get_header(const struct sip_request *req, const char *name)
08303 {
08304    int start = 0;
08305    return __get_header(req, name, &start);
08306 }
08307 
08308 
08309 AST_THREADSTORAGE(sip_content_buf);
08310 
08311 /*! \brief Get message body content */
08312 static char *get_content(struct sip_request *req)
08313 {
08314    struct ast_str *str;
08315    int i;
08316 
08317    if (!(str = ast_str_thread_get(&sip_content_buf, 128))) {
08318       return NULL;
08319    }
08320 
08321    ast_str_reset(str);
08322 
08323    for (i = 0; i < req->lines; i++) {
08324       if (ast_str_append(&str, 0, "%s\n", REQ_OFFSET_TO_STR(req, line[i])) < 0) {
08325          return NULL;
08326       }
08327    }
08328 
08329    return ast_str_buffer(str);
08330 }
08331 
08332 /*! \brief Read RTP from network */
08333 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
08334 {
08335    /* Retrieve audio/etc from channel.  Assumes p->lock is already held. */
08336    struct ast_frame *f;
08337    
08338    if (!p->rtp) {
08339       /* We have no RTP allocated for this channel */
08340       return &ast_null_frame;
08341    }
08342 
08343    switch(ast_channel_fdno(ast)) {
08344    case 0:
08345       f = ast_rtp_instance_read(p->rtp, 0);  /* RTP Audio */
08346       break;
08347    case 1:
08348       f = ast_rtp_instance_read(p->rtp, 1);  /* RTCP Control Channel */
08349       break;
08350    case 2:
08351       f = ast_rtp_instance_read(p->vrtp, 0); /* RTP Video */
08352       break;
08353    case 3:
08354       f = ast_rtp_instance_read(p->vrtp, 1); /* RTCP Control Channel for video */
08355       break;
08356    case 4:
08357       f = ast_rtp_instance_read(p->trtp, 0); /* RTP Text */
08358       if (sipdebug_text) {
08359          struct ast_str *out = ast_str_create(f->datalen * 4 + 6);
08360          int i;
08361          unsigned char* arr = f->data.ptr;
08362          do {
08363             if (!out) {
08364                break;
08365             }
08366             for (i = 0; i < f->datalen; i++) {
08367                ast_str_append(&out, 0, "%c", (arr[i] > ' ' && arr[i] < '}') ? arr[i] : '.');
08368             }
08369             ast_str_append(&out, 0, " -> ");
08370             for (i = 0; i < f->datalen; i++) {
08371                ast_str_append(&out, 0, "%02X ", (unsigned)arr[i]);
08372             }
08373             ast_verb(0, "%s\n", ast_str_buffer(out));
08374             ast_free(out);
08375          } while (0);
08376       }
08377       break;
08378    case 5:
08379       f = ast_udptl_read(p->udptl); /* UDPTL for T.38 */
08380       break;
08381    default:
08382       f = &ast_null_frame;
08383    }
08384    /* Don't forward RFC2833 if we're not supposed to */
08385    if (f && (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) &&
08386        (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833)) {
08387       ast_debug(1, "Ignoring DTMF (%c) RTP frame because dtmfmode is not RFC2833\n", f->subclass.integer);
08388       ast_frfree(f);
08389       return &ast_null_frame;
08390    }
08391 
08392    /* We already hold the channel lock */
08393    if (!p->owner || (f && f->frametype != AST_FRAME_VOICE)) {
08394       return f;
08395    }
08396 
08397    if (f && !ast_format_cap_iscompatible(ast_channel_nativeformats(p->owner), &f->subclass.format)) {
08398       if (!ast_format_cap_iscompatible(p->jointcaps, &f->subclass.format)) {
08399          ast_debug(1, "Bogus frame of format '%s' received from '%s'!\n",
08400             ast_getformatname(&f->subclass.format), ast_channel_name(p->owner));
08401          ast_frfree(f);
08402          return &ast_null_frame;
08403       }
08404       ast_debug(1, "Oooh, format changed to %s\n",
08405          ast_getformatname(&f->subclass.format));
08406       ast_format_cap_remove_bytype(ast_channel_nativeformats(p->owner), AST_FORMAT_TYPE_AUDIO);
08407       ast_format_cap_add(ast_channel_nativeformats(p->owner), &f->subclass.format);
08408       ast_set_read_format(p->owner, ast_channel_readformat(p->owner));
08409       ast_set_write_format(p->owner, ast_channel_writeformat(p->owner));
08410    }
08411 
08412    if (f && p->dsp) {
08413       f = ast_dsp_process(p->owner, p->dsp, f);
08414       if (f && f->frametype == AST_FRAME_DTMF) {
08415          if (f->subclass.integer == 'f') {
08416             ast_debug(1, "Fax CNG detected on %s\n", ast_channel_name(ast));
08417             *faxdetect = 1;
08418             /* If we only needed this DSP for fax detection purposes we can just drop it now */
08419             if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
08420                ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
08421             } else {
08422                ast_dsp_free(p->dsp);
08423                p->dsp = NULL;
08424             }
08425          } else {
08426             ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass.integer);
08427          }
08428       }
08429    }
08430 
08431    return f;
08432 }
08433 
08434 /*! \brief Read SIP RTP from channel */
08435 static struct ast_frame *sip_read(struct ast_channel *ast)
08436 {
08437    struct ast_frame *fr;
08438    struct sip_pvt *p = ast_channel_tech_pvt(ast);
08439    int faxdetected = FALSE;
08440 
08441    sip_pvt_lock(p);
08442    fr = sip_rtp_read(ast, p, &faxdetected);
08443    p->lastrtprx = time(NULL);
08444 
08445    /* If we detect a CNG tone and fax detection is enabled then send us off to the fax extension */
08446    if (faxdetected && ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
08447       if (strcmp(ast_channel_exten(ast), "fax")) {
08448          const char *target_context = S_OR(ast_channel_macrocontext(ast), ast_channel_context(ast));
08449          /* We need to unlock 'ast' here because
08450           * ast_exists_extension has the potential to start and
08451           * stop an autoservice on the channel. Such action is
08452           * prone to deadlock if the channel is locked.
08453           */
08454          sip_pvt_unlock(p);
08455          ast_channel_unlock(ast);
08456          if (ast_exists_extension(ast, target_context, "fax", 1,
08457             S_COR(ast_channel_caller(ast)->id.number.valid, ast_channel_caller(ast)->id.number.str, NULL))) {
08458             ast_channel_lock(ast);
08459             sip_pvt_lock(p);
08460             ast_verb(2, "Redirecting '%s' to fax extension due to CNG detection\n", ast_channel_name(ast));
08461             pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast_channel_exten(ast));
08462             if (ast_async_goto(ast, target_context, "fax", 1)) {
08463                ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast_channel_name(ast), target_context);
08464             }
08465             ast_frfree(fr);
08466             fr = &ast_null_frame;
08467          } else {
08468             ast_channel_lock(ast);
08469             sip_pvt_lock(p);
08470             ast_log(LOG_NOTICE, "FAX CNG detected but no fax extension\n");
08471          }
08472       }
08473    }
08474 
08475    /* Only allow audio through if they sent progress with SDP, or if the channel is actually answered */
08476    if (fr && fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast_channel_state(ast) != AST_STATE_UP) {
08477       ast_frfree(fr);
08478       fr = &ast_null_frame;
08479    }
08480 
08481    sip_pvt_unlock(p);
08482 
08483    return fr;
08484 }
08485 
08486 
08487 /*! \brief Generate 32 byte random string for callid's etc */
08488 static char *generate_random_string(char *buf, size_t size)
08489 {
08490    long val[4];
08491    int x;
08492 
08493    for (x=0; x<4; x++)
08494       val[x] = ast_random();
08495    snprintf(buf, size, "%08lx%08lx%08lx%08lx", (unsigned long)val[0], (unsigned long)val[1], (unsigned long)val[2], (unsigned long)val[3]);
08496 
08497    return buf;
08498 }
08499 
08500 static char *generate_uri(struct sip_pvt *pvt, char *buf, size_t size)
08501 {
08502    struct ast_str *uri = ast_str_alloca(size);
08503    ast_str_set(&uri, 0, "%s", pvt->socket.type == SIP_TRANSPORT_TLS ? "sips:" : "sip:");
08504    /* Here would be a great place to generate a UUID, but for now we'll
08505     * use the handy random string generation function we already have
08506     */
08507    ast_str_append(&uri, 0, "%s", generate_random_string(buf, size));
08508    ast_str_append(&uri, 0, "@%s", ast_sockaddr_stringify_remote(&pvt->ourip));
08509    ast_copy_string(buf, ast_str_buffer(uri), size);
08510    return buf;
08511 }
08512 
08513 /*!
08514  * \brief Build SIP Call-ID value for a non-REGISTER transaction
08515  *
08516  * \note The passed in pvt must not be in a dialogs container
08517  * since this function changes the hash key used by the
08518  * container.
08519  */
08520 static void build_callid_pvt(struct sip_pvt *pvt)
08521 {
08522    char buf[33];
08523    const char *host = S_OR(pvt->fromdomain, ast_sockaddr_stringify_remote(&pvt->ourip));
08524 
08525    ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
08526 }
08527 
08528 /*! \brief Unlink the given object from the container and return TRUE if it was in the container. */
08529 #define CONTAINER_UNLINK(container, obj, tag)                        \
08530    ({                                                    \
08531       int found = 0;                                        \
08532       typeof((obj)) __removed_obj;                             \
08533       __removed_obj = ao2_t_callback((container),                    \
08534          OBJ_UNLINK | OBJ_POINTER, ao2_match_by_addr, (obj), (tag));    \
08535       if (__removed_obj) {                                  \
08536          ao2_ref(__removed_obj, -1);                              \
08537          found = 1;                                         \
08538       }                                                  \
08539       found;                                                \
08540    })
08541 
08542 /*!
08543  * \internal
08544  * \brief Safely change the callid of the given SIP dialog.
08545  *
08546  * \param pvt SIP private structure to change callid
08547  * \param callid Specified new callid to use.  NULL if generate new callid.
08548  *
08549  * \return Nothing
08550  */
08551 static void change_callid_pvt(struct sip_pvt *pvt, const char *callid)
08552 {
08553    int in_dialog_container;
08554    int in_rtp_container;
08555    char *oldid = ast_strdupa(pvt->callid);
08556 
08557    ao2_lock(dialogs);
08558    ao2_lock(dialogs_rtpcheck);
08559    in_dialog_container = CONTAINER_UNLINK(dialogs, pvt,
08560       "About to change the callid -- remove the old name");
08561    in_rtp_container = CONTAINER_UNLINK(dialogs_rtpcheck, pvt,
08562       "About to change the callid -- remove the old name");
08563    if (callid) {
08564       ast_string_field_set(pvt, callid, callid);
08565    } else {
08566       build_callid_pvt(pvt);
08567    }
08568    if (in_dialog_container) {
08569       ao2_t_link(dialogs, pvt, "New dialog callid -- inserted back into table");
08570    }
08571    if (in_rtp_container) {
08572       ao2_t_link(dialogs_rtpcheck, pvt, "New dialog callid -- inserted back into table");
08573    }
08574    ao2_unlock(dialogs_rtpcheck);
08575    ao2_unlock(dialogs);
08576 
08577    if (strcmp(oldid, pvt->callid)) {
08578       ast_debug(1, "SIP call-id changed from '%s' to '%s'\n", oldid, pvt->callid);
08579    }
08580 }
08581 
08582 /*! \brief Build SIP Call-ID value for a REGISTER transaction */
08583 static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain)
08584 {
08585    char buf[33];
08586 
08587    const char *host = S_OR(fromdomain, ast_sockaddr_stringify_host_remote(ourip));
08588 
08589    ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
08590 }
08591 
08592 /*! \brief Build SIP From tag value for REGISTER */
08593 static void build_localtag_registry(struct sip_registry *reg)
08594 {
08595    ast_string_field_build(reg, localtag, "as%08lx", (unsigned long)ast_random());
08596 }
08597 
08598 /*! \brief Make our SIP dialog tag */
08599 static void make_our_tag(struct sip_pvt *pvt)
08600 {
08601    ast_string_field_build(pvt, tag, "as%08lx", (unsigned long)ast_random());
08602 }
08603 
08604 /*! \brief Allocate Session-Timers struct w/in dialog */
08605 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p)
08606 {
08607    struct sip_st_dlg *stp;
08608 
08609    if (p->stimer) {
08610       ast_log(LOG_ERROR, "Session-Timer struct already allocated\n");
08611       return p->stimer;
08612    }
08613 
08614    if (!(stp = ast_calloc(1, sizeof(struct sip_st_dlg))))
08615       return NULL;
08616 
08617    p->stimer = stp;
08618 
08619    stp->st_schedid = -1;           /* Session-Timers ast_sched scheduler id */
08620 
08621    return p->stimer;
08622 }
08623 
08624 static void sip_pvt_callid_set(struct sip_pvt *pvt, struct ast_callid *callid)
08625 {
08626    if (pvt->logger_callid) {
08627       ast_callid_unref(pvt->logger_callid);
08628    }
08629    ast_callid_ref(callid);
08630    pvt->logger_callid = callid;
08631 }
08632 
08633 /*! \brief Allocate sip_pvt structure, set defaults and link in the container.
08634  * Returns a reference to the object so whoever uses it later must
08635  * remember to release the reference.
08636  */
08637 struct sip_pvt *sip_alloc(ast_string_field callid, struct ast_sockaddr *addr,
08638              int useglobal_nat, const int intended_method, struct sip_request *req, struct ast_callid *logger_callid)
08639 {
08640    struct sip_pvt *p;
08641 
08642    if (!(p = ao2_t_alloc(sizeof(*p), sip_destroy_fn, "allocate a dialog(pvt) struct")))
08643       return NULL;
08644 
08645    if (ast_string_field_init(p, 512)) {
08646       ao2_t_ref(p, -1, "failed to string_field_init, drop p");
08647       return NULL;
08648    }
08649 
08650    if (!(p->cc_params = ast_cc_config_params_init())) {
08651       ao2_t_ref(p, -1, "Yuck, couldn't allocate cc_params struct. Get rid o' p");
08652       return NULL;
08653    }
08654 
08655    if (logger_callid) {
08656       sip_pvt_callid_set(p, logger_callid);
08657    }
08658 
08659    p->caps = ast_format_cap_alloc_nolock();
08660    p->jointcaps = ast_format_cap_alloc_nolock();
08661    p->peercaps = ast_format_cap_alloc_nolock();
08662    p->redircaps = ast_format_cap_alloc_nolock();
08663    p->prefcaps = ast_format_cap_alloc_nolock();
08664 
08665    if (!p->caps|| !p->jointcaps || !p->peercaps || !p->redircaps) {
08666       p->caps = ast_format_cap_destroy(p->caps);
08667       p->jointcaps = ast_format_cap_destroy(p->jointcaps);
08668       p->peercaps = ast_format_cap_destroy(p->peercaps);
08669       p->redircaps = ast_format_cap_destroy(p->redircaps);
08670       p->prefcaps = ast_format_cap_destroy(p->prefcaps);
08671       ao2_t_ref(p, -1, "Yuck, couldn't allocate format capabilities. Get rid o' p");
08672       return NULL;
08673    }
08674 
08675 
08676    /* If this dialog is created as a result of a request or response, lets store
08677     * some information about it in the dialog. */
08678    if (req) {
08679       struct sip_via *via;
08680       const char *cseq = sip_get_header(req, "Cseq");
08681       uint32_t seqno;
08682 
08683       /* get branch parameter from initial Request that started this dialog */
08684       via = parse_via(sip_get_header(req, "Via"));
08685       if (via) {
08686          /* only store the branch if it begins with the magic prefix "z9hG4bK", otherwise
08687           * it is not useful to us to have it */
08688          if (!ast_strlen_zero(via->branch) && !strncasecmp(via->branch, "z9hG4bK", 7)) {
08689             ast_string_field_set(p, initviabranch, via->branch);
08690             ast_string_field_set(p, initviasentby, via->sent_by);
08691          }
08692          free_via(via);
08693       }
08694 
08695       /* Store initial incoming cseq. An error in sscanf here is ignored.  There is no approperiate
08696        * except not storing the number.  CSeq validation must take place before dialog creation in find_call */
08697       if (!ast_strlen_zero(cseq) && (sscanf(cseq, "%30u", &seqno) == 1)) {
08698          p->init_icseq = seqno;
08699       }
08700       /* Later in ast_sip_ouraddrfor we need this to choose the right ip and port for the specific transport */
08701       set_socket_transport(&p->socket, req->socket.type);
08702    } else {
08703       set_socket_transport(&p->socket, SIP_TRANSPORT_UDP);
08704    }
08705 
08706    p->socket.fd = -1;
08707    p->method = intended_method;
08708    p->initid = -1;
08709    p->waitid = -1;
08710    p->reinviteid = -1;
08711    p->autokillid = -1;
08712    p->request_queue_sched_id = -1;
08713    p->provisional_keepalive_sched_id = -1;
08714    p->t38id = -1;
08715    p->subscribed = NONE;
08716    p->stateid = -1;
08717    p->sessionversion_remote = -1;
08718    p->session_modify = TRUE;
08719    p->stimer = NULL;
08720    p->prefs = default_prefs;     /* Set default codecs for this call */
08721    ast_copy_string(p->zone, default_zone, sizeof(p->zone));
08722    p->maxforwards = sip_cfg.default_max_forwards;
08723 
08724    if (intended_method != SIP_OPTIONS) {  /* Peerpoke has it's own system */
08725       p->timer_t1 = global_t1;   /* Default SIP retransmission timer T1 (RFC 3261) */
08726       p->timer_b = global_timer_b;  /* Default SIP transaction timer B (RFC 3261) */
08727    }
08728 
08729    if (!addr) {
08730       p->ourip = internip;
08731    } else {
08732       ast_sockaddr_copy(&p->sa, addr);
08733       ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
08734    }
08735 
08736    /* Copy global flags to this PVT at setup. */
08737    ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
08738    ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
08739    ast_copy_flags(&p->flags[2], &global_flags[2], SIP_PAGE3_FLAGS_TO_COPY);
08740 
08741    p->do_history = recordhistory;
08742 
08743    p->branch = ast_random();  
08744    make_our_tag(p);
08745    p->ocseq = INITIAL_CSEQ;
08746    p->allowed_methods = UINT_MAX;
08747 
08748    if (sip_methods[intended_method].need_rtp) {
08749       p->maxcallbitrate = default_maxcallbitrate;
08750       p->autoframing = global_autoframing;
08751    }
08752 
08753    if (useglobal_nat && addr) {
08754       /* Setup NAT structure according to global settings if we have an address */
08755       ast_sockaddr_copy(&p->recv, addr);
08756       check_via(p, req);
08757       do_setnat(p);
08758    }
08759 
08760    if (p->method != SIP_REGISTER) {
08761       ast_string_field_set(p, fromdomain, default_fromdomain);
08762       p->fromdomainport = default_fromdomainport;
08763    }
08764    build_via(p);
08765    if (!callid)
08766       build_callid_pvt(p);
08767    else
08768       ast_string_field_set(p, callid, callid);
08769    /* Assign default music on hold class */
08770    ast_string_field_set(p, mohinterpret, default_mohinterpret);
08771    ast_string_field_set(p, mohsuggest, default_mohsuggest);
08772    ast_format_cap_copy(p->caps, sip_cfg.caps);
08773    p->allowtransfer = sip_cfg.allowtransfer;
08774    if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
08775        (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
08776       p->noncodeccapability |= AST_RTP_DTMF;
08777    }
08778    ast_string_field_set(p, context, sip_cfg.default_context);
08779    ast_string_field_set(p, parkinglot, default_parkinglot);
08780    ast_string_field_set(p, engine, default_engine);
08781 
08782    AST_LIST_HEAD_INIT_NOLOCK(&p->request_queue);
08783    AST_LIST_HEAD_INIT_NOLOCK(&p->offered_media);
08784 
08785    /* Add to active dialog list */
08786 
08787    ao2_t_link(dialogs, p, "link pvt into dialogs table");
08788 
08789    ast_debug(1, "Allocating new SIP dialog for %s - %s (%s)\n", callid ? callid : p->callid, sip_methods[intended_method].text, p->rtp ? "With RTP" : "No RTP");
08790    return p;
08791 }
08792 
08793 /*!
08794  * \brief Process the Via header according to RFC 3261 section 18.2.2.
08795  * \param p a sip_pvt structure that will be modified according to the received
08796  * header
08797  * \param req a sip request with a Via header to process
08798  *
08799  * This function will update the destination of the response according to the
08800  * Via header in the request and RFC 3261 section 18.2.2. We do not have a
08801  * transport layer so we ignore certain values like the 'received' param (we
08802  * set the destination address to the addres the request came from in the
08803  * respprep() function).
08804  *
08805  * \retval -1 error
08806  * \retval 0 success
08807  */
08808 static int process_via(struct sip_pvt *p, const struct sip_request *req)
08809 {
08810    struct sip_via *via = parse_via(sip_get_header(req, "Via"));
08811 
08812    if (!via) {
08813       ast_log(LOG_ERROR, "error processing via header\n");
08814       return -1;
08815    }
08816 
08817    if (via->maddr) {
08818       if (ast_sockaddr_resolve_first_transport(&p->sa, via->maddr, PARSE_PORT_FORBID, p->socket.type)) {
08819          ast_log(LOG_WARNING, "Can't find address for maddr '%s'\n", via->maddr);
08820          ast_log(LOG_ERROR, "error processing via header\n");
08821          free_via(via);
08822          return -1;
08823       }
08824 
08825       if (ast_sockaddr_is_ipv4_multicast(&p->sa)) {
08826          setsockopt(sipsock, IPPROTO_IP, IP_MULTICAST_TTL, &via->ttl, sizeof(via->ttl));
08827       }
08828    }
08829 
08830    ast_sockaddr_set_port(&p->sa, via->port ? via->port : STANDARD_SIP_PORT);
08831 
08832    free_via(via);
08833    return 0;
08834 }
08835 
08836 /* \brief arguments used for Request/Response to matching */
08837 struct match_req_args {
08838    int method;
08839    const char *callid;
08840    const char *totag;
08841    const char *fromtag;
08842    uint32_t seqno;
08843 
08844    /* Set if this method is a Response */
08845    int respid;
08846 
08847    /* Set if the method is a Request */
08848    const char *ruri;
08849    const char *viabranch;
08850    const char *viasentby;
08851 
08852    /* Set this if the Authentication header is present in the Request. */
08853    int authentication_present;
08854 };
08855 
08856 enum match_req_res {
08857    SIP_REQ_MATCH,
08858    SIP_REQ_NOT_MATCH,
08859    SIP_REQ_LOOP_DETECTED, /* multiple incoming requests with same call-id but different branch parameters have been detected */
08860    SIP_REQ_FORKED, /* An outgoing request has been forked as result of receiving two differing 200ok responses. */
08861 };
08862 
08863 /*
08864  * \brief Match a incoming Request/Response to a dialog
08865  *
08866  * \retval enum match_req_res indicating if the dialog matches the arg
08867  */
08868 static enum match_req_res match_req_to_dialog(struct sip_pvt *sip_pvt_ptr, struct match_req_args *arg)
08869 {
08870    const char *init_ruri = NULL;
08871    if (sip_pvt_ptr->initreq.headers) {
08872       init_ruri = REQ_OFFSET_TO_STR(&sip_pvt_ptr->initreq, rlpart2);
08873    }
08874 
08875    /*
08876     * Match Tags and call-id to Dialog
08877     */
08878    if (!ast_strlen_zero(arg->callid) && strcmp(sip_pvt_ptr->callid, arg->callid)) {
08879       /* call-id does not match. */
08880       return SIP_REQ_NOT_MATCH;
08881    }
08882    if (arg->method == SIP_RESPONSE) {
08883       /* Verify fromtag of response matches the tag we gave them. */
08884       if (strcmp(arg->fromtag, sip_pvt_ptr->tag)) {
08885          /* fromtag from response does not match our tag */
08886          return SIP_REQ_NOT_MATCH;
08887       }
08888 
08889       /* Verify totag if we have one stored for this dialog, but never be strict about this for
08890        * a response until the dialog is established */
08891       if (!ast_strlen_zero(sip_pvt_ptr->theirtag) && ast_test_flag(&sip_pvt_ptr->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
08892          if (ast_strlen_zero(arg->totag)) {
08893             /* missing totag when they already gave us one earlier */
08894             return SIP_REQ_NOT_MATCH;
08895          }
08896          /* compare the totag of response with the tag we have stored for them */
08897          if (strcmp(arg->totag, sip_pvt_ptr->theirtag)) {
08898             /* totag did not match what we had stored for them. */
08899             char invite_branch[32] = { 0, };
08900             if (sip_pvt_ptr->invite_branch) {
08901                snprintf(invite_branch, sizeof(invite_branch), "z9hG4bK%08x", (unsigned)sip_pvt_ptr->invite_branch);
08902             }
08903             /* Forked Request Detection
08904              *
08905              * If this is a 200ok response and the totags do not match, this
08906              * might be a forked response to an outgoing Request. Detection of
08907              * a forked response must meet the criteria below.
08908              *
08909              * 1. must be a 2xx Response
08910              * 2. call-d equal to call-id of Request. this is done earlier
08911              * 3. from-tag equal to from-tag of Request. this is done earlier
08912              * 4. branch parameter equal to branch of inital Request
08913              * 5. to-tag _NOT_ equal to previous 2xx response that already established the dialog.
08914              */
08915             if ((arg->respid == 200) &&
08916                !ast_strlen_zero(invite_branch) &&
08917                !ast_strlen_zero(arg->viabranch) &&
08918                !strcmp(invite_branch, arg->viabranch)) {
08919                return SIP_REQ_FORKED;
08920             }
08921 
08922             /* The totag did not match the one we had stored, and this is not a Forked Request. */
08923             return SIP_REQ_NOT_MATCH;
08924          }
08925       }
08926    } else {
08927       /* Verify the fromtag of Request matches the tag they provided earlier.
08928        * If this is a Request with authentication credentials, forget their old
08929        * tag as it is not valid after the 401 or 407 response. */
08930       if (!arg->authentication_present && strcmp(arg->fromtag, sip_pvt_ptr->theirtag)) {
08931          /* their tag does not match the one was have stored for them */
08932          return SIP_REQ_NOT_MATCH;
08933       }
08934       /* Verify if totag is present in Request, that it matches what we gave them as our tag earlier */
08935       if (!ast_strlen_zero(arg->totag) && (strcmp(arg->totag, sip_pvt_ptr->tag))) {
08936          /* totag from Request does not match our tag */
08937          return SIP_REQ_NOT_MATCH;
08938       }
08939    }
08940 
08941    /*
08942     * Compare incoming request against initial transaction.
08943     * 
08944     * This is a best effort attempt at distinguishing forked requests from
08945     * our initial transaction.  If all the elements are NOT in place to evaluate
08946     * this, this block is ignored and the dialog match is made regardless.
08947     * Once the totag is established after the dialog is confirmed, this is not necessary.
08948     *
08949     * CRITERIA required for initial transaction matching.
08950     * 
08951     * 1. Is a Request
08952     * 2. Callid and theirtag match (this is done in the dialog matching block)
08953     * 3. totag is NOT present
08954     * 4. CSeq matchs our initial transaction's cseq number
08955     * 5. pvt has init via branch parameter stored
08956     */
08957    if ((arg->method != SIP_RESPONSE) &&                 /* must be a Request */
08958       ast_strlen_zero(arg->totag) &&                   /* must not have a totag */
08959       (sip_pvt_ptr->init_icseq == arg->seqno) &&       /* the cseq must be the same as this dialogs initial cseq */
08960       !ast_strlen_zero(sip_pvt_ptr->initviabranch) &&  /* The dialog must have started with a RFC3261 compliant branch tag */
08961       init_ruri) {                                     /* the dialog must have an initial request uri associated with it */
08962       /* This Request matches all the criteria required for Loop/Merge detection.
08963        * Now we must go down the path of comparing VIA's and RURIs. */
08964       if (ast_strlen_zero(arg->viabranch) ||
08965          strcmp(arg->viabranch, sip_pvt_ptr->initviabranch) ||
08966          ast_strlen_zero(arg->viasentby) ||
08967          strcmp(arg->viasentby, sip_pvt_ptr->initviasentby)) {
08968          /* At this point, this request does not match this Dialog.*/
08969 
08970          /* if methods are different this is just a mismatch */
08971          if ((sip_pvt_ptr->method != arg->method)) {
08972             return SIP_REQ_NOT_MATCH;
08973          }
08974 
08975          /* If RUIs are different, this is a forked request to a separate URI.
08976           * Returning a mismatch allows this Request to be processed separately. */
08977          if (sip_uri_cmp(init_ruri, arg->ruri)) {
08978             /* not a match, request uris are different */
08979             return SIP_REQ_NOT_MATCH;
08980          }
08981 
08982          /* Loop/Merge Detected
08983           *
08984           * ---Current Matches to Initial Request---
08985           * request uri
08986           * Call-id
08987           * their-tag
08988           * no totag present
08989           * method
08990           * cseq
08991           *
08992           * --- Does not Match Initial Request ---
08993           * Top Via
08994           *
08995           * Without the same Via, this can not match our initial transaction for this dialog,
08996           * but given that this Request matches everything else associated with that initial
08997           * Request this is most certainly a Forked request in which we have already received
08998           * part of the fork.
08999           */
09000          return SIP_REQ_LOOP_DETECTED;
09001       }
09002    } /* end of Request Via check */
09003 
09004    /* Match Authentication Request.
09005     *
09006     * A Request with an Authentication header must come back with the
09007     * same Request URI.  Otherwise it is not a match.
09008     */
09009    if ((arg->method != SIP_RESPONSE) &&      /* Must be a Request type to even begin checking this */
09010       ast_strlen_zero(arg->totag) &&        /* no totag is present to match */
09011       arg->authentication_present &&        /* Authentication header is present in Request */
09012       sip_uri_cmp(init_ruri, arg->ruri)) {  /* Compare the Request URI of both the last Request and this new one */
09013 
09014       /* Authentication was provided, but the Request URI did not match the last one on this dialog. */
09015       return SIP_REQ_NOT_MATCH;
09016    }
09017 
09018    return SIP_REQ_MATCH;
09019 }
09020 
09021 /*! \brief This function creates a dialog to handle a forked request.  This dialog
09022  * exists only to properly terminiate the the forked request immediately.
09023  */
09024 static void forked_invite_init(struct sip_request *req, const char *new_theirtag, struct sip_pvt *original, struct ast_sockaddr *addr)
09025 {
09026    struct sip_pvt *p;
09027    const char *callid;
09028    struct ast_callid *logger_callid;
09029 
09030    sip_pvt_lock(original);
09031    callid = ast_strdupa(original->callid);
09032    logger_callid = original->logger_callid;
09033    if (logger_callid) {
09034       ast_callid_ref(logger_callid);
09035    }
09036    sip_pvt_unlock(original);
09037 
09038    p = sip_alloc(callid, addr, 1, SIP_INVITE, req, logger_callid);
09039    if (logger_callid) {
09040       ast_callid_unref(logger_callid);
09041    }
09042    if (!p)  {
09043       return; /* alloc error */
09044    }
09045 
09046    /* Lock p and original private structures. */
09047    sip_pvt_lock(p);
09048    while (sip_pvt_trylock(original)) {
09049       /* Can't use DEADLOCK_AVOIDANCE since p is an ao2 object */
09050       sip_pvt_unlock(p);
09051       sched_yield();
09052       sip_pvt_lock(p);
09053    }
09054 
09055    p->invitestate = INV_TERMINATED;
09056    p->ocseq = original->ocseq;
09057    p->branch = original->branch;
09058 
09059    memcpy(&p->flags, &original->flags, sizeof(p->flags));
09060    copy_request(&p->initreq, &original->initreq);
09061    ast_string_field_set(p, theirtag, new_theirtag);
09062    ast_string_field_set(p, tag, original->tag);
09063    ast_string_field_set(p, uri, original->uri);
09064    ast_string_field_set(p, our_contact, original->our_contact);
09065    ast_string_field_set(p, fullcontact, original->fullcontact);
09066 
09067    sip_pvt_unlock(original);
09068 
09069    parse_ok_contact(p, req);
09070    build_route(p, req, 1, 0);
09071 
09072    transmit_request(p, SIP_ACK, p->ocseq, XMIT_UNRELIABLE, TRUE);
09073    transmit_request(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
09074 
09075    pvt_set_needdestroy(p, "forked request"); /* this dialog will terminate once the BYE is responed to or times out. */
09076    sip_pvt_unlock(p);
09077    dialog_unref(p, "setup forked invite termination");
09078 }
09079 
09080 /*! \internal
09081  *
09082  * \brief Locks both pvt and pvt owner if owner is present.
09083  *
09084  * \note This function gives a ref to pvt->owner if it is present and locked.
09085  *       This reference must be decremented after pvt->owner is unlocked.
09086  *
09087  * \note This function will never give you up,
09088  * \note This function will never let you down.
09089  * \note This function will run around and desert you.
09090  *
09091  * \pre pvt is not locked
09092  * \post pvt is locked
09093  * \post pvt->owner is locked and its reference count is increased (if pvt->owner is not NULL)
09094  *
09095  * \returns a pointer to the locked and reffed pvt->owner channel if it exists.
09096  */
09097 static struct ast_channel *sip_pvt_lock_full(struct sip_pvt *pvt)
09098 {
09099    struct ast_channel *chan;
09100 
09101    /* Locking is simple when it is done right.  If you see a deadlock resulting
09102     * in this function, it is not this function's fault, Your problem exists elsewhere.
09103     * This function is perfect... seriously. */
09104    for (;;) {
09105       /* First, get the channel and grab a reference to it */
09106       sip_pvt_lock(pvt);
09107       chan = pvt->owner;
09108       if (chan) {
09109          /* The channel can not go away while we hold the pvt lock.
09110           * Give the channel a ref so it will not go away after we let
09111           * the pvt lock go. */
09112          ast_channel_ref(chan);
09113       } else {
09114          /* no channel, return pvt locked */
09115          return NULL;
09116       }
09117 
09118       /* We had to hold the pvt lock while getting a ref to the owner channel
09119        * but now we have to let this lock go in order to preserve proper
09120        * locking order when grabbing the channel lock */
09121       sip_pvt_unlock(pvt);
09122 
09123       /* Look, no deadlock avoidance, hooray! */
09124       ast_channel_lock(chan);
09125       sip_pvt_lock(pvt);
09126 
09127       if (pvt->owner == chan) {
09128          /* done */
09129          break;
09130       }
09131 
09132       /* If the owner changed while everything was unlocked, no problem,
09133        * just start over and everthing will work.  This is rare, do not be
09134        * confused by this loop and think this it is an expensive operation.
09135        * The majority of the calls to this function will never involve multiple
09136        * executions of this loop. */
09137       ast_channel_unlock(chan);
09138       ast_channel_unref(chan);
09139       sip_pvt_unlock(pvt);
09140    }
09141 
09142    /* If owner exists, it is locked and reffed */
09143    return pvt->owner;
09144 }
09145 
09146 /*! \brief find or create a dialog structure for an incoming SIP message.
09147  * Connect incoming SIP message to current dialog or create new dialog structure
09148  * Returns a reference to the sip_pvt object, remember to give it back once done.
09149  *     Called by handle_request_do
09150  */
09151 static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method)
09152 {
09153    char totag[128];
09154    char fromtag[128];
09155    const char *callid = sip_get_header(req, "Call-ID");
09156    const char *from = sip_get_header(req, "From");
09157    const char *to = sip_get_header(req, "To");
09158    const char *cseq = sip_get_header(req, "Cseq");
09159    struct sip_pvt *sip_pvt_ptr;
09160    uint32_t seqno;
09161    /* Call-ID, to, from and Cseq are required by RFC 3261. (Max-forwards and via too - ignored now) */
09162    /* sip_get_header always returns non-NULL so we must use ast_strlen_zero() */
09163    if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
09164          ast_strlen_zero(from) || ast_strlen_zero(cseq) ||
09165          (sscanf(cseq, "%30u", &seqno) != 1)) {
09166 
09167       /* RFC 3261 section 24.4.1.   Send a 400 Bad Request if the request is malformed. */
09168       if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
09169          transmit_response_using_temp(callid, addr, 1, intended_method,
09170                        req, "400 Bad Request");
09171       }
09172       return NULL;   /* Invalid packet */
09173    }
09174 
09175    if (sip_cfg.pedanticsipchecking) {
09176       /* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
09177          we need more to identify a branch - so we have to check branch, from
09178          and to tags to identify a call leg.
09179          For Asterisk to behave correctly, you need to turn on pedanticsipchecking
09180          in sip.conf
09181          */
09182       if (gettag(req, "To", totag, sizeof(totag)))
09183          req->has_to_tag = 1; /* Used in handle_request/response */
09184       gettag(req, "From", fromtag, sizeof(fromtag));
09185 
09186       ast_debug(5, "= Looking for  Call ID: %s (Checking %s) --From tag %s --To-tag %s  \n", callid, req->method==SIP_RESPONSE ? "To" : "From", fromtag, totag);
09187 
09188       /* All messages must always have From: tag */
09189       if (ast_strlen_zero(fromtag)) {
09190          ast_debug(5, "%s request has no from tag, dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
09191          return NULL;
09192       }
09193       /* reject requests that must always have a To: tag */
09194       if (ast_strlen_zero(totag) && (req->method == SIP_ACK || req->method == SIP_BYE || req->method == SIP_INFO )) {
09195          if (req->method != SIP_ACK) {
09196             transmit_response_using_temp(callid, addr, 1, intended_method, req, "481 Call leg/transaction does not exist");
09197          }
09198          ast_debug(5, "%s must have a to tag. dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
09199          return NULL;
09200       }
09201    }
09202 
09203    if (!sip_cfg.pedanticsipchecking) {
09204       struct sip_pvt tmp_dialog = {
09205          .callid = callid,
09206       };
09207       sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find in dialogs");
09208       if (sip_pvt_ptr) {  /* well, if we don't find it-- what IS in there? */
09209          /* Found the call */
09210          return sip_pvt_ptr;
09211       }
09212    } else { /* in pedantic mode! -- do the fancy search */
09213       struct sip_pvt tmp_dialog = {
09214          .callid = callid,
09215       };
09216       /* if a Outbound forked Request is detected, this pvt will point
09217        * to the dialog the Request is forking off of. */
09218       struct sip_pvt *fork_pvt = NULL;
09219       struct match_req_args args = { 0, };
09220       int found;
09221       struct ao2_iterator *iterator = ao2_t_callback(dialogs,
09222          OBJ_POINTER | OBJ_MULTIPLE,
09223          dialog_find_multiple,
09224          &tmp_dialog,
09225          "pedantic ao2_find in dialogs");
09226       struct sip_via *via = NULL;
09227 
09228       args.method = req->method;
09229       args.callid = NULL; /* we already matched this. */
09230       args.totag = totag;
09231       args.fromtag = fromtag;
09232       args.seqno = seqno;
09233       /* get via header information. */
09234       args.ruri = REQ_OFFSET_TO_STR(req, rlpart2);
09235       via = parse_via(sip_get_header(req, "Via"));
09236       if (via) {
09237          args.viasentby = via->sent_by;
09238          args.viabranch = via->branch;
09239       }
09240       /* determine if this is a Request with authentication credentials. */
09241       if (!ast_strlen_zero(sip_get_header(req, "Authorization")) ||
09242          !ast_strlen_zero(sip_get_header(req, "Proxy-Authorization"))) {
09243          args.authentication_present = 1;
09244       }
09245       /* if it is a response, get the response code */
09246       if (req->method == SIP_RESPONSE) {
09247          const char* e = ast_skip_blanks(REQ_OFFSET_TO_STR(req, rlpart2));
09248          int respid;
09249          if (!ast_strlen_zero(e) && (sscanf(e, "%30d", &respid) == 1)) {
09250             args.respid = respid;
09251          }
09252       }
09253 
09254       /* Iterate a list of dialogs already matched by Call-id */
09255       while (iterator && (sip_pvt_ptr = ao2_iterator_next(iterator))) {
09256          sip_pvt_lock(sip_pvt_ptr);
09257          found = match_req_to_dialog(sip_pvt_ptr, &args);
09258          sip_pvt_unlock(sip_pvt_ptr);
09259 
09260          switch (found) {
09261          case SIP_REQ_MATCH:
09262             ao2_iterator_destroy(iterator);
09263             dialog_unref(fork_pvt, "unref fork_pvt");
09264             free_via(via);
09265             return sip_pvt_ptr; /* return pvt with ref */
09266          case SIP_REQ_LOOP_DETECTED:
09267             /* This is likely a forked Request that somehow resulted in us receiving multiple parts of the fork.
09268             * RFC 3261 section 8.2.2.2, Indicate that we want to merge requests by sending a 482 response. */
09269             transmit_response_using_temp(callid, addr, 1, intended_method, req, "482 (Loop Detected)");
09270             dialog_unref(sip_pvt_ptr, "pvt did not match incoming SIP msg, unref from search.");
09271             ao2_iterator_destroy(iterator);
09272             dialog_unref(fork_pvt, "unref fork_pvt");
09273             free_via(via);
09274             return NULL;
09275          case SIP_REQ_FORKED:
09276             dialog_unref(fork_pvt, "throwing way pvt to fork off of.");
09277             fork_pvt = dialog_ref(sip_pvt_ptr, "this pvt has a forked request, save this off to copy information into new dialog\n");
09278             /* fall through */
09279          case SIP_REQ_NOT_MATCH:
09280          default:
09281             dialog_unref(sip_pvt_ptr, "pvt did not match incoming SIP msg, unref from search");
09282             break;
09283          }
09284       }
09285       if (iterator) {
09286          ao2_iterator_destroy(iterator);
09287       }
09288 
09289       /* Handle any possible forked requests. This must be done only after transaction matching is complete. */
09290       if (fork_pvt) {
09291          /* XXX right now we only support handling forked INVITE Requests. Any other
09292           * forked request type must be added here. */
09293          if (fork_pvt->method == SIP_INVITE) {
09294             forked_invite_init(req, args.totag, fork_pvt, addr);
09295             dialog_unref(fork_pvt, "throwing way old forked pvt");
09296             free_via(via);
09297             return NULL;
09298          }
09299          fork_pvt = dialog_unref(fork_pvt, "throwing way pvt to fork off of");
09300       }
09301 
09302       free_via(via);
09303    } /* end of pedantic mode Request/Reponse to Dialog matching */
09304 
09305    /* See if the method is capable of creating a dialog */
09306    if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
09307       struct sip_pvt *p = NULL;
09308       struct ast_callid *logger_callid = NULL;
09309 
09310       if (intended_method == SIP_INVITE) {
09311          logger_callid = ast_create_callid();
09312       }
09313 
09314       /* Ok, time to create a new SIP dialog object, a pvt */
09315       if (!(p = sip_alloc(callid, addr, 1, intended_method, req, logger_callid)))  {
09316          /* We have a memory or file/socket error (can't allocate RTP sockets or something) so we're not
09317             getting a dialog from sip_alloc.
09318 
09319             Without a dialog we can't retransmit and handle ACKs and all that, but at least
09320             send an error message.
09321 
09322             Sorry, we apologize for the inconvienience
09323          */
09324          transmit_response_using_temp(callid, addr, 1, intended_method, req, "500 Server internal error");
09325          ast_debug(4, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
09326       }
09327       /* If we created an ast_callid for an invite, we need to free it now. */
09328       if (logger_callid) {
09329          ast_callid_unref(logger_callid);
09330       }
09331       return p; /* can be NULL */
09332    } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
09333       /* A method we do not support, let's take it on the volley */
09334       transmit_response_using_temp(callid, addr, 1, intended_method, req, "501 Method Not Implemented");
09335       ast_debug(2, "Got a request with unsupported SIP method.\n");
09336    } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
09337       /* This is a request outside of a dialog that we don't know about */
09338       transmit_response_using_temp(callid, addr, 1, intended_method, req, "481 Call leg/transaction does not exist");
09339       ast_debug(2, "That's odd...  Got a request in unknown dialog. Callid %s\n", callid ? callid : "<unknown>");
09340    }
09341    /* We do not respond to responses for dialogs that we don't know about, we just drop
09342       the session quickly */
09343    if (intended_method == SIP_RESPONSE)
09344       ast_debug(2, "That's odd...  Got a response on a call we don't know about. Callid %s\n", callid ? callid : "<unknown>");
09345 
09346    return NULL;
09347 }
09348 
09349 /*! \brief create sip_registry object from register=> line in sip.conf and link into reg container */
09350 static int sip_register(const char *value, int lineno)
09351 {
09352    struct sip_registry *reg, *tmp;
09353 
09354    if (!(reg = ast_calloc_with_stringfields(1, struct sip_registry, 256))) {
09355       ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
09356       return -1;
09357    }
09358 
09359    ASTOBJ_INIT(reg);
09360 
09361    ast_copy_string(reg->name, value, sizeof(reg->name));
09362    if (sip_parse_register_line(reg, default_expiry, value, lineno)) {
09363       registry_unref(reg, "failure to parse, unref the reg pointer");
09364       return -1;
09365    }
09366 
09367    /* set default expiry if necessary */
09368    if (reg->refresh && !reg->expiry && !reg->configured_expiry) {
09369       reg->refresh = reg->expiry = reg->configured_expiry = default_expiry;
09370    }
09371 
09372    /* Add the new registry entry to the list, but only if it isn't already there */
09373    if ((tmp = ASTOBJ_CONTAINER_FIND(&regl, reg->name))) {
09374       registry_unref(tmp, "throw away found registry");
09375    } else {
09376       ast_atomic_fetchadd_int(&regobjs, 1);
09377       ASTOBJ_CONTAINER_LINK(&regl, reg);
09378    }
09379 
09380    /* release the reference given by ASTOBJ_INIT. The container has another reference */
09381    registry_unref(reg, "unref the reg pointer");
09382 
09383    return 0;
09384 }
09385 
09386 /*! \brief Parse mwi=> line in sip.conf and add to list */
09387 static int sip_subscribe_mwi(const char *value, int lineno)
09388 {
09389    struct sip_subscription_mwi *mwi;
09390    int portnum = 0;
09391    enum sip_transport transport = SIP_TRANSPORT_UDP;
09392    char buf[256] = "";
09393    char *username = NULL, *hostname = NULL, *secret = NULL, *authuser = NULL, *porta = NULL, *mailbox = NULL;
09394 
09395    if (!value) {
09396       return -1;
09397    }
09398 
09399    ast_copy_string(buf, value, sizeof(buf));
09400 
09401    username = buf;
09402 
09403    if ((hostname = strrchr(buf, '@'))) {
09404       *hostname++ = '\0';
09405    } else {
09406       return -1;
09407    }
09408 
09409    if ((secret = strchr(username, ':'))) {
09410       *secret++ = '\0';
09411       if ((authuser = strchr(secret, ':'))) {
09412          *authuser++ = '\0';
09413       }
09414    }
09415 
09416    if ((mailbox = strchr(hostname, '/'))) {
09417       *mailbox++ = '\0';
09418    }
09419 
09420    if (ast_strlen_zero(username) || ast_strlen_zero(hostname) || ast_strlen_zero(mailbox)) {
09421       ast_log(LOG_WARNING, "Format for MWI subscription is user[:secret[:authuser]]@host[:port]/mailbox at line %d\n", lineno);
09422       return -1;
09423    }
09424 
09425    if ((porta = strchr(hostname, ':'))) {
09426       *porta++ = '\0';
09427       if (!(portnum = atoi(porta))) {
09428          ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
09429          return -1;
09430       }
09431    }
09432 
09433    if (!(mwi = ast_calloc_with_stringfields(1, struct sip_subscription_mwi, 256))) {
09434       return -1;
09435    }
09436 
09437    ASTOBJ_INIT(mwi);
09438    ast_string_field_set(mwi, username, username);
09439    if (secret) {
09440       ast_string_field_set(mwi, secret, secret);
09441    }
09442    if (authuser) {
09443       ast_string_field_set(mwi, authuser, authuser);
09444    }
09445    ast_string_field_set(mwi, hostname, hostname);
09446    ast_string_field_set(mwi, mailbox, mailbox);
09447    mwi->resub = -1;
09448    mwi->portno = portnum;
09449    mwi->transport = transport;
09450 
09451    ASTOBJ_CONTAINER_LINK(&submwil, mwi);
09452    ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
09453 
09454    return 0;
09455 }
09456 
09457 static void mark_method_allowed(unsigned int *allowed_methods, enum sipmethod method)
09458 {
09459    (*allowed_methods) |= (1 << method);
09460 }
09461 
09462 static void mark_method_unallowed(unsigned int *allowed_methods, enum sipmethod method)
09463 {
09464    (*allowed_methods) &= ~(1 << method);
09465 }
09466 
09467 /*! \brief Check if method is allowed for a device or a dialog */
09468 static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method)
09469 {
09470    return ((*allowed_methods) >> method) & 1;
09471 }
09472 
09473 static void mark_parsed_methods(unsigned int *methods, char *methods_str)
09474 {
09475    char *method;
09476    for (method = strsep(&methods_str, ","); !ast_strlen_zero(method); method = strsep(&methods_str, ",")) {
09477       int id = find_sip_method(ast_skip_blanks(method));
09478       if (id == SIP_UNKNOWN) {
09479          continue;
09480       }
09481       mark_method_allowed(methods, id);
09482    }
09483 }
09484 /*!
09485  * \brief parse the Allow header to see what methods the endpoint we
09486  * are communicating with allows.
09487  *
09488  * We parse the allow header on incoming Registrations and save the
09489  * result to the SIP peer that is registering. When the registration
09490  * expires, we clear what we know about the peer's allowed methods.
09491  * When the peer re-registers, we once again parse to see if the
09492  * list of allowed methods has changed.
09493  *
09494  * For peers that do not register, we parse the first message we receive
09495  * during a call to see what is allowed, and save the information
09496  * for the duration of the call.
09497  * \param req The SIP request we are parsing
09498  * \retval The methods allowed
09499  */
09500 static unsigned int parse_allowed_methods(struct sip_request *req)
09501 {
09502    char *allow = ast_strdupa(sip_get_header(req, "Allow"));
09503    unsigned int allowed_methods = SIP_UNKNOWN;
09504 
09505    if (ast_strlen_zero(allow)) {
09506       /* I have witnessed that REGISTER requests from Polycom phones do not
09507        * place the phone's allowed methods in an Allow header. Instead, they place the
09508        * allowed methods in a methods= parameter in the Contact header.
09509        */
09510       char *contact = ast_strdupa(sip_get_header(req, "Contact"));
09511       char *methods = strstr(contact, ";methods=");
09512 
09513       if (ast_strlen_zero(methods)) {
09514          /* RFC 3261 states:
09515           *
09516           * "The absence of an Allow header field MUST NOT be
09517           * interpreted to mean that the UA sending the message supports no
09518           * methods.   Rather, it implies that the UA is not providing any
09519           * information on what methods it supports."
09520           *
09521           * For simplicity, we'll assume that the peer allows all known
09522           * SIP methods if they have no Allow header. We can then clear out the necessary
09523           * bits if the peer lets us know that we have sent an unsupported method.
09524           */
09525          return UINT_MAX;
09526       }
09527       allow = ast_strip_quoted(methods + 9, "\"", "\"");
09528    }
09529    mark_parsed_methods(&allowed_methods, allow);
09530    return allowed_methods;
09531 }
09532 
09533 /*! A wrapper for parse_allowed_methods geared toward sip_pvts
09534  *
09535  * This function, in addition to setting the allowed methods for a sip_pvt
09536  * also will take into account the setting of the SIP_PAGE2_RPID_UPDATE flag.
09537  *
09538  * \param pvt The sip_pvt we are setting the allowed_methods for
09539  * \param req The request which we are parsing
09540  * \retval The methods alloweded by the sip_pvt
09541  */
09542 static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req)
09543 {
09544    pvt->allowed_methods = parse_allowed_methods(req);
09545    
09546    if (ast_test_flag(&pvt->flags[1], SIP_PAGE2_RPID_UPDATE)) {
09547       mark_method_allowed(&pvt->allowed_methods, SIP_UPDATE);
09548    }
09549    pvt->allowed_methods &= ~(pvt->disallowed_methods);
09550 
09551    return pvt->allowed_methods;
09552 }
09553 
09554 /*! \brief  Parse multiline SIP headers into one header
09555    This is enabled if pedanticsipchecking is enabled */
09556 static void lws2sws(struct ast_str *data)
09557 {
09558    char *msgbuf = data->str;
09559    int len = ast_str_strlen(data);
09560    int h = 0, t = 0;
09561    int lws = 0;
09562 
09563    for (; h < len;) {
09564       /* Eliminate all CRs */
09565       if (msgbuf[h] == '\r') {
09566          h++;
09567          continue;
09568       }
09569       /* Check for end-of-line */
09570       if (msgbuf[h] == '\n') {
09571          /* Check for end-of-message */
09572          if (h + 1 == len)
09573             break;
09574          /* Check for a continuation line */
09575          if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
09576             /* Merge continuation line */
09577             h++;
09578             continue;
09579          }
09580          /* Propagate LF and start new line */
09581          msgbuf[t++] = msgbuf[h++];
09582          lws = 0;
09583          continue;
09584       }
09585       if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
09586          if (lws) {
09587             h++;
09588             continue;
09589          }
09590          msgbuf[t++] = msgbuf[h++];
09591          lws = 1;
09592          continue;
09593       }
09594       msgbuf[t++] = msgbuf[h++];
09595       if (lws)
09596          lws = 0;
09597    }
09598    msgbuf[t] = '\0';
09599    data->used = t;
09600 }
09601 
09602 /*! \brief Parse a SIP message
09603    \note this function is used both on incoming and outgoing packets
09604 */
09605 static int parse_request(struct sip_request *req)
09606 {
09607    char *c = req->data->str;
09608    ptrdiff_t *dst = req->header;
09609    int i = 0, lim = SIP_MAX_HEADERS - 1;
09610    unsigned int skipping_headers = 0;
09611    ptrdiff_t current_header_offset = 0;
09612    char *previous_header = "";
09613 
09614    req->header[0] = 0;
09615    req->headers = -1;   /* mark that we are working on the header */
09616    for (; *c; c++) {
09617       if (*c == '\r') {    /* remove \r */
09618          *c = '\0';
09619       } else if (*c == '\n') {   /* end of this line */
09620          *c = '\0';
09621          current_header_offset = (c + 1) - ast_str_buffer(req->data);
09622          previous_header = ast_str_buffer(req->data) + dst[i];
09623          if (skipping_headers) {
09624             /* check to see if this line is blank; if so, turn off
09625                the skipping flag, so the next line will be processed
09626                as a body line */
09627             if (ast_strlen_zero(previous_header)) {
09628                skipping_headers = 0;
09629             }
09630             dst[i] = current_header_offset; /* record start of next line */
09631             continue;
09632          }
09633          if (sipdebug) {
09634             ast_debug(4, "%7s %2d [%3d]: %s\n",
09635                  req->headers < 0 ? "Header" : "Body",
09636                  i, (int) strlen(previous_header), previous_header);
09637          }
09638          if (ast_strlen_zero(previous_header) && req->headers < 0) {
09639             req->headers = i; /* record number of header lines */
09640             dst = req->line;  /* start working on the body */
09641             i = 0;
09642             lim = SIP_MAX_LINES - 1;
09643          } else { /* move to next line, check for overflows */
09644             if (i++ == lim) {
09645                /* if we're processing headers, then skip any remaining
09646                   headers and move on to processing the body, otherwise
09647                   we're done */
09648                if (req->headers != -1) {
09649                   break;
09650                } else {
09651                   req->headers = i;
09652                   dst = req->line;
09653                   i = 0;
09654                   lim = SIP_MAX_LINES - 1;
09655                   skipping_headers = 1;
09656                }
09657             }
09658          }
09659          dst[i] = current_header_offset; /* record start of next line */
09660       }
09661    }
09662 
09663    /* Check for last header or body line without CRLF. The RFC for SDP requires CRLF,
09664       but since some devices send without, we'll be generous in what we accept. However,
09665       if we've already reached the maximum number of lines for portion of the message
09666       we were parsing, we can't accept any more, so just ignore it.
09667    */
09668    previous_header = ast_str_buffer(req->data) + dst[i];
09669    if ((i < lim) && !ast_strlen_zero(previous_header)) {
09670       if (sipdebug) {
09671          ast_debug(4, "%7s %2d [%3d]: %s\n",
09672               req->headers < 0 ? "Header" : "Body",
09673               i, (int) strlen(previous_header), previous_header );
09674       }
09675       i++;
09676    }
09677 
09678    /* update count of header or body lines */
09679    if (req->headers >= 0) {   /* we are in the body */
09680       req->lines = i;
09681    } else {       /* no body */
09682       req->headers = i;
09683       req->lines = 0;
09684       /* req->data->used will be a NULL byte */
09685       req->line[0] = ast_str_strlen(req->data);
09686    }
09687 
09688    if (*c) {
09689       ast_log(LOG_WARNING, "Too many lines, skipping <%s>\n", c);
09690    }
09691 
09692    /* Split up the first line parts */
09693    return determine_firstline_parts(req);
09694 }
09695 
09696 /*!
09697   \brief Determine whether a SIP message contains an SDP in its body
09698   \param req the SIP request to process
09699   \return 1 if SDP found, 0 if not found
09700 
09701   Also updates req->sdp_start and req->sdp_count to indicate where the SDP
09702   lives in the message body.
09703 */
09704 static int find_sdp(struct sip_request *req)
09705 {
09706    const char *content_type;
09707    const char *content_length;
09708    const char *search;
09709    char *boundary;
09710    unsigned int x;
09711    int boundaryisquoted = FALSE;
09712    int found_application_sdp = FALSE;
09713    int found_end_of_headers = FALSE;
09714 
09715    content_length = sip_get_header(req, "Content-Length");
09716 
09717    if (!ast_strlen_zero(content_length)) {
09718       if (sscanf(content_length, "%30u", &x) != 1) {
09719          ast_log(LOG_WARNING, "Invalid Content-Length: %s\n", content_length);
09720          return 0;
09721       }
09722 
09723       /* Content-Length of zero means there can't possibly be an
09724          SDP here, even if the Content-Type says there is */
09725       if (x == 0)
09726          return 0;
09727    }
09728 
09729    content_type = sip_get_header(req, "Content-Type");
09730 
09731    /* if the body contains only SDP, this is easy */
09732    if (!strncasecmp(content_type, "application/sdp", 15)) {
09733       req->sdp_start = 0;
09734       req->sdp_count = req->lines;
09735       return req->lines ? 1 : 0;
09736    }
09737 
09738    /* if it's not multipart/mixed, there cannot be an SDP */
09739    if (strncasecmp(content_type, "multipart/mixed", 15))
09740       return 0;
09741 
09742    /* if there is no boundary marker, it's invalid */
09743    if ((search = strcasestr(content_type, ";boundary=")))
09744       search += 10;
09745    else if ((search = strcasestr(content_type, "; boundary=")))
09746       search += 11;
09747    else
09748       return 0;
09749 
09750    if (ast_strlen_zero(search))
09751       return 0;
09752 
09753    /* If the boundary is quoted with ", remove quote */
09754    if (*search == '\"')  {
09755       search++;
09756       boundaryisquoted = TRUE;
09757    }
09758 
09759    /* make a duplicate of the string, with two extra characters
09760       at the beginning */
09761    boundary = ast_strdupa(search - 2);
09762    boundary[0] = boundary[1] = '-';
09763    /* Remove final quote */
09764    if (boundaryisquoted)
09765       boundary[strlen(boundary) - 1] = '\0';
09766 
09767    /* search for the boundary marker, the empty line delimiting headers from
09768       sdp part and the end boundry if it exists */
09769 
09770    for (x = 0; x < (req->lines); x++) {
09771       const char *line = REQ_OFFSET_TO_STR(req, line[x]);
09772       if (!strncasecmp(line, boundary, strlen(boundary))){
09773          if (found_application_sdp && found_end_of_headers) {
09774             req->sdp_count = (x - 1) - req->sdp_start;
09775             return 1;
09776          }
09777          found_application_sdp = FALSE;
09778       }
09779       if (!strcasecmp(line, "Content-Type: application/sdp"))
09780          found_application_sdp = TRUE;
09781       
09782       if (ast_strlen_zero(line)) {
09783          if (found_application_sdp && !found_end_of_headers){
09784             req->sdp_start = x;
09785             found_end_of_headers = TRUE;
09786          }
09787       }
09788    }
09789    if (found_application_sdp && found_end_of_headers) {
09790       req->sdp_count = x - req->sdp_start;
09791       return TRUE;
09792    }
09793    return FALSE;
09794 }
09795 
09796 /*! \brief Change hold state for a call */
09797 static void change_hold_state(struct sip_pvt *dialog, struct sip_request *req, int holdstate, int sendonly)
09798 {
09799    if (sip_cfg.notifyhold && (!holdstate || !ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD)))
09800       sip_peer_hold(dialog, holdstate);
09801    if (sip_cfg.callevents)
09802       manager_event(EVENT_FLAG_CALL, "Hold",
09803                "Status: %s\r\n"
09804                "Channel: %s\r\n"
09805                "Uniqueid: %s\r\n",
09806                holdstate ? "On" : "Off",
09807                ast_channel_name(dialog->owner),
09808                ast_channel_uniqueid(dialog->owner));
09809    append_history(dialog, holdstate ? "Hold" : "Unhold", "%s", ast_str_buffer(req->data));
09810    if (!holdstate) { /* Put off remote hold */
09811       ast_clear_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD);   /* Clear both flags */
09812       return;
09813    }
09814    /* No address for RTP, we're on hold */
09815 
09816    /* Ensure hold flags are cleared so that overlapping flags do not conflict */
09817    ast_clear_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD);
09818 
09819    if (sendonly == 1)   /* One directional hold (sendonly/recvonly) */
09820       ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
09821    else if (sendonly == 2) /* Inactive stream */
09822       ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
09823    else
09824       ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
09825    return;
09826 }
09827 
09828 
09829 static int get_ip_and_port_from_sdp(struct sip_request *req, const enum media_type media, struct ast_sockaddr *addr)
09830 {
09831    const char *m;
09832    const char *c;
09833    int miterator = req->sdp_start;
09834    int citerator = req->sdp_start;
09835    unsigned int x = 0;
09836    unsigned int numberofports;
09837    int len;
09838    int af;
09839    char proto[4], host[258] = ""; /*Initialize to empty so we will know if we have any input */
09840 
09841    c = get_sdp_iterate(&citerator, req, "c");
09842    if (sscanf(c, "IN %3s %256s", proto, host) != 2) {
09843          ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
09844          /* Continue since there may be a valid host in a c= line specific to the audio stream */
09845    }
09846    /* We only want the m and c lines for audio */
09847    for (m = get_sdp_iterate(&miterator, req, "m"); !ast_strlen_zero(m); m = get_sdp_iterate(&miterator, req, "m")) {
09848       if ((media == SDP_AUDIO && ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
09849           (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0))) ||
09850          (media == SDP_VIDEO && ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
09851           (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len > 0)))) {
09852          /* See if there's a c= line for this media stream.
09853           * XXX There is no guarantee that we'll be grabbing the c= line for this
09854           * particular media stream here. However, this is the same logic used in process_sdp.
09855           */
09856          c = get_sdp_iterate(&citerator, req, "c");
09857          if (!ast_strlen_zero(c)) {
09858             sscanf(c, "IN %3s %256s", proto, host);
09859          }
09860          break;
09861       }
09862    }
09863 
09864    if (!strcmp("IP4", proto)) {
09865       af = AF_INET;
09866    } else if (!strcmp("IP6", proto)) {
09867       af = AF_INET6;
09868    } else {
09869       ast_log(LOG_WARNING, "Unknown protocol '%s'.\n", proto);
09870       return -1;
09871    }
09872 
09873    if (ast_strlen_zero(host) || x == 0) {
09874       ast_log(LOG_WARNING, "Failed to read an alternate host or port in SDP. Expect %s problems\n", media == SDP_AUDIO ? "audio" : "video");
09875       return -1;
09876    }
09877 
09878    if (ast_sockaddr_resolve_first_af(addr, host, 0, af)) {
09879       ast_log(LOG_WARNING, "Could not look up IP address of alternate hostname. Expect %s problems\n", media == SDP_AUDIO? "audio" : "video");
09880       return -1;
09881    }
09882 
09883    return 0;
09884 }
09885 
09886 /*! \internal
09887  * \brief Returns whether or not the address is null or ANY / unspecified (0.0.0.0 or ::)
09888  * \retval TRUE if the address is null or any
09889  * \retval FALSE if the address it not null or any
09890  * \note In some circumstances, calls should be placed on hold if either of these conditions exist.
09891  */
09892 static int sockaddr_is_null_or_any(const struct ast_sockaddr *addr)
09893 {
09894    return ast_sockaddr_isnull(addr) || ast_sockaddr_is_any(addr);
09895 }
09896 
09897 /*! \brief Check the media stream list to see if the given type already exists */
09898 static int has_media_stream(struct sip_pvt *p, enum media_type m)
09899 {
09900    struct offered_media *offer = NULL;
09901    AST_LIST_TRAVERSE(&p->offered_media, offer, next) {
09902       if (m == offer->type) {
09903          return 1;
09904       }
09905    }
09906    return 0;
09907 }
09908 
09909 /*! \brief Process SIP SDP offer, select formats and activate media channels
09910    If offer is rejected, we will not change any properties of the call
09911    Return 0 on success, a negative value on errors.
09912    Must be called after find_sdp().
09913 */
09914 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
09915 {
09916    int res = 0;
09917 
09918    /* Iterators for SDP parsing */
09919    int start = req->sdp_start;
09920    int next = start;
09921    int iterator = start;
09922 
09923    /* Temporary vars for SDP parsing */
09924    char type = '\0';
09925    const char *value = NULL;
09926    const char *m = NULL;           /* SDP media offer */
09927    const char *nextm = NULL;
09928    int len = -1;
09929    struct offered_media *offer;
09930 
09931    /* Host information */
09932    struct ast_sockaddr sessionsa;
09933    struct ast_sockaddr audiosa;
09934    struct ast_sockaddr videosa;
09935    struct ast_sockaddr textsa;
09936    struct ast_sockaddr imagesa;
09937    struct ast_sockaddr *sa = NULL;     /*!< RTP audio destination IP address */
09938    struct ast_sockaddr *vsa = NULL; /*!< RTP video destination IP address */
09939    struct ast_sockaddr *tsa = NULL; /*!< RTP text destination IP address */
09940    struct ast_sockaddr *isa = NULL; /*!< UDPTL image destination IP address */
09941    int portno = -1;        /*!< RTP audio destination port number */
09942    int vportno = -1;       /*!< RTP video destination port number */
09943    int tportno = -1;       /*!< RTP text destination port number */
09944    int udptlportno = -1;         /*!< UDPTL image destination port number */
09945 
09946    /* Peer capability is the capability in the SDP, non codec is RFC2833 DTMF (101) */
09947    struct ast_format_cap *peercapability = ast_format_cap_alloc_nolock();
09948    struct ast_format_cap *vpeercapability = ast_format_cap_alloc_nolock();
09949    struct ast_format_cap *tpeercapability = ast_format_cap_alloc_nolock();
09950 
09951    int peernoncodeccapability = 0, vpeernoncodeccapability = 0, tpeernoncodeccapability = 0;
09952 
09953    struct ast_rtp_codecs newaudiortp = { 0, }, newvideortp = { 0, }, newtextrtp = { 0, };
09954    struct ast_format_cap *newjointcapability = ast_format_cap_alloc_nolock(); /* Negotiated capability */
09955    struct ast_format_cap *newpeercapability = ast_format_cap_alloc_nolock();
09956    int newnoncodeccapability;
09957 
09958    const char *codecs;
09959    unsigned int codec;
09960 
09961    /* SRTP */
09962    int secure_audio = FALSE;
09963    int secure_video = FALSE;
09964 
09965    /* Others */
09966    int sendonly = -1;
09967    unsigned int numberofports;
09968    int last_rtpmap_codec = 0;
09969    int red_data_pt[10];    /* For T.140 RED */
09970    int red_num_gen = 0;    /* For T.140 RED */
09971    char red_fmtp[100] = "empty"; /* For T.140 RED */
09972    int debug = sip_debug_test_pvt(p);
09973 
09974    /* START UNKNOWN */
09975    char buf[SIPBUFSIZE];
09976    struct ast_format tmp_fmt;
09977    /* END UNKNOWN */
09978 
09979    /* Initial check */
09980    if (!p->rtp) {
09981       ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
09982       res = -1;
09983       goto process_sdp_cleanup;
09984    }
09985    if (!peercapability || !vpeercapability || !tpeercapability || !newpeercapability || !newjointcapability) {
09986       res = -1;
09987       goto process_sdp_cleanup;
09988    }
09989 
09990    if (ast_rtp_codecs_payloads_initialize(&newaudiortp) || ast_rtp_codecs_payloads_initialize(&newvideortp) ||
09991        ast_rtp_codecs_payloads_initialize(&newtextrtp)) {
09992       res = -1;
09993       goto process_sdp_cleanup;
09994    }
09995 
09996    /* Update our last rtprx when we receive an SDP, too */
09997    p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
09998 
09999    offered_media_list_destroy(p);
10000 
10001    /* Scan for the first media stream (m=) line to limit scanning of globals */
10002    nextm = get_sdp_iterate(&next, req, "m");
10003    if (ast_strlen_zero(nextm)) {
10004       ast_log(LOG_WARNING, "Insufficient information for SDP (m= not found)\n");
10005       res = -1;
10006       goto process_sdp_cleanup;
10007    }
10008 
10009    /* Scan session level SDP parameters (lines before first media stream) */
10010    while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
10011       int processed = FALSE;
10012       switch (type) {
10013       case 'o':
10014          /* If we end up receiving SDP that doesn't actually modify the session we don't want to treat this as a fatal
10015           * error. We just want to ignore the SDP and let the rest of the packet be handled as normal.
10016           */
10017          if (!process_sdp_o(value, p)) {
10018             res = (p->session_modify == FALSE) ? 0 : -1;
10019             goto process_sdp_cleanup;
10020          }
10021          processed = TRUE;
10022          break;
10023       case 'c':
10024          if (process_sdp_c(value, &sessionsa)) {
10025             processed = TRUE;
10026             sa = &sessionsa;
10027             vsa = sa;
10028             tsa = sa;
10029             isa = sa;
10030          }
10031          break;
10032       case 'a':
10033          if (process_sdp_a_sendonly(value, &sendonly)) {
10034             processed = TRUE;
10035          }
10036          else if (process_sdp_a_audio(value, p, &newaudiortp, &last_rtpmap_codec))
10037             processed = TRUE;
10038          else if (process_sdp_a_video(value, p, &newvideortp, &last_rtpmap_codec))
10039             processed = TRUE;
10040          else if (process_sdp_a_text(value, p, &newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
10041             processed = TRUE;
10042          else if (process_sdp_a_image(value, p))
10043             processed = TRUE;
10044 
10045          if (process_sdp_a_ice(value, p, p->rtp)) {
10046             processed = TRUE;
10047          }
10048          if (process_sdp_a_ice(value, p, p->vrtp)) {
10049             processed = TRUE;
10050          }
10051          if (process_sdp_a_ice(value, p, p->trtp)) {
10052             processed = TRUE;
10053          }
10054 
10055          if (process_sdp_a_dtls(value, p, p->rtp)) {
10056             processed = TRUE;
10057             if (p->srtp) {
10058                ast_set_flag(p->srtp, SRTP_CRYPTO_OFFER_OK);
10059             }
10060          }
10061          if (process_sdp_a_dtls(value, p, p->vrtp)) {
10062             processed = TRUE;
10063             if (p->vsrtp) {
10064                ast_set_flag(p->vsrtp, SRTP_CRYPTO_OFFER_OK);
10065             }
10066          }
10067          if (process_sdp_a_dtls(value, p, p->trtp)) {
10068             processed = TRUE;
10069             if (p->tsrtp) {
10070                ast_set_flag(p->tsrtp, SRTP_CRYPTO_OFFER_OK);
10071             }
10072          }
10073 
10074          break;
10075       }
10076 
10077       ast_debug(3, "Processing session-level SDP %c=%s... %s\n", type, value, (processed == TRUE)? "OK." : "UNSUPPORTED OR FAILED.");
10078    }
10079 
10080    /* default: novideo and notext set */
10081    p->novideo = TRUE;
10082    p->notext = TRUE;
10083 
10084    /* Scan media stream (m=) specific parameters loop */
10085    while (!ast_strlen_zero(nextm)) {
10086       int audio = FALSE;
10087       int video = FALSE;
10088       int image = FALSE;
10089       int text = FALSE;
10090       int processed_crypto = FALSE;
10091       char protocol[18] = {0,};
10092       unsigned int x;
10093       struct ast_rtp_engine_dtls *dtls;
10094 
10095       numberofports = 0;
10096       len = -1;
10097       start = next;
10098       m = nextm;
10099       iterator = next;
10100       nextm = get_sdp_iterate(&next, req, "m");
10101 
10102       if (!(offer = ast_calloc(1, sizeof(*offer)))) {
10103          ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer list\n");
10104          res = -1;
10105          goto process_sdp_cleanup;
10106       }
10107       AST_LIST_INSERT_TAIL(&p->offered_media, offer, next);
10108       offer->type = SDP_UNKNOWN;
10109 
10110       /* Check for 'audio' media offer */
10111       if (strncmp(m, "audio ", 6) == 0) {
10112          if ((sscanf(m, "audio %30u/%30u %17s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||
10113              (sscanf(m, "audio %30u %17s %n", &x, protocol, &len) == 2 && len > 0)) {
10114             codecs = m + len;
10115             /* produce zero-port m-line since it may be needed later
10116              * length is "m=audio 0 " + protocol + " " + codecs + "\r\n\0" */
10117             if (!(offer->decline_m_line = ast_malloc(10 + strlen(protocol) + 1 + strlen(codecs) + 3))) {
10118                ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer declination\n");
10119                res = -1;
10120                goto process_sdp_cleanup;
10121             }
10122             /* guaranteed to be exactly the right length */
10123             sprintf(offer->decline_m_line, "m=audio 0 %s %s\r\n", protocol, codecs);
10124 
10125             if (x == 0) {
10126                ast_log(LOG_WARNING, "Ignoring audio media offer because port number is zero\n");
10127                continue;
10128             }
10129 
10130             if (has_media_stream(p, SDP_AUDIO)) {
10131                ast_log(LOG_WARNING, "Declining non-primary audio stream: %s\n", m);
10132                continue;
10133             }
10134 
10135             /* Check number of ports offered for stream */
10136             if (numberofports > 1) {
10137                ast_log(LOG_WARNING, "%u ports offered for audio media, not supported by Asterisk. Will try anyway...\n", numberofports);
10138             }
10139 
10140             if ((!strcmp(protocol, "RTP/SAVPF") || !strcmp(protocol, "UDP/TLS/RTP/SAVPF")) && !ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
10141                if (req->method != SIP_RESPONSE) {
10142                   ast_log(LOG_NOTICE, "Received SAVPF profle in audio offer but AVPF is not enabled, enabling: %s\n", m);
10143                   secure_audio = 1;
10144                   ast_set_flag(&p->flags[2], SIP_PAGE3_USE_AVPF);
10145                }
10146                else {
10147 
10148                   ast_log(LOG_WARNING, "Received SAVPF profle in audio answer but AVPF is not enabled: %s\n", m);
10149                   continue;
10150                }
10151             } else if ((!strcmp(protocol, "RTP/SAVP") || !strcmp(protocol, "UDP/TLS/RTP/SAVP")) && ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
10152                if (req->method != SIP_RESPONSE) {
10153                   ast_log(LOG_NOTICE, "Received SAVP profle in audio offer but AVPF is enabled, disabling: %s\n", m);
10154                   secure_audio = 1;
10155                   ast_clear_flag(&p->flags[2], SIP_PAGE3_USE_AVPF);
10156                }
10157                else {
10158                   ast_log(LOG_WARNING, "Received SAVP profile in audio offer but AVPF is enabled: %s\n", m);
10159                   continue;
10160                }
10161             } else if (!strcmp(protocol, "UDP/TLS/RTP/SAVP") || !strcmp(protocol, "UDP/TLS/RTP/SAVPF")) {
10162                secure_audio = 1;
10163 
10164                if (p->srtp) {
10165                   ast_set_flag(p->srtp, SRTP_CRYPTO_OFFER_OK);
10166                }
10167             } else if (!strcmp(protocol, "RTP/SAVP") || !strcmp(protocol, "RTP/SAVPF")) {
10168                secure_audio = 1;
10169             } else if (!strcmp(protocol, "RTP/AVPF") && !ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
10170                if (req->method != SIP_RESPONSE) {
10171                   ast_log(LOG_NOTICE, "Received AVPF profile in audio offer but AVPF is not enabled, enabling: %s\n", m);
10172                   ast_set_flag(&p->flags[2], SIP_PAGE3_USE_AVPF);
10173                }
10174                else {
10175                   ast_log(LOG_WARNING, "Received AVP profile in audio answer but AVPF is enabled: %s\n", m);
10176                   continue;
10177                }
10178             } else if (!strcmp(protocol, "RTP/AVP") && ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
10179                if (req->method != SIP_RESPONSE) {
10180                   ast_log(LOG_NOTICE, "Received AVP profile in audio answer but AVPF is enabled, disabling: %s\n", m);
10181                   ast_clear_flag(&p->flags[2], SIP_PAGE3_USE_AVPF);
10182                }
10183                else {
10184                   ast_log(LOG_WARNING, "Received AVP profile in audio answer but AVPF is enabled: %s\n", m);
10185                   continue;
10186                }
10187             } else if ((!strcmp(protocol, "UDP/TLS/RTP/SAVP") || !strcmp(protocol, "UDP/TLS/RTP/SAVPF")) &&
10188                   (!(dtls = ast_rtp_instance_get_dtls(p->rtp)) || !dtls->active(p->rtp))) {
10189                ast_log(LOG_WARNING, "Received UDP/TLS in audio offer but DTLS is not enabled: %s\n", m);
10190                continue;
10191             } else if (strcmp(protocol, "RTP/AVP") && strcmp(protocol, "RTP/AVPF")) {
10192                ast_log(LOG_WARNING, "Unknown RTP profile in audio offer: %s\n", m);
10193                continue;
10194             }
10195 
10196             audio = TRUE;
10197             offer->type = SDP_AUDIO;
10198             portno = x;
10199 
10200             /* Scan through the RTP payload types specified in a "m=" line: */
10201             for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
10202                if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
10203                   ast_log(LOG_WARNING, "Invalid syntax in RTP audio format list: %s\n", codecs);
10204                   res = -1;
10205                   goto process_sdp_cleanup;
10206                }
10207                if (debug) {
10208                   ast_verbose("Found RTP audio format %u\n", codec);
10209                }
10210 
10211                ast_rtp_codecs_payloads_set_m_type(&newaudiortp, NULL, codec);
10212             }
10213          } else {
10214             ast_log(LOG_WARNING, "Rejecting audio media offer due to invalid or unsupported syntax: %s\n", m);
10215             res = -1;
10216             goto process_sdp_cleanup;
10217          }
10218       }
10219       /* Check for 'video' media offer */
10220       else if (strncmp(m, "video ", 6) == 0) {
10221          if ((sscanf(m, "video %30u/%30u %17s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||
10222              (sscanf(m, "video %30u %17s %n", &x, protocol, &len) == 2 && len > 0)) {
10223             codecs = m + len;
10224             /* produce zero-port m-line since it may be needed later
10225              * length is "m=video 0 " + protocol + " " + codecs + "\r\n\0" */
10226             if (!(offer->decline_m_line = ast_malloc(10 + strlen(protocol) + 1 + strlen(codecs) + 3))) {
10227                ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer declination\n");
10228                res = -1;
10229                goto process_sdp_cleanup;
10230             }
10231             /* guaranteed to be exactly the right length */
10232             sprintf(offer->decline_m_line, "m=video 0 %s %s\r\n", protocol, codecs);
10233 
10234             if (x == 0) {
10235                ast_log(LOG_WARNING, "Ignoring video stream offer because port number is zero\n");
10236                continue;
10237             }
10238 
10239             /* Check number of ports offered for stream */
10240             if (numberofports > 1) {
10241                ast_log(LOG_WARNING, "%u ports offered for video stream, not supported by Asterisk. Will try anyway...\n", numberofports);
10242             }
10243 
10244             if (has_media_stream(p, SDP_VIDEO)) {
10245                ast_log(LOG_WARNING, "Declining non-primary video stream: %s\n", m);
10246                continue;
10247             }
10248 
10249             if ((!strcmp(protocol, "RTP/SAVPF") || !strcmp(protocol, "UDP/TLS/RTP/SAVPF")) && !ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
10250                ast_log(LOG_WARNING, "Received SAVPF profle in video offer but AVPF is not enabled: %s\n", m);
10251                continue;
10252             } else if ((!strcmp(protocol, "RTP/SAVP") || !strcmp(protocol, "UDP/TLS/RTP/SAVP")) && ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
10253                ast_log(LOG_WARNING, "Received SAVP profile in video offer but AVPF is enabled: %s\n", m);
10254                continue;
10255             } else if (!strcmp(protocol, "UDP/TLS/RTP/SAVP") || !strcmp(protocol, "UDP/TLS/RTP/SAVPF")) {
10256                secure_video = 1;
10257 
10258                if (p->vsrtp || (p->vsrtp = sip_srtp_alloc())) {
10259                   ast_set_flag(p->vsrtp, SRTP_CRYPTO_OFFER_OK);
10260                }
10261             } else if (!strcmp(protocol, "RTP/SAVP") || !strcmp(protocol, "RTP/SAVPF")) {
10262                secure_video = 1;
10263             } else if (!strcmp(protocol, "RTP/AVPF") && !ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
10264                ast_log(LOG_WARNING, "Received AVPF profile in video offer but AVPF is not enabled: %s\n", m);
10265                continue;
10266             } else if (!strcmp(protocol, "RTP/AVP") && ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
10267                ast_log(LOG_WARNING, "Received AVP profile in video offer but AVPF is enabled: %s\n", m);
10268                continue;
10269             } else if (strcmp(protocol, "RTP/AVP") && strcmp(protocol, "RTP/AVPF")) {
10270                ast_log(LOG_WARNING, "Unknown RTP profile in video offer: %s\n", m);
10271                continue;
10272             }
10273 
10274             video = TRUE;
10275             p->novideo = FALSE;
10276             offer->type = SDP_VIDEO;
10277             vportno = x;
10278 
10279             /* Scan through the RTP payload types specified in a "m=" line: */
10280             for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
10281                if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
10282                   ast_log(LOG_WARNING, "Invalid syntax in RTP video format list: %s\n", codecs);
10283                   res = -1;
10284                   goto process_sdp_cleanup;
10285                }
10286                if (debug) {
10287                   ast_verbose("Found RTP video format %u\n", codec);
10288                }
10289                ast_rtp_codecs_payloads_set_m_type(&newvideortp, NULL, codec);
10290             }
10291          } else {
10292             ast_log(LOG_WARNING, "Rejecting video media offer due to invalid or unsupported syntax: %s\n", m);
10293             res = -1;
10294             goto process_sdp_cleanup;
10295          }
10296       }
10297       /* Check for 'text' media offer */
10298       else if (strncmp(m, "text ", 5) == 0) {
10299          if ((sscanf(m, "text %30u/%30u %17s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||
10300              (sscanf(m, "text %30u %17s %n", &x, protocol, &len) == 2 && len > 0)) {
10301             codecs = m + len;
10302             /* produce zero-port m-line since it may be needed later
10303              * length is "m=text 0 " + protocol + " " + codecs + "\r\n\0" */
10304             if (!(offer->decline_m_line = ast_malloc(9 + strlen(protocol) + 1 + strlen(codecs) + 3))) {
10305                ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer declination\n");
10306                res = -1;
10307                goto process_sdp_cleanup;
10308             }
10309             /* guaranteed to be exactly the right length */
10310             sprintf(offer->decline_m_line, "m=text 0 %s %s\r\n", protocol, codecs);
10311 
10312             if (x == 0) {
10313                ast_log(LOG_WARNING, "Ignoring text stream offer because port number is zero\n");
10314                continue;
10315             }
10316 
10317             /* Check number of ports offered for stream */
10318             if (numberofports > 1) {
10319                ast_log(LOG_WARNING, "%u ports offered for text stream, not supported by Asterisk. Will try anyway...\n", numberofports);
10320             }
10321 
10322             if (!strcmp(protocol, "RTP/AVPF") && !ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
10323                ast_log(LOG_WARNING, "Received AVPF profile in text offer but AVPF is not enabled: %s\n", m);
10324                continue;
10325             } else if (!strcmp(protocol, "RTP/AVP") && ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
10326                ast_log(LOG_WARNING, "Received AVP profile in text offer but AVPF is enabled: %s\n", m);
10327                continue;
10328             } else if (strcmp(protocol, "RTP/AVP") && strcmp(protocol, "RTP/AVPF")) {
10329                ast_log(LOG_WARNING, "Unknown RTP profile in text offer: %s\n", m);
10330                continue;
10331             }
10332 
10333             if (has_media_stream(p, SDP_TEXT)) {
10334                ast_log(LOG_WARNING, "Declining non-primary text stream: %s\n", m);
10335                continue;
10336             }
10337 
10338             text = TRUE;
10339             p->notext = FALSE;
10340             offer->type = SDP_TEXT;
10341             tportno = x;
10342 
10343             /* Scan through the RTP payload types specified in a "m=" line: */
10344             for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
10345                if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
10346                   ast_log(LOG_WARNING, "Invalid syntax in RTP video format list: %s\n", codecs);
10347                   res = -1;
10348                   goto process_sdp_cleanup;
10349                }
10350                if (debug) {
10351                   ast_verbose("Found RTP text format %u\n", codec);
10352                }
10353                ast_rtp_codecs_payloads_set_m_type(&newtextrtp, NULL, codec);
10354             }
10355          } else {
10356             ast_log(LOG_WARNING, "Rejecting text stream offer due to invalid or unsupported syntax: %s\n", m);
10357             res = -1;
10358             goto process_sdp_cleanup;
10359          }
10360       }
10361       /* Check for 'image' media offer */
10362       else if (strncmp(m, "image ", 6) == 0) {
10363          if (((sscanf(m, "image %30u udptl t38%n", &x, &len) == 1 && len > 0) ||
10364               (sscanf(m, "image %30u UDPTL t38%n", &x, &len) == 1 && len > 0))) {
10365             /* produce zero-port m-line since it may be needed later
10366              * length is "m=image 0 udptl t38" + "\r\n\0" */
10367             if (!(offer->decline_m_line = ast_malloc(22))) {
10368                ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer declination\n");
10369                res = -1;
10370                goto process_sdp_cleanup;
10371             }
10372             /* guaranteed to be exactly the right length */
10373             strcpy(offer->decline_m_line, "m=image 0 udptl t38\r\n");
10374 
10375             if (x == 0) {
10376                ast_log(LOG_WARNING, "Ignoring image stream offer because port number is zero\n");
10377                continue;
10378             }
10379 
10380             if (initialize_udptl(p)) {
10381                ast_log(LOG_WARNING, "Failed to initialize UDPTL, declining image stream\n");
10382                continue;
10383             }
10384 
10385             if (has_media_stream(p, SDP_IMAGE)) {
10386                ast_log(LOG_WARNING, "Declining non-primary image stream: %s\n", m);
10387                continue;
10388             }
10389 
10390             image = TRUE;
10391             if (debug) {
10392                ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
10393             }
10394 
10395             offer->type = SDP_IMAGE;
10396             udptlportno = x;
10397 
10398             if (p->t38.state != T38_ENABLED) {
10399                memset(&p->t38.their_parms, 0, sizeof(p->t38.their_parms));
10400 
10401                /* default EC to none, the remote end should
10402                 * respond with the EC they want to use */
10403                ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
10404             }
10405          } else if (sscanf(m, "image %30u %17s t38%n", &x, protocol, &len) == 2 && len > 0) {
10406             ast_log(LOG_WARNING, "Declining image stream due to unsupported transport: %s\n", m);
10407             /* produce zero-port m-line since this is guaranteed to be declined
10408              * length is "m=image 0 strlen(protocol) t38" + "\r\n\0" */
10409             if (!(offer->decline_m_line = ast_malloc(10 + strlen(protocol) + 7))) {
10410                ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer declination\n");
10411                res = -1;
10412                goto process_sdp_cleanup;
10413             }
10414             /* guaranteed to be exactly the right length */
10415             sprintf(offer->decline_m_line, "m=image 0 %s t38\r\n", protocol);
10416             continue;
10417          } else {
10418             ast_log(LOG_WARNING, "Rejecting image media offer due to invalid or unsupported syntax: %s\n", m);
10419             res = -1;
10420             goto process_sdp_cleanup;
10421          }
10422       } else {
10423          char type[20] = {0,};
10424          if ((sscanf(m, "%19s %30u/%30u %n", type, &x, &numberofports, &len) == 3 && len > 0) ||
10425               (sscanf(m, "%19s %30u %n", type, &x, &len) == 2 && len > 0)) {
10426             /* produce zero-port m-line since it may be needed later
10427              * length is "m=" + type + " 0 " + remainder + "\r\n\0" */
10428             if (!(offer->decline_m_line = ast_malloc(2 + strlen(type) + 3 + strlen(m + len) + 3))) {
10429                ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer declination\n");
10430                res = -1;
10431                goto process_sdp_cleanup;
10432             }
10433             /* guaranteed to be long enough */
10434             sprintf(offer->decline_m_line, "m=%s 0 %s\r\n", type, m + len);
10435             continue;
10436          } else {
10437             ast_log(LOG_WARNING, "Unsupported top-level media type in offer: %s\n", m);
10438             res = -1;
10439             goto process_sdp_cleanup;
10440          }
10441       }
10442 
10443       /* Media stream specific parameters */
10444       while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
10445          int processed = FALSE;
10446 
10447          switch (type) {
10448          case 'c':
10449             if (audio) {
10450                if (process_sdp_c(value, &audiosa)) {
10451                   processed = TRUE;
10452                   sa = &audiosa;
10453                }
10454             } else if (video) {
10455                if (process_sdp_c(value, &videosa)) {
10456                   processed = TRUE;
10457                   vsa = &videosa;
10458                }
10459             } else if (text) {
10460                if (process_sdp_c(value, &textsa)) {
10461                   processed = TRUE;
10462                   tsa = &textsa;
10463                }
10464             } else if (image) {
10465                if (process_sdp_c(value, &imagesa)) {
10466                   processed = TRUE;
10467                   isa = &imagesa;
10468                }
10469             }
10470             break;
10471          case 'a':
10472             /* Audio specific scanning */
10473             if (audio) {
10474                if (process_sdp_a_ice(value, p, p->rtp)) {
10475                   processed = TRUE;
10476                } else if (process_sdp_a_dtls(value, p, p->rtp)) {
10477                   processed_crypto = TRUE;
10478                   processed = TRUE;
10479                   if (p->srtp) {
10480                      ast_set_flag(p->srtp, SRTP_CRYPTO_OFFER_OK);
10481                   }
10482                } else if (process_sdp_a_sendonly(value, &sendonly)) {
10483                   processed = TRUE;
10484                } else if (!processed_crypto && process_crypto(p, p->rtp, &p->srtp, value)) {
10485                   processed_crypto = TRUE;
10486                   processed = TRUE;
10487                } else if (process_sdp_a_audio(value, p, &newaudiortp, &last_rtpmap_codec)) {
10488                   processed = TRUE;
10489                }
10490             }
10491             /* Video specific scanning */
10492             else if (video) {
10493                if (process_sdp_a_ice(value, p, p->vrtp)) {
10494                   processed = TRUE;
10495                } else if (process_sdp_a_dtls(value, p, p->vrtp)) {
10496                   processed_crypto = TRUE;
10497                   processed = TRUE;
10498                   if (p->vsrtp) {
10499                      ast_set_flag(p->vsrtp, SRTP_CRYPTO_OFFER_OK);
10500                   }
10501                } else if (!processed_crypto && process_crypto(p, p->vrtp, &p->vsrtp, value)) {
10502                   processed_crypto = TRUE;
10503                   processed = TRUE;
10504                } else if (process_sdp_a_video(value, p, &newvideortp, &last_rtpmap_codec)) {
10505                   processed = TRUE;
10506                }
10507             }
10508             /* Text (T.140) specific scanning */
10509             else if (text) {
10510                if (process_sdp_a_ice(value, p, p->trtp)) {
10511                   processed = TRUE;
10512                } else if (process_sdp_a_text(value, p, &newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec)) {
10513                   processed = TRUE;
10514                } else if (!processed_crypto && process_crypto(p, p->trtp, &p->tsrtp, value)) {
10515                   processed_crypto = TRUE;
10516                   processed = TRUE;
10517                }
10518             }
10519             /* Image (T.38 FAX) specific scanning */
10520             else if (image) {
10521                if (process_sdp_a_image(value, p))
10522                   processed = TRUE;
10523             }
10524             break;
10525          }
10526 
10527          ast_debug(3, "Processing media-level (%s) SDP %c=%s... %s\n",
10528               (audio == TRUE)? "audio" : (video == TRUE)? "video" : (text == TRUE)? "text" : "image",
10529               type, value,
10530               (processed == TRUE)? "OK." : "UNSUPPORTED OR FAILED.");
10531       }
10532 
10533       /* Ensure crypto lines are provided where necessary */
10534       if (audio && secure_audio && !processed_crypto) {
10535          ast_log(LOG_WARNING, "Rejecting secure audio stream without encryption details: %s\n", m);
10536          return -1;
10537       } else if (video && secure_video && !processed_crypto) {
10538          ast_log(LOG_WARNING, "Rejecting secure video stream without encryption details: %s\n", m);
10539          return -1;
10540       }
10541    }
10542 
10543    /* Sanity checks */
10544    if (!sa && !vsa && !tsa && !isa) {
10545       ast_log(LOG_WARNING, "Insufficient information in SDP (c=)...\n");
10546       res = -1;
10547       goto process_sdp_cleanup;
10548    }
10549 
10550    if ((portno == -1) &&
10551        (vportno == -1) &&
10552        (tportno == -1) &&
10553        (udptlportno == -1)) {
10554       ast_log(LOG_WARNING, "Failing due to no acceptable offer found\n");
10555       res = -1;
10556       goto process_sdp_cleanup;
10557    }
10558 
10559    if (secure_audio && !(p->srtp && (ast_test_flag(p->srtp, SRTP_CRYPTO_OFFER_OK)))) {
10560       ast_log(LOG_WARNING, "Can't provide secure audio requested in SDP offer\n");
10561       res = -1;
10562       goto process_sdp_cleanup;
10563    }
10564 
10565    if (!secure_audio && p->srtp) {
10566       ast_log(LOG_WARNING, "We are requesting SRTP for audio, but they responded without it!\n");
10567       res = -1;
10568       goto process_sdp_cleanup;
10569    }
10570 
10571    if (secure_video && !(p->vsrtp && (ast_test_flag(p->vsrtp, SRTP_CRYPTO_OFFER_OK)))) {
10572       ast_log(LOG_WARNING, "Can't provide secure video requested in SDP offer\n");
10573       res = -1;
10574       goto process_sdp_cleanup;
10575    }
10576 
10577    if (!p->novideo && !secure_video && p->vsrtp) {
10578       ast_log(LOG_WARNING, "We are requesting SRTP for video, but they responded without it!\n");
10579       res = -1;
10580       goto process_sdp_cleanup;
10581    }
10582 
10583    if (!(secure_audio || secure_video) && ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP)) {
10584       ast_log(LOG_WARNING, "Matched device setup to use SRTP, but request was not!\n");
10585       res = -1;
10586       goto process_sdp_cleanup;
10587    }
10588 
10589    if (udptlportno == -1) {
10590       change_t38_state(p, T38_DISABLED);
10591    }
10592 
10593    /* Now gather all of the codecs that we are asked for: */
10594    ast_rtp_codecs_payload_formats(&newaudiortp, peercapability, &peernoncodeccapability);
10595    ast_rtp_codecs_payload_formats(&newvideortp, vpeercapability, &vpeernoncodeccapability);
10596    ast_rtp_codecs_payload_formats(&newtextrtp, tpeercapability, &tpeernoncodeccapability);
10597 
10598    ast_format_cap_append(newpeercapability, peercapability);
10599    ast_format_cap_append(newpeercapability, vpeercapability);
10600    ast_format_cap_append(newpeercapability, tpeercapability);
10601 
10602    ast_format_cap_joint_copy(p->caps, newpeercapability, newjointcapability);
10603    if (ast_format_cap_is_empty(newjointcapability) && udptlportno == -1) {
10604       ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
10605       /* Do NOT Change current setting */
10606       res = -1;
10607       goto process_sdp_cleanup;
10608    }
10609 
10610    newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
10611 
10612    if (debug) {
10613       /* shame on whoever coded this.... */
10614       char s1[SIPBUFSIZE], s2[SIPBUFSIZE], s3[SIPBUFSIZE], s4[SIPBUFSIZE], s5[SIPBUFSIZE];
10615 
10616       ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s/text=%s, combined - %s\n",
10617              ast_getformatname_multiple(s1, SIPBUFSIZE, p->caps),
10618              ast_getformatname_multiple(s2, SIPBUFSIZE, peercapability),
10619              ast_getformatname_multiple(s3, SIPBUFSIZE, vpeercapability),
10620              ast_getformatname_multiple(s4, SIPBUFSIZE, tpeercapability),
10621              ast_getformatname_multiple(s5, SIPBUFSIZE, newjointcapability));
10622    }
10623    if (debug) {
10624       struct ast_str *s1 = ast_str_alloca(SIPBUFSIZE);
10625       struct ast_str *s2 = ast_str_alloca(SIPBUFSIZE);
10626       struct ast_str *s3 = ast_str_alloca(SIPBUFSIZE);
10627 
10628       ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
10629              ast_rtp_lookup_mime_multiple2(s1, NULL, p->noncodeccapability, 0, 0),
10630              ast_rtp_lookup_mime_multiple2(s2, NULL, peernoncodeccapability, 0, 0),
10631              ast_rtp_lookup_mime_multiple2(s3, NULL, newnoncodeccapability, 0, 0));
10632    }
10633 
10634    if (portno != -1 || vportno != -1 || tportno != -1) {
10635       /* We are now ready to change the sip session and RTP structures with the offered codecs, since
10636          they are acceptable */
10637       ast_format_cap_copy(p->jointcaps, newjointcapability);                /* Our joint codec profile for this call */
10638       ast_format_cap_copy(p->peercaps, newpeercapability);                  /* The other side's capability in latest offer */
10639       p->jointnoncodeccapability = newnoncodeccapability;     /* DTMF capabilities */
10640 
10641       /* respond with single most preferred joint codec, limiting the other side's choice */
10642       if (ast_test_flag(&p->flags[1], SIP_PAGE2_PREFERRED_CODEC)) {
10643          ast_codec_choose(&p->prefs, p->jointcaps, 1, &tmp_fmt);
10644          ast_format_cap_set(p->jointcaps, &tmp_fmt);
10645       }
10646    }
10647 
10648    /* Setup audio address and port */
10649    if (p->rtp) {
10650       if (sa && portno > 0) {
10651          start_ice(p->rtp, (req->method != SIP_RESPONSE) ? 0 : 1);
10652          ast_sockaddr_set_port(sa, portno);
10653          ast_rtp_instance_set_remote_address(p->rtp, sa);
10654          if (debug) {
10655             ast_verbose("Peer audio RTP is at port %s\n",
10656                    ast_sockaddr_stringify(sa));
10657          }
10658 
10659          ast_rtp_codecs_payloads_copy(&newaudiortp, ast_rtp_instance_get_codecs(p->rtp), p->rtp);
10660          /* Ensure RTCP is enabled since it may be inactive
10661             if we're coming back from a T.38 session */
10662          ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 1);
10663          /* Ensure audio RTCP reads are enabled */
10664          if (p->owner) {
10665             ast_channel_set_fd(p->owner, 1, ast_rtp_instance_fd(p->rtp, 1));
10666          }
10667 
10668          if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
10669             ast_clear_flag(&p->flags[0], SIP_DTMF);
10670             if (newnoncodeccapability & AST_RTP_DTMF) {
10671                /* XXX Would it be reasonable to drop the DSP at this point? XXX */
10672                ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
10673                /* Since RFC2833 is now negotiated we need to change some properties of the RTP stream */
10674                ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, 1);
10675                ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
10676             } else {
10677                ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
10678             }
10679          }
10680       } else if (udptlportno > 0) {
10681          if (debug)
10682             ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session.\n");
10683          /* Prevent audio RTCP reads */
10684          if (p->owner) {
10685             ast_channel_set_fd(p->owner, 1, -1);
10686          }
10687          /* Silence RTCP while audio RTP is inactive */
10688          ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 0);
10689       } else {
10690          ast_rtp_instance_stop(p->rtp);
10691          if (debug)
10692             ast_verbose("Peer doesn't provide audio\n");
10693       }
10694    }
10695 
10696    /* Setup video address and port */
10697    if (p->vrtp) {
10698       if (vsa && vportno > 0) {
10699          start_ice(p->vrtp, (req->method != SIP_RESPONSE) ? 0 : 1);
10700          ast_sockaddr_set_port(vsa, vportno);
10701          ast_rtp_instance_set_remote_address(p->vrtp, vsa);
10702          if (debug) {
10703             ast_verbose("Peer video RTP is at port %s\n",
10704                    ast_sockaddr_stringify(vsa));
10705          }
10706          ast_rtp_codecs_payloads_copy(&newvideortp, ast_rtp_instance_get_codecs(p->vrtp), p->vrtp);
10707       } else {
10708          ast_rtp_instance_stop(p->vrtp);
10709          if (debug)
10710             ast_verbose("Peer doesn't provide video\n");
10711       }
10712    }
10713 
10714    /* Setup text address and port */
10715    if (p->trtp) {
10716       if (tsa && tportno > 0) {
10717          start_ice(p->trtp, (req->method != SIP_RESPONSE) ? 0 : 1);
10718          ast_sockaddr_set_port(tsa, tportno);
10719          ast_rtp_instance_set_remote_address(p->trtp, tsa);
10720          if (debug) {
10721             ast_verbose("Peer T.140 RTP is at port %s\n",
10722                    ast_sockaddr_stringify(tsa));
10723          }
10724          if (ast_format_cap_iscompatible(p->jointcaps, ast_format_set(&tmp_fmt, AST_FORMAT_T140RED, 0))) {
10725             p->red = 1;
10726             ast_rtp_red_init(p->trtp, 300, red_data_pt, 2);
10727          } else {
10728             p->red = 0;
10729          }
10730          ast_rtp_codecs_payloads_copy(&newtextrtp, ast_rtp_instance_get_codecs(p->trtp), p->trtp);
10731       } else {
10732          ast_rtp_instance_stop(p->trtp);
10733          if (debug)
10734             ast_verbose("Peer doesn't provide T.140\n");
10735       }
10736    }
10737 
10738    /* Setup image address and port */
10739    if (p->udptl) {
10740       if (isa && udptlportno > 0) {
10741          if (ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP) && ast_test_flag(&p->flags[1], SIP_PAGE2_UDPTL_DESTINATION)) {
10742             ast_rtp_instance_get_remote_address(p->rtp, isa);
10743             if (!ast_sockaddr_isnull(isa) && debug) {
10744                ast_debug(1, "Peer T.38 UDPTL is set behind NAT and with destination, destination address now %s\n", ast_sockaddr_stringify(isa));
10745             }
10746          }
10747          ast_sockaddr_set_port(isa, udptlportno);
10748          ast_udptl_set_peer(p->udptl, isa);
10749          if (debug)
10750             ast_debug(1,"Peer T.38 UDPTL is at port %s\n", ast_sockaddr_stringify(isa));
10751 
10752          /* verify the far max ifp can be calculated. this requires far max datagram to be set. */
10753          if (!ast_udptl_get_far_max_datagram(p->udptl)) {
10754             /* setting to zero will force a default if none was provided by the SDP */
10755             ast_udptl_set_far_max_datagram(p->udptl, 0);
10756          }
10757 
10758          /* Remote party offers T38, we need to update state */
10759          if ((t38action == SDP_T38_ACCEPT) &&
10760              (p->t38.state == T38_LOCAL_REINVITE)) {
10761             change_t38_state(p, T38_ENABLED);
10762          } else if ((t38action == SDP_T38_INITIATE) &&
10763                p->owner && p->lastinvite) {
10764             change_t38_state(p, T38_PEER_REINVITE); /* T38 Offered in re-invite from remote party */
10765             /* If fax detection is enabled then send us off to the fax extension */
10766             if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38)) {
10767                ast_channel_lock(p->owner);
10768                if (strcmp(ast_channel_exten(p->owner), "fax")) {
10769                   const char *target_context = S_OR(ast_channel_macrocontext(p->owner), ast_channel_context(p->owner));
10770                   ast_channel_unlock(p->owner);
10771                   if (ast_exists_extension(p->owner, target_context, "fax", 1,
10772                      S_COR(ast_channel_caller(p->owner)->id.number.valid, ast_channel_caller(p->owner)->id.number.str, NULL))) {
10773                      ast_verb(2, "Redirecting '%s' to fax extension due to peer T.38 re-INVITE\n", ast_channel_name(p->owner));
10774                      pbx_builtin_setvar_helper(p->owner, "FAXEXTEN", ast_channel_exten(p->owner));
10775                      if (ast_async_goto(p->owner, target_context, "fax", 1)) {
10776                         ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast_channel_name(p->owner), target_context);
10777                      }
10778                   } else {
10779                      ast_log(LOG_NOTICE, "T.38 re-INVITE detected but no fax extension\n");
10780                   }
10781                } else {
10782                   ast_channel_unlock(p->owner);
10783                }
10784             }
10785          }
10786       } else {
10787          change_t38_state(p, T38_DISABLED);
10788          ast_udptl_stop(p->udptl);
10789          if (debug)
10790             ast_debug(1, "Peer doesn't provide T.38 UDPTL\n");
10791       }
10792    }
10793 
10794    if ((portno == -1) && (p->t38.state != T38_DISABLED) && (p->t38.state != T38_REJECTED)) {
10795       ast_debug(3, "Have T.38 but no audio, accepting offer anyway\n");
10796       res = 0;
10797       goto process_sdp_cleanup;
10798    }
10799 
10800    /* Ok, we're going with this offer */
10801    ast_debug(2, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, p->jointcaps));
10802 
10803    if (!p->owner) { /* There's no open channel owning us so we can return here. For a re-invite or so, we proceed */
10804       res = 0;
10805       goto process_sdp_cleanup;
10806    }
10807 
10808    ast_debug(4, "We have an owner, now see if we need to change this call\n");
10809    if (ast_format_cap_has_type(p->jointcaps, AST_FORMAT_TYPE_AUDIO)) {
10810       if (debug) {
10811          char s1[SIPBUFSIZE], s2[SIPBUFSIZE];
10812          ast_debug(1, "Setting native formats after processing SDP. peer joint formats %s, old nativeformats %s\n",
10813             ast_getformatname_multiple(s1, SIPBUFSIZE, p->jointcaps),
10814             ast_getformatname_multiple(s2, SIPBUFSIZE, ast_channel_nativeformats(p->owner)));
10815       }
10816 
10817       ast_codec_choose(&p->prefs, p->jointcaps, 1, &tmp_fmt);
10818 
10819       ast_format_cap_set(ast_channel_nativeformats(p->owner), &tmp_fmt);
10820       ast_format_cap_joint_append(p->caps, vpeercapability, ast_channel_nativeformats(p->owner));
10821       ast_format_cap_joint_append(p->caps, tpeercapability, ast_channel_nativeformats(p->owner));
10822 
10823       ast_set_read_format(p->owner, ast_channel_readformat(p->owner));
10824       ast_set_write_format(p->owner, ast_channel_writeformat(p->owner));
10825    }
10826 
10827    if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) && (!ast_sockaddr_isnull(sa) || !ast_sockaddr_isnull(vsa) || !ast_sockaddr_isnull(tsa) || !ast_sockaddr_isnull(isa)) && (!sendonly || sendonly == -1)) {
10828       ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
10829       /* Activate a re-invite */
10830       ast_queue_frame(p->owner, &ast_null_frame);
10831       change_hold_state(p, req, FALSE, sendonly);
10832    } else if ((sockaddr_is_null_or_any(sa) && sockaddr_is_null_or_any(vsa) && sockaddr_is_null_or_any(tsa) && sockaddr_is_null_or_any(isa)) || (sendonly && sendonly != -1)) {
10833       ast_queue_control_data(p->owner, AST_CONTROL_HOLD,
10834                    S_OR(p->mohsuggest, NULL),
10835                    !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
10836       if (sendonly)
10837          ast_rtp_instance_stop(p->rtp);
10838       /* RTCP needs to go ahead, even if we're on hold!!! */
10839       /* Activate a re-invite */
10840       ast_queue_frame(p->owner, &ast_null_frame);
10841       change_hold_state(p, req, TRUE, sendonly);
10842    }
10843 
10844 process_sdp_cleanup:
10845    if (res) {
10846       offered_media_list_destroy(p);
10847    }
10848    ast_rtp_codecs_payloads_destroy(&newtextrtp);
10849    ast_rtp_codecs_payloads_destroy(&newvideortp);
10850    ast_rtp_codecs_payloads_destroy(&newaudiortp);
10851    ast_format_cap_destroy(peercapability);
10852    ast_format_cap_destroy(vpeercapability);
10853    ast_format_cap_destroy(tpeercapability);
10854    ast_format_cap_destroy(newjointcapability);
10855    ast_format_cap_destroy(newpeercapability);
10856    return res;
10857 }
10858 
10859 static int process_sdp_o(const char *o, struct sip_pvt *p)
10860 {
10861    char *o_copy;
10862    char *token;
10863    int64_t rua_version;
10864 
10865    /* Store the SDP version number of remote UA. This will allow us to
10866    distinguish between session modifications and session refreshes. If
10867    the remote UA does not send an incremented SDP version number in a
10868    subsequent RE-INVITE then that means its not changing media session.
10869    The RE-INVITE may have been sent to update connected party, remote
10870    target or to refresh the session (Session-Timers).  Asterisk must not
10871    change media session and increment its own version number in answer
10872    SDP in this case. */
10873 
10874    p->session_modify = TRUE;
10875 
10876    if (ast_strlen_zero(o)) {
10877       ast_log(LOG_WARNING, "SDP syntax error. SDP without an o= line\n");
10878       return FALSE;
10879    }
10880 
10881    o_copy = ast_strdupa(o);
10882    token = strsep(&o_copy, " ");  /* Skip username   */
10883    if (!o_copy) {
10884       ast_log(LOG_WARNING, "SDP syntax error in o= line username\n");
10885       return FALSE;
10886    }
10887    token = strsep(&o_copy, " ");  /* Skip session-id */
10888    if (!o_copy) {
10889       ast_log(LOG_WARNING, "SDP syntax error in o= line session-id\n");
10890       return FALSE;
10891    }
10892    token = strsep(&o_copy, " ");  /* Version         */
10893    if (!o_copy) {
10894       ast_log(LOG_WARNING, "SDP syntax error in o= line\n");
10895       return FALSE;
10896    }
10897    if (!sscanf(token, "%30" SCNd64, &rua_version)) {
10898       ast_log(LOG_WARNING, "SDP syntax error in o= line version\n");
10899       return FALSE;
10900    }
10901 
10902    /* we need to check the SDP version number the other end sent us;
10903     * our rules for deciding what to accept are a bit complex.
10904     *
10905     * 1) if 'ignoresdpversion' has been set for this dialog, then
10906     *    we will just accept whatever they sent and assume it is
10907     *    a modification of the session, even if it is not
10908     * 2) otherwise, if this is the first SDP we've seen from them
10909     *    we accept it
10910     * 3) otherwise, if the new SDP version number is higher than the
10911     *    old one, we accept it
10912     * 4) otherwise, if this SDP is in response to us requesting a switch
10913     *    to T.38, we accept the SDP, but also generate a warning message
10914     *    that this peer should have the 'ignoresdpversion' option set,
10915     *    because it is not following the SDP offer/answer RFC; if we did
10916     *    not request a switch to T.38, then we stop parsing the SDP, as it
10917     *    has not changed from the previous version
10918     */
10919 
10920    if (ast_test_flag(&p->flags[1], SIP_PAGE2_IGNORESDPVERSION) ||
10921        (p->sessionversion_remote < 0) ||
10922        (p->sessionversion_remote < rua_version)) {
10923       p->sessionversion_remote = rua_version;
10924    } else {
10925       if (p->t38.state == T38_LOCAL_REINVITE) {
10926          p->sessionversion_remote = rua_version;
10927          ast_log(LOG_WARNING, "Call %s responded to our T.38 reinvite without changing SDP version; 'ignoresdpversion' should be set for this peer.\n", p->callid);
10928       } else {
10929          p->session_modify = FALSE;
10930          ast_debug(2, "Call %s responded to our reinvite without changing SDP version; ignoring SDP.\n", p->callid);
10931          return FALSE;
10932       }
10933    }
10934 
10935    return TRUE;
10936 }
10937 
10938 static int process_sdp_c(const char *c, struct ast_sockaddr *addr)
10939 {
10940    char proto[4], host[258];
10941    int af;
10942 
10943    /* Check for Media-description-level-address */
10944    if (sscanf(c, "IN %3s %255s", proto, host) == 2) {
10945       if (!strcmp("IP4", proto)) {
10946          af = AF_INET;
10947       } else if (!strcmp("IP6", proto)) {
10948          af = AF_INET6;
10949       } else {
10950          ast_log(LOG_WARNING, "Unknown protocol '%s'.\n", proto);
10951          return FALSE;
10952       }
10953       if (ast_sockaddr_resolve_first_af(addr, host, 0, af)) {
10954          ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in c= line, '%s'\n", c);
10955          return FALSE;
10956       }
10957       return TRUE;
10958    } else {
10959       ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
10960       return FALSE;
10961    }
10962    return FALSE;
10963 }
10964 
10965 static int process_sdp_a_sendonly(const char *a, int *sendonly)
10966 {
10967    int found = FALSE;
10968 
10969    if (!strcasecmp(a, "sendonly")) {
10970       if (*sendonly == -1)
10971          *sendonly = 1;
10972       found = TRUE;
10973    } else if (!strcasecmp(a, "inactive")) {
10974       if (*sendonly == -1)
10975          *sendonly = 2;
10976       found = TRUE;
10977    }  else if (!strcasecmp(a, "sendrecv")) {
10978       if (*sendonly == -1)
10979          *sendonly = 0;
10980       found = TRUE;
10981    }
10982    return found;
10983 }
10984 
10985 static int process_sdp_a_ice(const char *a, struct sip_pvt *p, struct ast_rtp_instance *instance)
10986 {
10987    struct ast_rtp_engine_ice *ice;
10988    int found = FALSE;
10989    char ufrag[256], pwd[256], foundation[32], transport[4], address[46], cand_type[6], relay_address[46] = "";
10990    struct ast_rtp_engine_ice_candidate candidate = { 0, };
10991    unsigned int port, relay_port = 0;
10992 
10993    if (!instance || !(ice = ast_rtp_instance_get_ice(instance))) {
10994       return found;
10995    }
10996 
10997    if (sscanf(a, "ice-ufrag: %255s", ufrag) == 1) {
10998       ice->set_authentication(instance, ufrag, NULL);
10999       found = TRUE;
11000    } else if (sscanf(a, "ice-pwd: %255s", pwd) == 1) {
11001       ice->set_authentication(instance, NULL, pwd);
11002       found = TRUE;
11003    } else if (sscanf(a, "candidate: %31s %30u %3s %30u %23s %30u typ %5s %*s %23s %*s %30u", foundation, &candidate.id, transport, (unsigned *)&candidate.priority,
11004            address, &port, cand_type, relay_address, &relay_port) >= 7) {
11005       candidate.foundation = foundation;
11006       candidate.transport = transport;
11007 
11008       ast_sockaddr_parse(&candidate.address, address, PARSE_PORT_FORBID);
11009       ast_sockaddr_set_port(&candidate.address, port);
11010 
11011       if (!strcasecmp(cand_type, "host")) {
11012          candidate.type = AST_RTP_ICE_CANDIDATE_TYPE_HOST;
11013       } else if (!strcasecmp(cand_type, "srflx")) {
11014          candidate.type = AST_RTP_ICE_CANDIDATE_TYPE_SRFLX;
11015       } else if (!strcasecmp(cand_type, "relay")) {
11016          candidate.type = AST_RTP_ICE_CANDIDATE_TYPE_RELAYED;
11017       } else {
11018          return found;
11019       }
11020 
11021       if (!ast_strlen_zero(relay_address)) {
11022          ast_sockaddr_parse(&candidate.relay_address, relay_address, PARSE_PORT_FORBID);
11023       }
11024 
11025       if (relay_port) {
11026          ast_sockaddr_set_port(&candidate.relay_address, relay_port);
11027       }
11028 
11029       ice->add_remote_candidate(instance, &candidate);
11030 
11031       found = TRUE;
11032    } else if (!strcasecmp(a, "ice-lite")) {
11033       ice->ice_lite(instance);
11034       found = TRUE;
11035    }
11036 
11037    return found;
11038 }
11039 
11040 static int process_sdp_a_dtls(const char *a, struct sip_pvt *p, struct ast_rtp_instance *instance)
11041 {
11042    struct ast_rtp_engine_dtls *dtls;
11043    int found = FALSE;
11044    char value[256], hash[32];
11045 
11046    if (!instance || !p->dtls_cfg.enabled || !(dtls = ast_rtp_instance_get_dtls(instance))) {
11047       return found;
11048    }
11049 
11050    if (sscanf(a, "setup: %255s", value) == 1) {
11051       found = TRUE;
11052 
11053       if (!strcasecmp(value, "active")) {
11054          dtls->set_setup(instance, AST_RTP_DTLS_SETUP_ACTIVE);
11055       } else if (!strcasecmp(value, "passive")) {
11056          dtls->set_setup(instance, AST_RTP_DTLS_SETUP_PASSIVE);
11057       } else if (!strcasecmp(value, "actpass")) {
11058          dtls->set_setup(instance, AST_RTP_DTLS_SETUP_ACTPASS);
11059       } else if (!strcasecmp(value, "holdconn")) {
11060          dtls->set_setup(instance, AST_RTP_DTLS_SETUP_HOLDCONN);
11061       } else {
11062          ast_log(LOG_WARNING, "Unsupported setup attribute value '%s' received on dialog '%s'\n",
11063             value, p->callid);
11064       }
11065    } else if (sscanf(a, "connection: %255s", value) == 1) {
11066       found = TRUE;
11067 
11068       if (!strcasecmp(value, "new")) {
11069          dtls->reset(instance);
11070       } else if (!strcasecmp(value, "existing")) {
11071          /* Since they want to just use what already exists we go on as if nothing happened */
11072       } else {
11073          ast_log(LOG_WARNING, "Unsupported connection attribute value '%s' received on dialog '%s'\n",
11074             value, p->callid);
11075       }
11076    } else if (sscanf(a, "fingerprint: %31s %255s", hash, value) == 2) {
11077       found = TRUE;
11078 
11079       if (!strcasecmp(hash, "sha-1")) {
11080          dtls->set_fingerprint(instance, AST_RTP_DTLS_HASH_SHA1, value);
11081       } else if (!strcasecmp(hash, "sha-256")) {
11082          dtls->set_fingerprint(instance, AST_RTP_DTLS_HASH_SHA256, value);
11083       } else {
11084          ast_log(LOG_WARNING, "Unsupported fingerprint hash type '%s' received on dialog '%s'\n",
11085             hash, p->callid);
11086       }
11087    }
11088 
11089    return found;
11090 }
11091 
11092 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec)
11093 {
11094    int found = FALSE;
11095    unsigned int codec;
11096    char mimeSubtype[128];
11097    char fmtp_string[256];
11098    unsigned int sample_rate;
11099    int debug = sip_debug_test_pvt(p);
11100 
11101    if (!strncasecmp(a, "ptime", 5)) {
11102       char *tmp = strrchr(a, ':');
11103       long int framing = 0;
11104       if (tmp) {
11105          tmp++;
11106          framing = strtol(tmp, NULL, 10);
11107          if (framing == LONG_MIN || framing == LONG_MAX) {
11108             framing = 0;
11109             ast_debug(1, "Can't read framing from SDP: %s\n", a);
11110          }
11111       }
11112       if (framing && p->autoframing) {
11113          struct ast_codec_pref *pref = &ast_rtp_instance_get_codecs(p->rtp)->pref;
11114          int codec_n;
11115          for (codec_n = 0; codec_n < AST_RTP_MAX_PT; codec_n++) {
11116             struct ast_rtp_payload_type format = ast_rtp_codecs_payload_lookup(ast_rtp_instance_get_codecs(p->rtp), codec_n);
11117             if (!format.asterisk_format)  /* non-codec or not found */
11118                continue;
11119             ast_debug(1, "Setting framing for %s to %ld\n", ast_getformatname(&format.format), framing);
11120             ast_codec_pref_setsize(pref, &format.format, framing);
11121          }
11122          ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, pref);
11123       }
11124       found = TRUE;
11125    } else if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
11126       /* We have a rtpmap to handle */
11127       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
11128          if (!(ast_rtp_codecs_payloads_set_rtpmap_type_rate(newaudiortp, NULL, codec, "audio", mimeSubtype,
11129              ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0, sample_rate))) {
11130             if (debug)
11131                ast_verbose("Found audio description format %s for ID %u\n", mimeSubtype, codec);
11132             //found_rtpmap_codecs[last_rtpmap_codec] = codec;
11133             (*last_rtpmap_codec)++;
11134             found = TRUE;
11135          } else {
11136             ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
11137             if (debug)
11138                ast_verbose("Found unknown media description format %s for ID %u\n", mimeSubtype, codec);
11139          }
11140       } else {
11141          if (debug)
11142             ast_verbose("Discarded description format %s for ID %u\n", mimeSubtype, codec);
11143       }
11144    } else if (sscanf(a, "fmtp: %30u %255[^\t\n]", &codec, fmtp_string) == 2) {
11145       struct ast_format *format;
11146 
11147       if ((format = ast_rtp_codecs_get_payload_format(newaudiortp, codec))) {
11148          unsigned int bit_rate;
11149 
11150          if (!ast_format_sdp_parse(format, fmtp_string)) {
11151             found = TRUE;
11152          } else {
11153             ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
11154          }
11155 
11156          switch ((int) format->id) {
11157          case AST_FORMAT_SIREN7:
11158             if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
11159                if (bit_rate != 32000) {
11160                   ast_log(LOG_WARNING, "Got Siren7 offer at %u bps, but only 32000 bps supported; ignoring.\n", bit_rate);
11161                   ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
11162                } else {
11163                   found = TRUE;
11164                }
11165             }
11166             break;
11167          case AST_FORMAT_SIREN14:
11168             if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
11169                if (bit_rate != 48000) {
11170                   ast_log(LOG_WARNING, "Got Siren14 offer at %u bps, but only 48000 bps supported; ignoring.\n", bit_rate);
11171                   ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
11172                } else {
11173                   found = TRUE;
11174                }
11175             }
11176             break;
11177          case AST_FORMAT_G719:
11178             if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
11179                if (bit_rate != 64000) {
11180                   ast_log(LOG_WARNING, "Got G.719 offer at %u bps, but only 64000 bps supported; ignoring.\n", bit_rate);
11181                   ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
11182                } else {
11183                   found = TRUE;
11184                }
11185             }
11186             break;
11187          }
11188       }
11189    }
11190 
11191    return found;
11192 }
11193 
11194 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec)
11195 {
11196    int found = FALSE;
11197    unsigned int codec;
11198    char mimeSubtype[128];
11199    unsigned int sample_rate;
11200    int debug = sip_debug_test_pvt(p);
11201    char fmtp_string[256];
11202 
11203    if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
11204       /* We have a rtpmap to handle */
11205       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
11206          /* Note: should really look at the '#chans' params too */
11207          if (!strncasecmp(mimeSubtype, "H26", 3) || !strncasecmp(mimeSubtype, "MP4", 3)) {
11208             if (!(ast_rtp_codecs_payloads_set_rtpmap_type_rate(newvideortp, NULL, codec, "video", mimeSubtype, 0, sample_rate))) {
11209                if (debug)
11210                   ast_verbose("Found video description format %s for ID %u\n", mimeSubtype, codec);
11211                //found_rtpmap_codecs[last_rtpmap_codec] = codec;
11212                (*last_rtpmap_codec)++;
11213                found = TRUE;
11214             } else {
11215                ast_rtp_codecs_payloads_unset(newvideortp, NULL, codec);
11216                if (debug)
11217                   ast_verbose("Found unknown media description format %s for ID %u\n", mimeSubtype, codec);
11218             }
11219          }
11220       } else {
11221          if (debug)
11222             ast_verbose("Discarded description format %s for ID %u\n", mimeSubtype, codec);
11223       }
11224    } else if (sscanf(a, "fmtp: %30u %255[^\t\n]", &codec, fmtp_string) == 2) {
11225       struct ast_format *format;
11226 
11227       if ((format = ast_rtp_codecs_get_payload_format(newvideortp, codec))) {
11228          if (!ast_format_sdp_parse(format, fmtp_string)) {
11229             found = TRUE;
11230          } else {
11231             ast_rtp_codecs_payloads_unset(newvideortp, NULL, codec);
11232          }
11233       }
11234    }
11235 
11236    return found;
11237 }
11238 
11239 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)
11240 {
11241    int found = FALSE;
11242    unsigned int codec;
11243    char mimeSubtype[128];
11244    unsigned int sample_rate;
11245    char *red_cp;
11246    int debug = sip_debug_test_pvt(p);
11247 
11248    if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
11249       /* We have a rtpmap to handle */
11250       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
11251          if (!strncasecmp(mimeSubtype, "T140", 4)) { /* Text */
11252             if (p->trtp) {
11253                /* ast_verbose("Adding t140 mimeSubtype to textrtp struct\n"); */
11254                ast_rtp_codecs_payloads_set_rtpmap_type_rate(newtextrtp, NULL, codec, "text", mimeSubtype, 0, sample_rate);
11255                found = TRUE;
11256             }
11257          } else if (!strncasecmp(mimeSubtype, "RED", 3)) { /* Text with Redudancy */
11258             if (p->trtp) {
11259                ast_rtp_codecs_payloads_set_rtpmap_type_rate(newtextrtp, NULL, codec, "text", mimeSubtype, 0, sample_rate);
11260                sprintf(red_fmtp, "fmtp:%u ", codec);
11261                if (debug)
11262                   ast_verbose("RED submimetype has payload type: %u\n", codec);
11263                found = TRUE;
11264             }
11265          }
11266       } else {
11267          if (debug)
11268             ast_verbose("Discarded description format %s for ID %u\n", mimeSubtype, codec);
11269       }
11270    } else if (!strncmp(a, red_fmtp, strlen(red_fmtp))) {
11271       /* count numbers of generations in fmtp */
11272       red_cp = &red_fmtp[strlen(red_fmtp)];
11273       strncpy(red_fmtp, a, 100);
11274 
11275       sscanf(red_cp, "%30u", (unsigned *)&red_data_pt[*red_num_gen]);
11276       red_cp = strtok(red_cp, "/");
11277       while (red_cp && (*red_num_gen)++ < AST_RED_MAX_GENERATION) {
11278          sscanf(red_cp, "%30u", (unsigned *)&red_data_pt[*red_num_gen]);
11279          red_cp = strtok(NULL, "/");
11280       }
11281       red_cp = red_fmtp;
11282       found = TRUE;
11283    }
11284 
11285    return found;
11286 }
11287 
11288 static int process_sdp_a_image(const char *a, struct sip_pvt *p)
11289 {
11290    int found = FALSE;
11291    char s[256];
11292    unsigned int x;
11293    char *attrib = ast_strdupa(a);
11294    char *pos;
11295 
11296    if (initialize_udptl(p)) {
11297       return found;
11298    }
11299 
11300    /* Due to a typo in an IANA registration of one of the T.38 attributes,
11301     * RFC5347 section 2.5.2 recommends that all T.38 attributes be parsed in
11302     * a case insensitive manner. Hence, the importance of proof reading (and
11303     * code reviews).
11304     */
11305    for (pos = attrib; *pos; ++pos) {
11306       *pos = tolower(*pos);
11307    }
11308 
11309    if ((sscanf(attrib, "t38faxmaxbuffer:%30u", &x) == 1)) {
11310       ast_debug(3, "MaxBufferSize:%u\n", x);
11311       found = TRUE;
11312    } else if ((sscanf(attrib, "t38maxbitrate:%30u", &x) == 1) || (sscanf(attrib, "t38faxmaxrate:%30u", &x) == 1)) {
11313       ast_debug(3, "T38MaxBitRate: %u\n", x);
11314       switch (x) {
11315       case 14400:
11316          p->t38.their_parms.rate = AST_T38_RATE_14400;
11317          break;
11318       case 12000:
11319          p->t38.their_parms.rate = AST_T38_RATE_12000;
11320          break;
11321       case 9600:
11322          p->t38.their_parms.rate = AST_T38_RATE_9600;
11323          break;
11324       case 7200:
11325          p->t38.their_parms.rate = AST_T38_RATE_7200;
11326          break;
11327       case 4800:
11328          p->t38.their_parms.rate = AST_T38_RATE_4800;
11329          break;
11330       case 2400:
11331          p->t38.their_parms.rate = AST_T38_RATE_2400;
11332          break;
11333       }
11334       found = TRUE;
11335    } else if ((sscanf(attrib, "t38faxversion:%30u", &x) == 1)) {
11336       ast_debug(3, "FaxVersion: %u\n", x);
11337       p->t38.their_parms.version = x;
11338       found = TRUE;
11339    } else if ((sscanf(attrib, "t38faxmaxdatagram:%30u", &x) == 1) || (sscanf(attrib, "t38maxdatagram:%30u", &x) == 1)) {
11340       /* override the supplied value if the configuration requests it */
11341       if (((signed int) p->t38_maxdatagram >= 0) && ((unsigned int) p->t38_maxdatagram > x)) {
11342          ast_debug(1, "Overriding T38FaxMaxDatagram '%u' with '%u'\n", x, p->t38_maxdatagram);
11343          x = p->t38_maxdatagram;
11344       }
11345       ast_debug(3, "FaxMaxDatagram: %u\n", x);
11346       ast_udptl_set_far_max_datagram(p->udptl, x);
11347       found = TRUE;
11348    } else if ((strncmp(attrib, "t38faxfillbitremoval", 20) == 0)) {
11349       if (sscanf(attrib, "t38faxfillbitremoval:%30u", &x) == 1) {
11350          ast_debug(3, "FillBitRemoval: %u\n", x);
11351          if (x == 1) {
11352             p->t38.their_parms.fill_bit_removal = TRUE;
11353          }
11354       } else {
11355          ast_debug(3, "FillBitRemoval\n");
11356          p->t38.their_parms.fill_bit_removal = TRUE;
11357       }
11358       found = TRUE;
11359    } else if ((strncmp(attrib, "t38faxtranscodingmmr", 20) == 0)) {
11360       if (sscanf(attrib, "t38faxtranscodingmmr:%30u", &x) == 1) {
11361          ast_debug(3, "Transcoding MMR: %u\n", x);
11362          if (x == 1) {
11363             p->t38.their_parms.transcoding_mmr = TRUE;
11364          }
11365       } else {
11366          ast_debug(3, "Transcoding MMR\n");
11367          p->t38.their_parms.transcoding_mmr = TRUE;
11368       }
11369       found = TRUE;
11370    } else if ((strncmp(attrib, "t38faxtranscodingjbig", 21) == 0)) {
11371       if (sscanf(attrib, "t38faxtranscodingjbig:%30u", &x) == 1) {
11372          ast_debug(3, "Transcoding JBIG: %u\n", x);
11373          if (x == 1) {
11374             p->t38.their_parms.transcoding_jbig = TRUE;
11375          }
11376       } else {
11377          ast_debug(3, "Transcoding JBIG\n");
11378          p->t38.their_parms.transcoding_jbig = TRUE;
11379       }
11380       found = TRUE;
11381    } else if ((sscanf(attrib, "t38faxratemanagement:%255s", s) == 1)) {
11382       ast_debug(3, "RateManagement: %s\n", s);
11383       if (!strcasecmp(s, "localTCF"))
11384          p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_LOCAL_TCF;
11385       else if (!strcasecmp(s, "transferredTCF"))
11386          p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF;
11387       found = TRUE;
11388    } else if ((sscanf(attrib, "t38faxudpec:%255s", s) == 1)) {
11389       ast_debug(3, "UDP EC: %s\n", s);
11390       if (!strcasecmp(s, "t38UDPRedundancy")) {
11391          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
11392       } else if (!strcasecmp(s, "t38UDPFEC")) {
11393          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
11394       } else {
11395          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
11396       }
11397       found = TRUE;
11398    }
11399 
11400    return found;
11401 }
11402 
11403 /*! \brief Add "Supported" header to sip message.  Since some options may
11404  *  be disabled in the config, the sip_pvt must be inspected to determine what
11405  *  is supported for this dialog. */
11406 static int add_supported(struct sip_pvt *pvt, struct sip_request *req)
11407 {
11408    int res;
11409    if (st_get_mode(pvt, 0) != SESSION_TIMER_MODE_REFUSE) {
11410       res = add_header(req, "Supported", "replaces, timer");
11411    } else {
11412       res = add_header(req, "Supported", "replaces");
11413    }
11414    return res;
11415 }
11416 
11417 /*! \brief Add header to SIP message */
11418 static int add_header(struct sip_request *req, const char *var, const char *value)
11419 {
11420    if (req->headers == SIP_MAX_HEADERS) {
11421       ast_log(LOG_WARNING, "Out of SIP header space\n");
11422       return -1;
11423    }
11424 
11425    if (req->lines) {
11426       ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
11427       return -1;
11428    }
11429 
11430    if (sip_cfg.compactheaders) {
11431       var = find_alias(var, var);
11432    }
11433 
11434    ast_str_append(&req->data, 0, "%s: %s\r\n", var, value);
11435    req->header[req->headers] = ast_str_strlen(req->data);
11436 
11437    req->headers++;
11438 
11439    return 0;   
11440 }
11441 
11442 /*! 
11443  * \pre dialog is assumed to be locked while calling this function
11444  * \brief Add 'Max-Forwards' header to SIP message 
11445  */
11446 static int add_max_forwards(struct sip_pvt *dialog, struct sip_request *req)
11447 {
11448    char clen[10];
11449 
11450    snprintf(clen, sizeof(clen), "%d", dialog->maxforwards);
11451 
11452    return add_header(req, "Max-Forwards", clen);
11453 }
11454 
11455 /*! \brief Add 'Content-Length' header and content to SIP message */
11456 static int finalize_content(struct sip_request *req)
11457 {
11458    char clen[10];
11459 
11460    if (req->lines) {
11461       ast_log(LOG_WARNING, "finalize_content() called on a message that has already been finalized\n");
11462       return -1;
11463    }
11464 
11465    snprintf(clen, sizeof(clen), "%zu", ast_str_strlen(req->content));
11466    add_header(req, "Content-Length", clen);
11467 
11468    if (ast_str_strlen(req->content)) {
11469       ast_str_append(&req->data, 0, "\r\n%s", ast_str_buffer(req->content));
11470    }
11471    req->lines = ast_str_strlen(req->content) ? 1 : 0;
11472    return 0;
11473 }
11474 
11475 /*! \brief Add content (not header) to SIP message */
11476 static int add_content(struct sip_request *req, const char *line)
11477 {
11478    if (req->lines) {
11479       ast_log(LOG_WARNING, "Can't add more content when the content has been finalized\n");
11480       return -1;
11481    }
11482 
11483    ast_str_append(&req->content, 0, "%s", line);
11484    return 0;
11485 }
11486 
11487 /*! \brief Copy one header field from one request to another */
11488 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
11489 {
11490    const char *tmp = sip_get_header(orig, field);
11491 
11492    if (!ast_strlen_zero(tmp)) /* Add what we're responding to */
11493       return add_header(req, field, tmp);
11494    ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
11495    return -1;
11496 }
11497 
11498 /*! \brief Copy all headers from one request to another */
11499 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
11500 {
11501    int start = 0;
11502    int copied = 0;
11503    for (;;) {
11504       const char *tmp = __get_header(orig, field, &start);
11505 
11506       if (ast_strlen_zero(tmp))
11507          break;
11508       /* Add what we're responding to */
11509       add_header(req, field, tmp);
11510       copied++;
11511    }
11512    return copied ? 0 : -1;
11513 }
11514 
11515 /*! \brief Copy SIP VIA Headers from the request to the response
11516 \note If the client indicates that it wishes to know the port we received from,
11517    it adds ;rport without an argument to the topmost via header. We need to
11518    add the port number (from our point of view) to that parameter.
11519 \verbatim
11520    We always add ;received=<ip address> to the topmost via header.
11521 \endverbatim
11522    Received: RFC 3261, rport RFC 3581 */
11523 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
11524 {
11525    int copied = 0;
11526    int start = 0;
11527 
11528    for (;;) {
11529       char new[512];
11530       const char *oh = __get_header(orig, field, &start);
11531 
11532       if (ast_strlen_zero(oh))
11533          break;
11534 
11535       if (!copied) { /* Only check for empty rport in topmost via header */
11536          char leftmost[512], *others, *rport;
11537 
11538          /* Only work on leftmost value */
11539          ast_copy_string(leftmost, oh, sizeof(leftmost));
11540          others = strchr(leftmost, ',');
11541          if (others)
11542              *others++ = '\0';
11543 
11544          /* Find ;rport;  (empty request) */
11545          rport = strstr(leftmost, ";rport");
11546          if (rport && *(rport+6) == '=')
11547             rport = NULL;     /* We already have a parameter to rport */
11548 
11549          if (((ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT)) || (rport && ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)))) {
11550             /* We need to add received port - rport */
11551             char *end;
11552 
11553             rport = strstr(leftmost, ";rport");
11554 
11555             if (rport) {
11556                end = strchr(rport + 1, ';');
11557                if (end)
11558                   memmove(rport, end, strlen(end) + 1);
11559                else
11560                   *rport = '\0';
11561             }
11562 
11563             /* Add rport to first VIA header if requested */
11564             snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
11565                leftmost, ast_sockaddr_stringify_addr_remote(&p->recv),
11566                ast_sockaddr_port(&p->recv),
11567                others ? "," : "", others ? others : "");
11568          } else {
11569             /* We should *always* add a received to the topmost via */
11570             snprintf(new, sizeof(new), "%s;received=%s%s%s",
11571                leftmost, ast_sockaddr_stringify_addr_remote(&p->recv),
11572                others ? "," : "", others ? others : "");
11573          }
11574          oh = new;   /* the header to copy */
11575       }  /* else add the following via headers untouched */
11576       add_header(req, field, oh);
11577       copied++;
11578    }
11579    if (!copied) {
11580       ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
11581       return -1;
11582    }
11583    return 0;
11584 }
11585 
11586 /*! \brief Add route header into request per learned route */
11587 static void add_route(struct sip_request *req, struct sip_route *route)
11588 {
11589    char r[SIPBUFSIZE*2], *p;
11590    int n, rem = sizeof(r);
11591 
11592    if (!route)
11593       return;
11594 
11595    p = r;
11596    for (;route ; route = route->next) {
11597       n = strlen(route->hop);
11598       if (rem < n+3) /* we need room for ",<route>" */
11599          break;
11600       if (p != r) {  /* add a separator after fist route */
11601          *p++ = ',';
11602          --rem;
11603       }
11604       *p++ = '<';
11605       ast_copy_string(p, route->hop, rem); /* cannot fail */
11606       p += n;
11607       *p++ = '>';
11608       rem -= (n+2);
11609    }
11610    *p = '\0';
11611    add_header(req, "Route", r);
11612 }
11613 
11614 /*! \brief Set destination from SIP URI
11615  *
11616  * Parse uri to h (host) and port - uri is already just the part inside the <>
11617  * general form we are expecting is sip[s]:username[:password][;parameter]@host[:port][;...]
11618  * If there's a port given, turn NAPTR/SRV off. NAPTR might indicate SIPS preference even
11619  * for SIP: uri's
11620  *
11621  * If there's a sips: uri scheme, TLS will be required.
11622  */
11623 static void set_destination(struct sip_pvt *p, char *uri)
11624 {
11625    char *trans, *h, *maddr, hostname[256];
11626    int hn;
11627    int debug=sip_debug_test_pvt(p);
11628    int tls_on = FALSE;
11629 
11630    if (debug)
11631       ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
11632 
11633    if ((trans = strcasestr(uri, ";transport="))) {
11634       trans += strlen(";transport=");
11635 
11636       if (!strncasecmp(trans, "ws", 2)) {
11637          if (debug)
11638             ast_verbose("set_destination: URI is for WebSocket, we can't set destination\n");
11639          return;
11640       }
11641    }
11642 
11643    /* Find and parse hostname */
11644    h = strchr(uri, '@');
11645    if (h)
11646       ++h;
11647    else {
11648       h = uri;
11649       if (!strncasecmp(h, "sip:", 4)) {
11650          h += 4;
11651       } else if (!strncasecmp(h, "sips:", 5)) {
11652          h += 5;
11653          tls_on = TRUE;
11654       }
11655    }
11656    hn = strcspn(h, ";>") + 1;
11657    if (hn > sizeof(hostname))
11658       hn = sizeof(hostname);
11659    ast_copy_string(hostname, h, hn);
11660    /* XXX bug here if string has been trimmed to sizeof(hostname) */
11661    h += hn - 1;
11662 
11663    /*! \todo XXX If we have sip_cfg.srvlookup on, then look for NAPTR/SRV,
11664     * otherwise, just look for A records */
11665    if (ast_sockaddr_resolve_first_transport(&p->sa, hostname, 0, p->socket.type)) {
11666       ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
11667       return;
11668    }
11669 
11670    /* Got the hostname - but maybe there's a "maddr=" to override address? */
11671    maddr = strstr(h, "maddr=");
11672    if (maddr) {
11673       int port;
11674 
11675       maddr += 6;
11676       hn = strspn(maddr, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
11677                     "0123456789-.:[]") + 1;
11678       if (hn > sizeof(hostname))
11679          hn = sizeof(hostname);
11680       ast_copy_string(hostname, maddr, hn);
11681 
11682       port = ast_sockaddr_port(&p->sa);
11683 
11684       /*! \todo XXX If we have sip_cfg.srvlookup on, then look for
11685        * NAPTR/SRV, otherwise, just look for A records */
11686       if (ast_sockaddr_resolve_first_transport(&p->sa, hostname, PARSE_PORT_FORBID, p->socket.type)) {
11687          ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
11688          return;
11689       }
11690 
11691       ast_sockaddr_set_port(&p->sa, port);
11692    }
11693 
11694    if (!ast_sockaddr_port(&p->sa)) {
11695       ast_sockaddr_set_port(&p->sa, tls_on ?
11696                   STANDARD_TLS_PORT : STANDARD_SIP_PORT);
11697    }
11698 
11699    if (debug) {
11700       ast_verbose("set_destination: set destination to %s\n",
11701              ast_sockaddr_stringify(&p->sa));
11702    }
11703 }
11704 
11705 /*! \brief Initialize SIP response, based on SIP request */
11706 static int init_resp(struct sip_request *resp, const char *msg)
11707 {
11708    /* Initialize a response */
11709    memset(resp, 0, sizeof(*resp));
11710    resp->method = SIP_RESPONSE;
11711    if (!(resp->data = ast_str_create(SIP_MIN_PACKET)))
11712       goto e_return;
11713    if (!(resp->content = ast_str_create(SIP_MIN_PACKET)))
11714       goto e_free_data;
11715    resp->header[0] = 0;
11716    ast_str_set(&resp->data, 0, "SIP/2.0 %s\r\n", msg);
11717    resp->headers++;
11718    return 0;
11719 
11720 e_free_data:
11721    ast_free(resp->data);
11722    resp->data = NULL;
11723 e_return:
11724    return -1;
11725 }
11726 
11727 /*! \brief Initialize SIP request */
11728 static int init_req(struct sip_request *req, int sipmethod, const char *recip)
11729 {
11730    /* Initialize a request */
11731    memset(req, 0, sizeof(*req));
11732    if (!(req->data = ast_str_create(SIP_MIN_PACKET)))
11733       goto e_return;
11734    if (!(req->content = ast_str_create(SIP_MIN_PACKET)))
11735       goto e_free_data;
11736    req->method = sipmethod;
11737    req->header[0] = 0;
11738    ast_str_set(&req->data, 0, "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
11739    req->headers++;
11740    return 0;
11741 
11742 e_free_data:
11743    ast_free(req->data);
11744    req->data = NULL;
11745 e_return:
11746    return -1;
11747 }
11748 
11749 /*! \brief Deinitialize SIP response/request */
11750 static void deinit_req(struct sip_request *req)
11751 {
11752    if (req->data) {
11753       ast_free(req->data);
11754       req->data = NULL;
11755    }
11756    if (req->content) {
11757       ast_free(req->content);
11758       req->content = NULL;
11759    }
11760 }
11761 
11762 
11763 /*! \brief Test if this response needs a contact header */
11764 static inline int resp_needs_contact(const char *msg, enum sipmethod method) {
11765    /* Requirements for Contact header inclusion in responses generated
11766     * from the header tables found in the following RFCs.  Where the
11767     * Contact header was marked mandatory (m) or optional (o) this
11768     * function returns 1.
11769     *
11770     * - RFC 3261 (ACK, BYE, CANCEL, INVITE, OPTIONS, REGISTER)
11771     * - RFC 2976 (INFO)
11772     * - RFC 3262 (PRACK)
11773     * - RFC 3265 (SUBSCRIBE, NOTIFY)
11774     * - RFC 3311 (UPDATE)
11775     * - RFC 3428 (MESSAGE)
11776     * - RFC 3515 (REFER)
11777     * - RFC 3903 (PUBLISH)
11778     */
11779 
11780    switch (method) {
11781       /* 1xx, 2xx, 3xx, 485 */
11782       case SIP_INVITE:
11783       case SIP_UPDATE:
11784       case SIP_SUBSCRIBE:
11785       case SIP_NOTIFY:
11786          if ((msg[0] >= '1' && msg[0] <= '3') || !strncmp(msg, "485", 3))
11787             return 1;
11788          break;
11789 
11790       /* 2xx, 3xx, 485 */
11791       case SIP_REGISTER:
11792       case SIP_OPTIONS:
11793          if (msg[0] == '2' || msg[0] == '3' || !strncmp(msg, "485", 3))
11794             return 1;
11795          break;
11796 
11797       /* 3xx, 485 */
11798       case SIP_BYE:
11799       case SIP_PRACK:
11800       case SIP_MESSAGE:
11801       case SIP_PUBLISH:
11802          if (msg[0] == '3' || !strncmp(msg, "485", 3))
11803             return 1;
11804          break;
11805 
11806       /* 2xx, 3xx, 4xx, 5xx, 6xx */
11807       case SIP_REFER:
11808          if (msg[0] >= '2' && msg[0] <= '6')
11809             return 1;
11810          break;
11811 
11812       /* contact will not be included for everything else */
11813       case SIP_ACK:
11814       case SIP_CANCEL:
11815       case SIP_INFO:
11816       case SIP_PING:
11817       default:
11818          return 0;
11819    }
11820    return 0;
11821 }
11822 
11823 /*! \brief Prepare SIP response packet */
11824 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
11825 {
11826    char newto[256];
11827    const char *ot;
11828 
11829    init_resp(resp, msg);
11830    copy_via_headers(p, resp, req, "Via");
11831    if (msg[0] == '1' || msg[0] == '2')
11832       copy_all_header(resp, req, "Record-Route");
11833    copy_header(resp, req, "From");
11834    ot = sip_get_header(req, "To");
11835    if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
11836       /* Add the proper tag if we don't have it already.  If they have specified
11837          their tag, use it.  Otherwise, use our own tag */
11838       if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
11839          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
11840       else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
11841          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
11842       else
11843          ast_copy_string(newto, ot, sizeof(newto));
11844       ot = newto;
11845    }
11846    add_header(resp, "To", ot);
11847    copy_header(resp, req, "Call-ID");
11848    copy_header(resp, req, "CSeq");
11849    if (!ast_strlen_zero(global_useragent))
11850       add_header(resp, "Server", global_useragent);
11851    add_header(resp, "Allow", ALLOWED_METHODS);
11852    add_supported(p, resp);
11853 
11854    /* If this is an invite, add Session-Timers related headers if the feature is active for this session */
11855    if (p->method == SIP_INVITE && p->stimer && p->stimer->st_active == TRUE) {
11856       char se_hdr[256];
11857       snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
11858          p->stimer->st_ref == SESSION_TIMER_REFRESHER_US ? "uas" : "uac");
11859       add_header(resp, "Session-Expires", se_hdr);
11860       /* RFC 2048, Section 9
11861        * If the refresher parameter in the Session-Expires header field in the
11862        * 2xx response has a value of 'uac', the UAS MUST place a Require
11863        * header field into the response with the value 'timer'.
11864        * ...
11865        * If the refresher parameter in
11866        * the 2xx response has a value of 'uas' and the Supported header field
11867        * in the request contained the value 'timer', the UAS SHOULD place a
11868        * Require header field into the response with the value 'timer'
11869        */
11870       if (p->stimer->st_ref == SESSION_TIMER_REFRESHER_THEM ||
11871             (p->stimer->st_ref == SESSION_TIMER_REFRESHER_US &&
11872              p->stimer->st_active_peer_ua == TRUE)) {
11873          resp->reqsipoptions |= SIP_OPT_TIMER;
11874       }
11875    }
11876 
11877    if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_PUBLISH)) {
11878       /* For registration responses, we also need expiry and
11879          contact info */
11880       add_expires(resp, p->expiry);
11881       if (p->expiry) {  /* Only add contact if we have an expiry time */
11882          char contact[SIPBUFSIZE];
11883          const char *contact_uri = p->method == SIP_SUBSCRIBE ? p->our_contact : p->fullcontact;
11884          char *brackets = strchr(contact_uri, '<');
11885          snprintf(contact, sizeof(contact), "%s%s%s;expires=%d", brackets ? "" : "<", contact_uri, brackets ? "" : ">", p->expiry);
11886          add_header(resp, "Contact", contact);  /* Not when we unregister */
11887       }
11888    } else if (!ast_strlen_zero(p->our_contact) && resp_needs_contact(msg, p->method)) {
11889       add_header(resp, "Contact", p->our_contact);
11890    }
11891 
11892    if (!ast_strlen_zero(p->url)) {
11893       add_header(resp, "Access-URL", p->url);
11894       ast_string_field_set(p, url, NULL);
11895    }
11896 
11897    /* default to routing the response to the address where the request
11898     * came from.  Since we don't have a transport layer, we do this here.
11899     * The process_via() function will update the port to either the port
11900     * specified in the via header or the default port later on (per RFC
11901     * 3261 section 18.2.2).
11902     */
11903    p->sa = p->recv;
11904 
11905    if (process_via(p, req)) {
11906       ast_log(LOG_WARNING, "error processing via header, will send response to originating address\n");
11907    }
11908 
11909    return 0;
11910 }
11911 
11912 /*! \brief Initialize a SIP request message (not the initial one in a dialog) */
11913 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, uint32_t seqno, int newbranch)
11914 {
11915    struct sip_request *orig = &p->initreq;
11916    char stripped[80];
11917    char tmp[80];
11918    char newto[256];
11919    const char *c;
11920    const char *ot, *of;
11921    int is_strict = FALSE;     /*!< Strict routing flag */
11922    int is_outbound = ast_test_flag(&p->flags[0], SIP_OUTGOING);   /* Session direction */
11923 
11924    snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
11925 
11926    if (!seqno) {
11927       p->ocseq++;
11928       seqno = p->ocseq;
11929    }
11930 
11931    /* A CANCEL must have the same branch as the INVITE that it is canceling. */
11932    if (sipmethod == SIP_CANCEL) {
11933       p->branch = p->invite_branch;
11934       build_via(p);
11935    } else if (newbranch && (sipmethod == SIP_INVITE)) {
11936       p->branch ^= ast_random();
11937       p->invite_branch = p->branch;
11938       build_via(p);
11939    } else if (newbranch) {
11940       p->branch ^= ast_random();
11941       build_via(p);
11942    }
11943 
11944    /* Check for strict or loose router */
11945    if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop, ";lr") == NULL) {
11946       is_strict = TRUE;
11947       if (sipdebug)
11948          ast_debug(1, "Strict routing enforced for session %s\n", p->callid);
11949    }
11950 
11951    if (sipmethod == SIP_CANCEL)
11952       c = REQ_OFFSET_TO_STR(&p->initreq, rlpart2); /* Use original URI */
11953    else if (sipmethod == SIP_ACK) {
11954       /* Use URI from Contact: in 200 OK (if INVITE)
11955       (we only have the contacturi on INVITEs) */
11956       if (!ast_strlen_zero(p->okcontacturi))
11957          c = is_strict ? p->route->hop : p->okcontacturi;
11958       else
11959          c = REQ_OFFSET_TO_STR(&p->initreq, rlpart2);
11960    } else if (!ast_strlen_zero(p->okcontacturi))
11961       c = is_strict ? p->route->hop : p->okcontacturi; /* Use for BYE or REINVITE */
11962    else if (!ast_strlen_zero(p->uri))
11963       c = p->uri;
11964    else {
11965       char *n;
11966       /* We have no URI, use To: or From:  header as URI (depending on direction) */
11967       ast_copy_string(stripped, sip_get_header(orig, is_outbound ? "To" : "From"),
11968             sizeof(stripped));
11969       n = get_in_brackets(stripped);
11970       c = remove_uri_parameters(n);
11971    }  
11972    init_req(req, sipmethod, c);
11973 
11974    snprintf(tmp, sizeof(tmp), "%u %s", seqno, sip_methods[sipmethod].text);
11975 
11976    add_header(req, "Via", p->via);
11977    /*
11978     * Use the learned route set unless this is a CANCEL on an ACK for a non-2xx
11979     * final response. For a CANCEL or ACK, we have to send to the same destination
11980     * as the original INVITE.
11981     */
11982    if (p->route &&
11983          !(sipmethod == SIP_CANCEL ||
11984             (sipmethod == SIP_ACK && (p->invitestate == INV_COMPLETED || p->invitestate == INV_CANCELLED)))) {
11985       set_destination(p, p->route->hop);
11986       add_route(req, is_strict ? p->route->next : p->route);
11987    }
11988    add_max_forwards(p, req);
11989 
11990    ot = sip_get_header(orig, "To");
11991    of = sip_get_header(orig, "From");
11992 
11993    /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
11994       as our original request, including tag (or presumably lack thereof) */
11995    if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
11996       /* Add the proper tag if we don't have it already.  If they have specified
11997          their tag, use it.  Otherwise, use our own tag */
11998       if (is_outbound && !ast_strlen_zero(p->theirtag))
11999          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
12000       else if (!is_outbound)
12001          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
12002       else
12003          snprintf(newto, sizeof(newto), "%s", ot);
12004       ot = newto;
12005    }
12006 
12007    if (is_outbound) {
12008       add_header(req, "From", of);
12009       add_header(req, "To", ot);
12010    } else {
12011       add_header(req, "From", ot);
12012       add_header(req, "To", of);
12013    }
12014    /* Do not add Contact for MESSAGE, BYE and Cancel requests */
12015    if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
12016       add_header(req, "Contact", p->our_contact);
12017 
12018    copy_header(req, orig, "Call-ID");
12019    add_header(req, "CSeq", tmp);
12020 
12021    if (!ast_strlen_zero(global_useragent))
12022       add_header(req, "User-Agent", global_useragent);
12023 
12024    if (!ast_strlen_zero(p->url)) {
12025       add_header(req, "Access-URL", p->url);
12026       ast_string_field_set(p, url, NULL);
12027    }
12028 
12029    /* Add Session-Timers related headers if the feature is active for this session.
12030       An exception to this behavior is the ACK request. Since Asterisk never requires
12031       session-timers support from a remote end-point (UAS) in an INVITE, it must
12032       not send 'Require: timer' header in the ACK request.
12033       This should only be added in the INVITE transactions, not MESSAGE or REFER or other
12034       in-dialog messages.
12035    */
12036    if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE
12037        && sipmethod == SIP_INVITE) {
12038       char se_hdr[256];
12039       snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
12040          p->stimer->st_ref == SESSION_TIMER_REFRESHER_US ? "uac" : "uas");
12041       add_header(req, "Session-Expires", se_hdr);
12042       snprintf(se_hdr, sizeof(se_hdr), "%d", st_get_se(p, FALSE));
12043       add_header(req, "Min-SE", se_hdr);
12044    }
12045 
12046    return 0;
12047 }
12048 
12049 /*! \brief Base transmit response function */
12050 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
12051 {
12052    struct sip_request resp;
12053    uint32_t seqno = 0;
12054 
12055    if (reliable && (sscanf(sip_get_header(req, "CSeq"), "%30u ", &seqno) != 1)) {
12056       ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", sip_get_header(req, "CSeq"));
12057       return -1;
12058    }
12059    respprep(&resp, p, msg, req);
12060 
12061    if (ast_test_flag(&p->flags[0], SIP_SENDRPID)
12062          && ast_test_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND)
12063          && (!strncmp(msg, "180", 3) || !strncmp(msg, "183", 3))) {
12064       ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
12065       add_rpid(&resp, p);
12066    }
12067    if (ast_test_flag(&p->flags[0], SIP_OFFER_CC)) {
12068       add_cc_call_info_to_response(p, &resp);
12069    }
12070 
12071    /* If we are sending a 302 Redirect we can add a diversion header if the redirect information is set */
12072    if (!strncmp(msg, "302", 3)) {
12073       add_diversion(&resp, p);
12074    }
12075 
12076    /* If we are cancelling an incoming invite for some reason, add information
12077       about the reason why we are doing this in clear text */
12078    if (p->method == SIP_INVITE && msg[0] != '1') {
12079       char buf[20];
12080 
12081       if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON)) {
12082          int hangupcause = 0;
12083 
12084          if (p->owner && ast_channel_hangupcause(p->owner)) {
12085             hangupcause = ast_channel_hangupcause(p->owner);
12086          } else if (p->hangupcause) {
12087             hangupcause = p->hangupcause;
12088          } else {
12089             int respcode;
12090             if (sscanf(msg, "%30d ", &respcode))
12091                hangupcause = hangup_sip2cause(respcode);
12092          }
12093 
12094          if (hangupcause) {
12095             sprintf(buf, "Q.850;cause=%i", hangupcause & 0x7f);
12096             add_header(&resp, "Reason", buf);
12097          }
12098       }
12099 
12100       if (p->owner && ast_channel_hangupcause(p->owner)) {
12101          add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(ast_channel_hangupcause(p->owner)));
12102          snprintf(buf, sizeof(buf), "%d", ast_channel_hangupcause(p->owner));
12103          add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
12104       }
12105    }
12106    return send_response(p, &resp, reliable, seqno);
12107 }
12108 
12109 static int transmit_response_with_sip_etag(struct sip_pvt *p, const char *msg, const struct sip_request *req, struct sip_esc_entry *esc_entry, int need_new_etag)
12110 {
12111    struct sip_request resp;
12112 
12113    if (need_new_etag) {
12114       create_new_sip_etag(esc_entry, 1);
12115    }
12116    respprep(&resp, p, msg, req);
12117    add_header(&resp, "SIP-ETag", esc_entry->entity_tag);
12118 
12119    return send_response(p, &resp, 0, 0);
12120 }
12121 
12122 static int temp_pvt_init(void *data)
12123 {
12124    struct sip_pvt *p = data;
12125 
12126    p->do_history = 0;   /* XXX do we need it ? isn't already all 0 ? */
12127    return ast_string_field_init(p, 512);
12128 }
12129 
12130 static void temp_pvt_cleanup(void *data)
12131 {
12132    struct sip_pvt *p = data;
12133 
12134    ast_string_field_free_memory(p);
12135 
12136    ast_free(data);
12137 }
12138 
12139 /*! \brief Transmit response, no retransmits, using a temporary pvt structure */
12140 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)
12141 {
12142    struct sip_pvt *p = NULL;
12143 
12144    if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
12145       ast_log(LOG_ERROR, "Failed to get temporary pvt\n");
12146       return -1;
12147    }
12148 
12149    /* XXX the structure may be dirty from previous usage.
12150     * Here we should state clearly how we should reinitialize it
12151     * before using it.
12152     * E.g. certainly the threadstorage should be left alone,
12153     * but other thihngs such as flags etc. maybe need cleanup ?
12154     */
12155 
12156    /* Initialize the bare minimum */
12157    p->method = intended_method;
12158 
12159    if (!addr) {
12160       ast_sockaddr_copy(&p->ourip, &internip);
12161    } else {
12162       ast_sockaddr_copy(&p->sa, addr);
12163       ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
12164    }
12165 
12166    p->branch = ast_random();
12167    make_our_tag(p);
12168    p->ocseq = INITIAL_CSEQ;
12169 
12170    if (useglobal_nat && addr) {
12171       ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT_FORCE_RPORT);
12172       ast_copy_flags(&p->flags[2], &global_flags[2], SIP_PAGE3_NAT_AUTO_RPORT);
12173       ast_sockaddr_copy(&p->recv, addr);
12174       check_via(p, req);
12175    }
12176 
12177    ast_string_field_set(p, fromdomain, default_fromdomain);
12178    p->fromdomainport = default_fromdomainport;
12179    build_via(p);
12180    ast_string_field_set(p, callid, callid);
12181 
12182    copy_socket_data(&p->socket, &req->socket);
12183 
12184    /* Use this temporary pvt structure to send the message */
12185    __transmit_response(p, msg, req, XMIT_UNRELIABLE);
12186 
12187    /* Free the string fields, but not the pool space */
12188    ast_string_field_init(p, 0);
12189 
12190    return 0;
12191 }
12192 
12193 /*! \brief Transmit response, no retransmits */
12194 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req)
12195 {
12196    return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
12197 }
12198 
12199 /*! \brief Transmit response, no retransmits */
12200 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported)
12201 {
12202    struct sip_request resp;
12203    respprep(&resp, p, msg, req);
12204    add_date(&resp);
12205    add_header(&resp, "Unsupported", unsupported);
12206    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
12207 }
12208 
12209 /*! \brief Transmit 422 response with Min-SE header (Session-Timers)  */
12210 static int transmit_response_with_minse(struct sip_pvt *p, const char *msg, const struct sip_request *req, int minse_int)
12211 {
12212    struct sip_request resp;
12213    char minse_str[20];
12214 
12215    respprep(&resp, p, msg, req);
12216    add_date(&resp);
12217 
12218    snprintf(minse_str, sizeof(minse_str), "%d", minse_int);
12219    add_header(&resp, "Min-SE", minse_str);
12220    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
12221 }
12222 
12223 
12224 /*! \brief Transmit response, Make sure you get an ACK
12225    This is only used for responses to INVITEs, where we need to make sure we get an ACK
12226 */
12227 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
12228 {
12229    return __transmit_response(p, msg, req, req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL);
12230 }
12231 
12232 /*! \brief Add date header to SIP message */
12233 static void add_date(struct sip_request *req)
12234 {
12235    char tmp[256];
12236    struct tm tm;
12237    time_t t = time(NULL);
12238 
12239    gmtime_r(&t, &tm);
12240    strftime(tmp, sizeof(tmp), "%a, %d %b %Y %T GMT", &tm);
12241    add_header(req, "Date", tmp);
12242 }
12243 
12244 /*! \brief Add Expires header to SIP message */
12245 static void add_expires(struct sip_request *req, int expires)
12246 {
12247    char tmp[32];
12248 
12249    snprintf(tmp, sizeof(tmp), "%d", expires);
12250    add_header(req, "Expires", tmp);
12251 }
12252 
12253 /*! \brief Append Retry-After header field when transmitting response */
12254 static int transmit_response_with_retry_after(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *seconds)
12255 {
12256    struct sip_request resp;
12257    respprep(&resp, p, msg, req);
12258    add_header(&resp, "Retry-After", seconds);
12259    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
12260 }
12261 
12262 /*! \brief Add date before transmitting response */
12263 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
12264 {
12265    struct sip_request resp;
12266    respprep(&resp, p, msg, req);
12267    add_date(&resp);
12268    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
12269 }
12270 
12271 /*! \brief Append Accept header, content length before transmitting response */
12272 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
12273 {
12274    struct sip_request resp;
12275    respprep(&resp, p, msg, req);
12276    add_header(&resp, "Accept", "application/sdp");
12277    return send_response(p, &resp, reliable, 0);
12278 }
12279 
12280 /*! \brief Append Min-Expires header, content length before transmitting response */
12281 static int transmit_response_with_minexpires(struct sip_pvt *p, const char *msg, const struct sip_request *req, int minexpires)
12282 {
12283    struct sip_request resp;
12284    char tmp[32];
12285 
12286    snprintf(tmp, sizeof(tmp), "%d", minexpires);
12287    respprep(&resp, p, msg, req);
12288    add_header(&resp, "Min-Expires", tmp);
12289    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
12290 }
12291 
12292 /*! \brief Respond with authorization request */
12293 static int transmit_response_with_auth(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *nonce, enum xmittype reliable, const char *header, int stale)
12294 {
12295    struct sip_request resp;
12296    char tmp[512];
12297    uint32_t seqno = 0;
12298 
12299    if (reliable && (sscanf(sip_get_header(req, "CSeq"), "%30u ", &seqno) != 1)) {
12300       ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", sip_get_header(req, "CSeq"));
12301       return -1;
12302    }
12303    /* Choose Realm */
12304    get_realm(p, req);
12305 
12306    /* Stale means that they sent us correct authentication, but
12307       based it on an old challenge (nonce) */
12308    snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", p->realm, nonce, stale ? ", stale=true" : "");
12309    respprep(&resp, p, msg, req);
12310    add_header(&resp, header, tmp);
12311    append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
12312    return send_response(p, &resp, reliable, seqno);
12313 }
12314 
12315 /*!
12316  \brief Extract domain from SIP To/From header
12317  \return -1 on error, 1 if domain string is empty, 0 if domain was properly extracted
12318  \note TODO: Such code is all over SIP channel, there is a sense to organize
12319       this patern in one function
12320 */
12321 static int get_domain(const char *str, char *domain, int len)
12322 {
12323    char tmpf[256];
12324    char *a, *from;
12325 
12326    *domain = '\0';
12327    ast_copy_string(tmpf, str, sizeof(tmpf));
12328    from = get_in_brackets(tmpf);
12329    if (!ast_strlen_zero(from)) {
12330       if (strncasecmp(from, "sip:", 4)) {
12331          ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", from);
12332          return -1;
12333       }
12334       from += 4;
12335    } else
12336       from = NULL;
12337 
12338    if (from) {
12339       int bracket = 0;
12340 
12341       /* Strip any params or options from user */
12342       if ((a = strchr(from, ';')))
12343          *a = '\0';
12344       /* Strip port from domain if present */
12345       for (a = from; *a != '\0'; ++a) {
12346          if (*a == ':' && bracket == 0) {
12347             *a = '\0';
12348             break;
12349          } else if (*a == '[') {
12350             ++bracket;
12351          } else if (*a == ']') {
12352             --bracket;
12353          }
12354       }
12355       if ((a = strchr(from, '@'))) {
12356          *a = '\0';
12357          ast_copy_string(domain, a + 1, len);
12358       } else
12359          ast_copy_string(domain, from, len);
12360    }
12361 
12362    return ast_strlen_zero(domain);
12363 }
12364 
12365 /*!
12366   \brief Choose realm based on From header and then To header or use globaly configured realm.
12367   Realm from From/To header should be listed among served domains in config file: domain=...
12368 */
12369 static void get_realm(struct sip_pvt *p, const struct sip_request *req)
12370 {
12371    char domain[MAXHOSTNAMELEN];
12372 
12373    if (!ast_strlen_zero(p->realm))
12374       return;
12375 
12376    if (sip_cfg.domainsasrealm &&
12377        !AST_LIST_EMPTY(&domain_list))
12378    {
12379       /* Check From header first */
12380       if (!get_domain(sip_get_header(req, "From"), domain, sizeof(domain))) {
12381          if (check_sip_domain(domain, NULL, 0)) {
12382             ast_string_field_set(p, realm, domain);
12383             return;
12384          }
12385       }
12386       /* Check To header */
12387       if (!get_domain(sip_get_header(req, "To"), domain, sizeof(domain))) {
12388          if (check_sip_domain(domain, NULL, 0)) {
12389             ast_string_field_set(p, realm, domain);
12390             return;
12391          }
12392       }
12393    }
12394    
12395    /* Use default realm from config file */
12396    ast_string_field_set(p, realm, sip_cfg.realm);
12397 }
12398 
12399 /*!
12400  * \internal
12401  *
12402  * \arg msg Only use a string constant for the msg, here, it is shallow copied
12403  *
12404  * \note assumes the sip_pvt is locked.
12405  */
12406 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp)
12407 {
12408    int res;
12409 
12410    if (!(res = with_sdp ? transmit_response_with_sdp(p, msg, req, XMIT_UNRELIABLE, FALSE, FALSE) : transmit_response(p, msg, req))) {
12411       p->last_provisional = msg;
12412       update_provisional_keepalive(p, with_sdp);
12413    }
12414 
12415    return res;
12416 }
12417 
12418 /*!
12419  * \internal
12420  * \brief Destroy all additional MESSAGE headers.
12421  *
12422  * \param pvt SIP private dialog struct.
12423  *
12424  * \return Nothing
12425  */
12426 static void destroy_msg_headers(struct sip_pvt *pvt)
12427 {
12428    struct sip_msg_hdr *doomed;
12429 
12430    while ((doomed = AST_LIST_REMOVE_HEAD(&pvt->msg_headers, next))) {
12431       ast_free(doomed);
12432    }
12433 }
12434 
12435 /*!
12436  * \internal
12437  * \brief Add a MESSAGE header to the dialog.
12438  *
12439  * \param pvt SIP private dialog struct.
12440  * \param hdr_name Name of header for MESSAGE.
12441  * \param hdr_value Value of header for MESSAGE.
12442  *
12443  * \return Nothing
12444  */
12445 static void add_msg_header(struct sip_pvt *pvt, const char *hdr_name, const char *hdr_value)
12446 {
12447    size_t hdr_len_name;
12448    size_t hdr_len_value;
12449    struct sip_msg_hdr *node;
12450    char *pos;
12451 
12452    hdr_len_name = strlen(hdr_name) + 1;
12453    hdr_len_value = strlen(hdr_value) + 1;
12454 
12455    node = ast_calloc(1, sizeof(*node) + hdr_len_name + hdr_len_value);
12456    if (!node) {
12457       return;
12458    }
12459    pos = node->stuff;
12460    node->name = pos;
12461    strcpy(pos, hdr_name);
12462    pos += hdr_len_name;
12463    node->value = pos;
12464    strcpy(pos, hdr_value);
12465 
12466    AST_LIST_INSERT_TAIL(&pvt->msg_headers, node, next);
12467 }
12468 
12469 /*! \brief Add text body to SIP message */
12470 static int add_text(struct sip_request *req, struct sip_pvt *p)
12471 {
12472    const char *content_type = NULL;
12473    struct sip_msg_hdr *node;
12474 
12475    /* Add any additional MESSAGE headers. */
12476    AST_LIST_TRAVERSE(&p->msg_headers, node, next) {
12477       if (!strcasecmp(node->name, "Content-Type")) {
12478          /* Save content type */
12479          content_type = node->value;
12480       } else {
12481          add_header(req, node->name, node->value);
12482       }
12483    }
12484    if (ast_strlen_zero(content_type)) {
12485       /* "Content-Type" not set - use default value */
12486       content_type = "text/plain;charset=UTF-8";
12487    }
12488    add_header(req, "Content-Type", content_type);
12489 
12490    /* XXX Convert \n's to \r\n's XXX */
12491    add_content(req, p->msg_body);
12492    return 0;
12493 }
12494 
12495 /*! \brief Add DTMF INFO tone to sip message
12496    Mode =   0 for application/dtmf-relay (Cisco)
12497       1 for application/dtmf
12498 */
12499 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode)
12500 {
12501    char tmp[256];
12502    int event;
12503    if (mode) {
12504       /* Application/dtmf short version used by some implementations */
12505       if ('0' <= digit && digit <= '9') {
12506          event = digit - '0';
12507       } else if (digit == '*') {
12508          event = 10;
12509       } else if (digit == '#') {
12510          event = 11;
12511       } else if ('A' <= digit && digit <= 'D') {
12512          event = 12 + digit - 'A';
12513       } else if ('a' <= digit && digit <= 'd') {
12514          event = 12 + digit - 'a';
12515       } else {
12516          /* Unknown digit */
12517          event = 0;
12518       }
12519       snprintf(tmp, sizeof(tmp), "%d\r\n", event);
12520       add_header(req, "Content-Type", "application/dtmf");
12521       add_content(req, tmp);
12522    } else {
12523       /* Application/dtmf-relay as documented by Cisco */
12524       snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
12525       add_header(req, "Content-Type", "application/dtmf-relay");
12526       add_content(req, tmp);
12527    }
12528    return 0;
12529 }
12530 
12531 /*!
12532  * \pre if p->owner exists, it must be locked
12533  * \brief Add Remote-Party-ID header to SIP message
12534  */
12535 static int add_rpid(struct sip_request *req, struct sip_pvt *p)
12536 {
12537    struct ast_str *tmp = ast_str_alloca(256);
12538    char tmp2[256];
12539    char *lid_num;
12540    char *lid_name;
12541    int lid_pres;
12542    const char *fromdomain;
12543    const char *privacy = NULL;
12544    const char *screen = NULL;
12545    struct ast_party_id connected_id;
12546    const char *anonymous_string = "\"Anonymous\" <sip:anonymous@anonymous.invalid>";
12547 
12548    if (!ast_test_flag(&p->flags[0], SIP_SENDRPID)) {
12549       return 0;
12550    }
12551 
12552    if (!p->owner) {
12553       return 0;
12554    }
12555    connected_id = ast_channel_connected_effective_id(p->owner);
12556    lid_num = S_COR(connected_id.number.valid, connected_id.number.str, NULL);
12557    if (!lid_num) {
12558       return 0;
12559    }
12560    lid_name = S_COR(connected_id.name.valid, connected_id.name.str, NULL);
12561    if (!lid_name) {
12562       lid_name = lid_num;
12563    }
12564    lid_pres = ast_party_id_presentation(&connected_id);
12565 
12566    if (((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) &&
12567          (ast_test_flag(&p->flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND) == SIP_PAGE2_TRUST_ID_OUTBOUND_NO)) {
12568       /* If pres is not allowed and we don't trust the peer, we don't apply an RPID header */
12569       return 0;
12570    }
12571 
12572    fromdomain = p->fromdomain;
12573    if (!fromdomain ||
12574          ((ast_test_flag(&p->flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND) == SIP_PAGE2_TRUST_ID_OUTBOUND_YES) &&
12575          !strcmp("anonymous.invalid", fromdomain))) {
12576       /* If the fromdomain is NULL or if it was set to anonymous.invalid due to privacy settings and we trust the peer,
12577        * use the host IP address */
12578       fromdomain = ast_sockaddr_stringify_host_remote(&p->ourip);
12579    }
12580 
12581    lid_num = ast_uri_encode(lid_num, tmp2, sizeof(tmp2), ast_uri_sip_user);
12582 
12583    if (ast_test_flag(&p->flags[0], SIP_SENDRPID_PAI)) {
12584       if (ast_test_flag(&p->flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND) != SIP_PAGE2_TRUST_ID_OUTBOUND_LEGACY) {
12585          /* trust_id_outbound = yes - Always give full information even if it's private, but append a privacy header
12586           * When private data is included */
12587          ast_str_set(&tmp, -1, "\"%s\" <sip:%s@%s>", lid_name, lid_num, fromdomain);
12588          if ((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
12589             add_header(req, "Privacy", "id");
12590          }
12591       } else {
12592          /* trust_id_outbound = legacy - behave in a non RFC-3325 compliant manner and send anonymized data when
12593           * when handling private data. */
12594          if ((lid_pres & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED) {
12595             ast_str_set(&tmp, -1, "\"%s\" <sip:%s@%s>", lid_name, lid_num, fromdomain);
12596          } else {
12597             ast_str_set(&tmp, -1, "%s", anonymous_string);
12598          }
12599       }
12600       add_header(req, "P-Asserted-Identity", ast_str_buffer(tmp));
12601    } else {
12602       ast_str_set(&tmp, -1, "\"%s\" <sip:%s@%s>;party=%s", lid_name, lid_num, fromdomain, p->outgoing_call ? "calling" : "called");
12603 
12604       switch (lid_pres) {
12605       case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
12606       case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
12607          privacy = "off";
12608          screen = "no";
12609          break;
12610       case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
12611       case AST_PRES_ALLOWED_NETWORK_NUMBER:
12612          privacy = "off";
12613          screen = "yes";
12614          break;
12615       case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
12616       case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
12617          privacy = "full";
12618          screen = "no";
12619          break;
12620       case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
12621       case AST_PRES_PROHIB_NETWORK_NUMBER:
12622          privacy = "full";
12623          screen = "yes";
12624          break;
12625       case AST_PRES_NUMBER_NOT_AVAILABLE:
12626          break;
12627       default:
12628          if ((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
12629             privacy = "full";
12630          }
12631          else
12632             privacy = "off";
12633          screen = "no";
12634          break;
12635       }
12636 
12637       if (!ast_strlen_zero(privacy) && !ast_strlen_zero(screen)) {
12638          ast_str_append(&tmp, -1, ";privacy=%s;screen=%s", privacy, screen);
12639       }
12640 
12641       add_header(req, "Remote-Party-ID", ast_str_buffer(tmp));
12642    }
12643    return 0;
12644 }
12645 
12646 /*! \brief add XML encoded media control with update
12647    \note XML: The only way to turn 0 bits of information into a few hundred. (markster) */
12648 static int add_vidupdate(struct sip_request *req)
12649 {
12650    const char *xml_is_a_huge_waste_of_space =
12651       "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
12652       " <media_control>\r\n"
12653       "  <vc_primitive>\r\n"
12654       "   <to_encoder>\r\n"
12655       "    <picture_fast_update>\r\n"
12656       "    </picture_fast_update>\r\n"
12657       "   </to_encoder>\r\n"
12658       "  </vc_primitive>\r\n"
12659       " </media_control>\r\n";
12660    add_header(req, "Content-Type", "application/media_control+xml");
12661    add_content(req, xml_is_a_huge_waste_of_space);
12662    return 0;
12663 }
12664 
12665 /*! \brief Add ICE attributes to SDP */
12666 static void add_ice_to_sdp(struct ast_rtp_instance *instance, struct ast_str **a_buf)
12667 {
12668    struct ast_rtp_engine_ice *ice = ast_rtp_instance_get_ice(instance);
12669    const char *username, *password;
12670    struct ao2_container *candidates;
12671    struct ao2_iterator i;
12672    struct ast_rtp_engine_ice_candidate *candidate;
12673 
12674    /* If no ICE support is present we can't very well add the attributes */
12675    if (!ice || !(candidates = ice->get_local_candidates(instance))) {
12676       return;
12677    }
12678 
12679    if ((username = ice->get_ufrag(instance))) {
12680       ast_str_append(a_buf, 0, "a=ice-ufrag:%s\r\n", username);
12681    }
12682    if ((password = ice->get_password(instance))) {
12683       ast_str_append(a_buf, 0, "a=ice-pwd:%s\r\n", password);
12684    }
12685 
12686    i = ao2_iterator_init(candidates, 0);
12687 
12688    while ((candidate = ao2_iterator_next(&i))) {
12689       ast_str_append(a_buf, 0, "a=candidate:%s %u %s %d ", candidate->foundation, candidate->id, candidate->transport, candidate->priority);
12690       ast_str_append(a_buf, 0, "%s ", ast_sockaddr_stringify_host(&candidate->address));
12691 
12692       if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_SRFLX
12693          && candidate->id == AST_RTP_ICE_COMPONENT_RTCP) {
12694          ast_str_append(a_buf, 0, "%d typ ", ast_sockaddr_port(&candidate->address) + 1);
12695       } else {
12696          ast_str_append(a_buf, 0, "%s typ ", ast_sockaddr_stringify_port(&candidate->address));
12697       }
12698 
12699       if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_HOST) {
12700          ast_str_append(a_buf, 0, "host");
12701       } else if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_SRFLX) {
12702          ast_str_append(a_buf, 0, "srflx");
12703       } else if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_RELAYED) {
12704          ast_str_append(a_buf, 0, "relay");
12705       }
12706 
12707       if (!ast_sockaddr_isnull(&candidate->relay_address)) {
12708          ast_str_append(a_buf, 0, " raddr %s ", ast_sockaddr_stringify_host(&candidate->relay_address));
12709          ast_str_append(a_buf, 0, "rport %s", ast_sockaddr_stringify_port(&candidate->relay_address));
12710       }
12711 
12712       ast_str_append(a_buf, 0, "\r\n");
12713       ao2_ref(candidate, -1);
12714    }
12715 
12716    ao2_iterator_destroy(&i);
12717 
12718    ao2_ref(candidates, -1);
12719 }
12720 
12721 /*! \brief Start ICE negotiation on an RTP instance */
12722 static void start_ice(struct ast_rtp_instance *instance, int offer)
12723 {
12724    struct ast_rtp_engine_ice *ice = ast_rtp_instance_get_ice(instance);
12725 
12726    if (!ice) {
12727       return;
12728    }
12729 
12730    /* If we are the offerer then we are the controlling agent, otherwise they are */
12731    ice->set_role(instance, offer ? AST_RTP_ICE_ROLE_CONTROLLING : AST_RTP_ICE_ROLE_CONTROLLED);
12732    ice->start(instance);
12733 }
12734 
12735 /*! \brief Add DTLS attributes to SDP */
12736 static void add_dtls_to_sdp(struct ast_rtp_instance *instance, struct ast_str **a_buf)
12737 {
12738    struct ast_rtp_engine_dtls *dtls;
12739    enum ast_rtp_dtls_hash hash;
12740    const char *fingerprint;
12741 
12742    if (!instance || !(dtls = ast_rtp_instance_get_dtls(instance)) || !dtls->active(instance)) {
12743       return;
12744    }
12745 
12746    switch (dtls->get_connection(instance)) {
12747    case AST_RTP_DTLS_CONNECTION_NEW:
12748       ast_str_append(a_buf, 0, "a=connection:new\r\n");
12749       break;
12750    case AST_RTP_DTLS_CONNECTION_EXISTING:
12751       ast_str_append(a_buf, 0, "a=connection:existing\r\n");
12752       break;
12753    default:
12754       break;
12755    }
12756 
12757    switch (dtls->get_setup(instance)) {
12758    case AST_RTP_DTLS_SETUP_ACTIVE:
12759       ast_str_append(a_buf, 0, "a=setup:active\r\n");
12760       break;
12761    case AST_RTP_DTLS_SETUP_PASSIVE:
12762       ast_str_append(a_buf, 0, "a=setup:passive\r\n");
12763       break;
12764    case AST_RTP_DTLS_SETUP_ACTPASS:
12765       ast_str_append(a_buf, 0, "a=setup:actpass\r\n");
12766       break;
12767    case AST_RTP_DTLS_SETUP_HOLDCONN:
12768       ast_str_append(a_buf, 0, "a=setup:holdconn\r\n");
12769       break;
12770    default:
12771       break;
12772    }
12773 
12774    hash = dtls->get_fingerprint_hash(instance);
12775    fingerprint = dtls->get_fingerprint(instance);
12776    if (fingerprint && (hash == AST_RTP_DTLS_HASH_SHA1 || hash == AST_RTP_DTLS_HASH_SHA256)) {
12777       ast_str_append(a_buf, 0, "a=fingerprint:%s %s\r\n", hash == AST_RTP_DTLS_HASH_SHA1 ? "SHA-1" : "SHA-256",
12778          fingerprint);
12779    }
12780 }
12781 
12782 /*! \brief Add codec offer to SDP offer/answer body in INVITE or 200 OK */
12783 static void add_codec_to_sdp(const struct sip_pvt *p,
12784    struct ast_format *format,
12785    struct ast_str **m_buf,
12786    struct ast_str **a_buf,
12787    int debug,
12788    int *min_packet_size)
12789 {
12790    int rtp_code;
12791    struct ast_format_list fmt;
12792    const char *mime;
12793    unsigned int rate;
12794 
12795    if (debug)
12796       ast_verbose("Adding codec %u (%s) to SDP\n", format->id, ast_getformatname(format));
12797 
12798    if (((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->rtp), 1, format, 0)) == -1) ||
12799        !(mime = ast_rtp_lookup_mime_subtype2(1, format, 0, ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0)) ||
12800        !(rate = ast_rtp_lookup_sample_rate2(1, format, 0))) {
12801       return;
12802    }
12803 
12804    if (p->rtp) {
12805       struct ast_codec_pref *pref = &ast_rtp_instance_get_codecs(p->rtp)->pref;
12806       fmt = ast_codec_pref_getsize(pref, format);
12807    } else /* I don't see how you couldn't have p->rtp, but good to check for and error out if not there like earlier code */
12808       return;
12809    ast_str_append(m_buf, 0, " %d", rtp_code);
12810    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%u\r\n", rtp_code, mime, rate);
12811 
12812    ast_format_sdp_generate(format, rtp_code, a_buf);
12813 
12814    switch ((int) format->id) {
12815    case AST_FORMAT_G729A:
12816       /* Indicate that we don't support VAD (G.729 annex B) */
12817       ast_str_append(a_buf, 0, "a=fmtp:%d annexb=no\r\n", rtp_code);
12818       break;
12819    case AST_FORMAT_G723_1:
12820       /* Indicate that we don't support VAD (G.723.1 annex A) */
12821       ast_str_append(a_buf, 0, "a=fmtp:%d annexa=no\r\n", rtp_code);
12822       break;
12823    case AST_FORMAT_ILBC:
12824       /* Add information about us using only 20/30 ms packetization */
12825       ast_str_append(a_buf, 0, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
12826       break;
12827    case AST_FORMAT_SIREN7:
12828       /* Indicate that we only expect 32Kbps */
12829       ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=32000\r\n", rtp_code);
12830       break;
12831    case AST_FORMAT_SIREN14:
12832       /* Indicate that we only expect 48Kbps */
12833       ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=48000\r\n", rtp_code);
12834       break;
12835    case AST_FORMAT_G719:
12836       /* Indicate that we only expect 64Kbps */
12837       ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=64000\r\n", rtp_code);
12838       break;
12839    }
12840 
12841    if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
12842       *min_packet_size = fmt.cur_ms;
12843 
12844    /* Our first codec packetization processed cannot be zero */
12845    if ((*min_packet_size)==0 && fmt.cur_ms)
12846       *min_packet_size = fmt.cur_ms;
12847 }
12848 
12849 /*! \brief Add video codec offer to SDP offer/answer body in INVITE or 200 OK */
12850 /* This is different to the audio one now so we can add more caps later */
12851 static void add_vcodec_to_sdp(const struct sip_pvt *p, struct ast_format *format,
12852               struct ast_str **m_buf, struct ast_str **a_buf,
12853               int debug, int *min_packet_size)
12854 {
12855    int rtp_code;
12856    const char *subtype;
12857    unsigned int rate;
12858 
12859    if (!p->vrtp)
12860       return;
12861 
12862    if (debug)
12863       ast_verbose("Adding video codec %u (%s) to SDP\n", format->id, ast_getformatname(format));
12864 
12865    if (((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->vrtp), 1, format, 0)) == -1) ||
12866        !(subtype = ast_rtp_lookup_mime_subtype2(1, format, 0, 0)) ||
12867        !(rate = ast_rtp_lookup_sample_rate2(1, format, 0))) {
12868       return;
12869    }
12870 
12871    ast_str_append(m_buf, 0, " %d", rtp_code);
12872    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%u\r\n", rtp_code, subtype, rate);
12873 
12874    ast_format_sdp_generate(format, rtp_code, a_buf);
12875 }
12876 
12877 /*! \brief Add text codec offer to SDP offer/answer body in INVITE or 200 OK */
12878 static void add_tcodec_to_sdp(const struct sip_pvt *p, struct ast_format *format,
12879               struct ast_str **m_buf, struct ast_str **a_buf,
12880               int debug, int *min_packet_size)
12881 {
12882    int rtp_code;
12883 
12884    if (!p->trtp)
12885       return;
12886 
12887    if (debug)
12888       ast_verbose("Adding text codec %u (%s) to SDP\n", format->id, ast_getformatname(format));
12889 
12890    if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->trtp), 1, format, 0)) == -1)
12891       return;
12892 
12893    ast_str_append(m_buf, 0, " %d", rtp_code);
12894    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%u\r\n", rtp_code,
12895              ast_rtp_lookup_mime_subtype2(1, format, 0, 0),
12896              ast_rtp_lookup_sample_rate2(1, format, 0));
12897    /* Add fmtp code here */
12898 
12899    if (format->id == AST_FORMAT_T140RED) {
12900       struct ast_format tmp_fmt;
12901       int t140code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->trtp), 1, ast_format_set(&tmp_fmt, AST_FORMAT_T140, 0), 0);
12902       ast_str_append(a_buf, 0, "a=fmtp:%d %d/%d/%d\r\n", rtp_code,
12903           t140code,
12904           t140code,
12905           t140code);
12906 
12907    }
12908 }
12909 
12910 
12911 /*! \brief Get Max T.38 Transmission rate from T38 capabilities */
12912 static unsigned int t38_get_rate(enum ast_control_t38_rate rate)
12913 {
12914    switch (rate) {
12915    case AST_T38_RATE_2400:
12916       return 2400;
12917    case AST_T38_RATE_4800:
12918       return 4800;
12919    case AST_T38_RATE_7200:
12920       return 7200;
12921    case AST_T38_RATE_9600:
12922       return 9600;
12923    case AST_T38_RATE_12000:
12924       return 12000;
12925    case AST_T38_RATE_14400:
12926       return 14400;
12927    default:
12928       return 0;
12929    }
12930 }
12931 
12932 /*! \brief Add RFC 2833 DTMF offer to SDP */
12933 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
12934             struct ast_str **m_buf, struct ast_str **a_buf,
12935             int debug)
12936 {
12937    int rtp_code;
12938 
12939    if (debug)
12940       ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", (unsigned)format, ast_rtp_lookup_mime_subtype2(0, NULL, format, 0));
12941    if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->rtp), 0, NULL, format)) == -1)
12942       return;
12943 
12944    ast_str_append(m_buf, 0, " %d", rtp_code);
12945    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%u\r\n", rtp_code,
12946              ast_rtp_lookup_mime_subtype2(0, NULL, format, 0),
12947              ast_rtp_lookup_sample_rate2(0, NULL, format));
12948    if (format == AST_RTP_DTMF)   /* Indicate we support DTMF and FLASH... */
12949       ast_str_append(a_buf, 0, "a=fmtp:%d 0-16\r\n", rtp_code);
12950 }
12951 
12952 /*! \brief Set all IP media addresses for this call
12953    \note called from add_sdp()
12954 */
12955 static void get_our_media_address(struct sip_pvt *p, int needvideo, int needtext,
12956               struct ast_sockaddr *addr, struct ast_sockaddr *vaddr,
12957               struct ast_sockaddr *taddr, struct ast_sockaddr *dest,
12958               struct ast_sockaddr *vdest, struct ast_sockaddr *tdest)
12959 {
12960    int use_externip = 0;
12961 
12962    /* First, get our address */
12963    ast_rtp_instance_get_local_address(p->rtp, addr);
12964    if (p->vrtp) {
12965       ast_rtp_instance_get_local_address(p->vrtp, vaddr);
12966    }
12967    if (p->trtp) {
12968       ast_rtp_instance_get_local_address(p->trtp, taddr);
12969    }
12970 
12971    /* If our real IP differs from the local address returned by the RTP engine, use it. */
12972    /* The premise is that if we are already using that IP to communicate with the client, */
12973    /* we should be using it for RTP too. */
12974         use_externip = ast_sockaddr_cmp_addr(&p->ourip, addr);
12975 
12976    /* Now, try to figure out where we want them to send data */
12977    /* Is this a re-invite to move the media out, then use the original offer from caller  */
12978    if (!ast_sockaddr_isnull(&p->redirip)) {  /* If we have a redirection IP, use it */
12979       ast_sockaddr_copy(dest, &p->redirip);
12980    } else {
12981       /*
12982        * Audio Destination IP:
12983        *
12984        * 1. Specifically configured media address.
12985        * 2. Local address as specified by the RTP engine.
12986        * 3. The local IP as defined by chan_sip.
12987        *
12988        * Audio Destination Port:
12989        *
12990        * 1. Provided by the RTP engine.
12991        */
12992       ast_sockaddr_copy(dest,
12993               !ast_sockaddr_isnull(&media_address) ? &media_address :
12994               !ast_sockaddr_is_any(addr) && !use_externip ? addr    :
12995               &p->ourip);
12996       ast_sockaddr_set_port(dest, ast_sockaddr_port(addr));
12997    }
12998 
12999    if (needvideo) {
13000       /* Determine video destination */
13001       if (!ast_sockaddr_isnull(&p->vredirip)) {
13002          ast_sockaddr_copy(vdest, &p->vredirip);
13003       } else {
13004          /*
13005           * Video Destination IP:
13006           *
13007           * 1. Specifically configured media address.
13008           * 2. Local address as specified by the RTP engine.
13009           * 3. The local IP as defined by chan_sip.
13010           *
13011           * Video Destination Port:
13012           *
13013           * 1. Provided by the RTP engine.
13014           */
13015          ast_sockaddr_copy(vdest,
13016                  !ast_sockaddr_isnull(&media_address) ? &media_address :
13017                  !ast_sockaddr_is_any(vaddr) && !use_externip ? vaddr  :
13018                  &p->ourip);
13019          ast_sockaddr_set_port(vdest, ast_sockaddr_port(vaddr));
13020       }
13021    }
13022 
13023    if (needtext) {
13024       /* Determine text destination */
13025       if (!ast_sockaddr_isnull(&p->tredirip)) {
13026          ast_sockaddr_copy(tdest, &p->tredirip);
13027       } else {
13028          /*
13029           * Text Destination IP:
13030           *
13031           * 1. Specifically configured media address.
13032           * 2. Local address as specified by the RTP engine.
13033           * 3. The local IP as defined by chan_sip.
13034           *
13035           * Text Destination Port:
13036           *
13037           * 1. Provided by the RTP engine.
13038           */
13039          ast_sockaddr_copy(tdest,
13040                  !ast_sockaddr_isnull(&media_address) ? &media_address  :
13041                  !ast_sockaddr_is_any(taddr) && !use_externip ? taddr   :
13042                  &p->ourip);
13043          ast_sockaddr_set_port(tdest, ast_sockaddr_port(taddr));
13044       }
13045    }
13046 }
13047 
13048 static void get_crypto_attrib(struct sip_pvt *p, struct sip_srtp *srtp, const char **a_crypto)
13049 {
13050    int taglen = 80;
13051 
13052    /* Set encryption properties */
13053    if (srtp) {
13054       if (!srtp->crypto) {
13055          srtp->crypto = sdp_crypto_setup();
13056       }
13057 
13058       if (p->dtls_cfg.enabled) {
13059          /* If DTLS-SRTP is enabled the key details will be pulled from TLS */
13060          return;
13061       }
13062 
13063       /* set the key length based on INVITE or settings */
13064       if (ast_test_flag(srtp, SRTP_CRYPTO_TAG_80)) {
13065          taglen = 80;
13066       } else if (ast_test_flag(&p->flags[2], SIP_PAGE3_SRTP_TAG_32) ||
13067           ast_test_flag(srtp, SRTP_CRYPTO_TAG_32)) {
13068          taglen = 32;
13069       }
13070 
13071       if (srtp->crypto && (sdp_crypto_offer(srtp->crypto, taglen) >= 0)) {
13072          *a_crypto = sdp_crypto_attrib(srtp->crypto);
13073       }
13074 
13075       if (!*a_crypto) {
13076          ast_log(LOG_WARNING, "No SRTP key management enabled\n");
13077       }
13078    }
13079 }
13080 
13081 static char *get_sdp_rtp_profile(const struct sip_pvt *p, unsigned int secure, struct ast_rtp_instance *instance)
13082 {
13083    struct ast_rtp_engine_dtls *dtls;
13084 
13085    if ((dtls = ast_rtp_instance_get_dtls(instance)) && dtls->active(instance)) {
13086       if (ast_test_flag(&p->flags[2], SIP_PAGE3_FORCE_AVP)) {
13087          return ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF) ? "RTP/SAVPF" : "RTP/SAVP";
13088       } else {
13089          return ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF) ? "UDP/TLS/RTP/SAVPF" : "UDP/TLS/RTP/SAVP";
13090       }
13091    } else {
13092       if (ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
13093          return secure ? "RTP/SAVPF" : "RTP/AVPF";
13094       } else {
13095          return secure ? "RTP/SAVP" : "RTP/AVP";
13096       }
13097    }
13098 }
13099 
13100 /*! \brief Add Session Description Protocol message
13101 
13102     If oldsdp is TRUE, then the SDP version number is not incremented. This mechanism
13103     is used in Session-Timers where RE-INVITEs are used for refreshing SIP sessions
13104     without modifying the media session in any way.
13105 */
13106 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38)
13107 {
13108    struct ast_format_cap *alreadysent = ast_format_cap_alloc_nolock();
13109    struct ast_format_cap *tmpcap = ast_format_cap_alloc_nolock();
13110    int res = AST_SUCCESS;
13111    int doing_directmedia = FALSE;
13112    struct ast_sockaddr addr = { {0,} };
13113    struct ast_sockaddr vaddr = { {0,} };
13114    struct ast_sockaddr taddr = { {0,} };
13115    struct ast_sockaddr udptladdr = { {0,} };
13116    struct ast_sockaddr dest = { {0,} };
13117    struct ast_sockaddr vdest = { {0,} };
13118    struct ast_sockaddr tdest = { {0,} };
13119    struct ast_sockaddr udptldest = { {0,} };
13120 
13121    /* SDP fields */
13122    struct offered_media *offer;
13123    char *version =   "v=0\r\n";     /* Protocol version */
13124    char subject[256];            /* Subject of the session */
13125    char owner[256];           /* Session owner/creator */
13126    char connection[256];            /* Connection data */
13127    char *session_time = "t=0 0\r\n";         /* Time the session is active */
13128    char bandwidth[256] = "";        /* Max bitrate */
13129    char *hold = "";
13130    struct ast_str *m_audio = ast_str_alloca(256);  /* Media declaration line for audio */
13131    struct ast_str *m_video = ast_str_alloca(256);  /* Media declaration line for video */
13132    struct ast_str *m_text = ast_str_alloca(256);   /* Media declaration line for text */
13133    struct ast_str *m_modem = ast_str_alloca(256);  /* Media declaration line for modem */
13134    struct ast_str *a_audio = ast_str_create(256); /* Attributes for audio */
13135    struct ast_str *a_video = ast_str_create(256); /* Attributes for video */
13136    struct ast_str *a_text = ast_str_create(256);  /* Attributes for text */
13137    struct ast_str *a_modem = ast_str_alloca(1024); /* Attributes for modem */
13138    const char *a_crypto = NULL;
13139    const char *v_a_crypto = NULL;
13140    const char *t_a_crypto = NULL;
13141 
13142    int x;
13143    struct ast_format tmp_fmt;
13144    int needaudio = FALSE;
13145    int needvideo = FALSE;
13146    int needtext = FALSE;
13147    int debug = sip_debug_test_pvt(p);
13148    int min_audio_packet_size = 0;
13149    int min_video_packet_size = 0;
13150    int min_text_packet_size = 0;
13151 
13152    char codecbuf[SIPBUFSIZE];
13153    char buf[SIPBUFSIZE];
13154 
13155    /* Set the SDP session name */
13156    snprintf(subject, sizeof(subject), "s=%s\r\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
13157 
13158    if (!alreadysent || !tmpcap) {
13159       res = AST_FAILURE;
13160       goto add_sdp_cleanup;
13161    }
13162    if (!p->rtp) {
13163       ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
13164       res = AST_FAILURE;
13165       goto add_sdp_cleanup;
13166 
13167    }
13168    /* XXX We should not change properties in the SIP dialog until
13169       we have acceptance of the offer if this is a re-invite */
13170 
13171    /* Set RTP Session ID and version */
13172    if (!p->sessionid) {
13173       p->sessionid = (int)ast_random();
13174       p->sessionversion = p->sessionid;
13175    } else {
13176       if (oldsdp == FALSE)
13177          p->sessionversion++;
13178    }
13179 
13180    if (add_audio) {
13181       doing_directmedia = (!ast_sockaddr_isnull(&p->redirip) && !(ast_format_cap_is_empty(p->redircaps))) ? TRUE : FALSE;
13182       /* Check if we need video in this call */
13183       if ((ast_format_cap_has_type(p->jointcaps, AST_FORMAT_TYPE_VIDEO)) && !p->novideo) {
13184          ast_format_cap_joint_copy(p->jointcaps, p->redircaps, tmpcap);
13185          if (doing_directmedia && !ast_format_cap_has_type(tmpcap, AST_FORMAT_TYPE_VIDEO)) {
13186             ast_debug(2, "This call needs video offers, but caller probably did not offer it!\n");
13187          } else if (p->vrtp) {
13188             needvideo = TRUE;
13189             ast_debug(2, "This call needs video offers!\n");
13190          } else {
13191             ast_debug(2, "This call needs video offers, but there's no video support enabled!\n");
13192          }
13193       }
13194       /* Check if we need text in this call */
13195       if ((ast_format_cap_has_type(p->jointcaps, AST_FORMAT_TYPE_TEXT)) && !p->notext) {
13196          if (sipdebug_text)
13197             ast_verbose("We think we can do text\n");
13198          if (p->trtp) {
13199             if (sipdebug_text) {
13200                ast_verbose("And we have a text rtp object\n");
13201             }
13202             needtext = TRUE;
13203             ast_debug(2, "This call needs text offers! \n");
13204          } else {
13205             ast_debug(2, "This call needs text offers, but there's no text support enabled ! \n");
13206          }
13207       }
13208    }
13209 
13210    get_our_media_address(p, needvideo, needtext, &addr, &vaddr, &taddr, &dest, &vdest, &tdest);
13211 
13212    snprintf(owner, sizeof(owner), "o=%s %d %d IN %s %s\r\n",
13213        ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner,
13214        p->sessionid, p->sessionversion,
13215        (ast_sockaddr_is_ipv6(&dest) && !ast_sockaddr_is_ipv4_mapped(&dest)) ?
13216          "IP6" : "IP4",
13217        ast_sockaddr_stringify_addr_remote(&dest));
13218 
13219    snprintf(connection, sizeof(connection), "c=IN %s %s\r\n",
13220        (ast_sockaddr_is_ipv6(&dest) && !ast_sockaddr_is_ipv4_mapped(&dest)) ?
13221          "IP6" : "IP4",
13222        ast_sockaddr_stringify_addr_remote(&dest));
13223 
13224    if (add_audio) {
13225       if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR) {
13226          hold = "a=recvonly\r\n";
13227          doing_directmedia = FALSE;
13228       } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE) {
13229          hold = "a=inactive\r\n";
13230          doing_directmedia = FALSE;
13231       } else {
13232          hold = "a=sendrecv\r\n";
13233       }
13234 
13235       ast_format_cap_copy(tmpcap, p->jointcaps);
13236 
13237       /* XXX note, Video and Text are negated - 'true' means 'no' */
13238       ast_debug(1, "** Our capability: %s Video flag: %s Text flag: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), tmpcap),
13239            p->novideo ? "True" : "False", p->notext ? "True" : "False");
13240       ast_debug(1, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcaps));
13241 
13242       if (doing_directmedia) {
13243          ast_format_cap_joint_copy(p->jointcaps, p->redircaps, tmpcap);
13244          ast_debug(1, "** Our native-bridge filtered capablity: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), tmpcap));
13245       }
13246 
13247       /* Check if we need audio */
13248       if (ast_format_cap_has_type(tmpcap, AST_FORMAT_TYPE_AUDIO))
13249          needaudio = TRUE;
13250 
13251       if (debug) {
13252          ast_verbose("Audio is at %s\n", ast_sockaddr_stringify_port(&addr));
13253       }
13254 
13255       /* Ok, we need video. Let's add what we need for video and set codecs.
13256          Video is handled differently than audio since we can not transcode. */
13257       if (needvideo) {
13258          get_crypto_attrib(p, p->vsrtp, &v_a_crypto);
13259          ast_str_append(&m_video, 0, "m=video %d %s", ast_sockaddr_port(&vdest),
13260                    get_sdp_rtp_profile(p, v_a_crypto ? 1 : 0, p->vrtp));
13261 
13262          /* Build max bitrate string */
13263          if (p->maxcallbitrate)
13264             snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
13265          if (debug) {
13266             ast_verbose("Video is at %s\n", ast_sockaddr_stringify(&vdest));
13267          }
13268 
13269          if (!doing_directmedia) {
13270             if (ast_test_flag(&p->flags[2], SIP_PAGE3_ICE_SUPPORT)) {
13271                add_ice_to_sdp(p->vrtp, &a_video);
13272             }
13273 
13274             add_dtls_to_sdp(p->vrtp, &a_video);
13275          }
13276       }
13277 
13278       /* Ok, we need text. Let's add what we need for text and set codecs.
13279          Text is handled differently than audio since we can not transcode. */
13280       if (needtext) {
13281          if (sipdebug_text)
13282             ast_verbose("Lets set up the text sdp\n");
13283          get_crypto_attrib(p, p->tsrtp, &t_a_crypto);
13284          ast_str_append(&m_text, 0, "m=text %d %s", ast_sockaddr_port(&tdest),
13285                    get_sdp_rtp_profile(p, t_a_crypto ? 1 : 0, p->trtp));
13286          if (debug) {  /* XXX should I use tdest below ? */
13287             ast_verbose("Text is at %s\n", ast_sockaddr_stringify(&taddr));
13288          }
13289 
13290          if (!doing_directmedia) {
13291             if (ast_test_flag(&p->flags[2], SIP_PAGE3_ICE_SUPPORT)) {
13292                add_ice_to_sdp(p->trtp, &a_text);
13293             }
13294 
13295             add_dtls_to_sdp(p->trtp, &a_text);
13296          }
13297       }
13298 
13299       /* Start building generic SDP headers */
13300 
13301       /* We break with the "recommendation" and send our IP, in order that our
13302          peer doesn't have to ast_gethostbyname() us */
13303 
13304       get_crypto_attrib(p, p->srtp, &a_crypto);
13305       ast_str_append(&m_audio, 0, "m=audio %d %s", ast_sockaddr_port(&dest),
13306                 get_sdp_rtp_profile(p, a_crypto ? 1 : 0, p->rtp));
13307 
13308       /* Now, start adding audio codecs. These are added in this order:
13309          - First what was requested by the calling channel
13310          - Then preferences in order from sip.conf device config for this peer/user
13311          - Then other codecs in capabilities, including video
13312       */
13313 
13314       /* Prefer the audio codec we were requested to use, first, no matter what
13315          Note that p->prefcodec can include video codecs, so ignore them
13316       */
13317       ast_format_cap_iter_start(p->prefcaps);
13318       while (!(ast_format_cap_iter_next(p->prefcaps, &tmp_fmt))) {
13319          if (AST_FORMAT_GET_TYPE(tmp_fmt.id) != AST_FORMAT_TYPE_AUDIO ||
13320             !ast_format_cap_iscompatible(tmpcap, &tmp_fmt)) {
13321             continue;
13322          }
13323          add_codec_to_sdp(p, &tmp_fmt, &m_audio, &a_audio, debug, &min_audio_packet_size);
13324          ast_format_cap_add(alreadysent, &tmp_fmt);
13325       }
13326       ast_format_cap_iter_end(p->prefcaps);
13327 
13328       /* Start by sending our preferred audio/video codecs */
13329       for (x = 0; x < AST_CODEC_PREF_SIZE; x++) {
13330          struct ast_format pref;
13331 
13332          if (!(ast_codec_pref_index(&p->prefs, x, &pref)))
13333             break;
13334 
13335          if (!ast_format_cap_get_compatible_format(tmpcap, &pref, &tmp_fmt))
13336             continue;
13337 
13338          if (ast_format_cap_iscompatible(alreadysent, &tmp_fmt))
13339             continue;
13340 
13341          if (AST_FORMAT_GET_TYPE(tmp_fmt.id) == AST_FORMAT_TYPE_AUDIO) {
13342             add_codec_to_sdp(p, &tmp_fmt, &m_audio, &a_audio, debug, &min_audio_packet_size);
13343          } else if (needvideo && (AST_FORMAT_GET_TYPE(tmp_fmt.id) == AST_FORMAT_TYPE_VIDEO)) {
13344             add_vcodec_to_sdp(p, &tmp_fmt, &m_video, &a_video, debug, &min_video_packet_size);
13345          } else if (needtext && (AST_FORMAT_GET_TYPE(tmp_fmt.id) == AST_FORMAT_TYPE_TEXT)) {
13346             add_tcodec_to_sdp(p, &tmp_fmt, &m_text, &a_text, debug, &min_text_packet_size);
13347          }
13348 
13349          ast_format_cap_add(alreadysent, &tmp_fmt);
13350       }
13351 
13352       /* Now send any other common audio and video codecs, and non-codec formats: */
13353       ast_format_cap_iter_start(tmpcap);
13354       while (!(ast_format_cap_iter_next(tmpcap, &tmp_fmt))) {
13355          if (ast_format_cap_iscompatible(alreadysent, &tmp_fmt))
13356             continue;
13357 
13358          if (AST_FORMAT_GET_TYPE(tmp_fmt.id) == AST_FORMAT_TYPE_AUDIO) {
13359             add_codec_to_sdp(p, &tmp_fmt, &m_audio, &a_audio, debug, &min_audio_packet_size);
13360          } else if (needvideo && (AST_FORMAT_GET_TYPE(tmp_fmt.id) == AST_FORMAT_TYPE_VIDEO)) {
13361             add_vcodec_to_sdp(p, &tmp_fmt, &m_video, &a_video, debug, &min_video_packet_size);
13362          } else if (needtext && (AST_FORMAT_GET_TYPE(tmp_fmt.id) == AST_FORMAT_TYPE_TEXT)) {
13363             add_tcodec_to_sdp(p, &tmp_fmt, &m_text, &a_text, debug, &min_text_packet_size);
13364          }
13365       }
13366       ast_format_cap_iter_end(tmpcap);
13367 
13368       /* Now add DTMF RFC2833 telephony-event as a codec */
13369       for (x = 1LL; x <= AST_RTP_MAX; x <<= 1) {
13370          if (!(p->jointnoncodeccapability & x))
13371             continue;
13372 
13373          add_noncodec_to_sdp(p, x, &m_audio, &a_audio, debug);
13374       }
13375 
13376       ast_debug(3, "-- Done with adding codecs to SDP\n");
13377 
13378       if (!p->owner || ast_channel_timingfd(p->owner) == -1) {
13379          ast_str_append(&a_audio, 0, "a=silenceSupp:off - - - -\r\n");
13380       }
13381 
13382       if (min_audio_packet_size)
13383          ast_str_append(&a_audio, 0, "a=ptime:%d\r\n", min_audio_packet_size);
13384 
13385       /* XXX don't think you can have ptime for video */
13386       if (min_video_packet_size)
13387          ast_str_append(&a_video, 0, "a=ptime:%d\r\n", min_video_packet_size);
13388 
13389       /* XXX don't think you can have ptime for text */
13390       if (min_text_packet_size)
13391          ast_str_append(&a_text, 0, "a=ptime:%d\r\n", min_text_packet_size);
13392 
13393       if (!doing_directmedia) {
13394          if (ast_test_flag(&p->flags[2], SIP_PAGE3_ICE_SUPPORT)) {
13395             add_ice_to_sdp(p->rtp, &a_audio);
13396          }
13397 
13398          add_dtls_to_sdp(p->rtp, &a_audio);
13399       }
13400    }
13401 
13402    if (add_t38) {
13403       /* Our T.38 end is */
13404       ast_udptl_get_us(p->udptl, &udptladdr);
13405 
13406       /* We don't use directmedia for T.38, so keep the destination the same as our IP address. */
13407       ast_sockaddr_copy(&udptldest, &p->ourip);
13408       ast_sockaddr_set_port(&udptldest, ast_sockaddr_port(&udptladdr));
13409 
13410       if (debug) {
13411          ast_debug(1, "T.38 UDPTL is at %s port %d\n", ast_sockaddr_stringify_addr(&p->ourip), ast_sockaddr_port(&udptladdr));
13412       }
13413 
13414       /* We break with the "recommendation" and send our IP, in order that our
13415          peer doesn't have to ast_gethostbyname() us */
13416 
13417       ast_str_append(&m_modem, 0, "m=image %d udptl t38\r\n", ast_sockaddr_port(&udptldest));
13418 
13419       if (ast_sockaddr_cmp(&udptldest, &dest)) {
13420          ast_str_append(&m_modem, 0, "c=IN %s %s\r\n",
13421                (ast_sockaddr_is_ipv6(&udptldest) && !ast_sockaddr_is_ipv4_mapped(&udptldest)) ?
13422                "IP6" : "IP4", ast_sockaddr_stringify_addr_remote(&udptldest));
13423       }
13424 
13425       ast_str_append(&a_modem, 0, "a=T38FaxVersion:%u\r\n", p->t38.our_parms.version);
13426       ast_str_append(&a_modem, 0, "a=T38MaxBitRate:%u\r\n", t38_get_rate(p->t38.our_parms.rate));
13427       if (p->t38.our_parms.fill_bit_removal) {
13428          ast_str_append(&a_modem, 0, "a=T38FaxFillBitRemoval\r\n");
13429       }
13430       if (p->t38.our_parms.transcoding_mmr) {
13431          ast_str_append(&a_modem, 0, "a=T38FaxTranscodingMMR\r\n");
13432       }
13433       if (p->t38.our_parms.transcoding_jbig) {
13434          ast_str_append(&a_modem, 0, "a=T38FaxTranscodingJBIG\r\n");
13435       }
13436       switch (p->t38.our_parms.rate_management) {
13437       case AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF:
13438          ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:transferredTCF\r\n");
13439          break;
13440       case AST_T38_RATE_MANAGEMENT_LOCAL_TCF:
13441          ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:localTCF\r\n");
13442          break;
13443       }
13444       ast_str_append(&a_modem, 0, "a=T38FaxMaxDatagram:%u\r\n", ast_udptl_get_local_max_datagram(p->udptl));
13445       switch (ast_udptl_get_error_correction_scheme(p->udptl)) {
13446       case UDPTL_ERROR_CORRECTION_NONE:
13447          break;
13448       case UDPTL_ERROR_CORRECTION_FEC:
13449          ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPFEC\r\n");
13450          break;
13451       case UDPTL_ERROR_CORRECTION_REDUNDANCY:
13452          ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPRedundancy\r\n");
13453          break;
13454       }
13455    }
13456 
13457    if (needaudio)
13458       ast_str_append(&m_audio, 0, "\r\n");
13459    if (needvideo)
13460       ast_str_append(&m_video, 0, "\r\n");
13461    if (needtext)
13462       ast_str_append(&m_text, 0, "\r\n");
13463 
13464    add_header(resp, "Content-Type", "application/sdp");
13465    add_content(resp, version);
13466    add_content(resp, owner);
13467    add_content(resp, subject);
13468    add_content(resp, connection);
13469    /* only if video response is appropriate */
13470    if (needvideo) {
13471       add_content(resp, bandwidth);
13472    }
13473    add_content(resp, session_time);
13474    /* if this is a response to an invite, order our offers properly */
13475    if (!AST_LIST_EMPTY(&p->offered_media)) {
13476       AST_LIST_TRAVERSE(&p->offered_media, offer, next) {
13477          switch (offer->type) {
13478          case SDP_AUDIO:
13479             if (needaudio) {
13480                add_content(resp, ast_str_buffer(m_audio));
13481                add_content(resp, ast_str_buffer(a_audio));
13482                add_content(resp, hold);
13483                if (a_crypto) {
13484                   add_content(resp, a_crypto);
13485                }
13486             } else {
13487                add_content(resp, offer->decline_m_line);
13488             }
13489             break;
13490          case SDP_VIDEO:
13491             if (needvideo) { /* only if video response is appropriate */
13492                add_content(resp, ast_str_buffer(m_video));
13493                add_content(resp, ast_str_buffer(a_video));
13494                add_content(resp, hold);   /* Repeat hold for the video stream */
13495                if (v_a_crypto) {
13496                   add_content(resp, v_a_crypto);
13497                }
13498             } else {
13499                add_content(resp, offer->decline_m_line);
13500             }
13501             break;
13502          case SDP_TEXT:
13503             if (needtext) { /* only if text response is appropriate */
13504                add_content(resp, ast_str_buffer(m_text));
13505                add_content(resp, ast_str_buffer(a_text));
13506                add_content(resp, hold);   /* Repeat hold for the text stream */
13507                if (t_a_crypto) {
13508                   add_content(resp, t_a_crypto);
13509                }
13510             } else {
13511                add_content(resp, offer->decline_m_line);
13512             }
13513             break;
13514          case SDP_IMAGE:
13515             if (add_t38) {
13516                add_content(resp, ast_str_buffer(m_modem));
13517                add_content(resp, ast_str_buffer(a_modem));
13518             } else {
13519                add_content(resp, offer->decline_m_line);
13520             }
13521             break;
13522          case SDP_UNKNOWN:
13523             add_content(resp, offer->decline_m_line);
13524             break;
13525          }
13526       }
13527    } else {
13528       /* generate new SDP from scratch, no offers */
13529       if (needaudio) {
13530          add_content(resp, ast_str_buffer(m_audio));
13531          add_content(resp, ast_str_buffer(a_audio));
13532          add_content(resp, hold);
13533          if (a_crypto) {
13534             add_content(resp, a_crypto);
13535          }
13536       }
13537       if (needvideo) { /* only if video response is appropriate */
13538          add_content(resp, ast_str_buffer(m_video));
13539          add_content(resp, ast_str_buffer(a_video));
13540          add_content(resp, hold);   /* Repeat hold for the video stream */
13541          if (v_a_crypto) {
13542             add_content(resp, v_a_crypto);
13543          }
13544       }
13545       if (needtext) { /* only if text response is appropriate */
13546          add_content(resp, ast_str_buffer(m_text));
13547          add_content(resp, ast_str_buffer(a_text));
13548          add_content(resp, hold);   /* Repeat hold for the text stream */
13549          if (t_a_crypto) {
13550             add_content(resp, t_a_crypto);
13551          }
13552       }
13553       if (add_t38) {
13554          add_content(resp, ast_str_buffer(m_modem));
13555          add_content(resp, ast_str_buffer(a_modem));
13556       }
13557    }
13558 
13559    /* Update lastrtprx when we send our SDP */
13560    p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
13561 
13562    /*
13563     * We unlink this dialog and link again into the
13564     * dialogs_rtpcheck container so its not in there twice.
13565     */
13566    ao2_lock(dialogs_rtpcheck);
13567    ao2_t_unlink(dialogs_rtpcheck, p, "unlink pvt into dialogs_rtpcheck container");
13568    ao2_t_link(dialogs_rtpcheck, p, "link pvt into dialogs_rtpcheck container");
13569    ao2_unlock(dialogs_rtpcheck);
13570 
13571    ast_debug(3, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, tmpcap));
13572 
13573 add_sdp_cleanup:
13574    ast_free(a_text);
13575    ast_free(a_video);
13576    ast_free(a_audio);
13577    alreadysent = ast_format_cap_destroy(alreadysent);
13578    tmpcap = ast_format_cap_destroy(tmpcap);
13579 
13580    return res;
13581 }
13582 
13583 /*! \brief Used for 200 OK and 183 early media */
13584 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
13585 {
13586    struct sip_request resp;
13587    uint32_t seqno;
13588 
13589    if (sscanf(sip_get_header(req, "CSeq"), "%30u ", &seqno) != 1) {
13590       ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", sip_get_header(req, "CSeq"));
13591       return -1;
13592    }
13593    respprep(&resp, p, msg, req);
13594    if (p->udptl) {
13595       add_sdp(&resp, p, 0, 0, 1);
13596    } else
13597       ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
13598    if (retrans && !p->pendinginvite)
13599       p->pendinginvite = seqno;     /* Buggy clients sends ACK on RINGING too */
13600    return send_response(p, &resp, retrans, seqno);
13601 }
13602 
13603 /*! \brief copy SIP request (mostly used to save request for responses) */
13604 static void copy_request(struct sip_request *dst, const struct sip_request *src)
13605 {
13606    /* XXX this function can encounter memory allocation errors, perhaps it
13607     * should return a value */
13608 
13609    struct ast_str *duplicate = dst->data;
13610    struct ast_str *duplicate_content = dst->content;
13611 
13612    /* copy the entire request then restore the original data and content
13613     * members from the dst request */
13614    *dst = *src;
13615    dst->data = duplicate;
13616    dst->content = duplicate_content;
13617 
13618    /* copy the data into the dst request */
13619    if (!dst->data && !(dst->data = ast_str_create(ast_str_strlen(src->data) + 1))) {
13620       return;
13621    }
13622    ast_str_copy_string(&dst->data, src->data);
13623 
13624    /* copy the content into the dst request (if it exists) */
13625    if (src->content) {
13626       if (!dst->content && !(dst->content = ast_str_create(ast_str_strlen(src->content) + 1))) {
13627          return;
13628       }
13629       ast_str_copy_string(&dst->content, src->content);
13630    }
13631 }
13632 
13633 static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp)
13634 {
13635    char uri[SIPBUFSIZE];
13636    struct ast_str *header = ast_str_alloca(SIPBUFSIZE);
13637    struct ast_cc_agent *agent = find_sip_cc_agent_by_original_callid(p);
13638    struct sip_cc_agent_pvt *agent_pvt;
13639 
13640    if (!agent) {
13641       /* Um, what? How could the SIP_OFFER_CC flag be set but there not be an
13642        * agent? Oh well, we'll just warn and return without adding the header.
13643        */
13644       ast_log(LOG_WARNING, "Can't find SIP CC agent for call '%s' even though OFFER_CC flag was set?\n", p->callid);
13645       return;
13646    }
13647 
13648    agent_pvt = agent->private_data;
13649 
13650    if (!ast_strlen_zero(agent_pvt->subscribe_uri)) {
13651       ast_copy_string(uri, agent_pvt->subscribe_uri, sizeof(uri));
13652    } else {
13653       generate_uri(p, uri, sizeof(uri));
13654       ast_copy_string(agent_pvt->subscribe_uri, uri, sizeof(agent_pvt->subscribe_uri));
13655    }
13656    /* XXX Hardcode "NR" as the m reason for now. This should perhaps be changed
13657     * to be more accurate. This parameter has no bearing on the actual operation
13658     * of the feature; it's just there for informational purposes.
13659     */
13660    ast_str_set(&header, 0, "<%s>;purpose=call-completion;m=%s", uri, "NR");
13661    add_header(resp, "Call-Info", ast_str_buffer(header));
13662    ao2_ref(agent, -1);
13663 }
13664 
13665 /*! \brief Used for 200 OK and 183 early media
13666    \return Will return XMIT_ERROR for network errors.
13667 */
13668 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)
13669 {
13670    struct sip_request resp;
13671    uint32_t seqno;
13672    if (sscanf(sip_get_header(req, "CSeq"), "%30u ", &seqno) != 1) {
13673       ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", sip_get_header(req, "CSeq"));
13674       return -1;
13675    }
13676    respprep(&resp, p, msg, req);
13677    if (rpid == TRUE) {
13678       add_rpid(&resp, p);
13679    }
13680    if (ast_test_flag(&p->flags[0], SIP_OFFER_CC)) {
13681       add_cc_call_info_to_response(p, &resp);
13682    }
13683    if (p->rtp) {
13684       if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
13685          ast_debug(1, "Setting framing from config on incoming call\n");
13686          ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &p->prefs);
13687       }
13688       ast_rtp_instance_activate(p->rtp);
13689       try_suggested_sip_codec(p);
13690       if (p->t38.state == T38_ENABLED) {
13691          add_sdp(&resp, p, oldsdp, TRUE, TRUE);
13692       } else {
13693          add_sdp(&resp, p, oldsdp, TRUE, FALSE);
13694       }
13695    } else
13696       ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
13697    if (reliable && !p->pendinginvite)
13698       p->pendinginvite = seqno;     /* Buggy clients sends ACK on RINGING too */
13699    add_required_respheader(&resp);
13700    return send_response(p, &resp, reliable, seqno);
13701 }
13702 
13703 /*! \brief Parse first line of incoming SIP request */
13704 static int determine_firstline_parts(struct sip_request *req)
13705 {
13706    char *e = ast_skip_blanks(req->data->str);   /* there shouldn't be any */
13707    char *local_rlpart1;
13708 
13709    if (!*e)
13710       return -1;
13711    req->rlpart1 = e - req->data->str;  /* method or protocol */
13712    local_rlpart1 = e;
13713    e = ast_skip_nonblanks(e);
13714    if (*e)
13715       *e++ = '\0';
13716    /* Get URI or status code */
13717    e = ast_skip_blanks(e);
13718    if ( !*e )
13719       return -1;
13720    ast_trim_blanks(e);
13721 
13722    if (!strcasecmp(local_rlpart1, "SIP/2.0") ) { /* We have a response */
13723       if (strlen(e) < 3)   /* status code is 3 digits */
13724          return -1;
13725       req->rlpart2 = e - req->data->str;
13726    } else { /* We have a request */
13727       if ( *e == '<' ) { /* XXX the spec says it must not be in <> ! */
13728          ast_debug(3, "Oops. Bogus uri in <> %s\n", e);
13729          e++;
13730          if (!*e)
13731             return -1;
13732       }
13733       req->rlpart2 = e - req->data->str;  /* URI */
13734       e = ast_skip_nonblanks(e);
13735       if (*e)
13736          *e++ = '\0';
13737       e = ast_skip_blanks(e);
13738       if (strcasecmp(e, "SIP/2.0") ) {
13739          ast_debug(3, "Skipping packet - Bad request protocol %s\n", e);
13740          return -1;
13741       }
13742    }
13743    return 1;
13744 }
13745 
13746 /*! \brief Transmit reinvite with SDP
13747 \note    A re-invite is basically a new INVITE with the same CALL-ID and TAG as the
13748    INVITE that opened the SIP dialogue
13749    We reinvite so that the audio stream (RTP) go directly between
13750    the SIP UAs. SIP Signalling stays with * in the path.
13751    
13752    If t38version is TRUE, we send T38 SDP for re-invite from audio/video to
13753    T38 UDPTL transmission on the channel
13754 
13755     If oldsdp is TRUE then the SDP version number is not incremented. This
13756     is needed for Session-Timers so we can send a re-invite to refresh the
13757     SIP session without modifying the media session.
13758 */
13759 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp)
13760 {
13761    struct sip_request req;
13762    
13763    reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ?  SIP_UPDATE : SIP_INVITE, 0, 1);
13764 
13765    add_header(&req, "Allow", ALLOWED_METHODS);
13766    add_supported(p, &req);
13767    if (sipdebug) {
13768       if (oldsdp == TRUE)
13769          add_header(&req, "X-asterisk-Info", "SIP re-invite (Session-Timers)");
13770       else
13771          add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
13772    }
13773 
13774    if (ast_test_flag(&p->flags[0], SIP_SENDRPID))
13775       add_rpid(&req, p);
13776 
13777    if (p->do_history) {
13778       append_history(p, "ReInv", "Re-invite sent");
13779    }
13780 
13781    offered_media_list_destroy(p);
13782 
13783    try_suggested_sip_codec(p);
13784    if (t38version) {
13785       add_sdp(&req, p, oldsdp, FALSE, TRUE);
13786    } else {
13787       add_sdp(&req, p, oldsdp, TRUE, FALSE);
13788    }
13789 
13790    /* Use this as the basis */
13791    initialize_initreq(p, &req);
13792    p->lastinvite = p->ocseq;
13793    ast_set_flag(&p->flags[0], SIP_OUTGOING);       /* Change direction of this dialog */
13794    p->ongoing_reinvite = 1;
13795    return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
13796 }
13797 
13798 /* \brief Remove URI parameters at end of URI, not in username part though */
13799 static char *remove_uri_parameters(char *uri)
13800 {
13801    char *atsign;
13802    atsign = strchr(uri, '@'); /* First, locate the at sign */
13803    if (!atsign) {
13804       atsign = uri;  /* Ok hostname only, let's stick with the rest */
13805    }
13806    atsign = strchr(atsign, ';'); /* Locate semi colon */
13807    if (atsign)
13808       *atsign = '\0';   /* Kill at the semi colon */
13809    return uri;
13810 }
13811 
13812 /*! \brief Check Contact: URI of SIP message */
13813 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
13814 {
13815    char stripped[SIPBUFSIZE];
13816    char *c;
13817 
13818    ast_copy_string(stripped, sip_get_header(req, "Contact"), sizeof(stripped));
13819    c = get_in_brackets(stripped);
13820    /* Cut the URI at the at sign after the @, not in the username part */
13821    c = remove_uri_parameters(c);
13822    if (!ast_strlen_zero(c)) {
13823       ast_string_field_set(p, uri, c);
13824    }
13825 
13826 }
13827 
13828 /*! \brief Build contact header - the contact header we send out */
13829 static void build_contact(struct sip_pvt *p)
13830 {
13831    char tmp[SIPBUFSIZE];
13832    char *user = ast_uri_encode(p->exten, tmp, sizeof(tmp), ast_uri_sip_user);
13833 
13834    if (p->socket.type == SIP_TRANSPORT_UDP) {
13835       ast_string_field_build(p, our_contact, "<sip:%s%s%s>", user,
13836          ast_strlen_zero(user) ? "" : "@", ast_sockaddr_stringify_remote(&p->ourip));
13837    } else {
13838       ast_string_field_build(p, our_contact, "<sip:%s%s%s;transport=%s>", user,
13839          ast_strlen_zero(user) ? "" : "@", ast_sockaddr_stringify_remote(&p->ourip),
13840          sip_get_transport(p->socket.type));
13841    }
13842 }
13843 
13844 /*! \brief Initiate new SIP request to peer/user */
13845 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri)
13846 {
13847    struct ast_str *invite = ast_str_alloca(256);
13848    char from[256];
13849    char to[256];
13850    char tmp_n[SIPBUFSIZE/2];  /* build a local copy of 'n' if needed */
13851    char tmp_l[SIPBUFSIZE/2];  /* build a local copy of 'l' if needed */
13852    const char *l = NULL;   /* XXX what is this, exactly ? */
13853    const char *n = NULL;   /* XXX what is this, exactly ? */
13854    const char *d = NULL;   /* domain in from header */
13855    const char *urioptions = "";
13856    int ourport;
13857    int cid_has_name = 1;
13858    int cid_has_num = 1;
13859    struct ast_party_id connected_id;
13860 
13861    if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
13862       const char *s = p->username;  /* being a string field, cannot be NULL */
13863 
13864       /* Test p->username against allowed characters in AST_DIGIT_ANY
13865          If it matches the allowed characters list, then sipuser = ";user=phone"
13866          If not, then sipuser = ""
13867       */
13868       /* + is allowed in first position in a tel: uri */
13869       if (*s == '+')
13870          s++;
13871       for (; *s; s++) {
13872          if (!strchr(AST_DIGIT_ANYNUM, *s) )
13873             break;
13874       }
13875       /* If we have only digits, add ;user=phone to the uri */
13876       if (!*s)
13877          urioptions = ";user=phone";
13878    }
13879 
13880 
13881    snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
13882 
13883    if (ast_strlen_zero(p->fromdomain)) {
13884       d = ast_sockaddr_stringify_host_remote(&p->ourip);
13885    }
13886    if (p->owner) {
13887       connected_id = ast_channel_connected_effective_id(p->owner);
13888 
13889       if ((ast_party_id_presentation(&connected_id) & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED) {
13890          if (connected_id.number.valid) {
13891             l = connected_id.number.str;
13892          }
13893          if (connected_id.name.valid) {
13894             n = connected_id.name.str;
13895          }
13896       } else {
13897          /* Even if we are using RPID, we shouldn't leak information in the From if the user wants
13898           * their callerid restricted */
13899          l = "anonymous";
13900          n = CALLERID_UNKNOWN;
13901          d = FROMDOMAIN_INVALID;
13902       }
13903    }
13904 
13905    /* Hey, it's a NOTIFY! See if they've configured a mwi_from.
13906     * XXX Right now, this logic works because the only place that mwi_from
13907     * is set on the sip_pvt is in sip_send_mwi_to_peer. If things changed, then
13908     * we might end up putting the mwi_from setting into other types of NOTIFY
13909     * messages as well.
13910     */
13911    if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->mwi_from)) {
13912       l = p->mwi_from;
13913    }
13914 
13915    if (ast_strlen_zero(l)) {
13916       cid_has_num = 0;
13917       l = default_callerid;
13918    }
13919    if (ast_strlen_zero(n)) {
13920       cid_has_name = 0;
13921       n = l;
13922    }
13923 
13924    /* Allow user to be overridden */
13925    if (!ast_strlen_zero(p->fromuser))
13926       l = p->fromuser;
13927    else /* Save for any further attempts */
13928       ast_string_field_set(p, fromuser, l);
13929 
13930    /* Allow user to be overridden */
13931    if (!ast_strlen_zero(p->fromname))
13932       n = p->fromname;
13933    else /* Save for any further attempts */
13934       ast_string_field_set(p, fromname, n);
13935 
13936    /* Allow domain to be overridden */
13937    if (!ast_strlen_zero(p->fromdomain))
13938       d = p->fromdomain;
13939    else /* Save for any further attempts */
13940       ast_string_field_set(p, fromdomain, d);
13941 
13942    ast_copy_string(tmp_l, l, sizeof(tmp_l));
13943    if (sip_cfg.pedanticsipchecking) {
13944       ast_escape_quoted(n, tmp_n, sizeof(tmp_n));
13945       n = tmp_n;
13946       ast_uri_encode(l, tmp_l, sizeof(tmp_l), ast_uri_sip_user);
13947    }
13948 
13949    ourport = (p->fromdomainport) ? p->fromdomainport : ast_sockaddr_port(&p->ourip);
13950 
13951    /* If a caller id name was specified, add a display name. */
13952    if (cid_has_name || !cid_has_num) {
13953       snprintf(from, sizeof(from), "\"%s\" ", n);
13954    } else {
13955       from[0] = '\0';
13956    }
13957 
13958    if (!sip_standard_port(p->socket.type, ourport)) {
13959       size_t offset = strlen(from);
13960       snprintf(&from[offset], sizeof(from) - offset, "<sip:%s@%s:%d>;tag=%s", tmp_l, d, ourport, p->tag);
13961    } else {
13962       size_t offset = strlen(from);
13963       snprintf(&from[offset], sizeof(from) - offset, "<sip:%s@%s>;tag=%s", tmp_l, d, p->tag);
13964    }
13965 
13966    if (!ast_strlen_zero(explicit_uri)) {
13967       ast_str_set(&invite, 0, "%s", explicit_uri);
13968    } else {
13969       /* If we're calling a registered SIP peer, use the fullcontact to dial to the peer */
13970       if (!ast_strlen_zero(p->fullcontact)) {
13971          /* If we have full contact, trust it */
13972          ast_str_append(&invite, 0, "%s", p->fullcontact);
13973       } else {
13974          /* Otherwise, use the username while waiting for registration */
13975          ast_str_append(&invite, 0, "sip:");
13976          if (!ast_strlen_zero(p->username)) {
13977             n = p->username;
13978             if (sip_cfg.pedanticsipchecking) {
13979                ast_uri_encode(n, tmp_n, sizeof(tmp_n), ast_uri_sip_user);
13980                n = tmp_n;
13981             }
13982             ast_str_append(&invite, 0, "%s@", n);
13983          }
13984          ast_str_append(&invite, 0, "%s", p->tohost);
13985          if (p->portinuri) {
13986             ast_str_append(&invite, 0, ":%d", ast_sockaddr_port(&p->sa));
13987          }
13988          ast_str_append(&invite, 0, "%s", urioptions);
13989       }
13990    }
13991 
13992    /* If custom URI options have been provided, append them */
13993    if (p->options && !ast_strlen_zero(p->options->uri_options))
13994       ast_str_append(&invite, 0, ";%s", p->options->uri_options);
13995    
13996    /* This is the request URI, which is the next hop of the call
13997       which may or may not be the destination of the call
13998    */
13999    ast_string_field_set(p, uri, ast_str_buffer(invite));
14000 
14001    if (!ast_strlen_zero(p->todnid)) {
14002       /*! \todo Need to add back the VXML URL here at some point, possibly use build_string for all this junk */
14003       if (!strchr(p->todnid, '@')) {
14004          /* We have no domain in the dnid */
14005          snprintf(to, sizeof(to), "<sip:%s@%s>%s%s", p->todnid, p->tohost, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
14006       } else {
14007          snprintf(to, sizeof(to), "<sip:%s>%s%s", p->todnid, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
14008       }
14009    } else {
14010       if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) {
14011          /* If this is a NOTIFY, use the From: tag in the subscribe (RFC 3265) */
14012          snprintf(to, sizeof(to), "<%s%s>;tag=%s", (strncasecmp(p->uri, "sip:", 4) ? "sip:" : ""), p->uri, p->theirtag);
14013       } else if (p->options && p->options->vxml_url) {
14014          /* If there is a VXML URL append it to the SIP URL */
14015          snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
14016       } else {
14017          snprintf(to, sizeof(to), "<%s>", p->uri);
14018       }
14019    }
14020 
14021    init_req(req, sipmethod, p->uri);
14022    /* now tmp_n is available so reuse it to build the CSeq */
14023    snprintf(tmp_n, sizeof(tmp_n), "%u %s", ++p->ocseq, sip_methods[sipmethod].text);
14024 
14025    add_header(req, "Via", p->via);
14026    add_max_forwards(p, req);
14027    /* This will be a no-op most of the time. However, under certain circumstances,
14028     * NOTIFY messages will use this function for preparing the request and should
14029     * have Route headers present.
14030     */
14031    add_route(req, p->route);
14032 
14033    add_header(req, "From", from);
14034    add_header(req, "To", to);
14035    ast_string_field_set(p, exten, l);
14036    build_contact(p);
14037    add_header(req, "Contact", p->our_contact);
14038    add_header(req, "Call-ID", p->callid);
14039    add_header(req, "CSeq", tmp_n);
14040    if (!ast_strlen_zero(global_useragent)) {
14041       add_header(req, "User-Agent", global_useragent);
14042    }
14043 }
14044 
14045 /*! \brief Add "Diversion" header to outgoing message
14046  *
14047  * We need to add a Diversion header if the owner channel of
14048  * this dialog has redirecting information associated with it.
14049  *
14050  * \param req The request/response to which we will add the header
14051  * \param pvt The sip_pvt which represents the call-leg
14052  */
14053 static void add_diversion(struct sip_request *req, struct sip_pvt *pvt)
14054 {
14055    struct ast_party_id diverting_from;
14056    const char *reason;
14057    char header_text[256];
14058 
14059    /* We skip this entirely if the configuration doesn't allow diversion headers */
14060    if (!sip_cfg.send_diversion) {
14061       return;
14062    }
14063 
14064    if (!pvt->owner) {
14065       return;
14066    }
14067 
14068    diverting_from = ast_channel_redirecting_effective_from(pvt->owner);
14069    if (!diverting_from.number.valid
14070       || ast_strlen_zero(diverting_from.number.str)) {
14071       return;
14072    }
14073 
14074    reason = sip_reason_code_to_str(ast_channel_redirecting(pvt->owner)->reason);
14075 
14076    /* We at least have a number to place in the Diversion header, which is enough */
14077    if (!diverting_from.name.valid
14078       || ast_strlen_zero(diverting_from.name.str)) {
14079       snprintf(header_text, sizeof(header_text), "<sip:%s@%s>;reason=%s", diverting_from.number.str,
14080             ast_sockaddr_stringify_host_remote(&pvt->ourip), reason);
14081    } else {
14082       snprintf(header_text, sizeof(header_text), "\"%s\" <sip:%s@%s>;reason=%s",
14083             diverting_from.name.str, diverting_from.number.str,
14084             ast_sockaddr_stringify_host_remote(&pvt->ourip), reason);
14085    }
14086 
14087    add_header(req, "Diversion", header_text);
14088 }
14089 
14090 static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri)
14091 {
14092    struct sip_pvt *pvt;
14093    int expires;
14094 
14095    epa_entry->publish_type = publish_type;
14096 
14097    if (!(pvt = sip_alloc(NULL, NULL, 0, SIP_PUBLISH, NULL, NULL))) {
14098       return -1;
14099    }
14100 
14101    sip_pvt_lock(pvt);
14102 
14103    if (create_addr(pvt, epa_entry->destination, NULL, TRUE)) {
14104       sip_pvt_unlock(pvt);
14105       dialog_unlink_all(pvt);
14106       dialog_unref(pvt, "create_addr failed in transmit_publish. Unref dialog");
14107       return -1;
14108    }
14109    ast_sip_ouraddrfor(&pvt->sa, &pvt->ourip, pvt);
14110    ast_set_flag(&pvt->flags[0], SIP_OUTGOING);
14111    expires = (publish_type == SIP_PUBLISH_REMOVE) ? 0 : DEFAULT_PUBLISH_EXPIRES;
14112    pvt->expiry = expires;
14113 
14114    /* Bump refcount for sip_pvt's reference */
14115    ao2_ref(epa_entry, +1);
14116    pvt->epa_entry = epa_entry;
14117 
14118    transmit_invite(pvt, SIP_PUBLISH, FALSE, 2, explicit_uri);
14119    sip_pvt_unlock(pvt);
14120    sip_scheddestroy(pvt, DEFAULT_TRANS_TIMEOUT);
14121    dialog_unref(pvt, "Done with the sip_pvt allocated for transmitting PUBLISH");
14122    return 0;
14123 }
14124 
14125 /*! 
14126  * \brief Build REFER/INVITE/OPTIONS/SUBSCRIBE message and transmit it
14127  * \param p sip_pvt structure
14128  * \param sipmethod
14129  * \param sdp unknown
14130  * \param init 0 = Prepare request within dialog, 1= prepare request, new branch,
14131  *  2= prepare new request and new dialog. do_proxy_auth calls this with init!=2
14132  * \param explicit_uri
14133 */
14134 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri)
14135 {
14136    struct sip_request req;
14137    struct ast_variable *var;
14138 
14139    if (init) {/* Bump branch even on initial requests */
14140       p->branch ^= ast_random();
14141       p->invite_branch = p->branch;
14142       build_via(p);
14143    }
14144    if (init > 1) {
14145       initreqprep(&req, p, sipmethod, explicit_uri);
14146    } else {
14147       /* If init=1, we should not generate a new branch. If it's 0, we need a new branch. */
14148       reqprep(&req, p, sipmethod, 0, init ? 0 : 1);
14149    }
14150 
14151    if (p->options && p->options->auth) {
14152       add_header(&req, p->options->authheader, p->options->auth);
14153    }
14154    add_date(&req);
14155    if (sipmethod == SIP_REFER && p->refer) { /* Call transfer */
14156       if (!ast_strlen_zero(p->refer->refer_to)) {
14157          add_header(&req, "Refer-To", p->refer->refer_to);
14158       }
14159       if (!ast_strlen_zero(p->refer->referred_by)) {
14160          add_header(&req, "Referred-By", p->refer->referred_by);
14161       }
14162    } else if (sipmethod == SIP_SUBSCRIBE) {
14163       if (p->subscribed == MWI_NOTIFICATION) {
14164          add_header(&req, "Event", "message-summary");
14165          add_header(&req, "Accept", "application/simple-message-summary");
14166       } else if (p->subscribed == CALL_COMPLETION) {
14167          add_header(&req, "Event", "call-completion");
14168          add_header(&req, "Accept", "application/call-completion");
14169       }
14170       add_expires(&req, p->expiry);
14171    }
14172 
14173    /* This new INVITE is part of an attended transfer. Make sure that the
14174    other end knows and replace the current call with this new call */
14175    if (p->options && !ast_strlen_zero(p->options->replaces)) {
14176       add_header(&req, "Replaces", p->options->replaces);
14177       add_header(&req, "Require", "replaces");
14178    }
14179 
14180    /* Add Session-Timers related headers */
14181    if (st_get_mode(p, 0) == SESSION_TIMER_MODE_ORIGINATE
14182       || (st_get_mode(p, 0) == SESSION_TIMER_MODE_ACCEPT
14183          && st_get_se(p, FALSE) != DEFAULT_MIN_SE)) {
14184       char i2astr[10];
14185 
14186       if (!p->stimer->st_interval) {
14187          p->stimer->st_interval = st_get_se(p, TRUE);
14188       }
14189 
14190       p->stimer->st_active = TRUE;
14191       if (st_get_mode(p, 0) == SESSION_TIMER_MODE_ORIGINATE) { 
14192          snprintf(i2astr, sizeof(i2astr), "%d", p->stimer->st_interval);
14193          add_header(&req, "Session-Expires", i2astr);
14194       }
14195 
14196       snprintf(i2astr, sizeof(i2astr), "%d", st_get_se(p, FALSE));
14197       add_header(&req, "Min-SE", i2astr);
14198    }
14199 
14200    add_header(&req, "Allow", ALLOWED_METHODS);
14201    add_supported(p, &req);
14202 
14203    if (p->owner && ((p->options && p->options->addsipheaders)
14204               || (p->refer && global_refer_addheaders))) {
14205       struct ast_channel *chan = p->owner; /* The owner channel */
14206       struct varshead *headp;
14207    
14208       ast_channel_lock(chan);
14209 
14210       headp = ast_channel_varshead(chan);
14211 
14212       if (!headp) {
14213          ast_log(LOG_WARNING, "No Headp for the channel...ooops!\n");
14214       } else {
14215          const struct ast_var_t *current;
14216          AST_LIST_TRAVERSE(headp, current, entries) {
14217             /* SIPADDHEADER: Add SIP header to outgoing call */
14218             if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
14219                char *content, *end;
14220                const char *header = ast_var_value(current);
14221                char *headdup = ast_strdupa(header);
14222 
14223                /* Strip of the starting " (if it's there) */
14224                if (*headdup == '"') {
14225                   headdup++;
14226                }
14227                if ((content = strchr(headdup, ':'))) {
14228                   *content++ = '\0';
14229                   content = ast_skip_blanks(content); /* Skip white space */
14230                   /* Strip the ending " (if it's there) */
14231                   end = content + strlen(content) -1;
14232                   if (*end == '"') {
14233                      *end = '\0';
14234                   }
14235 
14236                   add_header(&req, headdup, content);
14237                   if (sipdebug) {
14238                      ast_debug(1, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
14239                   }
14240                }
14241             }
14242          }
14243       }
14244 
14245       ast_channel_unlock(chan);
14246    }
14247    if ((sipmethod == SIP_INVITE || sipmethod == SIP_UPDATE) && ast_test_flag(&p->flags[0], SIP_SENDRPID))
14248       add_rpid(&req, p);
14249    if (sipmethod == SIP_INVITE) {
14250       add_diversion(&req, p);
14251    }
14252    if (sdp) {
14253       offered_media_list_destroy(p);
14254       if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
14255          ast_debug(1, "T38 is in state %u on channel %s\n", p->t38.state, p->owner ? ast_channel_name(p->owner) : "<none>");
14256          add_sdp(&req, p, FALSE, FALSE, TRUE);
14257       } else if (p->rtp) {
14258          try_suggested_sip_codec(p);
14259          add_sdp(&req, p, FALSE, TRUE, FALSE);
14260       }
14261    } else if (sipmethod == SIP_NOTIFY && p->notify) {
14262       for (var = p->notify->headers; var; var = var->next) {
14263          add_header(&req, var->name, var->value);
14264       }
14265       if (ast_str_strlen(p->notify->content)) {
14266          add_content(&req, ast_str_buffer(p->notify->content));
14267       }
14268    } else if (sipmethod == SIP_PUBLISH) {
14269       switch (p->epa_entry->static_data->event) {
14270       case CALL_COMPLETION:
14271          add_header(&req, "Event", "call-completion");
14272          add_expires(&req, p->expiry);
14273          if (p->epa_entry->publish_type != SIP_PUBLISH_INITIAL) {
14274             add_header(&req, "SIP-If-Match", p->epa_entry->entity_tag);
14275          }
14276 
14277          if (!ast_strlen_zero(p->epa_entry->body)) {
14278             add_header(&req, "Content-Type", "application/pidf+xml");
14279             add_content(&req, p->epa_entry->body);
14280          }
14281       default:
14282          break;
14283       }
14284    }
14285 
14286    if (!p->initreq.headers || init > 2) {
14287       initialize_initreq(p, &req);
14288    }
14289    if (sipmethod == SIP_INVITE || sipmethod == SIP_SUBSCRIBE) {
14290       p->lastinvite = p->ocseq;
14291    }
14292    return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
14293 }
14294 
14295 /*! \brief Send a subscription or resubscription for MWI */
14296 static int sip_subscribe_mwi_do(const void *data)
14297 {
14298    struct sip_subscription_mwi *mwi = (struct sip_subscription_mwi*)data;
14299    
14300    if (!mwi) {
14301       return -1;
14302    }
14303    
14304    mwi->resub = -1;
14305    __sip_subscribe_mwi_do(mwi);
14306    ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
14307    
14308    return 0;
14309 }
14310 
14311 static void on_dns_update_registry(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
14312 {
14313    struct sip_registry *reg = data;
14314    const char *old_str;
14315 
14316    /* This shouldn't happen, but just in case */
14317    if (ast_sockaddr_isnull(new)) {
14318       ast_debug(1, "Empty sockaddr change...ignoring!\n");
14319       return;
14320    }
14321 
14322    if (!ast_sockaddr_port(new)) {
14323       ast_sockaddr_set_port(new, reg->portno);
14324    }
14325 
14326    old_str = ast_strdupa(ast_sockaddr_stringify(old));
14327 
14328    ast_debug(1, "Changing registry %s from %s to %s\n", S_OR(reg->peername, reg->hostname), old_str, ast_sockaddr_stringify(new));
14329    ast_sockaddr_copy(&reg->us, new);
14330 }
14331 
14332 static void on_dns_update_peer(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
14333 {
14334    struct sip_peer *peer = data;
14335    const char *old_str;
14336 
14337    /* This shouldn't happen, but just in case */
14338    if (ast_sockaddr_isnull(new)) {
14339       ast_debug(1, "Empty sockaddr change...ignoring!\n");
14340       return;
14341    }
14342 
14343    if (!ast_sockaddr_isnull(&peer->addr)) {
14344       ao2_unlink(peers_by_ip, peer);
14345    }
14346 
14347    if (!ast_sockaddr_port(new)) {
14348       ast_sockaddr_set_port(new, default_sip_port(peer->socket.type));
14349    }
14350 
14351    old_str = ast_strdupa(ast_sockaddr_stringify(old));
14352    ast_debug(1, "Changing peer %s address from %s to %s\n", peer->name, old_str, ast_sockaddr_stringify(new));
14353 
14354    ao2_lock(peer);
14355    ast_sockaddr_copy(&peer->addr, new);
14356    ao2_unlock(peer);
14357 
14358    ao2_link(peers_by_ip, peer);
14359 }
14360 
14361 static void on_dns_update_mwi(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
14362 {
14363    struct sip_subscription_mwi *mwi = data;
14364    const char *old_str;
14365 
14366    /* This shouldn't happen, but just in case */
14367    if (ast_sockaddr_isnull(new)) {
14368       ast_debug(1, "Empty sockaddr change...ignoring!\n");
14369       return;
14370    }
14371 
14372    old_str = ast_strdupa(ast_sockaddr_stringify(old));
14373    ast_debug(1, "Changing mwi %s from %s to %s\n", mwi->hostname, old_str, ast_sockaddr_stringify(new));
14374    ast_sockaddr_copy(&mwi->us, new);
14375 }
14376 
14377 /*! \brief Actually setup an MWI subscription or resubscribe */
14378 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi)
14379 {
14380    /* If we have no DNS manager let's do a lookup */
14381    if (!mwi->dnsmgr) {
14382       char transport[MAXHOSTNAMELEN];
14383       struct sip_subscription_mwi *saved;
14384       snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(mwi->transport), get_srv_protocol(mwi->transport));
14385 
14386       mwi->us.ss.ss_family = get_address_family_filter(mwi->transport); /* Filter address family */
14387       saved = ASTOBJ_REF(mwi);
14388       ast_dnsmgr_lookup_cb(mwi->hostname, &mwi->us, &mwi->dnsmgr, sip_cfg.srvlookup ? transport : NULL, on_dns_update_mwi, saved);
14389       if (!mwi->dnsmgr) {
14390          ASTOBJ_UNREF(saved, sip_subscribe_mwi_destroy); /* dnsmgr disabled, remove reference */
14391       }
14392    }
14393 
14394    /* If we already have a subscription up simply send a resubscription */
14395    if (mwi->call) {
14396       transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 0, NULL);
14397       return 0;
14398    }
14399    
14400    /* Create a dialog that we will use for the subscription */
14401    if (!(mwi->call = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL, NULL))) {
14402       return -1;
14403    }
14404 
14405    ref_proxy(mwi->call, obproxy_get(mwi->call, NULL));
14406 
14407    if (!ast_sockaddr_port(&mwi->us) && mwi->portno) {
14408       ast_sockaddr_set_port(&mwi->us, mwi->portno);
14409    }
14410    
14411    /* Setup the destination of our subscription */
14412    if (create_addr(mwi->call, mwi->hostname, &mwi->us, 0)) {
14413       dialog_unlink_all(mwi->call);
14414       mwi->call = dialog_unref(mwi->call, "unref dialog after unlink_all");
14415       return 0;
14416    }
14417 
14418    mwi->call->expiry = mwi_expiry;
14419    
14420    if (!mwi->dnsmgr && mwi->portno) {
14421       ast_sockaddr_set_port(&mwi->call->sa, mwi->portno);
14422       ast_sockaddr_set_port(&mwi->call->recv, mwi->portno);
14423    } else {
14424       mwi->portno = ast_sockaddr_port(&mwi->call->sa);
14425    }
14426    
14427    /* Set various other information */
14428    if (!ast_strlen_zero(mwi->authuser)) {
14429       ast_string_field_set(mwi->call, peername, mwi->authuser);
14430       ast_string_field_set(mwi->call, authname, mwi->authuser);
14431       ast_string_field_set(mwi->call, fromuser, mwi->authuser);
14432    } else {
14433       ast_string_field_set(mwi->call, peername, mwi->username);
14434       ast_string_field_set(mwi->call, authname, mwi->username);
14435       ast_string_field_set(mwi->call, fromuser, mwi->username);
14436    }
14437    ast_string_field_set(mwi->call, username, mwi->username);
14438    if (!ast_strlen_zero(mwi->secret)) {
14439       ast_string_field_set(mwi->call, peersecret, mwi->secret);
14440    }
14441    set_socket_transport(&mwi->call->socket, mwi->transport);
14442    mwi->call->socket.port = htons(mwi->portno);
14443    ast_sip_ouraddrfor(&mwi->call->sa, &mwi->call->ourip, mwi->call);
14444    build_contact(mwi->call);
14445    build_via(mwi->call);
14446 
14447    /* Change the dialog callid. */
14448    change_callid_pvt(mwi->call, NULL);
14449 
14450    ast_set_flag(&mwi->call->flags[0], SIP_OUTGOING);
14451    
14452    /* Associate the call with us */
14453    mwi->call->mwi = ASTOBJ_REF(mwi);
14454 
14455    mwi->call->subscribed = MWI_NOTIFICATION;
14456 
14457    /* Actually send the packet */
14458    transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 2, NULL);
14459 
14460    return 0;
14461 }
14462 
14463 /*! \internal \brief Find the channel that is causing the RINGING update, ref'd */
14464 static struct ast_channel *find_ringing_channel(struct ao2_container *device_state_info, struct sip_pvt *p)
14465 {
14466    struct ao2_iterator citer;
14467    struct ast_device_state_info *device_state;
14468    struct ast_channel *c = NULL;
14469    struct timeval tv = {0,};
14470 
14471    /* iterate ringing devices and get the oldest of all causing channels */
14472    citer = ao2_iterator_init(device_state_info, 0);
14473    for (; (device_state = ao2_iterator_next(&citer)); ao2_ref(device_state, -1)) {
14474       if (!device_state->causing_channel || (device_state->device_state != AST_DEVICE_RINGING &&
14475           device_state->device_state != AST_DEVICE_RINGINUSE)) {
14476          continue;
14477       }
14478       ast_channel_lock(device_state->causing_channel);
14479       if (ast_tvzero(tv) || ast_tvcmp(ast_channel_creationtime(device_state->causing_channel), tv) < 0) {
14480          c = device_state->causing_channel;
14481          tv = ast_channel_creationtime(c);
14482       }
14483       ast_channel_unlock(device_state->causing_channel);
14484    }
14485    ao2_iterator_destroy(&citer);
14486    return c ? ast_channel_ref(c) : NULL;
14487 }
14488 
14489 /* XXX Candidate for moving into its own file */
14490 static int allow_notify_user_presence(struct sip_pvt *p)
14491 {
14492    return (strstr(p->useragent, "Digium")) ? 1 : 0;
14493 }
14494 
14495 /*! \brief Builds XML portion of NOTIFY messages for presence or dialog updates */
14496 static void state_notify_build_xml(struct state_notify_data *data, int full, const char *exten, const char *context, struct ast_str **tmp, struct sip_pvt *p, int subscribed, const char *mfrom, const char *mto)
14497 {
14498    enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
14499    const char *statestring = "terminated";
14500    const char *pidfstate = "--";
14501    const char *pidfnote ="Ready";
14502    char hint[AST_MAX_EXTENSION];
14503 
14504    switch (data->state) {
14505    case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
14506       statestring = (sip_cfg.notifyringing) ? "early" : "confirmed";
14507       local_state = NOTIFY_INUSE;
14508       pidfstate = "busy";
14509       pidfnote = "Ringing";
14510       break;
14511    case AST_EXTENSION_RINGING:
14512       statestring = "early";
14513       local_state = NOTIFY_INUSE;
14514       pidfstate = "busy";
14515       pidfnote = "Ringing";
14516       break;
14517    case AST_EXTENSION_INUSE:
14518       statestring = "confirmed";
14519       local_state = NOTIFY_INUSE;
14520       pidfstate = "busy";
14521       pidfnote = "On the phone";
14522       break;
14523    case AST_EXTENSION_BUSY:
14524       statestring = "confirmed";
14525       local_state = NOTIFY_CLOSED;
14526       pidfstate = "busy";
14527       pidfnote = "On the phone";
14528       break;
14529    case AST_EXTENSION_UNAVAILABLE:
14530       statestring = "terminated";
14531       local_state = NOTIFY_CLOSED;
14532       pidfstate = "away";
14533       pidfnote = "Unavailable";
14534       break;
14535    case AST_EXTENSION_ONHOLD:
14536       statestring = "confirmed";
14537       local_state = NOTIFY_CLOSED;
14538       pidfstate = "busy";
14539       pidfnote = "On hold";
14540       break;
14541    case AST_EXTENSION_NOT_INUSE:
14542    default:
14543       /* Default setting */
14544       break;
14545    }
14546 
14547    /* Check which device/devices we are watching  and if they are registered */
14548    if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, context, exten)) {
14549       char *hint2;
14550       char *individual_hint = NULL;
14551       int hint_count = 0, unavailable_count = 0;
14552 
14553       /* strip off any possible PRESENCE providers from hint */
14554       if ((hint2 = strrchr(hint, ','))) {
14555          *hint2 = '\0';
14556       }
14557       hint2 = hint;
14558 
14559       while ((individual_hint = strsep(&hint2, "&"))) {
14560          hint_count++;
14561 
14562          if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
14563             unavailable_count++;
14564       }
14565 
14566       /* If none of the hinted devices are registered, we will
14567        * override notification and show no availability.
14568        */
14569       if (hint_count > 0 && hint_count == unavailable_count) {
14570          local_state = NOTIFY_CLOSED;
14571          pidfstate = "away";
14572          pidfnote = "Not online";
14573       }
14574    }
14575 
14576    switch (subscribed) {
14577    case XPIDF_XML:
14578    case CPIM_PIDF_XML:
14579       ast_str_append(tmp, 0,
14580          "<?xml version=\"1.0\"?>\n"
14581          "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n"
14582          "<presence>\n");
14583       ast_str_append(tmp, 0, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
14584       ast_str_append(tmp, 0, "<atom id=\"%s\">\n", exten);
14585       ast_str_append(tmp, 0, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
14586       ast_str_append(tmp, 0, "<status status=\"%s\" />\n", (local_state ==  NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
14587       ast_str_append(tmp, 0, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
14588       ast_str_append(tmp, 0, "</address>\n</atom>\n</presence>\n");
14589       break;
14590    case PIDF_XML: /* Eyebeam supports this format */
14591       ast_str_append(tmp, 0,
14592          "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
14593          "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" \nxmlns:pp=\"urn:ietf:params:xml:ns:pidf:person\"\nxmlns:es=\"urn:ietf:params:xml:ns:pidf:rpid:status:rpid-status\"\nxmlns:ep=\"urn:ietf:params:xml:ns:pidf:rpid:rpid-person\"\nentity=\"%s\">\n", mfrom);
14594       ast_str_append(tmp, 0, "<pp:person><status>\n");
14595       if (pidfstate[0] != '-') {
14596          ast_str_append(tmp, 0, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
14597       }
14598       ast_str_append(tmp, 0, "</status></pp:person>\n");
14599       ast_str_append(tmp, 0, "<note>%s</note>\n", pidfnote); /* Note */
14600       ast_str_append(tmp, 0, "<tuple id=\"%s\">\n", exten); /* Tuple start */
14601       ast_str_append(tmp, 0, "<contact priority=\"1\">%s</contact>\n", mto);
14602       if (pidfstate[0] == 'b') /* Busy? Still open ... */
14603          ast_str_append(tmp, 0, "<status><basic>open</basic></status>\n");
14604       else
14605          ast_str_append(tmp, 0, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
14606 
14607       if (allow_notify_user_presence(p) && (data->presence_state != AST_PRESENCE_INVALID)
14608             && (data->presence_state != AST_PRESENCE_NOT_SET)) {
14609          ast_str_append(tmp, 0, "</tuple>\n");
14610          ast_str_append(tmp, 0, "<tuple id=\"digium-presence\">\n");
14611          ast_str_append(tmp, 0, "<status>\n");
14612          ast_str_append(tmp, 0, "<digium_presence type=\"%s\" subtype=\"%s\">%s</digium_presence>\n",
14613             ast_presence_state2str(data->presence_state),
14614             S_OR(data->presence_subtype, ""),
14615             S_OR(data->presence_message, ""));
14616          ast_str_append(tmp, 0, "</status>\n");
14617          ast_test_suite_event_notify("DIGIUM_PRESENCE_SENT",
14618                "PresenceState: %s\r\n"
14619                "Subtype: %s\r\n"
14620                "Message: %s",
14621                ast_presence_state2str(data->presence_state),
14622                S_OR(data->presence_subtype, ""),
14623                S_OR(data->presence_message, ""));
14624       }
14625       ast_str_append(tmp, 0, "</tuple>\n</presence>\n");
14626       break;
14627    case DIALOG_INFO_XML: /* SNOM subscribes in this format */
14628       ast_str_append(tmp, 0, "<?xml version=\"1.0\"?>\n");
14629       ast_str_append(tmp, 0, "<dialog-info xmlns=\"urn:ietf:params:xml:ns:dialog-info\" version=\"%u\" state=\"%s\" entity=\"%s\">\n", p->dialogver, full ? "full" : "partial", mto);
14630       if (data->state > 0 && (data->state & AST_EXTENSION_RINGING) && sip_cfg.notifyringing) {
14631          /* Twice the extension length should be enough for XML encoding */
14632          char local_display[AST_MAX_EXTENSION * 2];
14633          char remote_display[AST_MAX_EXTENSION * 2];
14634          char *local_target = ast_strdupa(mto);
14635          /* It may seem odd to base the remote_target on the To header here,
14636           * but testing by reporters on issue ASTERISK-16735 found that basing
14637           * on the From header would cause ringing state hints to not work
14638           * properly on certain SNOM devices. If you are using notifycid properly
14639           * (i.e. in the same extension and context as the dialed call) then this
14640           * should not be an issue since the data will be overwritten shortly
14641           * with channel caller ID
14642           */
14643          char *remote_target = ast_strdupa(mto);
14644 
14645          ast_xml_escape(exten, local_display, sizeof(local_display));
14646          ast_xml_escape(exten, remote_display, sizeof(remote_display));
14647 
14648          /* There are some limitations to how this works.  The primary one is that the
14649             callee must be dialing the same extension that is being monitored.  Simply dialing
14650             the hint'd device is not sufficient. */
14651          if (sip_cfg.notifycid) {
14652             struct ast_channel *callee;
14653 
14654             callee = find_ringing_channel(data->device_state_info, p);
14655             if (callee) {
14656                static char *anonymous = "anonymous";
14657                static char *invalid = "anonymous.invalid";
14658                char *cid_num;
14659                char *connected_num;
14660                int need;
14661                int cid_num_restricted, connected_num_restricted;
14662 
14663                ast_channel_lock(callee);
14664 
14665                cid_num_restricted = (ast_channel_caller(callee)->id.number.presentation &
14666                            AST_PRES_RESTRICTION) == AST_PRES_RESTRICTED;
14667                cid_num = S_COR(ast_channel_caller(callee)->id.number.valid,
14668                      S_COR(cid_num_restricted, anonymous,
14669                            ast_channel_caller(callee)->id.number.str), "");
14670 
14671                need = strlen(cid_num) + (cid_num_restricted ? strlen(invalid) :
14672                           strlen(p->fromdomain)) + sizeof("sip:@");
14673                local_target = ast_alloca(need);
14674 
14675                snprintf(local_target, need, "sip:%s@%s", cid_num,
14676                    cid_num_restricted ? invalid : p->fromdomain);
14677 
14678                ast_xml_escape(S_COR(ast_channel_caller(callee)->id.name.valid,
14679                           S_COR((ast_channel_caller(callee)->id.name.presentation &
14680                              AST_PRES_RESTRICTION) == AST_PRES_RESTRICTED, anonymous,
14681                            ast_channel_caller(callee)->id.name.str), ""),
14682                          local_display, sizeof(local_display));
14683 
14684                connected_num_restricted = (ast_channel_connected(callee)->id.number.presentation &
14685                             AST_PRES_RESTRICTION) == AST_PRES_RESTRICTED;
14686                connected_num = S_COR(ast_channel_connected(callee)->id.number.valid,
14687                            S_COR(connected_num_restricted, anonymous,
14688                             ast_channel_connected(callee)->id.number.str), "");
14689 
14690                need = strlen(connected_num) + (connected_num_restricted ? strlen(invalid) :
14691                            strlen(p->fromdomain)) + sizeof("sip:@");
14692                remote_target = ast_alloca(need);
14693 
14694                snprintf(remote_target, need, "sip:%s@%s", connected_num,
14695                    connected_num_restricted ? invalid : p->fromdomain);
14696 
14697                ast_xml_escape(S_COR(ast_channel_connected(callee)->id.name.valid,
14698                           S_COR((ast_channel_connected(callee)->id.name.presentation &
14699                              AST_PRES_RESTRICTION) == AST_PRES_RESTRICTED, anonymous,
14700                             ast_channel_connected(callee)->id.name.str), ""),
14701                          remote_display, sizeof(remote_display));
14702 
14703                ast_channel_unlock(callee);
14704                callee = ast_channel_unref(callee);
14705             }
14706 
14707             /* We create a fake call-id which the phone will send back in an INVITE
14708                Replaces header which we can grab and do some magic with. */
14709             if (sip_cfg.pedanticsipchecking) {
14710                ast_str_append(tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" local-tag=\"%s\" remote-tag=\"%s\" direction=\"recipient\">\n",
14711                   exten, p->callid, p->theirtag, p->tag);
14712             } else {
14713                ast_str_append(tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" direction=\"recipient\">\n",
14714                   exten, p->callid);
14715             }
14716             ast_str_append(tmp, 0,
14717                   "<remote>\n"
14718                   /* See the limitations of this above.  Luckily the phone seems to still be
14719                      happy when these values are not correct. */
14720                   "<identity display=\"%s\">%s</identity>\n"
14721                   "<target uri=\"%s\"/>\n"
14722                   "</remote>\n"
14723                   "<local>\n"
14724                   "<identity display=\"%s\">%s</identity>\n"
14725                   "<target uri=\"%s\"/>\n"
14726                   "</local>\n",
14727                   remote_display, remote_target, remote_target, local_display, local_target, local_target);
14728          } else {
14729             ast_str_append(tmp, 0, "<dialog id=\"%s\" direction=\"recipient\">\n", exten);
14730          }
14731 
14732       } else {
14733          ast_str_append(tmp, 0, "<dialog id=\"%s\">\n", exten);
14734       }
14735       ast_str_append(tmp, 0, "<state>%s</state>\n", statestring);
14736       if (data->state == AST_EXTENSION_ONHOLD) {
14737             ast_str_append(tmp, 0, "<local>\n<target uri=\"%s\">\n"
14738                                              "<param pname=\"+sip.rendering\" pvalue=\"no\"/>\n"
14739                                              "</target>\n</local>\n", mto);
14740       }
14741       ast_str_append(tmp, 0, "</dialog>\n</dialog-info>\n");
14742       break;
14743    case NONE:
14744    default:
14745       break;
14746    }
14747 }
14748 
14749 static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state)
14750 {
14751    struct sip_request req;
14752    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
14753    char uri[SIPBUFSIZE];
14754    char state_str[64];
14755    char subscription_state_hdr[64];
14756 
14757    if (state < CC_QUEUED || state > CC_READY) {
14758       ast_log(LOG_WARNING, "Invalid state provided for transmit_cc_notify (%u)\n", state);
14759       return -1;
14760    }
14761 
14762    reqprep(&req, subscription, SIP_NOTIFY, 0, TRUE);
14763    snprintf(state_str, sizeof(state_str), "%s\r\n", sip_cc_notify_state_map[state].state_string);
14764    add_header(&req, "Event", "call-completion");
14765    add_header(&req, "Content-Type", "application/call-completion");
14766    snprintf(subscription_state_hdr, sizeof(subscription_state_hdr), "active;expires=%d", subscription->expiry);
14767    add_header(&req, "Subscription-State", subscription_state_hdr);
14768    if (state == CC_READY) {
14769       generate_uri(subscription, agent_pvt->notify_uri, sizeof(agent_pvt->notify_uri));
14770       snprintf(uri, sizeof(uri) - 1, "cc-URI: %s\r\n", agent_pvt->notify_uri);
14771    }
14772    add_content(&req, state_str);
14773    if (state == CC_READY) {
14774       add_content(&req, uri);
14775    }
14776    return send_request(subscription, &req, XMIT_RELIABLE, subscription->ocseq);
14777 }
14778 
14779 /*! \brief Used in the SUBSCRIBE notification subsystem (RFC3265) */
14780 static int transmit_state_notify(struct sip_pvt *p, struct state_notify_data *data, int full, int timeout)
14781 {
14782    struct ast_str *tmp = ast_str_alloca(4000);
14783    char from[256], to[256];
14784    char *c, *mfrom, *mto;
14785    struct sip_request req;
14786    const struct cfsubscription_types *subscriptiontype;
14787 
14788    /* If the subscription has not yet been accepted do not send a NOTIFY */
14789    if (!ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
14790       return 0;
14791    }
14792 
14793    memset(from, 0, sizeof(from));
14794    memset(to, 0, sizeof(to));
14795 
14796    subscriptiontype = find_subscription_type(p->subscribed);
14797 
14798    ast_copy_string(from, sip_get_header(&p->initreq, "From"), sizeof(from));
14799    c = get_in_brackets(from);
14800    if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
14801       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
14802       return -1;
14803    }
14804 
14805    mfrom = remove_uri_parameters(c);
14806 
14807    ast_copy_string(to, sip_get_header(&p->initreq, "To"), sizeof(to));
14808    c = get_in_brackets(to);
14809    if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
14810       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
14811       return -1;
14812    }
14813    mto = remove_uri_parameters(c);
14814 
14815    reqprep(&req, p, SIP_NOTIFY, 0, 1);
14816 
14817    switch(data->state) {
14818    case AST_EXTENSION_DEACTIVATED:
14819       if (timeout)
14820          add_header(&req, "Subscription-State", "terminated;reason=timeout");
14821       else {
14822          add_header(&req, "Subscription-State", "terminated;reason=probation");
14823          add_header(&req, "Retry-After", "60");
14824       }
14825       break;
14826    case AST_EXTENSION_REMOVED:
14827       add_header(&req, "Subscription-State", "terminated;reason=noresource");
14828       break;
14829    default:
14830       if (p->expiry)
14831          add_header(&req, "Subscription-State", "active");
14832       else  /* Expired */
14833          add_header(&req, "Subscription-State", "terminated;reason=timeout");
14834    }
14835 
14836    switch (p->subscribed) {
14837    case XPIDF_XML:
14838    case CPIM_PIDF_XML:
14839       add_header(&req, "Event", subscriptiontype->event);
14840       state_notify_build_xml(data, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
14841       add_header(&req, "Content-Type", subscriptiontype->mediatype);
14842       p->dialogver++;
14843       break;
14844    case PIDF_XML: /* Eyebeam supports this format */
14845       add_header(&req, "Event", subscriptiontype->event);
14846       state_notify_build_xml(data, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
14847       add_header(&req, "Content-Type", subscriptiontype->mediatype);
14848       p->dialogver++;
14849       break;
14850    case DIALOG_INFO_XML: /* SNOM subscribes in this format */
14851       add_header(&req, "Event", subscriptiontype->event);
14852       state_notify_build_xml(data, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
14853       add_header(&req, "Content-Type", subscriptiontype->mediatype);
14854       p->dialogver++;
14855       break;
14856    case NONE:
14857    default:
14858       break;
14859    }
14860 
14861    add_content(&req, ast_str_buffer(tmp));
14862 
14863    p->pendinginvite = p->ocseq;  /* Remember that we have a pending NOTIFY in order not to confuse the NOTIFY subsystem */
14864 
14865    /* Send as XMIT_CRITICAL as we may never receive a 200 OK Response which clears p->pendinginvite.
14866     *
14867     * extensionstate_update() uses p->pendinginvite for queuing control.
14868     * Updates stall if pendinginvite <> 0.
14869     *
14870     * The most appropriate solution is to remove the subscription when the NOTIFY transaction fails.
14871     * The client will re-subscribe after restarting or maxexpiry timeout.
14872     */
14873 
14874    /* RFC6665 4.2.2.  Sending State Information to Subscribers
14875     * If the NOTIFY request fails due to expiration of SIP Timer F (transaction timeout),
14876     * the notifier SHOULD remove the subscription.
14877     */
14878    return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
14879 }
14880 
14881 /*! \brief Notify user of messages waiting in voicemail (RFC3842)
14882 \note - Notification only works for registered peers with mailbox= definitions
14883    in sip.conf
14884    - We use the SIP Event package message-summary
14885     MIME type defaults to  "application/simple-message-summary";
14886  */
14887 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten)
14888 {
14889    struct sip_request req;
14890    struct ast_str *out = ast_str_alloca(500);
14891    int ourport = (p->fromdomainport) ? p->fromdomainport : ast_sockaddr_port(&p->ourip);
14892    const char *domain;
14893    const char *exten = S_OR(vmexten, default_vmexten);
14894 
14895    initreqprep(&req, p, SIP_NOTIFY, NULL);
14896    add_header(&req, "Event", "message-summary");
14897    add_header(&req, "Content-Type", default_notifymime);
14898    ast_str_append(&out, 0, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
14899 
14900    /* domain initialization occurs here because initreqprep changes ast_sockaddr_stringify string. */
14901    domain = S_OR(p->fromdomain, ast_sockaddr_stringify_host_remote(&p->ourip));
14902 
14903    if (!sip_standard_port(p->socket.type, ourport)) {
14904       if (p->socket.type == SIP_TRANSPORT_UDP) {
14905          ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d\r\n", exten, domain, ourport);
14906       } else {
14907          ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d;transport=%s\r\n", exten, domain, ourport, sip_get_transport(p->socket.type));
14908       }
14909    } else {
14910       if (p->socket.type == SIP_TRANSPORT_UDP) {
14911          ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, domain);
14912       } else {
14913          ast_str_append(&out, 0, "Message-Account: sip:%s@%s;transport=%s\r\n", exten, domain, sip_get_transport(p->socket.type));
14914       }
14915    }
14916    /* Cisco has a bug in the SIP stack where it can't accept the
14917       (0/0) notification. This can temporarily be disabled in
14918       sip.conf with the "buggymwi" option */
14919    ast_str_append(&out, 0, "Voice-Message: %d/%d%s\r\n",
14920       newmsgs, oldmsgs, (ast_test_flag(&p->flags[1], SIP_PAGE2_BUGGY_MWI) ? "" : " (0/0)"));
14921 
14922    if (p->subscribed) {
14923       if (p->expiry) {
14924          add_header(&req, "Subscription-State", "active");
14925       } else { /* Expired */
14926          add_header(&req, "Subscription-State", "terminated;reason=timeout");
14927       }
14928    }
14929 
14930    add_content(&req, ast_str_buffer(out));
14931 
14932    if (!p->initreq.headers) {
14933       initialize_initreq(p, &req);
14934    }
14935    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
14936 }
14937 
14938 /*! \brief Notify a transferring party of the status of transfer (RFC3515) */
14939 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
14940 {
14941    struct sip_request req;
14942    char tmp[SIPBUFSIZE/2];
14943    
14944    reqprep(&req, p, SIP_NOTIFY, 0, 1);
14945    snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
14946    add_header(&req, "Event", tmp);
14947    add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
14948    add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
14949    add_header(&req, "Allow", ALLOWED_METHODS);
14950    add_supported(p, &req);
14951 
14952    snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
14953    add_content(&req, tmp);
14954 
14955    if (!p->initreq.headers) {
14956       initialize_initreq(p, &req);
14957    }
14958 
14959    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
14960 }
14961 
14962 static int manager_sipnotify(struct mansession *s, const struct message *m)
14963 {
14964    const char *channame = astman_get_header(m, "Channel");
14965    struct ast_variable *vars = astman_get_variables_order(m, ORDER_NATURAL);
14966    struct sip_pvt *p;
14967    struct ast_variable *header, *var;
14968 
14969    if (ast_strlen_zero(channame)) {
14970       astman_send_error(s, m, "SIPNotify requires a channel name");
14971       return 0;
14972    }
14973 
14974    if (!strncasecmp(channame, "sip/", 4)) {
14975       channame += 4;
14976    }
14977 
14978    if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL, NULL))) {
14979       astman_send_error(s, m, "Unable to build sip pvt data for notify (memory/socket error)");
14980       return 0;
14981    }
14982 
14983    if (create_addr(p, channame, NULL, 0)) {
14984       /* Maybe they're not registered, etc. */
14985       dialog_unlink_all(p);
14986       dialog_unref(p, "unref dialog inside for loop" );
14987       /* sip_destroy(p); */
14988       astman_send_error(s, m, "Could not create address");
14989       return 0;
14990    }
14991 
14992    /* Notify is outgoing call */
14993    ast_set_flag(&p->flags[0], SIP_OUTGOING);
14994    sip_notify_alloc(p);
14995 
14996    p->notify->headers = header = ast_variable_new("Subscription-State", "terminated", "");
14997 
14998    for (var = vars; var; var = var->next) {
14999       if (!strcasecmp(var->name, "Content")) {
15000          if (ast_str_strlen(p->notify->content))
15001             ast_str_append(&p->notify->content, 0, "\r\n");
15002          ast_str_append(&p->notify->content, 0, "%s", var->value);
15003       } else if (!strcasecmp(var->name, "Content-Length")) {
15004          ast_log(LOG_WARNING, "it is not necessary to specify Content-Length, ignoring\n");
15005       } else {
15006          header->next = ast_variable_new(var->name, var->value, "");
15007          header = header->next;
15008       }
15009    }
15010 
15011    sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
15012    transmit_invite(p, SIP_NOTIFY, 0, 2, NULL);
15013    dialog_unref(p, "bump down the count of p since we're done with it.");
15014 
15015    astman_send_ack(s, m, "Notify Sent");
15016    ast_variables_destroy(vars);
15017    return 0;
15018 }
15019 
15020 /*! \brief Send a provisional response indicating that a call was redirected
15021  */
15022 static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen)
15023 {
15024    struct sip_request resp;
15025 
15026    if (ast_channel_state(p->owner) == AST_STATE_UP || ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
15027       return;
15028    }
15029 
15030    respprep(&resp, p, "181 Call is being forwarded", &p->initreq);
15031    add_diversion(&resp, p);
15032    send_response(p, &resp, XMIT_UNRELIABLE, 0);
15033 }
15034 
15035 /*! \brief Notify peer that the connected line has changed */
15036 static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen)
15037 {
15038    struct ast_party_id connected_id = ast_channel_connected_effective_id(p->owner);
15039 
15040    if (!ast_test_flag(&p->flags[0], SIP_SENDRPID)) {
15041       return;
15042    }
15043    if (!connected_id.number.valid
15044       || ast_strlen_zero(connected_id.number.str)) {
15045       return;
15046    }
15047 
15048    append_history(p, "ConnectedLine", "%s party is now %s <%s>",
15049       ast_test_flag(&p->flags[0], SIP_OUTGOING) ? "Calling" : "Called",
15050       S_COR(connected_id.name.valid, connected_id.name.str, ""),
15051       S_COR(connected_id.number.valid, connected_id.number.str, ""));
15052 
15053    if (ast_channel_state(p->owner) == AST_STATE_UP || ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
15054       struct sip_request req;
15055 
15056       if (!p->pendinginvite && (p->invitestate == INV_CONFIRMED || p->invitestate == INV_TERMINATED)) {
15057          reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
15058 
15059          add_header(&req, "Allow", ALLOWED_METHODS);
15060          add_supported(p, &req);
15061          add_rpid(&req, p);
15062          add_sdp(&req, p, FALSE, TRUE, FALSE);
15063 
15064          initialize_initreq(p, &req);
15065          p->lastinvite = p->ocseq;
15066          ast_set_flag(&p->flags[0], SIP_OUTGOING);
15067          p->invitestate = INV_CALLING;
15068          send_request(p, &req, XMIT_CRITICAL, p->ocseq);
15069       } else if ((is_method_allowed(&p->allowed_methods, SIP_UPDATE)) && (!ast_strlen_zero(p->okcontacturi))) { 
15070          reqprep(&req, p, SIP_UPDATE, 0, 1);
15071          add_rpid(&req, p);
15072          add_header(&req, "X-Asterisk-rpid-update", "Yes");
15073          send_request(p, &req, XMIT_CRITICAL, p->ocseq);
15074       } else {
15075          /* We cannot send the update yet, so we have to wait until we can */
15076          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
15077       }
15078    } else {
15079       ast_set_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
15080       if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPID_IMMEDIATE)) {
15081          struct sip_request resp;
15082 
15083          if ((ast_channel_state(p->owner) == AST_STATE_RING) && !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT)) {
15084             ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
15085             respprep(&resp, p, "180 Ringing", &p->initreq);
15086             add_rpid(&resp, p);
15087             send_response(p, &resp, XMIT_UNRELIABLE, 0);
15088             ast_set_flag(&p->flags[0], SIP_RINGING);
15089          } else if (ast_channel_state(p->owner) == AST_STATE_RINGING) {
15090             ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
15091             respprep(&resp, p, "183 Session Progress", &p->initreq);
15092             add_rpid(&resp, p);
15093             send_response(p, &resp, XMIT_UNRELIABLE, 0);
15094             ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
15095          } else {
15096             ast_debug(1, "Unable able to send update to '%s' in state '%s'\n", ast_channel_name(p->owner), ast_state2str(ast_channel_state(p->owner)));
15097          }
15098       }
15099    }
15100 }
15101 
15102 static const struct _map_x_s regstatestrings[] = {
15103    { REG_STATE_FAILED,     "Failed" },
15104    { REG_STATE_UNREGISTERED, "Unregistered"},
15105    { REG_STATE_REGSENT, "Request Sent"},
15106    { REG_STATE_AUTHSENT, "Auth. Sent"},
15107    { REG_STATE_REGISTERED, "Registered"},
15108    { REG_STATE_REJECTED, "Rejected"},
15109    { REG_STATE_TIMEOUT, "Timeout"},
15110    { REG_STATE_NOAUTH, "No Authentication"},
15111    { -1, NULL } /* terminator */
15112 };
15113 
15114 /*! \brief Convert registration state status to string */
15115 static const char *regstate2str(enum sipregistrystate regstate)
15116 {
15117    return map_x_s(regstatestrings, regstate, "Unknown");
15118 }
15119 
15120 /*! \brief Update registration with SIP Proxy.
15121  * Called from the scheduler when the previous registration expires,
15122  * so we don't have to cancel the pending event.
15123  * We assume the reference so the sip_registry is valid, since it
15124  * is stored in the scheduled event anyways.
15125  */
15126 static int sip_reregister(const void *data)
15127 {
15128    /* if we are here, we know that we need to reregister. */
15129    struct sip_registry *r = (struct sip_registry *) data;
15130 
15131    /* if we couldn't get a reference to the registry object, punt */
15132    if (!r) {
15133       return 0;
15134    }
15135 
15136    if (r->call && r->call->do_history) {
15137       append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
15138    }
15139    /* Since registry's are only added/removed by the the monitor thread, this
15140       may be overkill to reference/dereference at all here */
15141    if (sipdebug) {
15142       ast_log(LOG_NOTICE, "   -- Re-registration for  %s@%s\n", r->username, r->hostname);
15143    }
15144 
15145    r->expire = -1;
15146    r->expiry = r->configured_expiry;
15147    __sip_do_register(r);
15148    registry_unref(r, "unref the re-register scheduled event");
15149    return 0;
15150 }
15151 
15152 /*! \brief Register with SIP proxy 
15153    \return see \ref __sip_xmit 
15154 */
15155 static int __sip_do_register(struct sip_registry *r)
15156 {
15157    int res;
15158 
15159    res = transmit_register(r, SIP_REGISTER, NULL, NULL);
15160    return res;
15161 }
15162 
15163 /*! \brief Registration timeout, register again
15164  * Registered as a timeout handler during transmit_register(),
15165  * to retransmit the packet if a reply does not come back.
15166  * This is called by the scheduler so the event is not pending anymore when
15167  * we are called.
15168  */
15169 static int sip_reg_timeout(const void *data)
15170 {
15171 
15172    /* if we are here, our registration timed out, so we'll just do it over */
15173    struct sip_registry *r = (struct sip_registry *)data; /* the ref count should have been bumped when the sched item was added */
15174    struct sip_pvt *p;
15175 
15176    /* if we couldn't get a reference to the registry object, punt */
15177    if (!r) {
15178       return 0;
15179    }
15180 
15181    if (r->dnsmgr) {
15182       /* If the registration has timed out, maybe the IP changed.  Force a refresh. */
15183       ast_dnsmgr_refresh(r->dnsmgr);
15184    }
15185 
15186    /* If the initial tranmission failed, we may not have an existing dialog,
15187     * so it is possible that r->call == NULL.
15188     * Otherwise destroy it, as we have a timeout so we don't want it.
15189     */
15190    if (r->call) {
15191       /* Unlink us, destroy old call.  Locking is not relevant here because all this happens
15192          in the single SIP manager thread. */
15193       p = r->call;
15194       sip_pvt_lock(p);
15195       pvt_set_needdestroy(p, "registration timeout");
15196       /* Pretend to ACK anything just in case */
15197       __sip_pretend_ack(p);
15198       sip_pvt_unlock(p);
15199 
15200       /* decouple the two objects */
15201       /* p->registry == r, so r has 2 refs, and the unref won't take the object away */
15202       if (p->registry) {
15203          p->registry = registry_unref(p->registry, "p->registry unreffed");
15204       }
15205       r->call = dialog_unref(r->call, "unrefing r->call");
15206    }
15207    /* If we have a limit, stop registration and give up */
15208    r->timeout = -1;
15209    if (global_regattempts_max && r->regattempts >= global_regattempts_max) {
15210       /* Ok, enough is enough. Don't try any more */
15211       /* We could add an external notification here...
15212          steal it from app_voicemail :-) */
15213       ast_log(LOG_NOTICE, "   -- Last Registration Attempt #%d failed, Giving up forever trying to register '%s@%s'\n", r->regattempts, r->username, r->hostname);
15214       r->regstate = REG_STATE_FAILED;
15215    } else {
15216       r->regstate = REG_STATE_UNREGISTERED;
15217       transmit_register(r, SIP_REGISTER, NULL, NULL);
15218       ast_log(LOG_NOTICE, "   -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts);
15219    }
15220    manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: SIP\r\nUsername: %s\r\nDomain: %s\r\nStatus: %s\r\n", r->username, r->hostname, regstate2str(r->regstate));
15221    registry_unref(r, "unreffing registry_unref r");
15222    return 0;
15223 }
15224 
15225 static const char *sip_sanitized_host(const char *host)
15226 {
15227    struct ast_sockaddr addr = { { 0, 0, }, };
15228 
15229    /* peer/sip_pvt->tohost and sip_registry->hostname should never have a port
15230     * in them, so we use PARSE_PORT_FORBID here. If this lookup fails, we return
15231     * the original host which is most likely a host name and not an IP. */
15232    if (!ast_sockaddr_parse(&addr, host, PARSE_PORT_FORBID)) {
15233       return host;
15234    }
15235    return ast_sockaddr_stringify_host_remote(&addr);
15236 }
15237 
15238 /*! \brief Transmit register to SIP proxy or UA
15239  * auth = NULL on the initial registration (from sip_reregister())
15240  */
15241 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
15242 {
15243    struct sip_request req;
15244    char from[256];
15245    char to[256];
15246    char tmp[80];
15247    char addr[80];
15248    struct sip_pvt *p;
15249    struct sip_peer *peer = NULL;
15250    int res;
15251    int portno = 0;
15252 
15253    /* exit if we are already in process with this registrar ?*/
15254    if (r == NULL || ((auth == NULL) && (r->regstate == REG_STATE_REGSENT || r->regstate == REG_STATE_AUTHSENT))) {
15255       if (r) {
15256          ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
15257       }
15258       return 0;
15259    }
15260 
15261    if (r->dnsmgr == NULL) {
15262       char transport[MAXHOSTNAMELEN];
15263       peer = sip_find_peer(r->hostname, NULL, TRUE, FINDPEERS, FALSE, 0);
15264       snprintf(transport, sizeof(transport), "_%s._%s",get_srv_service(r->transport), get_srv_protocol(r->transport)); /* have to use static sip_get_transport function */
15265       r->us.ss.ss_family = get_address_family_filter(r->transport); /* Filter address family */
15266 
15267       /* No point in doing a DNS lookup of the register hostname if we're just going to
15268        * end up using an outbound proxy. obproxy_get is safe to call with either of r->call
15269        * or peer NULL. Since we're only concerned with its existence, we're not going to
15270        * bother getting a ref to the proxy*/
15271       if (!obproxy_get(r->call, peer)) {
15272          registry_addref(r, "add reg ref for dnsmgr");
15273          ast_dnsmgr_lookup_cb(peer ? peer->tohost : r->hostname, &r->us, &r->dnsmgr, sip_cfg.srvlookup ? transport : NULL, on_dns_update_registry, r);
15274          if (!r->dnsmgr) {
15275             /*dnsmgr refresh disabled, no reference added! */
15276             registry_unref(r, "remove reg ref, dnsmgr disabled");
15277          }
15278       }
15279       if (peer) {
15280          peer = sip_unref_peer(peer, "removing peer ref for dnsmgr_lookup");
15281       }
15282    }
15283 
15284    if (r->call) { /* We have a registration */
15285       if (!auth) {
15286          ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
15287          return 0;
15288       } else {
15289          p = dialog_ref(r->call, "getting a copy of the r->call dialog in transmit_register");
15290          ast_string_field_set(p, theirtag, NULL);  /* forget their old tag, so we don't match tags when getting response */
15291       }
15292    } else {
15293       /* Build callid for registration if we haven't registered before */
15294       if (!r->callid_valid) {
15295          build_callid_registry(r, &internip, default_fromdomain);
15296          build_localtag_registry(r);
15297          r->callid_valid = TRUE;
15298       }
15299       /* Allocate SIP dialog for registration */
15300       if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER, NULL, NULL))) {
15301          ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
15302          return 0;
15303       }
15304 
15305       /* reset tag to consistent value from registry */
15306       ast_string_field_set(p, tag, r->localtag);
15307 
15308       if (p->do_history) {
15309          append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
15310       }
15311 
15312       p->socket.type = r->transport;
15313 
15314       /* Use port number specified if no SRV record was found */
15315       if (!ast_sockaddr_isnull(&r->us)) {
15316          if (!ast_sockaddr_port(&r->us) && r->portno) {
15317             ast_sockaddr_set_port(&r->us, r->portno);
15318          }
15319 
15320          /* It is possible that DNS was unavailable at the time the peer was created.
15321           * Here, if we've updated the address in the registry via manually calling
15322           * ast_dnsmgr_lookup_cb() above, then we call the same function that dnsmgr would
15323           * call if it was updating a peer's address */
15324          if ((peer = sip_find_peer(S_OR(r->peername, r->hostname), NULL, TRUE, FINDPEERS, FALSE, 0))) {
15325             if (ast_sockaddr_cmp(&peer->addr, &r->us)) {
15326                on_dns_update_peer(&peer->addr, &r->us, peer);
15327             }
15328             peer = sip_unref_peer(peer, "unref after sip_find_peer");
15329          }
15330       }
15331 
15332       /* Find address to hostname */
15333       if (create_addr(p, S_OR(r->peername, r->hostname), &r->us, 0)) {
15334          /* we have what we hope is a temporary network error,
15335           * probably DNS.  We need to reschedule a registration try */
15336          dialog_unlink_all(p);
15337          p = dialog_unref(p, "unref dialog after unlink_all");
15338          if (r->timeout > -1) {
15339             AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
15340                               registry_unref(_data, "del for REPLACE of registry ptr"),
15341                               registry_unref(r, "object ptr dec when SCHED_REPLACE add failed"),
15342                               registry_addref(r,"add for REPLACE registry ptr"));
15343             ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
15344          } else {
15345             r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, registry_addref(r, "add for REPLACE registry ptr"));
15346             ast_log(LOG_WARNING, "Probably a DNS error for registration to %s@%s, trying REGISTER again (after %d seconds)\n", r->username, r->hostname, global_reg_timeout);
15347          }
15348          r->regattempts++;
15349          return 0;
15350       }
15351 
15352       /* Copy back Call-ID in case create_addr changed it */
15353       ast_string_field_set(r, callid, p->callid);
15354 
15355       if (!r->dnsmgr && r->portno) {
15356          ast_sockaddr_set_port(&p->sa, r->portno);
15357          ast_sockaddr_set_port(&p->recv, r->portno);
15358       }
15359       if (!ast_strlen_zero(p->fromdomain)) {
15360          portno = (p->fromdomainport) ? p->fromdomainport : STANDARD_SIP_PORT;
15361       } else if (!ast_strlen_zero(r->regdomain)) {
15362          portno = (r->regdomainport) ? r->regdomainport : STANDARD_SIP_PORT;
15363       } else {
15364          portno = ast_sockaddr_port(&p->sa);
15365       }
15366 
15367       ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Registration is outgoing call */
15368       r->call = dialog_ref(p, "copying dialog into registry r->call");     /* Save pointer to SIP dialog */
15369       p->registry = registry_addref(r, "transmit_register: addref to p->registry in transmit_register"); /* Add pointer to registry in packet */
15370       if (!ast_strlen_zero(r->secret)) {  /* Secret (password) */
15371          ast_string_field_set(p, peersecret, r->secret);
15372       }
15373       if (!ast_strlen_zero(r->md5secret))
15374          ast_string_field_set(p, peermd5secret, r->md5secret);
15375       /* User name in this realm
15376       - if authuser is set, use that, otherwise use username */
15377       if (!ast_strlen_zero(r->authuser)) {
15378          ast_string_field_set(p, peername, r->authuser);
15379          ast_string_field_set(p, authname, r->authuser);
15380       } else if (!ast_strlen_zero(r->username)) {
15381          ast_string_field_set(p, peername, r->username);
15382          ast_string_field_set(p, authname, r->username);
15383          ast_string_field_set(p, fromuser, r->username);
15384       }
15385       if (!ast_strlen_zero(r->username)) {
15386          ast_string_field_set(p, username, r->username);
15387       }
15388       /* Save extension in packet */
15389       if (!ast_strlen_zero(r->callback)) {
15390          ast_string_field_set(p, exten, r->callback);
15391       }
15392 
15393       /* Set transport and port so the correct contact is built */
15394       set_socket_transport(&p->socket, r->transport);
15395       if (r->transport == SIP_TRANSPORT_TLS || r->transport == SIP_TRANSPORT_TCP) {
15396          p->socket.port =
15397              htons(ast_sockaddr_port(&sip_tcp_desc.local_address));
15398       }
15399 
15400       /*
15401         check which address we should use in our contact header
15402         based on whether the remote host is on the external or
15403         internal network so we can register through nat
15404        */
15405       ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
15406       build_contact(p);
15407    }
15408 
15409    /* set up a timeout */
15410    if (auth == NULL)  {
15411       if (r->timeout > -1) {
15412          ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
15413       }
15414       AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
15415                         registry_unref(_data,"reg ptr unrefed from del in SCHED_REPLACE"),
15416                         registry_unref(r,"reg ptr unrefed from add failure in SCHED_REPLACE"),
15417                         registry_addref(r,"reg ptr reffed from add in SCHED_REPLACE"));
15418       ast_debug(1, "Scheduled a registration timeout for %s id  #%d \n", r->hostname, r->timeout);
15419    }
15420 
15421    snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)), p->tag);
15422    if (!ast_strlen_zero(p->theirtag)) {
15423       snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)), p->theirtag);
15424    } else {
15425       snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)));
15426    }
15427 
15428    /* Fromdomain is what we are registering to, regardless of actual
15429       host name from SRV */
15430    if (portno && portno != STANDARD_SIP_PORT) {
15431       snprintf(addr, sizeof(addr), "sip:%s:%d", S_OR(p->fromdomain,S_OR(r->regdomain, sip_sanitized_host(r->hostname))), portno);
15432    } else {
15433       snprintf(addr, sizeof(addr), "sip:%s", S_OR(p->fromdomain,S_OR(r->regdomain, sip_sanitized_host(r->hostname))));
15434    }
15435 
15436    ast_string_field_set(p, uri, addr);
15437 
15438    p->branch ^= ast_random();
15439 
15440    init_req(&req, sipmethod, addr);
15441 
15442    /* Add to CSEQ */
15443    snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
15444    p->ocseq = r->ocseq;
15445 
15446    build_via(p);
15447    add_header(&req, "Via", p->via);
15448    add_max_forwards(p, &req);
15449    add_header(&req, "From", from);
15450    add_header(&req, "To", to);
15451    add_header(&req, "Call-ID", p->callid);
15452    add_header(&req, "CSeq", tmp);
15453    if (!ast_strlen_zero(global_useragent))
15454       add_header(&req, "User-Agent", global_useragent);
15455 
15456    if (auth) { /* Add auth header */
15457       add_header(&req, authheader, auth);
15458    } else if (!ast_strlen_zero(r->nonce)) {
15459       char digest[1024];
15460 
15461       /* We have auth data to reuse, build a digest header.
15462        * Note, this is not always useful because some parties do not
15463        * like nonces to be reused (for good reasons!) so they will
15464        * challenge us anyways.
15465        */
15466       if (sipdebug) {
15467          ast_debug(1, "   >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
15468       }
15469       ast_string_field_set(p, realm, r->realm);
15470       ast_string_field_set(p, nonce, r->nonce);
15471       ast_string_field_set(p, domain, r->authdomain);
15472       ast_string_field_set(p, opaque, r->opaque);
15473       ast_string_field_set(p, qop, r->qop);
15474       p->noncecount = ++r->noncecount;
15475 
15476       memset(digest, 0, sizeof(digest));
15477       if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
15478          add_header(&req, "Authorization", digest);
15479       } else {
15480          ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
15481       }
15482    }
15483 
15484    add_expires(&req, r->expiry);
15485    add_header(&req, "Contact", p->our_contact);
15486 
15487    initialize_initreq(p, &req);
15488    if (sip_debug_test_pvt(p)) {
15489       ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
15490    }
15491    r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
15492    r->regattempts++; /* Another attempt */
15493    ast_debug(4, "REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
15494    res = send_request(p, &req, XMIT_CRITICAL, p->ocseq);
15495    dialog_unref(p, "p is finished here at the end of transmit_register");
15496    return res;
15497 }
15498 
15499 /*!
15500  * \brief Transmit with SIP MESSAGE method
15501  * \note The p->msg_headers and p->msg_body are already setup.
15502  */
15503 static int transmit_message(struct sip_pvt *p, int init, int auth)
15504 {
15505    struct sip_request req;
15506 
15507    if (init) {
15508       initreqprep(&req, p, SIP_MESSAGE, NULL);
15509       initialize_initreq(p, &req);
15510    } else {
15511       reqprep(&req, p, SIP_MESSAGE, 0, 1);
15512    }
15513    if (auth) {
15514       return transmit_request_with_auth(p, SIP_MESSAGE, p->ocseq, XMIT_RELIABLE, 0);
15515    } else {
15516       add_text(&req, p);
15517       return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
15518    }
15519 }
15520 
15521 /*! \brief Allocate SIP refer structure */
15522 static int sip_refer_alloc(struct sip_pvt *p)
15523 {
15524    p->refer = ast_calloc_with_stringfields(1, struct sip_refer, 512);
15525    return p->refer ? 1 : 0;
15526 }
15527 
15528 /*! \brief Allocate SIP refer structure */
15529 static int sip_notify_alloc(struct sip_pvt *p)
15530 {
15531    p->notify = ast_calloc(1, sizeof(struct sip_notify));
15532    if (p->notify) {
15533       p->notify->content = ast_str_create(128);
15534    }
15535    return p->notify ? 1 : 0;
15536 }
15537 
15538 /*! \brief Transmit SIP REFER message (initiated by the transfer() dialplan application
15539    \note this is currently broken as we have no way of telling the dialplan
15540    engine whether a transfer succeeds or fails.
15541    \todo Fix the transfer() dialplan function so that a transfer may fail
15542 */
15543 static int transmit_refer(struct sip_pvt *p, const char *dest)
15544 {
15545    char from[256];
15546    const char *of;
15547    char *c;
15548    char referto[256];
15549    int   use_tls=FALSE;
15550 
15551    if (sipdebug) {
15552       ast_debug(1, "SIP transfer of %s to %s\n", p->callid, dest);
15553    }
15554 
15555    /* Are we transfering an inbound or outbound call ? */
15556    if (ast_test_flag(&p->flags[0], SIP_OUTGOING))  {
15557       of = sip_get_header(&p->initreq, "To");
15558    } else {
15559       of = sip_get_header(&p->initreq, "From");
15560    }
15561 
15562    ast_copy_string(from, of, sizeof(from));
15563    of = get_in_brackets(from);
15564    ast_string_field_set(p, from, of);
15565    if (!strncasecmp(of, "sip:", 4)) {
15566       of += 4;
15567    } else if (!strncasecmp(of, "sips:", 5)) {
15568       of += 5;
15569       use_tls = TRUE;
15570    } else {
15571       ast_log(LOG_NOTICE, "From address missing 'sip(s):', assuming sip:\n");
15572    }
15573    /* Get just the username part */
15574    if (strchr(dest, '@')) {
15575       c = NULL;
15576    } else if ((c = strchr(of, '@'))) {
15577       *c++ = '\0';
15578    }
15579    if (c) {
15580       snprintf(referto, sizeof(referto), "<sip%s:%s@%s>", use_tls ? "s" : "", dest, c);
15581    } else {
15582       snprintf(referto, sizeof(referto), "<sip%s:%s>", use_tls ? "s" : "", dest);
15583    }
15584 
15585    /* save in case we get 407 challenge */
15586    sip_refer_alloc(p);
15587    ast_string_field_set(p->refer, refer_to, referto);
15588    ast_string_field_set(p->refer, referred_by, p->our_contact);
15589    p->refer->status = REFER_SENT;   /* Set refer status */
15590 
15591    return transmit_invite(p, SIP_REFER, FALSE, 0, NULL);
15592    /* We should propably wait for a NOTIFY here until we ack the transfer */
15593    /* Maybe fork a new thread and wait for a STATUS of REFER_200OK on the refer status before returning to app_transfer */
15594 
15595    /*! \todo In theory, we should hang around and wait for a reply, before
15596    returning to the dial plan here. Don't know really how that would
15597    affect the transfer() app or the pbx, but, well, to make this
15598    useful we should have a STATUS code on transfer().
15599    */
15600 }
15601 
15602 /*! \brief Send SIP INFO advice of charge message */
15603 static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded)
15604 {
15605    struct sip_request req;
15606    struct ast_str *str = ast_str_alloca(512);
15607    const struct ast_aoc_unit_entry *unit_entry = ast_aoc_get_unit_info(decoded, 0);
15608    enum ast_aoc_charge_type charging = ast_aoc_get_charge_type(decoded);
15609 
15610    reqprep(&req, p, SIP_INFO, 0, 1);
15611 
15612    if (ast_aoc_get_msg_type(decoded) == AST_AOC_D) {
15613       ast_str_append(&str, 0, "type=active;");
15614    } else if (ast_aoc_get_msg_type(decoded) == AST_AOC_E) {
15615       ast_str_append(&str, 0, "type=terminated;");
15616    } else {
15617       /* unsupported message type */
15618       return -1;
15619    }
15620 
15621    switch (charging) {
15622    case AST_AOC_CHARGE_FREE:
15623       ast_str_append(&str, 0, "free-of-charge;");
15624       break;
15625    case AST_AOC_CHARGE_CURRENCY:
15626       ast_str_append(&str, 0, "charging;");
15627       ast_str_append(&str, 0, "charging-info=currency;");
15628       ast_str_append(&str, 0, "amount=%u;", ast_aoc_get_currency_amount(decoded));
15629       ast_str_append(&str, 0, "multiplier=%s;", ast_aoc_get_currency_multiplier_decimal(decoded));
15630       if (!ast_strlen_zero(ast_aoc_get_currency_name(decoded))) {
15631          ast_str_append(&str, 0, "currency=%s;", ast_aoc_get_currency_name(decoded));
15632       }
15633       break;
15634    case AST_AOC_CHARGE_UNIT:
15635       ast_str_append(&str, 0, "charging;");
15636       ast_str_append(&str, 0, "charging-info=pulse;");
15637       if (unit_entry) {
15638          ast_str_append(&str, 0, "recorded-units=%u;", unit_entry->amount);
15639       }
15640       break;
15641    default:
15642       ast_str_append(&str, 0, "not-available;");
15643    };
15644 
15645    add_header(&req, "AOC", ast_str_buffer(str));
15646 
15647    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
15648 }
15649 
15650 /*! \brief Send SIP INFO dtmf message, see Cisco documentation on cisco.com */
15651 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
15652 {
15653    struct sip_request req;
15654    
15655    reqprep(&req, p, SIP_INFO, 0, 1);
15656    add_digit(&req, digit, duration, (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO));
15657    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
15658 }
15659 
15660 /*! \brief Send SIP INFO with video update request */
15661 static int transmit_info_with_vidupdate(struct sip_pvt *p)
15662 {
15663    struct sip_request req;
15664    
15665    reqprep(&req, p, SIP_INFO, 0, 1);
15666    add_vidupdate(&req);
15667    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
15668 }
15669 
15670 /*! \brief Transmit generic SIP request
15671    returns XMIT_ERROR if transmit failed with a critical error (don't retry)
15672 */
15673 static int transmit_request(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch)
15674 {
15675    struct sip_request resp;
15676    
15677    reqprep(&resp, p, sipmethod, seqno, newbranch);
15678    if (sipmethod == SIP_CANCEL && p->answered_elsewhere) {
15679       add_header(&resp, "Reason", "SIP;cause=200;text=\"Call completed elsewhere\"");
15680    }
15681 
15682    if (sipmethod == SIP_ACK) {
15683       p->invitestate = INV_CONFIRMED;
15684    }
15685 
15686    return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
15687 }
15688 
15689 /*! \brief return the request and response header for a 401 or 407 code */
15690 void sip_auth_headers(enum sip_auth_type code, char **header, char **respheader)
15691 {
15692    if (code == WWW_AUTH) {       /* 401 */
15693       *header = "WWW-Authenticate";
15694       *respheader = "Authorization";
15695    } else if (code == PROXY_AUTH) { /* 407 */
15696       *header = "Proxy-Authenticate";
15697       *respheader = "Proxy-Authorization";
15698    } else {
15699       ast_verbose("-- wrong response code %u\n", code);
15700       *header = *respheader = "Invalid";
15701    }
15702 }
15703 
15704 /*! \brief Transmit SIP request, auth added */
15705 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch)
15706 {
15707    struct sip_request resp;
15708    
15709    reqprep(&resp, p, sipmethod, seqno, newbranch);
15710    if (!ast_strlen_zero(p->realm)) {
15711       char digest[1024];
15712 
15713       memset(digest, 0, sizeof(digest));
15714       if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
15715          char *dummy, *response;
15716          enum sip_auth_type code = p->options ? p->options->auth_type : PROXY_AUTH; /* XXX force 407 if unknown */
15717          sip_auth_headers(code, &dummy, &response);
15718          add_header(&resp, response, digest);
15719       } else {
15720          ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
15721       }
15722    }
15723 
15724    switch (sipmethod) {
15725    case SIP_BYE:
15726    {
15727       char buf[20];
15728 
15729       /*
15730        * We are hanging up.  If we know a cause for that, send it in
15731        * clear text to make debugging easier.
15732        */
15733       if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON) && p->hangupcause) {
15734          snprintf(buf, sizeof(buf), "Q.850;cause=%d", p->hangupcause & 0x7f);
15735          add_header(&resp, "Reason", buf);
15736       }
15737 
15738       add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->hangupcause));
15739       snprintf(buf, sizeof(buf), "%d", p->hangupcause);
15740       add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
15741       break;
15742    }
15743    case SIP_MESSAGE:
15744       add_text(&resp, p);
15745       break;
15746    default:
15747       break;
15748    }
15749 
15750    return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);   
15751 }
15752 
15753 /*! \brief Remove registration data from realtime database or AST/DB when registration expires */
15754 static void destroy_association(struct sip_peer *peer)
15755 {
15756    int realtimeregs = ast_check_realtime("sipregs");
15757    char *tablename = (realtimeregs) ? "sipregs" : "sippeers";
15758 
15759    if (!sip_cfg.ignore_regexpire) {
15760       if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
15761          ast_update_realtime(tablename, "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", "regserver", "", "useragent", "", "lastms", "0", SENTINEL);
15762       } else {
15763          ast_db_del("SIP/Registry", peer->name);
15764          ast_db_del("SIP/PeerMethods", peer->name);
15765       }
15766    }
15767 }
15768 
15769 static void set_socket_transport(struct sip_socket *socket, int transport)
15770 {
15771    /* if the transport type changes, clear all socket data */
15772    if (socket->type != transport) {
15773       socket->fd = -1;
15774       socket->type = transport;
15775       if (socket->tcptls_session) {
15776          ao2_ref(socket->tcptls_session, -1);
15777          socket->tcptls_session = NULL;
15778       } else if (socket->ws_session) {
15779          ast_websocket_unref(socket->ws_session);
15780          socket->ws_session = NULL;
15781       }
15782    }
15783 }
15784 
15785 /*! \brief Expire registration of SIP peer */
15786 static int expire_register(const void *data)
15787 {
15788    struct sip_peer *peer = (struct sip_peer *)data;
15789 
15790    if (!peer) {      /* Hmmm. We have no peer. Weird. */
15791       return 0;
15792    }
15793 
15794    peer->expire = -1;
15795    peer->portinuri = 0;
15796 
15797    destroy_association(peer); /* remove registration data from storage */
15798    set_socket_transport(&peer->socket, peer->default_outbound_transport);
15799 
15800    if (peer->socket.tcptls_session) {
15801       ao2_ref(peer->socket.tcptls_session, -1);
15802       peer->socket.tcptls_session = NULL;
15803    } else if (peer->socket.ws_session) {
15804       ast_websocket_unref(peer->socket.ws_session);
15805       peer->socket.ws_session = NULL;
15806    }
15807 
15808    manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
15809    register_peer_exten(peer, FALSE);   /* Remove regexten */
15810    ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", peer->name);
15811 
15812    /* Do we need to release this peer from memory?
15813       Only for realtime peers and autocreated peers
15814    */
15815    if (peer->is_realtime) {
15816       ast_debug(3, "-REALTIME- peer expired registration. Name: %s. Realtime peer objects now %d\n", peer->name, rpeerobjs);
15817    }
15818 
15819    if (peer->selfdestruct ||
15820        ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
15821       unlink_peer_from_tables(peer);
15822    } else if (!ast_sockaddr_isnull(&peer->addr)) {
15823       /* If we aren't self-destructing a temp_peer, we still need to unlink the peer
15824        * from the peers_by_ip table, otherwise we end up with multiple copies hanging
15825        * around each time a registration expires and the peer re-registers. */
15826       ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
15827    }
15828 
15829    /* Only clear the addr after we check for destruction.  The addr must remain
15830     * in order to unlink from the peers_by_ip container correctly */
15831    memset(&peer->addr, 0, sizeof(peer->addr));
15832 
15833    sip_unref_peer(peer, "removing peer ref for expire_register");
15834 
15835    return 0;
15836 }
15837 
15838 /*! \brief Poke peer (send qualify to check if peer is alive and well) */
15839 static int sip_poke_peer_s(const void *data)
15840 {
15841    struct sip_peer *peer = (struct sip_peer *)data;
15842    struct sip_peer *foundpeer;
15843 
15844    peer->pokeexpire = -1;
15845 
15846    foundpeer = ao2_find(peers, peer, OBJ_POINTER);
15847    if (!foundpeer) {
15848       sip_unref_peer(peer, "removing poke peer ref");
15849       return 0;
15850    } else if (foundpeer->name != peer->name) {
15851       sip_unref_peer(foundpeer, "removing above peer ref");
15852       sip_unref_peer(peer, "removing poke peer ref");
15853       return 0;
15854    }
15855 
15856    sip_unref_peer(foundpeer, "removing above peer ref");
15857    sip_poke_peer(peer, 0);
15858    sip_unref_peer(peer, "removing poke peer ref");
15859 
15860    return 0;
15861 }
15862 
15863 /*! \brief Get registration details from Asterisk DB */
15864 static void reg_source_db(struct sip_peer *peer)
15865 {
15866    char data[256];
15867    struct ast_sockaddr sa;
15868    int expire;
15869    char full_addr[128];
15870    AST_DECLARE_APP_ARGS(args,
15871       AST_APP_ARG(addr);
15872       AST_APP_ARG(port);
15873       AST_APP_ARG(expiry_str);
15874       AST_APP_ARG(username);
15875       AST_APP_ARG(contact);
15876    );
15877 
15878    /* If read-only RT backend, then refresh from local DB cache */
15879    if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
15880       return;
15881    }
15882    if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data))) {
15883       return;
15884    }
15885 
15886    AST_NONSTANDARD_RAW_ARGS(args, data, ':');
15887 
15888    snprintf(full_addr, sizeof(full_addr), "%s:%s", args.addr, args.port);
15889 
15890    if (!ast_sockaddr_parse(&sa, full_addr, 0)) {
15891       return;
15892    }
15893 
15894    if (args.expiry_str) {
15895       expire = atoi(args.expiry_str);
15896    } else {
15897       return;
15898    }
15899 
15900    if (args.username) {
15901       ast_string_field_set(peer, username, args.username);
15902    }
15903    if (args.contact) {
15904       ast_string_field_set(peer, fullcontact, args.contact);
15905    }
15906 
15907    ast_debug(2, "SIP Seeding peer from astdb: '%s' at %s@%s for %d\n",
15908        peer->name, peer->username, ast_sockaddr_stringify_host(&sa), expire);
15909 
15910    ast_sockaddr_copy(&peer->addr, &sa);
15911    if (peer->maxms) {
15912       /* Don't poke peer immediately, just schedule it within qualifyfreq */
15913       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
15914             ast_random() % ((peer->qualifyfreq) ? peer->qualifyfreq : global_qualifyfreq) + 1,
15915             sip_poke_peer_s, peer,
15916             sip_unref_peer(_data, "removing poke peer ref"),
15917             sip_unref_peer(peer, "removing poke peer ref"),
15918             sip_ref_peer(peer, "adding poke peer ref"));
15919    }
15920    AST_SCHED_REPLACE_UNREF(peer->expire, sched, (expire + 10) * 1000, expire_register, peer,
15921          sip_unref_peer(_data, "remove registration ref"),
15922          sip_unref_peer(peer, "remove registration ref"),
15923          sip_ref_peer(peer, "add registration ref"));
15924    register_peer_exten(peer, TRUE);
15925 }
15926 
15927 /*! \brief Save contact header for 200 OK on INVITE */
15928 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
15929 {
15930    char contact[SIPBUFSIZE];
15931    char *c;
15932 
15933    /* Look for brackets */
15934    ast_copy_string(contact, sip_get_header(req, "Contact"), sizeof(contact));
15935    c = get_in_brackets(contact);
15936 
15937    /* Save full contact to call pvt for later bye or re-invite */
15938    ast_string_field_set(pvt, fullcontact, c);
15939 
15940    /* Save URI for later ACKs, BYE or RE-invites */
15941    ast_string_field_set(pvt, okcontacturi, c);
15942 
15943    /* We should return false for URI:s we can't handle,
15944       like tel:, mailto:,ldap: etc */
15945    return TRUE;      
15946 }
15947 
15948 /*! \brief parse uri in a way that allows semicolon stripping if legacy mode is enabled
15949  *
15950  * \note This calls parse_uri which has the unexpected property that passing more
15951  *       arguments results in more splitting. Most common is to leave out the pass
15952  *       argument, causing user to contain user:pass if available.
15953  */
15954 static int parse_uri_legacy_check(char *uri, const char *scheme, char **user, char **pass, char **hostport, char **transport)
15955 {
15956    int ret = parse_uri(uri, scheme, user, pass, hostport, transport);
15957    if (sip_cfg.legacy_useroption_parsing) { /* if legacy mode is active, strip semis from the user field */
15958       char *p;
15959       if ((p = strchr(uri, (int)';'))) {
15960          *p = '\0';
15961       }
15962    }
15963    return ret;
15964 }
15965 
15966 static int __set_address_from_contact(const char *fullcontact, struct ast_sockaddr *addr, int tcp)
15967 {
15968    char *hostport, *transport;
15969    char contact_buf[256];
15970    char *contact;
15971 
15972    /* Work on a copy */
15973    ast_copy_string(contact_buf, fullcontact, sizeof(contact_buf));
15974    contact = contact_buf;
15975 
15976    /* 
15977     * We have only the part in <brackets> here so we just need to parse a SIP URI.
15978     *
15979     * Note: The outbound proxy could be using UDP between the proxy and Asterisk.
15980     * We still need to be able to send to the remote agent through the proxy.
15981     */
15982 
15983    if (parse_uri_legacy_check(contact, "sip:,sips:", &contact, NULL, &hostport,
15984             &transport)) {
15985       ast_log(LOG_WARNING, "Invalid contact uri %s (missing sip: or sips:), attempting to use anyway\n", fullcontact);
15986    }
15987 
15988    /* XXX This could block for a long time XXX */
15989    /* We should only do this if it's a name, not an IP */
15990    /* \todo - if there's no PORT number in contact - we are required to check NAPTR/SRV records
15991       to find transport, port address and hostname. If there's a port number, we have to
15992       assume that the hostport part is a host name and only look for an A/AAAA record in DNS.
15993    */
15994 
15995    /* If we took in an invalid URI, hostport may not have been initialized */
15996    /* ast_sockaddr_resolve requires an initialized hostport string. */
15997    if (ast_strlen_zero(hostport)) {
15998       ast_log(LOG_WARNING, "Invalid URI: parse_uri failed to acquire hostport\n");
15999       return -1;
16000    }
16001 
16002    if (ast_sockaddr_resolve_first_transport(addr, hostport, 0, get_transport_str2enum(transport))) {
16003       ast_log(LOG_WARNING, "Invalid host name in Contact: (can't "
16004          "resolve in DNS) : '%s'\n", hostport);
16005       return -1;
16006    }
16007 
16008    /* set port */
16009    if (!ast_sockaddr_port(addr)) {
16010       ast_sockaddr_set_port(addr,
16011                   (get_transport_str2enum(transport) ==
16012                    SIP_TRANSPORT_TLS ||
16013                    !strncasecmp(fullcontact, "sips", 4)) ?
16014                   STANDARD_TLS_PORT : STANDARD_SIP_PORT);
16015    }
16016 
16017    return 0;
16018 }
16019 
16020 /*! \brief Change the other partys IP address based on given contact */
16021 static int set_address_from_contact(struct sip_pvt *pvt)
16022 {
16023    if (ast_test_flag(&pvt->flags[0], SIP_NAT_FORCE_RPORT)) {
16024       /* NAT: Don't trust the contact field.  Just use what they came to us
16025          with. */
16026       /*! \todo We need to save the TRANSPORT here too */
16027       pvt->sa = pvt->recv;
16028       return 0;
16029    }
16030 
16031    return __set_address_from_contact(pvt->fullcontact, &pvt->sa, pvt->socket.type == SIP_TRANSPORT_TLS ? 1 : 0);
16032 }
16033 
16034 /*! \brief Parse contact header and save registration (peer registration) */
16035 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
16036 {
16037    char contact[SIPBUFSIZE];
16038    char data[SIPBUFSIZE];
16039    const char *expires = sip_get_header(req, "Expires");
16040    int expire = atoi(expires);
16041    char *curi = NULL, *hostport = NULL, *transport = NULL;
16042    int transport_type;
16043    const char *useragent;
16044    struct ast_sockaddr oldsin, testsa;
16045    char *firstcuri = NULL;
16046    int start = 0;
16047    int wildcard_found = 0;
16048    int single_binding_found = 0;
16049 
16050    ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
16051 
16052    if (ast_strlen_zero(expires)) {  /* No expires header, try look in Contact: */
16053       char *s = strcasestr(contact, ";expires=");
16054       if (s) {
16055          expires = strsep(&s, ";"); /* trim ; and beyond */
16056          if (sscanf(expires + 9, "%30d", &expire) != 1) {
16057             expire = default_expiry;
16058          }
16059       } else {
16060          /* Nothing has been specified */
16061          expire = default_expiry;
16062       }
16063    }
16064 
16065    if (expire > max_expiry) {
16066       expire = max_expiry;
16067    }
16068    if (expire < min_expiry && expire != 0) {
16069       expire = min_expiry;
16070    }
16071    pvt->expiry = expire;
16072 
16073    copy_socket_data(&pvt->socket, &req->socket);
16074 
16075    do {
16076       /* Look for brackets */
16077       curi = contact;
16078       if (strchr(contact, '<') == NULL)   /* No <, check for ; and strip it */
16079          strsep(&curi, ";");  /* This is Header options, not URI options */
16080       curi = get_in_brackets(contact);
16081       if (!firstcuri) {
16082          firstcuri = ast_strdupa(curi);
16083       }
16084 
16085       if (!strcasecmp(curi, "*")) {
16086          wildcard_found = 1;
16087       } else {
16088          single_binding_found = 1;
16089       }
16090 
16091       if (wildcard_found && (ast_strlen_zero(expires) || expire != 0 || single_binding_found)) {
16092          /* Contact header parameter "*" detected, so punt if: Expires header is missing,
16093           * Expires value is not zero, or another Contact header is present. */
16094          return PARSE_REGISTER_FAILED;
16095       }
16096 
16097       ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
16098    } while (!ast_strlen_zero(contact));
16099    curi = firstcuri;
16100 
16101    /* if they did not specify Contact: or Expires:, they are querying
16102       what we currently have stored as their contact address, so return
16103       it
16104    */
16105    if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
16106       /* If we have an active registration, tell them when the registration is going to expire */
16107       if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact)) {
16108          pvt->expiry = ast_sched_when(sched, peer->expire);
16109       }
16110       return PARSE_REGISTER_QUERY;
16111    } else if (!strcasecmp(curi, "*") || !expire) { /* Unregister this peer */
16112       /* This means remove all registrations and return OK */
16113       AST_SCHED_DEL_UNREF(sched, peer->expire,
16114             sip_unref_peer(peer, "remove register expire ref"));
16115       ast_verb(3, "Unregistered SIP '%s'\n", peer->name);
16116       expire_register(sip_ref_peer(peer,"add ref for explicit expire_register"));
16117       return PARSE_REGISTER_UPDATE;
16118    }
16119 
16120    /* Store whatever we got as a contact from the client */
16121    ast_string_field_set(peer, fullcontact, curi);
16122 
16123    /* For the 200 OK, we should use the received contact */
16124    ast_string_field_build(pvt, our_contact, "<%s>", curi);
16125 
16126    /* Make sure it's a SIP URL */
16127    if (ast_strlen_zero(curi) || parse_uri_legacy_check(curi, "sip:,sips:", &curi, NULL, &hostport, &transport)) {
16128       ast_log(LOG_NOTICE, "Not a valid SIP contact (missing sip:/sips:) trying to use anyway\n");
16129    }
16130 
16131    /* handle the transport type specified in Contact header. */
16132    if (!(transport_type = get_transport_str2enum(transport))) {
16133       transport_type = pvt->socket.type;
16134    }
16135 
16136    /* if the peer's socket type is different than the Registration
16137     * transport type, change it.  If it got this far, it is a
16138     * supported type, but check just in case */
16139    if ((peer->socket.type != transport_type) && (peer->transports & transport_type)) {
16140       set_socket_transport(&peer->socket, transport_type);
16141    }
16142 
16143    oldsin = peer->addr;
16144 
16145    /* If we were already linked into the peers_by_ip container unlink ourselves so nobody can find us */
16146    if (!ast_sockaddr_isnull(&peer->addr) && (!peer->is_realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS))) {
16147       ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
16148    }
16149 
16150    if ((transport_type != SIP_TRANSPORT_WS) && (transport_type != SIP_TRANSPORT_WSS) &&
16151        (!ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) && !ast_test_flag(&peer->flags[0], SIP_NAT_RPORT_PRESENT))) {
16152       /* use the data provided in the Contact header for call routing */
16153       ast_debug(1, "Store REGISTER's Contact header for call routing.\n");
16154       /* XXX This could block for a long time XXX */
16155       /*! \todo Check NAPTR/SRV if we have not got a port in the URI */
16156       if (ast_sockaddr_resolve_first_transport(&testsa, hostport, 0, peer->socket.type)) {
16157          ast_log(LOG_WARNING, "Invalid hostport '%s'\n", hostport);
16158          ast_string_field_set(peer, fullcontact, "");
16159          ast_string_field_set(pvt, our_contact, "");
16160          return PARSE_REGISTER_FAILED;
16161       }
16162 
16163       /* If we have a port number in the given URI, make sure we do remember to not check for NAPTR/SRV records.
16164          The hostport part is actually a host. */
16165       peer->portinuri = ast_sockaddr_port(&testsa) ? TRUE : FALSE;
16166 
16167       if (!ast_sockaddr_port(&testsa)) {
16168          ast_sockaddr_set_port(&testsa, default_sip_port(transport_type));
16169       }
16170 
16171       ast_sockaddr_copy(&peer->addr, &testsa);
16172    } else {
16173       /* Don't trust the contact field.  Just use what they came to us
16174          with */
16175       ast_debug(1, "Store REGISTER's src-IP:port for call routing.\n");
16176       peer->addr = pvt->recv;
16177    }
16178 
16179    /* Check that they're allowed to register at this IP */
16180    if (ast_apply_acl(sip_cfg.contact_acl, &peer->addr, "SIP contact ACL: ") != AST_SENSE_ALLOW ||
16181          ast_apply_acl(peer->contactacl, &peer->addr, "SIP contact ACL: ") != AST_SENSE_ALLOW) {
16182       ast_log(LOG_WARNING, "Domain '%s' disallowed by contact ACL (violating IP %s)\n", hostport,
16183             ast_sockaddr_stringify_addr(&peer->addr));
16184       ast_string_field_set(peer, fullcontact, "");
16185       ast_string_field_set(pvt, our_contact, "");
16186       return PARSE_REGISTER_DENIED;
16187    }
16188 
16189    /* if the Contact header information copied into peer->addr matches the
16190     * received address, and the transport types are the same, then copy socket
16191     * data into the peer struct */
16192    if ((peer->socket.type == pvt->socket.type) &&
16193       !ast_sockaddr_cmp(&peer->addr, &pvt->recv)) {
16194       copy_socket_data(&peer->socket, &pvt->socket);
16195    }
16196 
16197    /* Now that our address has been updated put ourselves back into the container for lookups */
16198    if (!peer->is_realtime || ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
16199       ao2_t_link(peers_by_ip, peer, "ao2_link into peers_by_ip table");
16200    }
16201 
16202    /* Save SIP options profile */
16203    peer->sipoptions = pvt->sipoptions;
16204 
16205    if (!ast_strlen_zero(curi) && ast_strlen_zero(peer->username)) {
16206       ast_string_field_set(peer, username, curi);
16207    }
16208 
16209    AST_SCHED_DEL_UNREF(sched, peer->expire,
16210          sip_unref_peer(peer, "remove register expire ref"));
16211 
16212    if (peer->is_realtime && !ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
16213       peer->expire = -1;
16214    } else {
16215       peer->expire = ast_sched_add(sched, (expire + 10) * 1000, expire_register,
16216             sip_ref_peer(peer, "add registration ref"));
16217       if (peer->expire == -1) {
16218          sip_unref_peer(peer, "remote registration ref");
16219       }
16220    }
16221    snprintf(data, sizeof(data), "%s:%d:%s:%s", ast_sockaddr_stringify(&peer->addr),
16222        expire, peer->username, peer->fullcontact);
16223    /* We might not immediately be able to reconnect via TCP, but try caching it anyhow */
16224    if (!peer->rt_fromcontact || !sip_cfg.peer_rtupdate)
16225       ast_db_put("SIP/Registry", peer->name, data);
16226    manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Registered\r\nAddress: %s\r\n", peer->name,  ast_sockaddr_stringify(&peer->addr));
16227 
16228    /* Is this a new IP address for us? */
16229    if (ast_sockaddr_cmp(&peer->addr, &oldsin)) {
16230       ast_verb(3, "Registered SIP '%s' at %s\n", peer->name,
16231          ast_sockaddr_stringify(&peer->addr));
16232    }
16233    sip_pvt_unlock(pvt);
16234    sip_poke_peer(peer, 0);
16235    sip_pvt_lock(pvt);
16236    register_peer_exten(peer, 1);
16237 
16238    /* Save User agent */
16239    useragent = sip_get_header(req, "User-Agent");
16240    if (strcasecmp(useragent, peer->useragent)) {
16241       ast_string_field_set(peer, useragent, useragent);
16242       ast_verb(4, "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
16243    }
16244    return PARSE_REGISTER_UPDATE;
16245 }
16246 
16247 /*! \brief Remove route from route list */
16248 static void free_old_route(struct sip_route *route)
16249 {
16250    struct sip_route *next;
16251 
16252    while (route) {
16253       next = route->next;
16254       ast_free(route);
16255       route = next;
16256    }
16257 }
16258 
16259 /*! \brief List all routes - mostly for debugging */
16260 static void list_route(struct sip_route *route)
16261 {
16262    if (!route) {
16263       ast_verbose("list_route: no route\n");
16264    } else {
16265       for (;route; route = route->next)
16266          ast_verbose("list_route: hop: <%s>\n", route->hop);
16267    }
16268 }
16269 
16270 /*! \brief Build route list from Record-Route header 
16271     \param resp the SIP response code or 0 for a request */
16272 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards, int resp)
16273 {
16274    struct sip_route *thishop, *head, *tail;
16275    int start = 0;
16276    int len;
16277    const char *rr, *c;
16278 
16279    /* Once a persistent route is set, don't fool with it */
16280    if (p->route && p->route_persistent) {
16281       ast_debug(1, "build_route: Retaining previous route: <%s>\n", p->route->hop);
16282       return;
16283    }
16284 
16285    if (p->route) {
16286       free_old_route(p->route);
16287       p->route = NULL;
16288    }
16289 
16290    /* We only want to create the route set the first time this is called except
16291       it is called from a provisional response.*/
16292    if ((resp < 100) || (resp > 199)) {
16293       p->route_persistent = 1;
16294    }
16295 
16296    /* Build a tailq, then assign it to p->route when done.
16297     * If backwards, we add entries from the head so they end up
16298     * in reverse order. However, we do need to maintain a correct
16299     * tail pointer because the contact is always at the end.
16300     */
16301    head = NULL;
16302    tail = head;
16303    /* 1st we pass through all the hops in any Record-Route headers */
16304    for (;;) {
16305       /* Each Record-Route header */
16306       int len = 0;
16307       const char *uri;
16308       rr = __get_header(req, "Record-Route", &start);
16309       if (*rr == '\0') {
16310          break;
16311       }
16312       while (!get_in_brackets_const(rr, &uri, &len)) {
16313          len++;
16314          rr = strchr(rr, ',');
16315          if(rr >= uri && rr < (uri + len)) {
16316             /* comma inside brackets*/
16317             const char *next_br = strchr(rr, '<');
16318             if (next_br && next_br < (uri + len)) {
16319                rr++;
16320                continue;
16321             }
16322             continue;
16323          }
16324          if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
16325             ast_copy_string(thishop->hop, uri, len);
16326             ast_debug(2, "build_route: Record-Route hop: <%s>\n", thishop->hop);
16327             /* Link in */
16328             if (backwards) {
16329                /* Link in at head so they end up in reverse order */
16330                thishop->next = head;
16331                head = thishop;
16332                /* If this was the first then it'll be the tail */
16333                if (!tail) {
16334                   tail = thishop;
16335                }
16336             } else {
16337                thishop->next = NULL;
16338                /* Link in at the end */
16339                if (tail) {
16340                   tail->next = thishop;
16341                } else {
16342                   head = thishop;
16343                }
16344                tail = thishop;
16345             }
16346          }
16347          rr = strchr(uri + len, ',');
16348          if (rr == NULL) {
16349             /* No more field-values, we're done with this header */
16350             break;
16351          }
16352          /* Advance past comma */
16353          rr++;
16354       }
16355    }
16356 
16357    /* Only append the contact if we are dealing with a strict router */
16358    if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop, ";lr") == NULL) ) {
16359       /* 2nd append the Contact: if there is one */
16360       /* Can be multiple Contact headers, comma separated values - we just take the first */
16361       char *contact = ast_strdupa(sip_get_header(req, "Contact"));
16362       if (!ast_strlen_zero(contact)) {
16363          ast_debug(2, "build_route: Contact hop: %s\n", contact);
16364          /* Look for <: delimited address */
16365          c = get_in_brackets(contact);
16366          len = strlen(c) + 1;
16367          if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
16368             /* ast_calloc is not needed because all fields are initialized in this block */
16369             ast_copy_string(thishop->hop, c, len);
16370             thishop->next = NULL;
16371             /* Goes at the end */
16372             if (tail) {
16373                tail->next = thishop;
16374             } else {
16375                head = thishop;
16376             }
16377          }
16378       }
16379    }
16380 
16381    /* Store as new route */
16382    p->route = head;
16383 
16384    /* For debugging dump what we ended up with */
16385    if (sip_debug_test_pvt(p)) {
16386       list_route(p->route);
16387    }
16388 }
16389 
16390 /*! \brief builds the sip_pvt's nonce field which is used for the authentication 
16391  *  challenge.  When forceupdate is not set, the nonce is only updated if
16392  *  the current one is stale.  In this case, a stalenonce is one which
16393  *  has already received a response, if a nonce has not received a response
16394  *  it is not always necessary or beneficial to create a new one. */
16395 
16396 static void build_nonce(struct sip_pvt *p, int forceupdate)
16397 {
16398    if (p->stalenonce || forceupdate || ast_strlen_zero(p->nonce)) {
16399       ast_string_field_build(p, nonce, "%08lx", (unsigned long)ast_random()); /* Create nonce for challenge */
16400       p->stalenonce = 0;
16401    }
16402 }
16403 
16404 /*! \brief Takes the digest response and parses it */
16405 void sip_digest_parser(char *c, struct digestkeys *keys)
16406 {
16407         struct digestkeys *i = i;
16408 
16409         while(c && *(c = ast_skip_blanks(c)) ) { /* lookup for keys */
16410                 for (i = keys; i->key != NULL; i++) {
16411                         const char *separator = ",";    /* default */
16412 
16413                         if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
16414                                 continue;
16415                         }
16416                         /* Found. Skip keyword, take text in quotes or up to the separator. */
16417                         c += strlen(i->key);
16418                         if (*c == '"') { /* in quotes. Skip first and look for last */
16419                                 c++;
16420                                 separator = "\"";
16421                         }
16422                         i->s = c;
16423                         strsep(&c, separator);
16424                         break;
16425                 }
16426                 if (i->key == NULL) { /* not found, jump after space or comma */
16427          strsep(&c, " ,");
16428       }
16429         }
16430 }
16431 
16432 /*! \brief  Check user authorization from peer definition
16433    Some actions, like REGISTER and INVITEs from peers require
16434    authentication (if peer have secret set)
16435     \return 0 on success, non-zero on error
16436 */
16437 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
16438                 const char *secret, const char *md5secret, int sipmethod,
16439                 const char *uri, enum xmittype reliable)
16440 {
16441    const char *response;
16442    char *reqheader, *respheader;
16443    const char *authtoken;
16444    char a1_hash[256];
16445    char resp_hash[256]="";
16446    char *c;
16447    int is_bogus_peer = 0;
16448    int  wrongnonce = FALSE;
16449    int  good_response;
16450    const char *usednonce = p->nonce;
16451    struct ast_str *buf;
16452    int res;
16453 
16454    /* table of recognised keywords, and their value in the digest */
16455    struct digestkeys keys[] = {
16456       [K_RESP] = { "response=", "" },
16457       [K_URI] = { "uri=", "" },
16458       [K_USER] = { "username=", "" },
16459       [K_NONCE] = { "nonce=", "" },
16460       [K_LAST] = { NULL, NULL}
16461    };
16462 
16463    /* Always OK if no secret */
16464    if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret)) {
16465       return AUTH_SUCCESSFUL;
16466    }
16467 
16468    /* Always auth with WWW-auth since we're NOT a proxy */
16469    /* Using proxy-auth in a B2BUA may block proxy authorization in the same transaction */
16470    response = "401 Unauthorized";
16471 
16472    /*
16473     * Note the apparent swap of arguments below, compared to other
16474     * usages of sip_auth_headers().
16475     */
16476    sip_auth_headers(WWW_AUTH, &respheader, &reqheader);
16477 
16478    authtoken = sip_get_header(req, reqheader);
16479    if (req->ignore && !ast_strlen_zero(p->nonce) && ast_strlen_zero(authtoken)) {
16480       /* This is a retransmitted invite/register/etc, don't reconstruct authentication
16481          information */
16482       if (!reliable) {
16483          /* Resend message if this was NOT a reliable delivery.   Otherwise the
16484             retransmission should get it */
16485          transmit_response_with_auth(p, response, req, p->nonce, reliable, respheader, 0);
16486          /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
16487          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16488       }
16489       return AUTH_CHALLENGE_SENT;
16490    } else if (ast_strlen_zero(p->nonce) || ast_strlen_zero(authtoken)) {
16491       /* We have no auth, so issue challenge and request authentication */
16492       build_nonce(p, 1); /* Create nonce for challenge */
16493       transmit_response_with_auth(p, response, req, p->nonce, reliable, respheader, 0);
16494       /* Schedule auto destroy in 32 seconds */
16495       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16496       return AUTH_CHALLENGE_SENT;
16497    }
16498 
16499    /* --- We have auth, so check it */
16500 
16501    /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
16502       an example in the spec of just what it is you're doing a hash on. */
16503 
16504    if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
16505       return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
16506    }
16507 
16508    /* Make a copy of the response and parse it */
16509    res = ast_str_set(&buf, 0, "%s", authtoken);
16510 
16511    if (res == AST_DYNSTR_BUILD_FAILED) {
16512       return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
16513    }
16514 
16515    c = buf->str;
16516 
16517    sip_digest_parser(c, keys);
16518 
16519    /* We cannot rely on the bogus_peer having a bad md5 value. Someone could
16520     * use it to construct valid auth. */
16521    if (md5secret && strcmp(md5secret, BOGUS_PEER_MD5SECRET) == 0) {
16522       is_bogus_peer = 1;
16523    }
16524 
16525    /* Verify that digest username matches  the username we auth as */
16526    if (strcmp(username, keys[K_USER].s) && !is_bogus_peer) {
16527       ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
16528          username, keys[K_USER].s);
16529       /* Oops, we're trying something here */
16530       return AUTH_USERNAME_MISMATCH;
16531    }
16532 
16533    /* Verify nonce from request matches our nonce, and the nonce has not already been responded to.
16534     * If this check fails, send 401 with new nonce */
16535    if (strcasecmp(p->nonce, keys[K_NONCE].s) || p->stalenonce) { /* XXX it was 'n'casecmp ? */
16536       wrongnonce = TRUE;
16537       usednonce = keys[K_NONCE].s;
16538    } else {
16539       p->stalenonce = 1; /* now, since the nonce has a response, mark it as stale so it can't be sent or responded to again */
16540    }
16541 
16542    if (!ast_strlen_zero(md5secret)) {
16543       ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
16544    } else {
16545       char a1[256];
16546 
16547       snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
16548       ast_md5_hash(a1_hash, a1);
16549    }
16550 
16551    /* compute the expected response to compare with what we received */
16552    {
16553       char a2[256];
16554       char a2_hash[256];
16555       char resp[256];
16556 
16557       snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
16558             S_OR(keys[K_URI].s, uri));
16559       ast_md5_hash(a2_hash, a2);
16560       snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
16561       ast_md5_hash(resp_hash, resp);
16562    }
16563 
16564    good_response = keys[K_RESP].s &&
16565          !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash)) &&
16566          !is_bogus_peer; /* lastly, check that the peer isn't the fake peer */
16567    if (wrongnonce) {
16568       if (good_response) {
16569          if (sipdebug)
16570             ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", sip_get_header(req, "From"));
16571          /* We got working auth token, based on stale nonce . */
16572          build_nonce(p, 0);
16573          transmit_response_with_auth(p, response, req, p->nonce, reliable, respheader, TRUE);
16574       } else {
16575          /* Everything was wrong, so give the device one more try with a new challenge */
16576          if (!req->ignore) {
16577             if (sipdebug) {
16578                ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", sip_get_header(req, "To"));
16579             }
16580             build_nonce(p, 1);
16581          } else {
16582             if (sipdebug) {
16583                ast_log(LOG_NOTICE, "Duplicate authentication received from '%s'\n", sip_get_header(req, "To"));
16584             }
16585          }
16586          transmit_response_with_auth(p, response, req, p->nonce, reliable, respheader, FALSE);
16587       }
16588 
16589       /* Schedule auto destroy in 32 seconds */
16590       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16591       return AUTH_CHALLENGE_SENT;
16592    }
16593    if (good_response) {
16594       append_history(p, "AuthOK", "Auth challenge successful for %s", username);
16595       return AUTH_SUCCESSFUL;
16596    }
16597 
16598    /* Ok, we have a bad username/secret pair */
16599    /* Tell the UAS not to re-send this authentication data, because
16600       it will continue to fail
16601    */
16602 
16603    return AUTH_SECRET_FAILED;
16604 }
16605 
16606 /*! \brief Change onhold state of a peer using a pvt structure */
16607 static void sip_peer_hold(struct sip_pvt *p, int hold)
16608 {
16609    if (!p->relatedpeer) {
16610       return;
16611    }
16612 
16613    /* If they put someone on hold, increment the value... otherwise decrement it */
16614    ast_atomic_fetchadd_int(&p->relatedpeer->onhold, (hold ? +1 : -1));
16615 
16616    /* Request device state update */
16617    ast_devstate_changed(AST_DEVICE_UNKNOWN, (ast_test_flag(ast_channel_flags(p->owner), AST_FLAG_DISABLE_DEVSTATE_CACHE) ? AST_DEVSTATE_NOT_CACHABLE : AST_DEVSTATE_CACHABLE),
16618               "SIP/%s", p->relatedpeer->name);
16619 
16620    return;
16621 }
16622 
16623 /*! \brief Receive MWI events that we have subscribed to */
16624 static void mwi_event_cb(const struct ast_event *event, void *userdata)
16625 {
16626    struct sip_peer *peer = userdata;
16627 
16628    sip_send_mwi_to_peer(peer, 0);
16629 }
16630 
16631 static void network_change_event_subscribe(void)
16632 {
16633    if (!network_change_event_subscription) {
16634       network_change_event_subscription = ast_event_subscribe(AST_EVENT_NETWORK_CHANGE,
16635          network_change_event_cb, "SIP Network Change", NULL, AST_EVENT_IE_END);
16636    }
16637 }
16638 
16639 static void network_change_event_unsubscribe(void)
16640 {
16641    if (network_change_event_subscription) {
16642       network_change_event_subscription = ast_event_unsubscribe(network_change_event_subscription);
16643    }
16644 }
16645 
16646 static void acl_change_event_subscribe(void)
16647 {
16648    if (!acl_change_event_subscription) {
16649       acl_change_event_subscription = ast_event_subscribe(AST_EVENT_ACL_CHANGE,
16650       acl_change_event_cb, "Manager must react to Named ACL changes", NULL, AST_EVENT_IE_END);
16651    }
16652 
16653 }
16654 
16655 static void acl_change_event_unsubscribe(void)
16656 {
16657    if (acl_change_event_subscription) {
16658       acl_change_event_subscription = ast_event_unsubscribe(acl_change_event_subscription);
16659    }
16660 }
16661 
16662 static int network_change_event_sched_cb(const void *data)
16663 {
16664    network_change_event_sched_id = -1;
16665    sip_send_all_registers();
16666    sip_send_all_mwi_subscriptions();
16667    return 0;
16668 }
16669 
16670 static void network_change_event_cb(const struct ast_event *event, void *userdata)
16671 {
16672    ast_debug(1, "SIP, got a network change event, renewing all SIP registrations.\n");
16673    if (network_change_event_sched_id == -1) {
16674       network_change_event_sched_id = ast_sched_add(sched, 1000, network_change_event_sched_cb, NULL);
16675    }
16676 }
16677 
16678 static void cb_extensionstate_destroy(int id, void *data)
16679 {
16680    struct sip_pvt *p = data;
16681 
16682    dialog_unref(p, "the extensionstate containing this dialog ptr was destroyed");
16683 }
16684 
16685 /*! \brief Callback for the devicestate notification (SUBSCRIBE) support subsystem
16686 \note If you add an "hint" priority to the extension in the dial plan,
16687    you will get notifications on device state changes */
16688 static int extensionstate_update(const char *context, const char *exten, struct state_notify_data *data, struct sip_pvt *p, int force)
16689 {
16690    sip_pvt_lock(p);
16691 
16692    switch (data->state) {
16693    case AST_EXTENSION_DEACTIVATED:  /* Retry after a while */
16694    case AST_EXTENSION_REMOVED:   /* Extension is gone */
16695       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);  /* Delete subscription in 32 secs */
16696       ast_verb(2, "Extension state: Watcher for hint %s %s. Notify User %s\n", exten, data->state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", p->username);
16697       p->subscribed = NONE;
16698       append_history(p, "Subscribestatus", "%s", data->state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
16699       break;
16700    default: /* Tell user */
16701       if (force) {
16702          /* we must skip the next two checks for a queued state change or resubscribe */
16703       } else if ((p->laststate == data->state && (~data->state & AST_EXTENSION_RINGING)) &&
16704             (p->last_presence_state == data->presence_state &&
16705                !strcmp(p->last_presence_subtype, data->presence_subtype) &&
16706                !strcmp(p->last_presence_message, data->presence_message))) {
16707          /* don't notify unchanged state or unchanged early-state causing parties again */
16708          sip_pvt_unlock(p);
16709          return 0;
16710       } else if (data->state & AST_EXTENSION_RINGING) {
16711          /* check if another channel than last time is ringing now to be notified */
16712          struct ast_channel *ringing = find_ringing_channel(data->device_state_info, p);
16713          if (ringing) {
16714             if (!ast_tvcmp(ast_channel_creationtime(ringing), p->last_ringing_channel_time)) {
16715                /* we assume here that no two channels have the exact same creation time */
16716                ao2_ref(ringing, -1);
16717                sip_pvt_unlock(p);
16718                return 0;
16719             } else {
16720                p->last_ringing_channel_time = ast_channel_creationtime(ringing);
16721                ao2_ref(ringing, -1);
16722             }
16723          }
16724          /* If no ringing channel was found, it doesn't necessarily indicate anything bad.
16725           * Likely, a device state change occurred for a custom device state, which does not
16726           * correspond to any channel. In such a case, just go ahead and pass the notification
16727           * along.
16728           */
16729       }
16730       /* ref before unref because the new could be the same as the old one. Don't risk destruction! */
16731       if (data->device_state_info) {
16732          ao2_ref(data->device_state_info, 1);
16733       }
16734       ao2_cleanup(p->last_device_state_info);
16735       p->last_device_state_info = data->device_state_info;
16736       p->laststate = data->state;
16737       p->last_presence_state = data->presence_state;
16738       ast_string_field_set(p, last_presence_subtype, S_OR(data->presence_subtype, ""));
16739       ast_string_field_set(p, last_presence_message, S_OR(data->presence_message, ""));
16740       break;
16741    }
16742    if (p->subscribed != NONE) {  /* Only send state NOTIFY if we know the format */
16743       if (!p->pendinginvite) {
16744          transmit_state_notify(p, data, 1, FALSE);
16745          if (p->last_device_state_info) {
16746             /* We don't need the saved ref anymore, don't keep channels ref'd. */
16747             ao2_ref(p->last_device_state_info, -1);
16748             p->last_device_state_info = NULL;
16749          }
16750       } else {
16751          /* We already have a NOTIFY sent that is not answered. Queue the state up.
16752             if many state changes happen meanwhile, we will only send a notification of the last one */
16753          ast_set_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
16754       }
16755    }
16756 
16757    if (!force) {
16758       ast_verb(2, "Extension Changed %s[%s] new state %s for Notify User %s %s\n", exten, context, ast_extension_state2str(data->state), p->username,
16759             ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE) ? "(queued)" : "");
16760    }
16761 
16762    sip_pvt_unlock(p);
16763 
16764    return 0;
16765 }
16766 
16767 /*! \brief Callback for the devicestate notification (SUBSCRIBE) support subsystem
16768 \note If you add an "hint" priority to the extension in the dial plan,
16769    you will get notifications on device state changes */
16770 static int cb_extensionstate(char *context, char *exten, struct ast_state_cb_info *info, void *data)
16771 {
16772    struct sip_pvt *p = data;
16773    struct state_notify_data notify_data = {
16774       .state = info->exten_state,
16775       .device_state_info = info->device_state_info,
16776       .presence_state = info->presence_state,
16777       .presence_subtype = info->presence_subtype,
16778       .presence_message = info->presence_message,
16779    };
16780 
16781    if ((info->reason == AST_HINT_UPDATE_PRESENCE) && !(allow_notify_user_presence(p))) {
16782       /* ignore a presence triggered update if we know the useragent doesn't care */
16783       return 0;
16784    }
16785 
16786    return extensionstate_update(context, exten, &notify_data, p, FALSE);
16787 }
16788 
16789 /*! \brief Send a fake 401 Unauthorized response when the administrator
16790   wants to hide the names of local devices  from fishers
16791  */
16792 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable)
16793 {
16794    /* We have to emulate EXACTLY what we'd get with a good peer
16795     * and a bad password, or else we leak information. */
16796    const char *response = "401 Unauthorized";
16797    const char *reqheader = "Authorization";
16798    const char *respheader = "WWW-Authenticate";
16799    const char *authtoken;
16800    struct ast_str *buf;
16801    char *c;
16802 
16803    /* table of recognised keywords, and their value in the digest */
16804    enum keys { K_NONCE, K_LAST };
16805    struct x {
16806       const char *key;
16807       const char *s;
16808    } *i, keys[] = {
16809       [K_NONCE] = { "nonce=", "" },
16810       [K_LAST] = { NULL, NULL}
16811    };
16812 
16813    authtoken = sip_get_header(req, reqheader);
16814    if (req->ignore && !ast_strlen_zero(p->nonce) && ast_strlen_zero(authtoken)) {
16815       /* This is a retransmitted invite/register/etc, don't reconstruct authentication
16816        * information */
16817       transmit_response_with_auth(p, response, req, p->nonce, reliable, respheader, 0);
16818       /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
16819       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16820       return;
16821    } else if (ast_strlen_zero(p->nonce) || ast_strlen_zero(authtoken)) {
16822       /* We have no auth, so issue challenge and request authentication */
16823       build_nonce(p, 1);
16824       transmit_response_with_auth(p, response, req, p->nonce, reliable, respheader, 0);
16825       /* Schedule auto destroy in 32 seconds */
16826       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16827       return;
16828    }
16829 
16830    if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
16831       __transmit_response(p, "403 Forbidden", &p->initreq, reliable);
16832       return;
16833    }
16834 
16835    /* Make a copy of the response and parse it */
16836    if (ast_str_set(&buf, 0, "%s", authtoken) == AST_DYNSTR_BUILD_FAILED) {
16837       __transmit_response(p, "403 Forbidden", &p->initreq, reliable);
16838       return;
16839    }
16840 
16841    c = buf->str;
16842 
16843    while (c && *(c = ast_skip_blanks(c))) { /* lookup for keys */
16844       for (i = keys; i->key != NULL; i++) {
16845          const char *separator = ",";  /* default */
16846 
16847          if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
16848             continue;
16849          }
16850          /* Found. Skip keyword, take text in quotes or up to the separator. */
16851          c += strlen(i->key);
16852          if (*c == '"') { /* in quotes. Skip first and look for last */
16853             c++;
16854             separator = "\"";
16855          }
16856          i->s = c;
16857          strsep(&c, separator);
16858          break;
16859       }
16860       if (i->key == NULL) { /* not found, jump after space or comma */
16861          strsep(&c, " ,");
16862       }
16863    }
16864 
16865    /* Verify nonce from request matches our nonce.  If not, send 401 with new nonce */
16866    if (strcasecmp(p->nonce, keys[K_NONCE].s)) {
16867       if (!req->ignore) {
16868          build_nonce(p, 1);
16869       }
16870       transmit_response_with_auth(p, response, req, p->nonce, reliable, respheader, FALSE);
16871 
16872       /* Schedule auto destroy in 32 seconds */
16873       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16874    } else {
16875       __transmit_response(p, "403 Forbidden", &p->initreq, reliable);
16876    }
16877 }
16878 
16879 /*!
16880  * Terminate the uri at the first ';' or space.
16881  * Technically we should ignore escaped space per RFC3261 (19.1.1 etc)
16882  * but don't do it for the time being. Remember the uri format is:
16883  * (User-parameters was added after RFC 3261)
16884  *\verbatim
16885  *
16886  * sip:user:password;user-parameters@host:port;uri-parameters?headers
16887  * sips:user:password;user-parameters@host:port;uri-parameters?headers
16888  *
16889  *\endverbatim
16890  * \todo As this function does not support user-parameters, it's considered broken
16891  * and needs fixing.
16892  */
16893 static char *terminate_uri(char *uri)
16894 {
16895    char *t = uri;
16896    while (*t && *t > ' ' && *t != ';') {
16897       t++;
16898    }
16899    *t = '\0';
16900    return uri;
16901 }
16902 
16903 /*! \brief Terminate a host:port at the ':'
16904  * \param hostport The address of the hostport string
16905  *
16906  * \note In the case of a bracket-enclosed IPv6 address, the hostport variable
16907  * will contain the non-bracketed host as a result of calling this function.
16908  */
16909 static void extract_host_from_hostport(char **hostport)
16910 {
16911    char *dont_care;
16912    ast_sockaddr_split_hostport(*hostport, hostport, &dont_care, PARSE_PORT_IGNORE);
16913 }
16914 
16915 /*! \internal \brief Helper function to update a peer's lastmsgssent value
16916  */
16917 static void update_peer_lastmsgssent(struct sip_peer *peer, int value, int locked)
16918 {
16919    if (!locked) {
16920       ao2_lock(peer);
16921    }
16922    peer->lastmsgssent = value;
16923    if (!locked) {
16924       ao2_unlock(peer);
16925    }
16926 }
16927 
16928 
16929 /*! \brief Verify registration of user
16930    - Registration is done in several steps, first a REGISTER without auth
16931      to get a challenge (nonce) then a second one with auth
16932    - Registration requests are only matched with peers that are marked as "dynamic"
16933  */
16934 static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
16935                      struct sip_request *req, const char *uri)
16936 {
16937    enum check_auth_result res = AUTH_NOT_FOUND;
16938    struct sip_peer *peer;
16939    char tmp[256];
16940    char *c, *name, *unused_password, *domain;
16941    char *uri2 = ast_strdupa(uri);
16942    int send_mwi = 0;
16943 
16944    terminate_uri(uri2);
16945 
16946    ast_copy_string(tmp, sip_get_header(req, "To"), sizeof(tmp));
16947 
16948    c = get_in_brackets(tmp);
16949    c = remove_uri_parameters(c);
16950 
16951    if (parse_uri_legacy_check(c, "sip:,sips:", &name, &unused_password, &domain, NULL)) {
16952       ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_sockaddr_stringify_addr(addr));
16953       return -1;
16954    }
16955 
16956    SIP_PEDANTIC_DECODE(name);
16957    SIP_PEDANTIC_DECODE(domain);
16958 
16959    extract_host_from_hostport(&domain);
16960 
16961    if (ast_strlen_zero(domain)) {
16962       /* <sip:name@[EMPTY]>, never good */
16963       transmit_response(p, "404 Not found", &p->initreq);
16964       return AUTH_UNKNOWN_DOMAIN;
16965    }
16966 
16967    if (ast_strlen_zero(name)) {
16968       /* <sip:[EMPTY][@]hostport>, unsure whether valid for
16969        * registration. RFC 3261, 10.2 states:
16970        * "The To header field and the Request-URI field typically
16971        * differ, as the former contains a user name."
16972        * But, Asterisk has always treated the domain-only uri as a
16973        * username: we allow admins to create accounts described by
16974        * domain name. */
16975       name = domain;
16976    }
16977 
16978    /* This here differs from 1.4 and 1.6: the domain matching ACLs were
16979     * skipped if it was a domain-only URI (used as username). Here we treat
16980     * <sip:hostport> as <sip:host@hostport> and won't forget to test the
16981     * domain ACLs against host. */
16982    if (!AST_LIST_EMPTY(&domain_list)) {
16983       if (!check_sip_domain(domain, NULL, 0)) {
16984          if (sip_cfg.alwaysauthreject) {
16985             transmit_fake_auth_response(p, &p->initreq, XMIT_UNRELIABLE);
16986          } else {
16987             transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
16988          }
16989          return AUTH_UNKNOWN_DOMAIN;
16990       }
16991    }
16992 
16993    ast_string_field_set(p, exten, name);
16994    build_contact(p);
16995    if (req->ignore) {
16996       /* Expires is a special case, where we only want to load the peer if this isn't a deregistration attempt */
16997       const char *expires = sip_get_header(req, "Expires");
16998       int expire = atoi(expires);
16999 
17000       if (ast_strlen_zero(expires)) { /* No expires header; look in Contact */
17001          if ((expires = strcasestr(sip_get_header(req, "Contact"), ";expires="))) {
17002             expire = atoi(expires + 9);
17003          }
17004       }
17005       if (!ast_strlen_zero(expires) && expire == 0) {
17006          transmit_response_with_date(p, "200 OK", req);
17007          return 0;
17008       }
17009    }
17010    peer = sip_find_peer(name, NULL, TRUE, FINDPEERS, FALSE, 0);
17011 
17012    /* If we don't want username disclosure, use the bogus_peer when a user
17013     * is not found. */
17014    if (!peer && sip_cfg.alwaysauthreject && sip_cfg.autocreatepeer == AUTOPEERS_DISABLED) {
17015       peer = bogus_peer;
17016       sip_ref_peer(peer, "register_verify: ref the bogus_peer");
17017    }
17018 
17019    if (!(peer && ast_apply_acl(peer->acl, addr, "SIP Peer ACL: "))) {
17020       /* Peer fails ACL check */
17021       if (peer) {
17022          sip_unref_peer(peer, "register_verify: sip_unref_peer: from sip_find_peer operation");
17023          peer = NULL;
17024          res = AUTH_ACL_FAILED;
17025       } else {
17026          res = AUTH_NOT_FOUND;
17027       }
17028    }
17029 
17030    if (peer) {
17031       ao2_lock(peer);
17032       if (!peer->host_dynamic) {
17033          ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
17034          res = AUTH_PEER_NOT_DYNAMIC;
17035       } else {
17036 
17037          set_peer_nat(p, peer);
17038 
17039          ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT_FORCE_RPORT);
17040 
17041          if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri2, XMIT_UNRELIABLE))) {
17042             if (sip_cancel_destroy(p))
17043                ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
17044 
17045             if (check_request_transport(peer, req)) {
17046                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
17047                transmit_response_with_date(p, "403 Forbidden", req);
17048                res = AUTH_BAD_TRANSPORT;
17049             } else {
17050 
17051                /* We have a successful registration attempt with proper authentication,
17052                now, update the peer */
17053                switch (parse_register_contact(p, peer, req)) {
17054                case PARSE_REGISTER_DENIED:
17055                   ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
17056                   transmit_response_with_date(p, "603 Denied", req);
17057                   res = 0;
17058                   break;
17059                case PARSE_REGISTER_FAILED:
17060                   ast_log(LOG_WARNING, "Failed to parse contact info\n");
17061                   transmit_response_with_date(p, "400 Bad Request", req);
17062                   res = 0;
17063                   break;
17064                case PARSE_REGISTER_QUERY:
17065                   ast_string_field_set(p, fullcontact, peer->fullcontact);
17066                   transmit_response_with_date(p, "200 OK", req);
17067                   res = 0;
17068                   send_mwi = 1;
17069                   break;
17070                case PARSE_REGISTER_UPDATE:
17071                   ast_string_field_set(p, fullcontact, peer->fullcontact);
17072                   /* If expiry is 0, peer has been unregistered already */
17073                   if (p->expiry != 0) {
17074                      update_peer(peer, p->expiry);
17075                   }
17076                   /* Say OK and ask subsystem to retransmit msg counter */
17077                   transmit_response_with_date(p, "200 OK", req);
17078                   send_mwi = 1;
17079                   res = 0;
17080                   break;
17081                }
17082             }
17083 
17084          }
17085       }
17086       ao2_unlock(peer);
17087    }
17088    if (!peer && sip_cfg.autocreatepeer != AUTOPEERS_DISABLED) {
17089       /* Create peer if we have autocreate mode enabled */
17090       peer = temp_peer(name);
17091       if (peer) {
17092          ao2_t_link(peers, peer, "link peer into peer table");
17093          if (!ast_sockaddr_isnull(&peer->addr)) {
17094             ao2_t_link(peers_by_ip, peer, "link peer into peers-by-ip table");
17095          }
17096          ao2_lock(peer);
17097          if (sip_cancel_destroy(p))
17098             ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
17099          switch (parse_register_contact(p, peer, req)) {
17100          case PARSE_REGISTER_DENIED:
17101             ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
17102             transmit_response_with_date(p, "403 Forbidden", req);
17103             res = 0;
17104             break;
17105          case PARSE_REGISTER_FAILED:
17106             ast_log(LOG_WARNING, "Failed to parse contact info\n");
17107             transmit_response_with_date(p, "400 Bad Request", req);
17108             res = 0;
17109             break;
17110          case PARSE_REGISTER_QUERY:
17111             ast_string_field_set(p, fullcontact, peer->fullcontact);
17112             transmit_response_with_date(p, "200 OK", req);
17113             send_mwi = 1;
17114             res = 0;
17115             break;
17116          case PARSE_REGISTER_UPDATE:
17117             ast_string_field_set(p, fullcontact, peer->fullcontact);
17118             /* Say OK and ask subsystem to retransmit msg counter */
17119             transmit_response_with_date(p, "200 OK", req);
17120             manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Registered\r\nAddress: %s\r\n", peer->name, ast_sockaddr_stringify(addr));
17121             send_mwi = 1;
17122             res = 0;
17123             break;
17124          }
17125          ao2_unlock(peer);
17126       }
17127    }
17128    if (!res) {
17129       if (send_mwi) {
17130          sip_pvt_unlock(p);
17131          sip_send_mwi_to_peer(peer, 0);
17132          sip_pvt_lock(p);
17133       } else {
17134          update_peer_lastmsgssent(peer, -1, 0);
17135       }
17136       ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", peer->name);
17137    }
17138    if (res < 0) {
17139       switch (res) {
17140       case AUTH_SECRET_FAILED:
17141          /* Wrong password in authentication. Go away, don't try again until you fixed it */
17142          transmit_response(p, "403 Forbidden", &p->initreq);
17143          if (global_authfailureevents) {
17144             const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
17145             const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
17146             manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
17147                      "ChannelType: SIP\r\n"
17148                      "Peer: SIP/%s\r\n"
17149                      "PeerStatus: Rejected\r\n"
17150                      "Cause: AUTH_SECRET_FAILED\r\n"
17151                      "Address: %s\r\n"
17152                      "Port: %s\r\n",
17153                      name, peer_addr, peer_port);
17154          }
17155          break;
17156       case AUTH_USERNAME_MISMATCH:
17157          /* Username and digest username does not match.
17158             Asterisk uses the From: username for authentication. We need the
17159             devices to use the same authentication user name until we support
17160             proper authentication by digest auth name */
17161       case AUTH_NOT_FOUND:
17162       case AUTH_PEER_NOT_DYNAMIC:
17163       case AUTH_ACL_FAILED:
17164          if (sip_cfg.alwaysauthreject) {
17165             transmit_fake_auth_response(p, &p->initreq, XMIT_UNRELIABLE);
17166             if (global_authfailureevents) {
17167                const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
17168                const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
17169                manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
17170                         "ChannelType: SIP\r\n"
17171                         "Peer: SIP/%s\r\n"
17172                         "PeerStatus: Rejected\r\n"
17173                         "Cause: %s\r\n"
17174                         "Address: %s\r\n"
17175                         "Port: %s\r\n",
17176                         name,
17177                         res == AUTH_PEER_NOT_DYNAMIC ? "AUTH_PEER_NOT_DYNAMIC" : "URI_NOT_FOUND",
17178                         peer_addr, peer_port);
17179             }
17180          } else {
17181             /* URI not found */
17182             if (res == AUTH_PEER_NOT_DYNAMIC) {
17183                transmit_response(p, "403 Forbidden", &p->initreq);
17184                if (global_authfailureevents) {
17185                   const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
17186                   const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
17187                   manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
17188                      "ChannelType: SIP\r\n"
17189                      "Peer: SIP/%s\r\n"
17190                      "PeerStatus: Rejected\r\n"
17191                      "Cause: AUTH_PEER_NOT_DYNAMIC\r\n"
17192                      "Address: %s\r\n"
17193                      "Port: %s\r\n",
17194                      name, peer_addr, peer_port);
17195                }
17196             } else {
17197                transmit_response(p, "404 Not found", &p->initreq);
17198                if (global_authfailureevents) {
17199                   const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
17200                   const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
17201                   manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
17202                      "ChannelType: SIP\r\n"
17203                      "Peer: SIP/%s\r\n"
17204                      "PeerStatus: Rejected\r\n"
17205                      "Cause: %s\r\n"
17206                      "Address: %s\r\n"
17207                      "Port: %s\r\n",
17208                      name,
17209                      (res == AUTH_USERNAME_MISMATCH) ? "AUTH_USERNAME_MISMATCH" : "URI_NOT_FOUND",
17210                      peer_addr, peer_port);
17211                }
17212             }
17213          }
17214          break;
17215       case AUTH_BAD_TRANSPORT:
17216       default:
17217          break;
17218       }
17219    }
17220    if (peer) {
17221       sip_unref_peer(peer, "register_verify: sip_unref_peer: tossing stack peer pointer at end of func");
17222    }
17223 
17224    return res;
17225 }
17226 
17227 /*! \brief Translate referring cause */
17228 static void sip_set_redirstr(struct sip_pvt *p, char *reason) {
17229 
17230    if (!strcmp(reason, "unknown")) {
17231       ast_string_field_set(p, redircause, "UNKNOWN");
17232    } else if (!strcmp(reason, "user-busy")) {
17233       ast_string_field_set(p, redircause, "BUSY");
17234    } else if (!strcmp(reason, "no-answer")) {
17235       ast_string_field_set(p, redircause, "NOANSWER");
17236    } else if (!strcmp(reason, "unavailable")) {
17237       ast_string_field_set(p, redircause, "UNREACHABLE");
17238    } else if (!strcmp(reason, "unconditional")) {
17239       ast_string_field_set(p, redircause, "UNCONDITIONAL");
17240    } else if (!strcmp(reason, "time-of-day")) {
17241       ast_string_field_set(p, redircause, "UNKNOWN");
17242    } else if (!strcmp(reason, "do-not-disturb")) {
17243       ast_string_field_set(p, redircause, "UNKNOWN");
17244    } else if (!strcmp(reason, "deflection")) {
17245       ast_string_field_set(p, redircause, "UNKNOWN");
17246    } else if (!strcmp(reason, "follow-me")) {
17247       ast_string_field_set(p, redircause, "UNKNOWN");
17248    } else if (!strcmp(reason, "out-of-service")) {
17249       ast_string_field_set(p, redircause, "UNREACHABLE");
17250    } else if (!strcmp(reason, "away")) {
17251       ast_string_field_set(p, redircause, "UNREACHABLE");
17252    } else {
17253       ast_string_field_set(p, redircause, "UNKNOWN");
17254    }
17255 }
17256 
17257 /*! \brief Parse the parts of the P-Asserted-Identity header
17258  * on an incoming packet. Returns 1 if a valid header is found
17259  * and it is different from the current caller id.
17260  */
17261 static int get_pai(struct sip_pvt *p, struct sip_request *req)
17262 {
17263    char pai[256];
17264    char privacy[64];
17265    char *cid_num = NULL;
17266    char *cid_name = NULL;
17267    char emptyname[1] = "";
17268    int callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
17269    char *uri = NULL;
17270    int is_anonymous = 0, do_update = 1, no_name = 0;
17271 
17272    ast_copy_string(pai, sip_get_header(req, "P-Asserted-Identity"), sizeof(pai));
17273 
17274    if (ast_strlen_zero(pai)) {
17275       return 0;
17276    }
17277 
17278    /* use the reqresp_parser function get_name_and_number*/
17279    if (get_name_and_number(pai, &cid_name, &cid_num)) {
17280       return 0;
17281    }
17282 
17283    if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(cid_num)) {
17284       ast_shrink_phone_number(cid_num);
17285    }
17286 
17287    uri = get_in_brackets(pai);
17288    if (!strncasecmp(uri, "sip:anonymous@anonymous.invalid", 31)) {
17289       callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
17290       /*XXX Assume no change in cid_num. Perhaps it should be
17291        * blanked?
17292        */
17293       ast_free(cid_num);
17294       is_anonymous = 1;
17295       cid_num = (char *)p->cid_num;
17296    }
17297 
17298    ast_copy_string(privacy, sip_get_header(req, "Privacy"), sizeof(privacy));
17299    if (!ast_strlen_zero(privacy) && !strncmp(privacy, "id", 2)) {
17300       callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
17301    }
17302    if (!cid_name) {
17303       no_name = 1;
17304       cid_name = (char *)emptyname;
17305    }  
17306    /* Only return true if the supplied caller id is different */
17307    if (!strcasecmp(p->cid_num, cid_num) && !strcasecmp(p->cid_name, cid_name) && p->callingpres == callingpres) {
17308       do_update = 0;
17309    } else {
17310 
17311       ast_string_field_set(p, cid_num, cid_num);
17312       ast_string_field_set(p, cid_name, cid_name);
17313       p->callingpres = callingpres;
17314 
17315       if (p->owner) {
17316          ast_set_callerid(p->owner, cid_num, cid_name, NULL);
17317          ast_channel_caller(p->owner)->id.name.presentation = callingpres;
17318          ast_channel_caller(p->owner)->id.number.presentation = callingpres;
17319       }
17320    }
17321 
17322    /* get_name_and_number allocates memory for cid_num and cid_name so we have to free it */
17323    if (!is_anonymous) {
17324       ast_free(cid_num);
17325    }
17326    if (!no_name) {
17327       ast_free(cid_name);
17328    }
17329 
17330    return do_update;
17331 }
17332 
17333 /*! \brief Get name, number and presentation from remote party id header,
17334  *  returns true if a valid header was found and it was different from the
17335  *  current caller id.
17336  */
17337 static int get_rpid(struct sip_pvt *p, struct sip_request *oreq)
17338 {
17339    char tmp[256];
17340    struct sip_request *req;
17341    char *cid_num = "";
17342    char *cid_name = "";
17343    int callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
17344    char *privacy = "";
17345    char *screen = "";
17346    char *start, *end;
17347 
17348    if (!ast_test_flag(&p->flags[0], SIP_TRUSTRPID))
17349       return 0;
17350    req = oreq;
17351    if (!req)
17352       req = &p->initreq;
17353    ast_copy_string(tmp, sip_get_header(req, "Remote-Party-ID"), sizeof(tmp));
17354    if (ast_strlen_zero(tmp)) {
17355       return get_pai(p, req);
17356    }
17357 
17358    /*
17359     * RPID is not:
17360     *   rpid = (name-addr / addr-spec) *(SEMI rpi-token)
17361     * But it is:
17362     *   rpid = [display-name] LAQUOT addr-spec RAQUOT *(SEMI rpi-token)
17363     * Ergo, calling parse_name_andor_addr() on it wouldn't be
17364     * correct because that would allow addr-spec style too.
17365     */
17366    start = tmp;
17367    /* Quoted (note that we're not dealing with escapes properly) */
17368    if (*start == '"') {
17369       *start++ = '\0';
17370       end = strchr(start, '"');
17371       if (!end)
17372          return 0;
17373       *end++ = '\0';
17374       cid_name = start;
17375       start = ast_skip_blanks(end);
17376    /* Unquoted */
17377    } else {
17378       cid_name = start;
17379       start = end = strchr(start, '<');
17380       if (!start) {
17381          return 0;
17382       }
17383       /* trim blanks if there are any. the mandatory NUL is done below */
17384       while (--end >= cid_name && *end < 33) {
17385          *end = '\0';
17386       }
17387    }
17388 
17389    if (*start != '<')
17390       return 0;
17391    *start++ = '\0';
17392    end = strchr(start, '@');
17393    if (!end)
17394       return 0;
17395    *end++ = '\0';
17396    if (strncasecmp(start, "sip:", 4))
17397       return 0;
17398    cid_num = start + 4;
17399    if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(cid_num))
17400       ast_shrink_phone_number(cid_num);
17401    start = end;
17402 
17403    end = strchr(start, '>');
17404    if (!end)
17405       return 0;
17406    *end++ = '\0';
17407    if (*end) {
17408       start = end;
17409       if (*start != ';')
17410          return 0;
17411       *start++ = '\0';
17412       while (!ast_strlen_zero(start)) {
17413          end = strchr(start, ';');
17414          if (end)
17415             *end++ = '\0';
17416          if (!strncasecmp(start, "privacy=", 8))
17417             privacy = start + 8;
17418          else if (!strncasecmp(start, "screen=", 7))
17419             screen = start + 7;
17420          start = end;
17421       }
17422 
17423       if (!strcasecmp(privacy, "full")) {
17424          if (!strcasecmp(screen, "yes"))
17425             callingpres = AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN;
17426          else if (!strcasecmp(screen, "no"))
17427             callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
17428       } else {
17429          if (!strcasecmp(screen, "yes"))
17430             callingpres = AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
17431          else if (!strcasecmp(screen, "no"))
17432             callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
17433       }
17434    }
17435 
17436    /* Only return true if the supplied caller id is different */
17437    if (!strcasecmp(p->cid_num, cid_num) && !strcasecmp(p->cid_name, cid_name) && p->callingpres == callingpres)
17438       return 0;
17439 
17440    ast_string_field_set(p, cid_num, cid_num);
17441    ast_string_field_set(p, cid_name, cid_name);
17442    p->callingpres = callingpres;
17443 
17444    if (p->owner) {
17445       ast_set_callerid(p->owner, cid_num, cid_name, NULL);
17446       ast_channel_caller(p->owner)->id.name.presentation = callingpres;
17447       ast_channel_caller(p->owner)->id.number.presentation = callingpres;
17448    }
17449 
17450    return 1;
17451 }
17452 
17453 /*! \brief Get referring dnis */
17454 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason)
17455 {
17456    char tmp[256], *exten, *rexten, *rdomain, *rname = NULL;
17457    char *params, *reason_param = NULL;
17458    struct sip_request *req;
17459 
17460    req = oreq ? oreq : &p->initreq;
17461 
17462    ast_copy_string(tmp, sip_get_header(req, "Diversion"), sizeof(tmp));
17463    if (ast_strlen_zero(tmp))
17464       return -1;
17465 
17466    if ((params = strchr(tmp, '>'))) {
17467       params = strchr(params, ';');
17468    }
17469 
17470    exten = get_in_brackets(tmp);
17471    if (!strncasecmp(exten, "sip:", 4)) {
17472       exten += 4;
17473    } else if (!strncasecmp(exten, "sips:", 5)) {
17474       exten += 5;
17475    } else {
17476       ast_log(LOG_WARNING, "Huh?  Not an RDNIS SIP header (%s)?\n", exten);
17477       return -1;
17478    }
17479 
17480    /* Get diversion-reason param if present */
17481    if (params) {
17482       *params = '\0';   /* Cut off parameters  */
17483       params++;
17484       while (*params == ';' || *params == ' ')
17485          params++;
17486       /* Check if we have a reason parameter */
17487       if ((reason_param = strcasestr(params, "reason="))) {
17488          char *end;
17489          reason_param+=7;
17490          if ((end = strchr(reason_param, ';'))) {
17491             *end = '\0';
17492          }
17493          /* Remove enclosing double-quotes */
17494          if (*reason_param == '"')
17495             reason_param = ast_strip_quoted(reason_param, "\"", "\"");
17496          if (!ast_strlen_zero(reason_param)) {
17497             sip_set_redirstr(p, reason_param);
17498             if (p->owner) {
17499                pbx_builtin_setvar_helper(p->owner, "__PRIREDIRECTREASON", p->redircause);
17500                pbx_builtin_setvar_helper(p->owner, "__SIPREDIRECTREASON", reason_param);
17501             }
17502          }
17503       }
17504    }
17505 
17506    rdomain = exten;
17507    rexten = strsep(&rdomain, "@");  /* trim anything after @ */
17508    if (p->owner)
17509       pbx_builtin_setvar_helper(p->owner, "__SIPRDNISDOMAIN", rdomain);
17510 
17511    if (sip_debug_test_pvt(p))
17512       ast_verbose("RDNIS for this call is %s (reason %s)\n", exten, S_OR(reason_param, ""));
17513 
17514    /*ast_string_field_set(p, rdnis, rexten);*/
17515 
17516    if (*tmp == '\"') {
17517       char *end_quote;
17518       rname = tmp + 1;
17519       end_quote = strchr(rname, '\"');
17520       if (end_quote) {
17521          *end_quote = '\0';
17522       }
17523    }
17524 
17525    if (number) {
17526       *number = ast_strdup(rexten);
17527    }
17528 
17529    if (name && rname) {
17530       *name = ast_strdup(rname);
17531    }
17532 
17533    if (reason && !ast_strlen_zero(reason_param)) {
17534       *reason = sip_reason_str_to_code(reason_param);
17535    }
17536 
17537    return 0;
17538 }
17539 
17540 /*!
17541  * \brief Find out who the call is for.
17542  *
17543  * \details
17544  * We use the request uri as a destination.
17545  * This code assumes authentication has been done, so that the
17546  * device (peer/user) context is already set.
17547  *
17548  * \return 0 on success (found a matching extension), non-zero on failure
17549  *
17550  * \note If the incoming uri is a SIPS: uri, we are required to carry this across
17551  * the dialplan, so that the outbound call also is a sips: call or encrypted
17552  * IAX2 call. If that's not available, the call should FAIL.
17553  */
17554 static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id)
17555 {
17556    char tmp[256] = "", *uri, *unused_password, *domain;
17557    RAII_VAR(char *, tmpf, NULL, ast_free);
17558    char *from = NULL;
17559    struct sip_request *req;
17560    char *decoded_uri;
17561 
17562    req = oreq;
17563    if (!req) {
17564       req = &p->initreq;
17565    }
17566 
17567    /* Find the request URI */
17568    if (req->rlpart2) {
17569       ast_copy_string(tmp, REQ_OFFSET_TO_STR(req, rlpart2), sizeof(tmp));
17570    }
17571 
17572    uri = ast_strdupa(get_in_brackets(tmp));
17573 
17574    if (parse_uri_legacy_check(uri, "sip:,sips:", &uri, &unused_password, &domain, NULL)) {
17575       ast_log(LOG_WARNING, "Not a SIP header (%s)?\n", uri);
17576       return SIP_GET_DEST_INVALID_URI;
17577    }
17578 
17579    SIP_PEDANTIC_DECODE(domain);
17580    SIP_PEDANTIC_DECODE(uri);
17581 
17582    extract_host_from_hostport(&domain);
17583 
17584    if (ast_strlen_zero(uri)) {
17585       /*
17586        * Either there really was no extension found or the request
17587        * URI had encoded nulls that made the string "empty".  Use "s"
17588        * as the extension.
17589        */
17590       uri = "s";
17591    }
17592 
17593    ast_string_field_set(p, domain, domain);
17594 
17595    /* Now find the From: caller ID and name */
17596    /* XXX Why is this done in get_destination? Isn't it already done?
17597       Needs to be checked
17598         */
17599    tmpf = ast_strdup(sip_get_header(req, "From"));
17600    if (!ast_strlen_zero(tmpf)) {
17601       from = get_in_brackets(tmpf);
17602       if (parse_uri_legacy_check(from, "sip:,sips:", &from, NULL, &domain, NULL)) {
17603          ast_log(LOG_WARNING, "Not a SIP header (%s)?\n", from);
17604          return SIP_GET_DEST_INVALID_URI;
17605       }
17606 
17607       SIP_PEDANTIC_DECODE(from);
17608       SIP_PEDANTIC_DECODE(domain);
17609 
17610       extract_host_from_hostport(&domain);
17611 
17612       ast_string_field_set(p, fromdomain, domain);
17613    }
17614 
17615    if (!AST_LIST_EMPTY(&domain_list)) {
17616       char domain_context[AST_MAX_EXTENSION];
17617 
17618       domain_context[0] = '\0';
17619       if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
17620          if (!sip_cfg.allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
17621             ast_debug(1, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
17622             return SIP_GET_DEST_REFUSED;
17623          }
17624       }
17625       /* If we don't have a peer (i.e. we're a guest call),
17626        * overwrite the original context */
17627       if (!ast_test_flag(&p->flags[1], SIP_PAGE2_HAVEPEERCONTEXT) && !ast_strlen_zero(domain_context)) {
17628          ast_string_field_set(p, context, domain_context);
17629       }
17630    }
17631 
17632    /* If the request coming in is a subscription and subscribecontext has been specified use it */
17633    if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext)) {
17634       ast_string_field_set(p, context, p->subscribecontext);
17635    }
17636 
17637    if (sip_debug_test_pvt(p)) {
17638       ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
17639    }
17640 
17641    /* Since extensions.conf can have unescaped characters, try matching a
17642     * decoded uri in addition to the non-decoded uri. */
17643    decoded_uri = ast_strdupa(uri);
17644    ast_uri_decode(decoded_uri, ast_uri_sip_user);
17645 
17646    /* If this is a subscription we actually just need to see if a hint exists for the extension */
17647    if (req->method == SIP_SUBSCRIBE) {
17648       char hint[AST_MAX_EXTENSION];
17649       int which = 0;
17650       if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, uri) ||
17651           (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, decoded_uri) && (which = 1))) {
17652          if (!oreq) {
17653             ast_string_field_set(p, exten, which ? decoded_uri : uri);
17654          }
17655          return SIP_GET_DEST_EXTEN_FOUND;
17656       } else {
17657          return SIP_GET_DEST_EXTEN_NOT_FOUND;
17658       }
17659    } else {
17660       struct ast_cc_agent *agent;
17661       /* Check the dialplan for the username part of the request URI,
17662          the domain will be stored in the SIPDOMAIN variable
17663          Return 0 if we have a matching extension */
17664       if (ast_exists_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from))) {
17665          if (!oreq) {
17666             ast_string_field_set(p, exten, uri);
17667          }
17668          return SIP_GET_DEST_EXTEN_FOUND;
17669       }
17670       if (ast_exists_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))
17671          || !strcmp(decoded_uri, ast_pickup_ext())) {
17672          if (!oreq) {
17673             ast_string_field_set(p, exten, decoded_uri);
17674          }
17675          return SIP_GET_DEST_EXTEN_FOUND;
17676       }
17677       if ((agent = find_sip_cc_agent_by_notify_uri(tmp))) {
17678          struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
17679          /* This is a CC recall. We can set p's extension to the exten from
17680           * the original INVITE
17681           */
17682          ast_string_field_set(p, exten, agent_pvt->original_exten);
17683          /* And we need to let the CC core know that the caller is attempting
17684           * his recall
17685           */
17686          ast_cc_agent_recalling(agent->core_id, "SIP caller %s is attempting recall",
17687                agent->device_name);
17688          if (cc_recall_core_id) {
17689             *cc_recall_core_id = agent->core_id;
17690          }
17691          ao2_ref(agent, -1);
17692          return SIP_GET_DEST_EXTEN_FOUND;
17693       }
17694    }
17695 
17696    if (ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)
17697       && (ast_canmatch_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from))
17698          || ast_canmatch_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))
17699          || !strncmp(decoded_uri, ast_pickup_ext(), strlen(decoded_uri)))) {
17700       /* Overlap dialing is enabled and we need more digits to match an extension. */
17701       return SIP_GET_DEST_EXTEN_MATCHMORE;
17702    }
17703 
17704    return SIP_GET_DEST_EXTEN_NOT_FOUND;
17705 }
17706 
17707 /*! \brief Lock dialog lock and find matching pvt lock
17708    \return a reference, remember to release it when done
17709 */
17710 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag)
17711 {
17712    struct sip_pvt *sip_pvt_ptr;
17713    struct sip_pvt tmp_dialog = {
17714       .callid = callid,
17715    };
17716 
17717    if (totag) {
17718       ast_debug(4, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
17719    }
17720 
17721    /* Search dialogs and find the match */
17722 
17723    sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find of dialog in dialogs table");
17724    if (sip_pvt_ptr) {
17725       /* Go ahead and lock it (and its owner) before returning */
17726       sip_pvt_lock(sip_pvt_ptr);
17727       if (sip_cfg.pedanticsipchecking) {
17728          unsigned char frommismatch = 0, tomismatch = 0;
17729 
17730          if (ast_strlen_zero(fromtag)) {
17731             sip_pvt_unlock(sip_pvt_ptr);
17732             ast_debug(4, "Matched %s call for callid=%s - no from tag specified, pedantic check fails\n",
17733                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
17734             return NULL;
17735          }
17736 
17737          if (ast_strlen_zero(totag)) {
17738             sip_pvt_unlock(sip_pvt_ptr);
17739             ast_debug(4, "Matched %s call for callid=%s - no to tag specified, pedantic check fails\n",
17740                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
17741             return NULL;
17742          }
17743          /* RFC 3891
17744           * > 3.  User Agent Server Behavior: Receiving a Replaces Header
17745           * > The Replaces header contains information used to match an existing
17746           * > SIP dialog (call-id, to-tag, and from-tag).  Upon receiving an INVITE
17747           * > with a Replaces header, the User Agent (UA) attempts to match this
17748           * > information with a confirmed or early dialog.  The User Agent Server
17749           * > (UAS) matches the to-tag and from-tag parameters as if they were tags
17750           * > present in an incoming request.  In other words, the to-tag parameter
17751           * > is compared to the local tag, and the from-tag parameter is compared
17752           * > to the remote tag.
17753           *
17754           * Thus, the totag is always compared to the local tag, regardless if
17755           * this our call is an incoming or outgoing call.
17756           */
17757          frommismatch = !!strcmp(fromtag, sip_pvt_ptr->theirtag);
17758          tomismatch = !!strcmp(totag, sip_pvt_ptr->tag);
17759 
17760                         /* Don't check from if the dialog is not established, due to multi forking the from
17761                          * can change when the call is not answered yet.
17762                          */
17763          if ((frommismatch && ast_test_flag(&sip_pvt_ptr->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) || tomismatch) {
17764             sip_pvt_unlock(sip_pvt_ptr);
17765             if (frommismatch) {
17766                ast_debug(4, "Matched %s call for callid=%s - pedantic from tag check fails; their tag is %s our tag is %s\n",
17767                     sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
17768                     fromtag, sip_pvt_ptr->theirtag);
17769             }
17770             if (tomismatch) {
17771                ast_debug(4, "Matched %s call for callid=%s - pedantic to tag check fails; their tag is %s our tag is %s\n",
17772                     sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
17773                     totag, sip_pvt_ptr->tag);
17774             }
17775             return NULL;
17776          }
17777       }
17778 
17779       if (totag)
17780          ast_debug(4, "Matched %s call - their tag is %s Our tag is %s\n",
17781                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING",
17782                  sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
17783 
17784       /* deadlock avoidance... */
17785       while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
17786          sip_pvt_unlock(sip_pvt_ptr);
17787          usleep(1);
17788          sip_pvt_lock(sip_pvt_ptr);
17789       }
17790    }
17791    
17792    return sip_pvt_ptr;
17793 }
17794 
17795 /*! \brief Call transfer support (the REFER method)
17796  *    Extracts Refer headers into pvt dialog structure
17797  *
17798  * \note If we get a SIPS uri in the refer-to header, we're required to set up a secure signalling path
17799  * to that extension. As a minimum, this needs to be added to a channel variable, if not a channel
17800  * flag.
17801  */
17802 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
17803 {
17804    const char *p_referred_by = NULL;
17805    char *h_refer_to = NULL;
17806    char *h_referred_by = NULL;
17807    char *refer_to;
17808    const char *p_refer_to;
17809    char *referred_by_uri = NULL;
17810    char *ptr;
17811    struct sip_request *req = NULL;
17812    const char *transfer_context = NULL;
17813    struct sip_refer *refer;
17814 
17815    req = outgoing_req;
17816    refer = transferer->refer;
17817 
17818    if (!req) {
17819       req = &transferer->initreq;
17820    }
17821 
17822    p_refer_to = sip_get_header(req, "Refer-To");
17823    if (ast_strlen_zero(p_refer_to)) {
17824       ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
17825       return -2;  /* Syntax error */
17826    }
17827    h_refer_to = ast_strdupa(p_refer_to);
17828    refer_to = get_in_brackets(h_refer_to);
17829    if (!strncasecmp(refer_to, "sip:", 4)) {
17830       refer_to += 4;       /* Skip sip: */
17831    } else if (!strncasecmp(refer_to, "sips:", 5)) {
17832       refer_to += 5;
17833    } else {
17834       ast_log(LOG_WARNING, "Can't transfer to non-sip: URI.  (Refer-to: %s)?\n", refer_to);
17835       return -3;
17836    }
17837 
17838    /* Get referred by header if it exists */
17839    p_referred_by = sip_get_header(req, "Referred-By");
17840 
17841    /* Give useful transfer information to the dialplan */
17842    if (transferer->owner) {
17843       struct ast_channel *peer = ast_bridged_channel(transferer->owner);
17844       if (peer) {
17845          pbx_builtin_setvar_helper(peer, "SIPREFERRINGCONTEXT", transferer->context);
17846          pbx_builtin_setvar_helper(peer, "SIPREFERREDBYHDR", p_referred_by);
17847       }
17848    }
17849 
17850    if (!ast_strlen_zero(p_referred_by)) {
17851       h_referred_by = ast_strdupa(p_referred_by);
17852 
17853       referred_by_uri = get_in_brackets(h_referred_by);
17854 
17855       if (!strncasecmp(referred_by_uri, "sip:", 4)) {
17856          referred_by_uri += 4;      /* Skip sip: */
17857       } else if (!strncasecmp(referred_by_uri, "sips:", 5)) {
17858          referred_by_uri += 5;      /* Skip sips: */
17859       } else {
17860          ast_log(LOG_WARNING, "Huh?  Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
17861          referred_by_uri = NULL;
17862       }
17863    }
17864 
17865    /* Check for arguments in the refer_to header */
17866    if ((ptr = strcasestr(refer_to, "replaces="))) {
17867       char *to = NULL, *from = NULL, *callid;
17868 
17869       /* This is an attended transfer */
17870       refer->attendedtransfer = 1;
17871 
17872       callid = ast_strdupa(ptr + 9);
17873       ast_uri_decode(callid, ast_uri_sip_user);
17874       if ((ptr = strchr(callid, ';'))) { /* Find options */
17875          *ptr++ = '\0';
17876       }
17877       ast_string_field_set(refer, replaces_callid, callid);
17878 
17879       if (ptr) {
17880          /* Find the different tags before we destroy the string */
17881          to = strcasestr(ptr, "to-tag=");
17882          from = strcasestr(ptr, "from-tag=");
17883       }
17884       
17885       /* Grab the to header */
17886       if (to) {
17887          ptr = to + 7;
17888          if ((to = strchr(ptr, '&'))) {
17889             *to = '\0';
17890          }
17891          if ((to = strchr(ptr, ';'))) {
17892             *to = '\0';
17893          }
17894          ast_string_field_set(refer, replaces_callid_totag, ptr);
17895       }
17896 
17897       if (from) {
17898          ptr = from + 9;
17899          if ((from = strchr(ptr, '&'))) {
17900             *from = '\0';
17901          }
17902          if ((from = strchr(ptr, ';'))) {
17903             *from = '\0';
17904          }
17905          ast_string_field_set(refer, replaces_callid_fromtag, ptr);
17906       }
17907 
17908       if (!strcmp(refer->replaces_callid, transferer->callid) &&
17909          (!sip_cfg.pedanticsipchecking ||
17910          (!strcmp(refer->replaces_callid_fromtag, transferer->theirtag) &&
17911          !strcmp(refer->replaces_callid_totag, transferer->tag)))) {
17912             ast_log(LOG_WARNING, "Got an attempt to replace own Call-ID on %s\n", transferer->callid);
17913             return -4;
17914       }
17915 
17916       if (!sip_cfg.pedanticsipchecking) {
17917          ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", refer->replaces_callid);
17918       } else {
17919          ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s F-tag: %s T-tag: %s\n", refer->replaces_callid, refer->replaces_callid_fromtag ? refer->replaces_callid_fromtag : "<none>", refer->replaces_callid_totag ? refer->replaces_callid_totag : "<none>");
17920       }
17921    }
17922 
17923    if ((ptr = strchr(refer_to, '@'))) {   /* Separate domain */
17924       char *urioption = NULL, *domain;
17925       int bracket = 0;
17926       *ptr++ = '\0';
17927 
17928       if ((urioption = strchr(ptr, ';'))) { /* Separate urioptions */
17929          *urioption++ = '\0';
17930       }
17931 
17932       domain = ptr;
17933 
17934       /* Remove :port */
17935       for (; *ptr != '\0'; ++ptr) {
17936          if (*ptr == ':' && bracket == 0) {
17937             *ptr = '\0';
17938             break;
17939          } else if (*ptr == '[') {
17940             ++bracket;
17941          } else if (*ptr == ']') {
17942             --bracket;
17943          }
17944       }
17945 
17946       SIP_PEDANTIC_DECODE(domain);
17947       SIP_PEDANTIC_DECODE(urioption);
17948 
17949       /* Save the domain for the dial plan */
17950       ast_string_field_set(refer, refer_to_domain, domain);
17951       if (urioption) {
17952          ast_string_field_set(refer, refer_to_urioption, urioption);
17953       }
17954    }
17955 
17956    if ((ptr = strchr(refer_to, ';'))) /* Remove options */
17957       *ptr = '\0';
17958 
17959    SIP_PEDANTIC_DECODE(refer_to);
17960    ast_string_field_set(refer, refer_to, refer_to);
17961 
17962    if (referred_by_uri) {
17963       if ((ptr = strchr(referred_by_uri, ';'))) /* Remove options */
17964          *ptr = '\0';
17965       SIP_PEDANTIC_DECODE(referred_by_uri);
17966       ast_string_field_build(refer, referred_by, "<sip:%s>", referred_by_uri);
17967    } else {
17968       ast_string_field_set(refer, referred_by, "");
17969    }
17970 
17971    /* Determine transfer context */
17972    if (transferer->owner) {
17973       /* By default, use the context in the channel sending the REFER */
17974       transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
17975       if (ast_strlen_zero(transfer_context)) {
17976          transfer_context = ast_channel_macrocontext(transferer->owner);
17977       }
17978    }
17979    if (ast_strlen_zero(transfer_context)) {
17980       transfer_context = S_OR(transferer->context, sip_cfg.default_context);
17981    }
17982 
17983    ast_string_field_set(refer, refer_to_context, transfer_context);
17984 
17985    /* Either an existing extension or the parking extension */
17986    if (refer->attendedtransfer || ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL)) {
17987       if (sip_debug_test_pvt(transferer)) {
17988          ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
17989       }
17990       /* We are ready to transfer to the extension */
17991       return 0;
17992    }
17993    if (sip_debug_test_pvt(transferer))
17994       ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
17995 
17996    /* Failure, we can't find this extension */
17997    return -1;
17998 }
17999 
18000 
18001 /*! \brief Call transfer support (old way, deprecated by the IETF)
18002  * \note does not account for SIPS: uri requirements, nor check transport
18003  */
18004 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
18005 {
18006    char tmp[256] = "", *c, *a;
18007    struct sip_request *req = oreq ? oreq : &p->initreq;
18008    struct sip_refer *refer = NULL;
18009    const char *transfer_context = NULL;
18010 
18011    if (!p->refer && !sip_refer_alloc(p))
18012       return -1;
18013 
18014    refer = p->refer;
18015 
18016    ast_copy_string(tmp, sip_get_header(req, "Also"), sizeof(tmp));
18017    c = get_in_brackets(tmp);
18018 
18019    if (parse_uri_legacy_check(c, "sip:,sips:", &c, NULL, &a, NULL)) {
18020       ast_log(LOG_WARNING, "Huh?  Not a SIP header in Also: transfer (%s)?\n", c);
18021       return -1;
18022    }
18023 
18024    SIP_PEDANTIC_DECODE(c);
18025    SIP_PEDANTIC_DECODE(a);
18026 
18027    if (!ast_strlen_zero(a)) {
18028       ast_string_field_set(refer, refer_to_domain, a);
18029    }
18030 
18031    if (sip_debug_test_pvt(p))
18032       ast_verbose("Looking for %s in %s\n", c, p->context);
18033 
18034    /* Determine transfer context */
18035    if (p->owner) {
18036       /* By default, use the context in the channel sending the REFER */
18037       transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
18038       if (ast_strlen_zero(transfer_context)) {
18039          transfer_context = ast_channel_macrocontext(p->owner);
18040       }
18041    }
18042    if (ast_strlen_zero(transfer_context)) {
18043       transfer_context = S_OR(p->context, sip_cfg.default_context);
18044    }
18045 
18046    if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
18047       /* This is a blind transfer */
18048       ast_debug(1, "SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
18049       ast_string_field_set(refer, refer_to, c);
18050       ast_string_field_set(refer, referred_by, "");
18051       ast_string_field_set(refer, refer_contact, "");
18052       /* Set new context */
18053       ast_string_field_set(p, context, transfer_context);
18054       return 0;
18055    } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
18056       return 1;
18057    }
18058 
18059    return -1;
18060 }
18061 
18062 /*! \brief Set the peers nat flags if they are using auto_* settings */
18063 static void set_peer_nat(const struct sip_pvt *p, struct sip_peer *peer)
18064 {
18065 
18066    if (!p || !peer) {
18067       return;
18068    }
18069 
18070    if (ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_RPORT)) {
18071       if (p->natdetected) {
18072          ast_set_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT);
18073       } else {
18074          ast_clear_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT);
18075       }
18076    }
18077 
18078    if (ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_COMEDIA)) {
18079       if (p->natdetected) {
18080          ast_set_flag(&peer->flags[1], SIP_PAGE2_SYMMETRICRTP);
18081       } else {
18082          ast_clear_flag(&peer->flags[1], SIP_PAGE2_SYMMETRICRTP);
18083       }
18084    }
18085 }
18086 
18087 /*! \brief Check and see if the requesting UA is likely to be behind a NAT.
18088  *
18089  * If the requesting NAT is behind NAT, set the * natdetected flag so that
18090  * later, peers with nat=auto_* can use the value. Also, set the flags so
18091  * that Asterisk responds identically whether or not a peer exists so as
18092  * not to leak peer name information.
18093  */
18094 static void check_for_nat(const struct ast_sockaddr *addr, struct sip_pvt *p)
18095 {
18096 
18097    if (!addr || !p) {
18098       return;
18099    }
18100 
18101    if (ast_sockaddr_cmp_addr(addr, &p->recv)) {
18102       char *tmp_str = ast_strdupa(ast_sockaddr_stringify_addr(addr));
18103       ast_debug(3, "NAT detected for %s / %s\n", tmp_str, ast_sockaddr_stringify_addr(&p->recv));
18104       p->natdetected = 1;
18105       if (ast_test_flag(&p->flags[2], SIP_PAGE3_NAT_AUTO_RPORT)) {
18106          ast_set_flag(&p->flags[0], SIP_NAT_FORCE_RPORT);
18107       }
18108       if (ast_test_flag(&p->flags[2], SIP_PAGE3_NAT_AUTO_COMEDIA)) {
18109          ast_set_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
18110       }
18111    } else {
18112       p->natdetected = 0;
18113       if (ast_test_flag(&p->flags[2], SIP_PAGE3_NAT_AUTO_RPORT)) {
18114          ast_clear_flag(&p->flags[0], SIP_NAT_FORCE_RPORT);
18115       }
18116       if (ast_test_flag(&p->flags[2], SIP_PAGE3_NAT_AUTO_COMEDIA)) {
18117          ast_clear_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
18118       }
18119    }
18120 
18121 }
18122 
18123 /*! \brief check Via: header for hostname, port and rport request/answer */
18124 static void check_via(struct sip_pvt *p, const struct sip_request *req)
18125 {
18126    char via[512];
18127    char *c, *maddr;
18128    struct ast_sockaddr tmp = { { 0, } };
18129    uint16_t port;
18130 
18131    ast_copy_string(via, sip_get_header(req, "Via"), sizeof(via));
18132 
18133    /* If this is via WebSocket we don't use the Via header contents at all */
18134    if (!strncasecmp(via, "SIP/2.0/WS", 10)) {
18135       return;
18136    }
18137 
18138    /* Work on the leftmost value of the topmost Via header */
18139    c = strchr(via, ',');
18140    if (c)
18141       *c = '\0';
18142 
18143    /* Check for rport */
18144    c = strstr(via, ";rport");
18145    if (c && (c[6] != '=')) { /* rport query, not answer */
18146       ast_set_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT);
18147       ast_set_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT);
18148    }
18149 
18150    /* Check for maddr */
18151    maddr = strstr(via, "maddr=");
18152    if (maddr) {
18153       maddr += 6;
18154       c = maddr + strspn(maddr, "abcdefghijklmnopqrstuvwxyz"
18155                       "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-.:[]");
18156       *c = '\0';
18157    }
18158 
18159    c = strchr(via, ';');
18160    if (c)
18161       *c = '\0';
18162 
18163    c = strchr(via, ' ');
18164    if (c) {
18165       *c = '\0';
18166       c = ast_skip_blanks(c+1);
18167       if (strcasecmp(via, "SIP/2.0/UDP") && strcasecmp(via, "SIP/2.0/TCP") && strcasecmp(via, "SIP/2.0/TLS")) {
18168          ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
18169          return;
18170       }
18171 
18172       if (maddr && ast_sockaddr_resolve_first(&p->sa, maddr, 0)) {
18173          p->sa = p->recv;
18174       }
18175 
18176       if (ast_sockaddr_resolve_first(&tmp, c, 0)) {
18177          ast_log(LOG_WARNING, "Could not resolve socket address for '%s'\n", c);
18178          port = STANDARD_SIP_PORT;
18179       } else if (!(port = ast_sockaddr_port(&tmp))) {
18180          port = STANDARD_SIP_PORT;
18181          ast_sockaddr_set_port(&tmp, port);
18182       }
18183 
18184       ast_sockaddr_set_port(&p->sa, port);
18185 
18186       check_for_nat(&tmp, p);
18187 
18188       if (sip_debug_test_pvt(p)) {
18189          ast_verbose("Sending to %s (%s)\n",
18190                 ast_sockaddr_stringify(sip_real_dst(p)),
18191                 sip_nat_mode(p));
18192       }
18193    }
18194 }
18195 
18196 /*! \brief Validate device authentication */
18197 static enum check_auth_result check_peer_ok(struct sip_pvt *p, char *of,
18198    struct sip_request *req, int sipmethod, struct ast_sockaddr *addr,
18199    struct sip_peer **authpeer,
18200    enum xmittype reliable, char *calleridname, char *uri2)
18201 {
18202    enum check_auth_result res;
18203    int debug = sip_debug_test_addr(addr);
18204    struct sip_peer *peer;
18205 
18206    if (sipmethod == SIP_SUBSCRIBE) {
18207       /* For subscribes, match on device name only; for other methods,
18208       * match on IP address-port of the incoming request.
18209       */
18210       peer = sip_find_peer(of, NULL, TRUE, FINDALLDEVICES, FALSE, 0);
18211    } else {
18212       /* First find devices based on username (avoid all type=peer's) */
18213       peer = sip_find_peer(of, NULL, TRUE, FINDUSERS, FALSE, 0);
18214 
18215       /* Then find devices based on IP */
18216       if (!peer) {
18217          char *uri_tmp, *callback = NULL, *dummy;
18218          uri_tmp = ast_strdupa(uri2);
18219          parse_uri(uri_tmp, "sip:,sips:", &callback, &dummy, &dummy, &dummy);
18220          if (!ast_strlen_zero(callback) && (peer = sip_find_peer_by_ip_and_exten(&p->recv, callback, p->socket.type))) {
18221             ; /* found, fall through */
18222          } else {
18223             peer = sip_find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
18224          }
18225       }
18226    }
18227 
18228    if (!peer) {
18229       if (debug) {
18230          ast_verbose("No matching peer for '%s' from '%s'\n",
18231             of, ast_sockaddr_stringify(&p->recv));
18232       }
18233 
18234       /* If you don't mind, we can return 404s for devices that do
18235        * not exist: username disclosure. If we allow guests, there
18236        * is no way around that. */
18237       if (sip_cfg.allowguest || !sip_cfg.alwaysauthreject) {
18238          return AUTH_DONT_KNOW;
18239       }
18240 
18241       /* If you do mind, we use a peer that will never authenticate.
18242        * This ensures that we follow the same code path as regular
18243        * auth: less chance for username disclosure. */
18244       peer = bogus_peer;
18245       sip_ref_peer(peer, "sip_ref_peer: check_peer_ok: must ref bogus_peer so unreffing it does not fail");
18246    }
18247 
18248    /*  build_peer, called through sip_find_peer, is not able to check the
18249     *  sip_pvt->natdetected flag in order to determine if the peer is behind
18250     *  NAT or not when SIP_PAGE3_NAT_AUTO_RPORT or SIP_PAGE3_NAT_AUTO_COMEDIA
18251     *  are set on the peer.  So we check for that here and set the peer's
18252     *  address accordingly.
18253     */
18254    set_peer_nat(p, peer);
18255 
18256    if (p->natdetected && ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_RPORT)) {
18257       ast_sockaddr_copy(&peer->addr, &p->recv);
18258    }
18259 
18260    if (!ast_apply_acl(peer->acl, addr, "SIP Peer ACL: ")) {
18261       ast_debug(2, "Found peer '%s' for '%s', but fails host access\n", peer->name, of);
18262       sip_unref_peer(peer, "sip_unref_peer: check_peer_ok: from sip_find_peer call, early return of AUTH_ACL_FAILED");
18263       return AUTH_ACL_FAILED;
18264    }
18265    if (debug && peer != bogus_peer) {
18266       ast_verbose("Found peer '%s' for '%s' from %s\n",
18267          peer->name, of, ast_sockaddr_stringify(&p->recv));
18268    }
18269 
18270    /* XXX what about p->prefs = peer->prefs; ? */
18271    /* Set Frame packetization */
18272    if (p->rtp) {
18273       ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &peer->prefs);
18274       p->autoframing = peer->autoframing;
18275    }
18276 
18277    /* Take the peer */
18278    ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
18279    ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
18280    ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
18281 
18282    if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && p->udptl) {
18283       p->t38_maxdatagram = peer->t38_maxdatagram;
18284       set_t38_capabilities(p);
18285    }
18286 
18287    ast_rtp_dtls_cfg_copy(&peer->dtls_cfg, &p->dtls_cfg);
18288 
18289    /* Copy SIP extensions profile to peer */
18290    /* XXX is this correct before a successful auth ? */
18291    if (p->sipoptions)
18292       peer->sipoptions = p->sipoptions;
18293 
18294    do_setnat(p);
18295 
18296    ast_string_field_set(p, peersecret, peer->secret);
18297    ast_string_field_set(p, peermd5secret, peer->md5secret);
18298    ast_string_field_set(p, subscribecontext, peer->subscribecontext);
18299    ast_string_field_set(p, mohinterpret, peer->mohinterpret);
18300    ast_string_field_set(p, mohsuggest, peer->mohsuggest);
18301    if (!ast_strlen_zero(peer->parkinglot)) {
18302       ast_string_field_set(p, parkinglot, peer->parkinglot);
18303    }
18304    ast_string_field_set(p, engine, peer->engine);
18305    p->disallowed_methods = peer->disallowed_methods;
18306    set_pvt_allowed_methods(p, req);
18307    ast_cc_copy_config_params(p->cc_params, peer->cc_params);
18308    if (peer->callingpres)  /* Peer calling pres setting will override RPID */
18309       p->callingpres = peer->callingpres;
18310    if (peer->maxms && peer->lastms)
18311       p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
18312    else
18313       p->timer_t1 = peer->timer_t1;
18314 
18315    /* Set timer B to control transaction timeouts */
18316    if (peer->timer_b)
18317       p->timer_b = peer->timer_b;
18318    else
18319       p->timer_b = 64 * p->timer_t1;
18320 
18321    p->allowtransfer = peer->allowtransfer;
18322 
18323    if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
18324       /* Pretend there is no required authentication */
18325       ast_string_field_set(p, peersecret, NULL);
18326       ast_string_field_set(p, peermd5secret, NULL);
18327    }
18328    if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable))) {
18329       /* If we have a call limit, set flag */
18330       if (peer->call_limit)
18331          ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
18332       ast_string_field_set(p, peername, peer->name);
18333       ast_string_field_set(p, authname, peer->name);
18334 
18335       ast_rtp_dtls_cfg_copy(&peer->dtls_cfg, &p->dtls_cfg);
18336 
18337       if (sipmethod == SIP_INVITE) {
18338          /* destroy old channel vars and copy in new ones. */
18339          ast_variables_destroy(p->chanvars);
18340          p->chanvars = copy_vars(peer->chanvars);
18341       }
18342 
18343       if (authpeer) {
18344          ao2_t_ref(peer, 1, "copy pointer into (*authpeer)");
18345          (*authpeer) = peer;  /* Add a ref to the object here, to keep it in memory a bit longer if it is realtime */
18346       }
18347 
18348       if (!ast_strlen_zero(peer->username)) {
18349          ast_string_field_set(p, username, peer->username);
18350          /* Use the default username for authentication on outbound calls */
18351          /* XXX this takes the name from the caller... can we override ? */
18352          ast_string_field_set(p, authname, peer->username);
18353       }
18354       if (!get_rpid(p, req)) {
18355          if (!ast_strlen_zero(peer->cid_num)) {
18356             char *tmp = ast_strdupa(peer->cid_num);
18357             if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
18358                ast_shrink_phone_number(tmp);
18359             ast_string_field_set(p, cid_num, tmp);
18360          }
18361          if (!ast_strlen_zero(peer->cid_name))
18362             ast_string_field_set(p, cid_name, peer->cid_name);
18363          if (peer->callingpres)
18364             p->callingpres = peer->callingpres;
18365       }
18366       if (!ast_strlen_zero(peer->cid_tag)) {
18367          ast_string_field_set(p, cid_tag, peer->cid_tag);
18368       }
18369       ast_string_field_set(p, fullcontact, peer->fullcontact);
18370       if (!ast_strlen_zero(peer->context)) {
18371          ast_string_field_set(p, context, peer->context);
18372       }
18373       if (!ast_strlen_zero(peer->messagecontext)) {
18374          ast_string_field_set(p, messagecontext, peer->messagecontext);
18375       }
18376       if (!ast_strlen_zero(peer->mwi_from)) {
18377          ast_string_field_set(p, mwi_from, peer->mwi_from);
18378       }
18379       ast_string_field_set(p, peersecret, peer->secret);
18380       ast_string_field_set(p, peermd5secret, peer->md5secret);
18381       ast_string_field_set(p, language, peer->language);
18382       ast_string_field_set(p, accountcode, peer->accountcode);
18383       p->amaflags = peer->amaflags;
18384       p->callgroup = peer->callgroup;
18385       p->pickupgroup = peer->pickupgroup;
18386       ast_unref_namedgroups(p->named_callgroups);
18387       p->named_callgroups = ast_ref_namedgroups(peer->named_callgroups);
18388       ast_unref_namedgroups(p->named_pickupgroups);
18389       p->named_pickupgroups = ast_ref_namedgroups(peer->named_pickupgroups);
18390       ast_format_cap_copy(p->caps, peer->caps);
18391       ast_format_cap_copy(p->jointcaps, peer->caps);
18392       p->prefs = peer->prefs;
18393       ast_copy_string(p->zone, peer->zone, sizeof(p->zone));
18394       if (peer->maxforwards > 0) {
18395          p->maxforwards = peer->maxforwards;
18396       }
18397       if (!(ast_format_cap_is_empty(p->peercaps))) {
18398          struct ast_format_cap *tmp = ast_format_cap_joint(p->jointcaps, p->peercaps);
18399          struct ast_format_cap *tmp2;
18400          if (tmp) {
18401             tmp2 = p->jointcaps;
18402             p->jointcaps = tmp;
18403             ast_format_cap_destroy(tmp2);
18404          }
18405       }
18406       p->maxcallbitrate = peer->maxcallbitrate;
18407       if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
18408           (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
18409          p->noncodeccapability |= AST_RTP_DTMF;
18410       else
18411          p->noncodeccapability &= ~AST_RTP_DTMF;
18412       p->jointnoncodeccapability = p->noncodeccapability;
18413       p->rtptimeout = peer->rtptimeout;
18414       p->rtpholdtimeout = peer->rtpholdtimeout;
18415       p->rtpkeepalive = peer->rtpkeepalive;
18416       if (!dialog_initialize_rtp(p)) {
18417          if (p->rtp) {
18418             ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &peer->prefs);
18419             p->autoframing = peer->autoframing;
18420          }
18421       } else {
18422          res = AUTH_RTP_FAILED;
18423       }
18424    }
18425    sip_unref_peer(peer, "check_peer_ok: sip_unref_peer: tossing temp ptr to peer from sip_find_peer");
18426    return res;
18427 }
18428 
18429 
18430 /*! \brief  Check if matching user or peer is defined
18431    Match user on From: user name and peer on IP/port
18432    This is used on first invite (not re-invites) and subscribe requests
18433     \return 0 on success, non-zero on failure
18434 */
18435 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
18436                      int sipmethod, const char *uri, enum xmittype reliable,
18437                      struct ast_sockaddr *addr, struct sip_peer **authpeer)
18438 {
18439    char *of, *name, *unused_password, *domain;
18440    RAII_VAR(char *, ofbuf, NULL, ast_free); /* beware, everyone starts pointing to this */
18441    RAII_VAR(char *, namebuf, NULL, ast_free);
18442    enum check_auth_result res = AUTH_DONT_KNOW;
18443    char calleridname[256];
18444    char *uri2 = ast_strdupa(uri);
18445 
18446    terminate_uri(uri2); /* trim extra stuff */
18447 
18448    ofbuf = ast_strdup(sip_get_header(req, "From"));
18449    /* XXX here tries to map the username for invite things */
18450 
18451    /* strip the display-name portion off the beginning of the FROM header. */
18452    if (!(of = (char *) get_calleridname(ofbuf, calleridname, sizeof(calleridname)))) {
18453       ast_log(LOG_ERROR, "FROM header can not be parsed\n");
18454       return res;
18455    }
18456 
18457    if (calleridname[0]) {
18458       ast_string_field_set(p, cid_name, calleridname);
18459    }
18460 
18461    if (ast_strlen_zero(p->exten)) {
18462       char *t = uri2;
18463       if (!strncasecmp(t, "sip:", 4))
18464          t+= 4;
18465       else if (!strncasecmp(t, "sips:", 5))
18466          t += 5;
18467       ast_string_field_set(p, exten, t);
18468       t = strchr(p->exten, '@');
18469       if (t)
18470          *t = '\0';
18471 
18472       if (ast_strlen_zero(p->our_contact))
18473          build_contact(p);
18474    }
18475 
18476    of = get_in_brackets(of);
18477 
18478    /* save the URI part of the From header */
18479    ast_string_field_set(p, from, of);
18480 
18481    if (parse_uri_legacy_check(of, "sip:,sips:", &name, &unused_password, &domain, NULL)) {
18482       ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
18483    }
18484 
18485    SIP_PEDANTIC_DECODE(name);
18486    SIP_PEDANTIC_DECODE(domain);
18487 
18488    extract_host_from_hostport(&domain);
18489 
18490    if (ast_strlen_zero(domain)) {
18491       /* <sip:name@[EMPTY]>, never good */
18492       ast_log(LOG_ERROR, "Empty domain name in FROM header\n");
18493       return res;
18494    }
18495 
18496    if (ast_strlen_zero(name)) {
18497       /* <sip:[EMPTY][@]hostport>. Asterisk 1.4 and 1.6 have always
18498        * treated that as a username, so we continue the tradition:
18499        * uri is now <sip:host@hostport>. */
18500       name = domain;
18501    } else {
18502       /* Non-empty name, try to get caller id from it */
18503       char *tmp = ast_strdupa(name);
18504       /* We need to be able to handle from-headers looking like
18505          <sip:8164444422;phone-context=+1@1.2.3.4:5060;user=phone;tag=SDadkoa01-gK0c3bdb43>
18506       */
18507       tmp = strsep(&tmp, ";");
18508       if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp)) {
18509          ast_shrink_phone_number(tmp);
18510       }
18511       ast_string_field_set(p, cid_num, tmp);
18512    }
18513 
18514    if (global_match_auth_username) {
18515       /*
18516        * XXX This is experimental code to grab the search key from the
18517        * Auth header's username instead of the 'From' name, if available.
18518        * Do not enable this block unless you understand the side effects (if any!)
18519        * Note, the search for "username" should be done in a more robust way.
18520        * Note2, at the moment we check both fields, though maybe we should
18521        * pick one or another depending on the request ? XXX
18522        */
18523       const char *hdr = sip_get_header(req, "Authorization");
18524       if (ast_strlen_zero(hdr)) {
18525          hdr = sip_get_header(req, "Proxy-Authorization");
18526       }
18527 
18528       if (!ast_strlen_zero(hdr) && (hdr = strstr(hdr, "username=\""))) {
18529          namebuf = name = ast_strdup(hdr + strlen("username=\""));
18530          name = strsep(&name, "\"");
18531       }
18532    }
18533 
18534    res = check_peer_ok(p, name, req, sipmethod, addr,
18535          authpeer, reliable, calleridname, uri2);
18536    if (res != AUTH_DONT_KNOW) {
18537       return res;
18538    }
18539 
18540    /* Finally, apply the guest policy */
18541    if (sip_cfg.allowguest) {
18542       /* Ignore check_return warning from Coverity for get_rpid below. */
18543       get_rpid(p, req);
18544       p->rtptimeout = global_rtptimeout;
18545       p->rtpholdtimeout = global_rtpholdtimeout;
18546       p->rtpkeepalive = global_rtpkeepalive;
18547       if (!dialog_initialize_rtp(p)) {
18548          res = AUTH_SUCCESSFUL;
18549       } else {
18550          res = AUTH_RTP_FAILED;
18551       }
18552    } else {
18553       res = AUTH_SECRET_FAILED; /* we don't want any guests, authentication will fail */
18554    }
18555 
18556    if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT)) {
18557       ast_set_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT);
18558    }
18559 
18560    return res;
18561 }
18562 
18563 /*! \brief  Find user
18564    If we get a match, this will add a reference pointer to the user object in ASTOBJ, that needs to be unreferenced
18565 */
18566 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr)
18567 {
18568    return check_user_full(p, req, sipmethod, uri, reliable, addr, NULL);
18569 }
18570 
18571 static int set_message_vars_from_req(struct ast_msg *msg, struct sip_request *req)
18572 {
18573    size_t x;
18574    char name_buf[1024];
18575    char val_buf[1024];
18576    const char *name;
18577    char *c;
18578    int res = 0;
18579 
18580    for (x = 0; x < req->headers; x++) {
18581       const char *header = REQ_OFFSET_TO_STR(req, header[x]);
18582 
18583       if ((c = strchr(header, ':'))) {
18584          ast_copy_string(name_buf, header, MIN((c - header + 1), sizeof(name_buf)));
18585          ast_copy_string(val_buf, ast_skip_blanks(c + 1), sizeof(val_buf));
18586          ast_trim_blanks(name_buf);
18587 
18588          /* Convert header name to full name alias. */
18589          name = find_full_alias(name_buf, name_buf);
18590 
18591          res = ast_msg_set_var(msg, name, val_buf);
18592          if (res) {
18593             break;
18594          }
18595       }
18596    }
18597    return res;
18598 }
18599 
18600 /*! \brief  Receive SIP MESSAGE method messages
18601 \note We only handle messages within current calls currently
18602    Reference: RFC 3428 */
18603 static void receive_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e)
18604 {
18605    char *buf;
18606    size_t len;
18607    struct ast_frame f;
18608    const char *content_type = sip_get_header(req, "Content-Type");
18609    struct ast_msg *msg;
18610    int res;
18611    char *from;
18612    char *to;
18613    char from_name[50];
18614    char stripped[SIPBUFSIZE];
18615 
18616    if (strncmp(content_type, "text/plain", strlen("text/plain"))) { /* No text/plain attachment */
18617       transmit_response(p, "415 Unsupported Media Type", req); /* Good enough, or? */
18618       if (!p->owner) {
18619          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18620       }
18621       return;
18622    }
18623 
18624    if (!(buf = get_content(req))) {
18625       ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
18626       transmit_response(p, "500 Internal Server Error", req);
18627       if (!p->owner) {
18628          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18629       }
18630       return;
18631    }
18632 
18633    /* Strip trailing line feeds from message body. (get_content may add
18634     * a trailing linefeed and we don't need any at the end) */
18635    len = strlen(buf);
18636    while (len > 0) {
18637       if (buf[--len] != '\n') {
18638          ++len;
18639          break;
18640       }
18641    }
18642    buf[len] = '\0';
18643 
18644    if (p->owner) {
18645       if (sip_debug_test_pvt(p)) {
18646          ast_verbose("SIP Text message received: '%s'\n", buf);
18647       }
18648       memset(&f, 0, sizeof(f));
18649       f.frametype = AST_FRAME_TEXT;
18650       f.subclass.integer = 0;
18651       f.offset = 0;
18652       f.data.ptr = buf;
18653       f.datalen = strlen(buf) + 1;
18654       ast_queue_frame(p->owner, &f);
18655       transmit_response(p, "202 Accepted", req); /* We respond 202 accepted, since we relay the message */
18656       return;
18657    }
18658 
18659    /*
18660     * At this point MESSAGE is outside of a call.
18661     *
18662     * NOTE: p->owner is NULL so no additional check is needed after
18663     * this point.
18664     */
18665 
18666    if (!sip_cfg.accept_outofcall_message) {
18667       /* Message outside of a call, we do not support that */
18668       ast_debug(1, "MESSAGE outside of a call administratively disabled.\n");
18669       transmit_response(p, "405 Method Not Allowed", req);
18670       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18671       return;
18672    }
18673 
18674    copy_request(&p->initreq, req);
18675 
18676    if (sip_cfg.auth_message_requests) {
18677       int res;
18678 
18679       set_pvt_allowed_methods(p, req);
18680       res = check_user(p, req, SIP_MESSAGE, e, XMIT_UNRELIABLE, addr);
18681       if (res == AUTH_CHALLENGE_SENT) {
18682          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18683          return;
18684       }
18685       if (res < 0) { /* Something failed in authentication */
18686          ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", sip_get_header(req, "From"));
18687          transmit_response(p, "403 Forbidden", req);
18688          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18689          return;
18690       }
18691       /* Auth was successful.  Proceed. */
18692    } else {
18693       struct sip_peer *peer;
18694 
18695       /*
18696        * MESSAGE outside of a call, not authenticating it.
18697        * Check to see if we match a peer anyway so that we can direct
18698        * it to the right context.
18699        */
18700 
18701       peer = sip_find_peer(NULL, &p->recv, TRUE, FINDPEERS, 0, p->socket.type);
18702       if (peer) {
18703          /* Only if no auth is required. */
18704          if (ast_strlen_zero(peer->secret) && ast_strlen_zero(peer->md5secret)) {
18705             ast_string_field_set(p, context, peer->context);
18706          }
18707          if (!ast_strlen_zero(peer->messagecontext)) {
18708             ast_string_field_set(p, messagecontext, peer->messagecontext);
18709          }
18710          ast_string_field_set(p, peername, peer->name);
18711          peer = sip_unref_peer(peer, "from sip_find_peer() in receive_message");
18712       }
18713    }
18714 
18715    /* Override the context with the message context _BEFORE_
18716     * getting the destination.  This way we can guarantee the correct
18717     * extension is used in the message context when it is present. */
18718    if (!ast_strlen_zero(p->messagecontext)) {
18719       ast_string_field_set(p, context, p->messagecontext);
18720    } else if (!ast_strlen_zero(sip_cfg.messagecontext)) {
18721       ast_string_field_set(p, context, sip_cfg.messagecontext);
18722    }
18723 
18724    switch (get_destination(p, NULL, NULL)) {
18725    case SIP_GET_DEST_REFUSED:
18726       /* Okay to send 403 since this is after auth processing */
18727       transmit_response(p, "403 Forbidden", req);
18728       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18729       return;
18730    case SIP_GET_DEST_INVALID_URI:
18731       transmit_response(p, "416 Unsupported URI Scheme", req);
18732       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18733       return;
18734    case SIP_GET_DEST_EXTEN_NOT_FOUND:
18735    case SIP_GET_DEST_EXTEN_MATCHMORE:
18736       transmit_response(p, "404 Not Found", req);
18737       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18738       return;
18739    case SIP_GET_DEST_EXTEN_FOUND:
18740       break;
18741    }
18742 
18743    if (!(msg = ast_msg_alloc())) {
18744       transmit_response(p, "500 Internal Server Error", req);
18745       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18746       return;
18747    }
18748 
18749    to = ast_strdupa(REQ_OFFSET_TO_STR(req, rlpart2));
18750    from = ast_strdupa(sip_get_header(req, "From"));
18751 
18752    res = ast_msg_set_to(msg, "%s", to);
18753 
18754    /* Build "display" <uri> for from string. */
18755    from = (char *) get_calleridname(from, from_name, sizeof(from_name));
18756    from = get_in_brackets(from);
18757    if (from_name[0]) {
18758       res |= ast_msg_set_from(msg, "\"%s\" <%s>", from_name, from);
18759    } else {
18760       res |= ast_msg_set_from(msg, "<%s>", from);
18761    }
18762 
18763    res |= ast_msg_set_body(msg, "%s", buf);
18764    res |= ast_msg_set_context(msg, "%s", p->context);
18765 
18766    res |= ast_msg_set_var(msg, "SIP_RECVADDR", ast_sockaddr_stringify(&p->recv));
18767    if (!ast_strlen_zero(p->peername)) {
18768       res |= ast_msg_set_var(msg, "SIP_PEERNAME", p->peername);
18769    }
18770 
18771    ast_copy_string(stripped, sip_get_header(req, "Contact"), sizeof(stripped));
18772    res |= ast_msg_set_var(msg, "SIP_FULLCONTACT", get_in_brackets(stripped));
18773 
18774    res |= ast_msg_set_exten(msg, "%s", p->exten);
18775    res |= set_message_vars_from_req(msg, req);
18776 
18777    if (res) {
18778       ast_msg_destroy(msg);
18779       transmit_response(p, "500 Internal Server Error", req);
18780    } else {
18781       ast_msg_queue(msg);
18782       transmit_response(p, "202 Accepted", req);
18783    }
18784 
18785    sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18786 }
18787 
18788 /*! \brief  CLI Command to show calls within limits set by call_limit */
18789 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18790 {
18791 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
18792 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
18793    char ilimits[40];
18794    char iused[40];
18795    int showall = FALSE;
18796    struct ao2_iterator i;
18797    struct sip_peer *peer;
18798    
18799    switch (cmd) {
18800    case CLI_INIT:
18801       e->command = "sip show inuse";
18802       e->usage =
18803          "Usage: sip show inuse [all]\n"
18804          "       List all SIP devices usage counters and limits.\n"
18805          "       Add option \"all\" to show all devices, not only those with a limit.\n";
18806       return NULL;
18807    case CLI_GENERATE:
18808       return NULL;
18809    }
18810 
18811    if (a->argc < 3)
18812       return CLI_SHOWUSAGE;
18813 
18814    if (a->argc == 4 && !strcmp(a->argv[3], "all"))
18815       showall = TRUE;
18816    
18817    ast_cli(a->fd, FORMAT, "* Peer name", "In use", "Limit");
18818 
18819    i = ao2_iterator_init(peers, 0);
18820    while ((peer = ao2_t_iterator_next(&i, "iterate thru peer table"))) {
18821       ao2_lock(peer);
18822       if (peer->call_limit)
18823          snprintf(ilimits, sizeof(ilimits), "%d", peer->call_limit);
18824       else
18825          ast_copy_string(ilimits, "N/A", sizeof(ilimits));
18826       snprintf(iused, sizeof(iused), "%d/%d/%d", peer->inuse, peer->ringing, peer->onhold);
18827       if (showall || peer->call_limit)
18828          ast_cli(a->fd, FORMAT2, peer->name, iused, ilimits);
18829       ao2_unlock(peer);
18830       sip_unref_peer(peer, "toss iterator pointer");
18831    }
18832    ao2_iterator_destroy(&i);
18833 
18834    return CLI_SUCCESS;
18835 #undef FORMAT
18836 #undef FORMAT2
18837 }
18838 
18839 
18840 /*! \brief Convert transfer mode to text string */
18841 static char *transfermode2str(enum transfermodes mode)
18842 {
18843    if (mode == TRANSFER_OPENFORALL)
18844       return "open";
18845    else if (mode == TRANSFER_CLOSED)
18846       return "closed";
18847    return "strict";
18848 }
18849 
18850 /*! \brief  Report Peer status in character string
18851  *  \return 0 if peer is unreachable, 1 if peer is online, -1 if unmonitored
18852  */
18853 
18854 
18855 /* Session-Timer Modes */
18856 static const struct _map_x_s stmodes[] = {
18857         { SESSION_TIMER_MODE_ACCEPT,    "Accept"},
18858         { SESSION_TIMER_MODE_ORIGINATE, "Originate"},
18859         { SESSION_TIMER_MODE_REFUSE,    "Refuse"},
18860         { -1,                           NULL},
18861 };
18862 
18863 static const char *stmode2str(enum st_mode m)
18864 {
18865    return map_x_s(stmodes, m, "Unknown");
18866 }
18867 
18868 static enum st_mode str2stmode(const char *s)
18869 {
18870    return map_s_x(stmodes, s, -1);
18871 }
18872 
18873 /* Session-Timer Refreshers */
18874 static const struct _map_x_s strefresher_params[] = {
18875         { SESSION_TIMER_REFRESHER_PARAM_UNKNOWN, "unknown" },
18876         { SESSION_TIMER_REFRESHER_PARAM_UAC,     "uac"     },
18877         { SESSION_TIMER_REFRESHER_PARAM_UAS,     "uas"     },
18878         { -1,                                NULL  },
18879 };
18880 
18881 static const struct _map_x_s strefreshers[] = {
18882         { SESSION_TIMER_REFRESHER_AUTO, "auto" },
18883         { SESSION_TIMER_REFRESHER_US,   "us"   },
18884         { SESSION_TIMER_REFRESHER_THEM, "them" },
18885         { -1,                           NULL   },
18886 };
18887 
18888 static const char *strefresherparam2str(enum st_refresher r)
18889 {
18890    return map_x_s(strefresher_params, r, "Unknown");
18891 }
18892 
18893 static enum st_refresher str2strefresherparam(const char *s)
18894 {
18895    return map_s_x(strefresher_params, s, -1);
18896 }
18897 
18898 /* Autocreatepeer modes */
18899 static struct _map_x_s autopeermodes[] = {
18900         { AUTOPEERS_DISABLED, "Off"},
18901         { AUTOPEERS_VOLATILE, "Volatile"},
18902         { AUTOPEERS_PERSIST,  "Persisted"},
18903         { -1, NULL},
18904 };
18905 
18906 static const char *strefresher2str(enum st_refresher r)
18907 {
18908    return map_x_s(strefreshers, r, "Unknown");
18909 }
18910 
18911 static const char *autocreatepeer2str(enum autocreatepeer_mode r)
18912 {
18913    return map_x_s(autopeermodes, r, "Unknown");
18914 }
18915 
18916 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
18917 {
18918    int res = 0;
18919    if (peer->maxms) {
18920       if (peer->lastms < 0) {
18921          ast_copy_string(status, "UNREACHABLE", statuslen);
18922       } else if (peer->lastms > peer->maxms) {
18923          snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
18924          res = 1;
18925       } else if (peer->lastms) {
18926          snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
18927          res = 1;
18928       } else {
18929          ast_copy_string(status, "UNKNOWN", statuslen);
18930       }
18931    } else {
18932       ast_copy_string(status, "Unmonitored", statuslen);
18933       /* Checking if port is 0 */
18934       res = -1;
18935    }
18936    return res;
18937 }
18938 
18939 /*! \brief  Show active TCP connections */
18940 static char *sip_show_tcp(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18941 {
18942    struct sip_threadinfo *th;
18943    struct ao2_iterator i;
18944 
18945 #define FORMAT2 "%-47.47s %9.9s %6.6s\n"
18946 #define FORMAT  "%-47.47s %-9.9s %-6.6s\n"
18947 
18948    switch (cmd) {
18949    case CLI_INIT:
18950       e->command = "sip show tcp";
18951       e->usage =
18952          "Usage: sip show tcp\n"
18953          "       Lists all active TCP/TLS sessions.\n";
18954       return NULL;
18955    case CLI_GENERATE:
18956       return NULL;
18957    }
18958 
18959    if (a->argc != 3)
18960       return CLI_SHOWUSAGE;
18961 
18962    ast_cli(a->fd, FORMAT2, "Address", "Transport", "Type");
18963 
18964    i = ao2_iterator_init(threadt, 0);
18965    while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
18966       ast_cli(a->fd, FORMAT,
18967          ast_sockaddr_stringify(&th->tcptls_session->remote_address),
18968          sip_get_transport(th->type),
18969          (th->tcptls_session->client ? "Client" : "Server"));
18970       ao2_t_ref(th, -1, "decrement ref from iterator");
18971    }
18972    ao2_iterator_destroy(&i);
18973 
18974    return CLI_SUCCESS;
18975 #undef FORMAT
18976 #undef FORMAT2
18977 }
18978 
18979 /*! \brief  CLI Command 'SIP Show Users' */
18980 static char *sip_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18981 {
18982    regex_t regexbuf;
18983    int havepattern = FALSE;
18984    struct ao2_iterator user_iter;
18985    struct sip_peer *user;
18986 
18987 #define FORMAT  "%-25.25s  %-15.15s  %-15.15s  %-15.15s  %-5.5s%-10.10s\n"
18988 
18989    switch (cmd) {
18990    case CLI_INIT:
18991       e->command = "sip show users";
18992       e->usage =
18993          "Usage: sip show users [like <pattern>]\n"
18994          "       Lists all known SIP users.\n"
18995          "       Optional regular expression pattern is used to filter the user list.\n";
18996       return NULL;
18997    case CLI_GENERATE:
18998       return NULL;
18999    }
19000 
19001    switch (a->argc) {
19002    case 5:
19003       if (!strcasecmp(a->argv[3], "like")) {
19004          if (regcomp(&regexbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
19005             return CLI_SHOWUSAGE;
19006          havepattern = TRUE;
19007       } else
19008          return CLI_SHOWUSAGE;
19009    case 3:
19010       break;
19011    default:
19012       return CLI_SHOWUSAGE;
19013    }
19014 
19015    ast_cli(a->fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "Forcerport");
19016 
19017    user_iter = ao2_iterator_init(peers, 0);
19018    while ((user = ao2_t_iterator_next(&user_iter, "iterate thru peers table"))) {
19019       ao2_lock(user);
19020       if (!(user->type & SIP_TYPE_USER)) {
19021          ao2_unlock(user);
19022          sip_unref_peer(user, "sip show users");
19023          continue;
19024       }
19025 
19026       if (havepattern && regexec(&regexbuf, user->name, 0, NULL, 0)) {
19027          ao2_unlock(user);
19028          sip_unref_peer(user, "sip show users");
19029          continue;
19030       }
19031 
19032       ast_cli(a->fd, FORMAT, user->name,
19033          user->secret,
19034          user->accountcode,
19035          user->context,
19036          AST_CLI_YESNO(ast_acl_list_is_empty(user->acl) == 0),
19037          AST_CLI_YESNO(ast_test_flag(&user->flags[0], SIP_NAT_FORCE_RPORT)));
19038       ao2_unlock(user);
19039       sip_unref_peer(user, "sip show users");
19040    }
19041    ao2_iterator_destroy(&user_iter);
19042 
19043    if (havepattern)
19044       regfree(&regexbuf);
19045 
19046    return CLI_SUCCESS;
19047 #undef FORMAT
19048 }
19049 
19050 /*! \brief Show SIP registrations in the manager API */
19051 static int manager_show_registry(struct mansession *s, const struct message *m)
19052 {
19053    const char *id = astman_get_header(m, "ActionID");
19054    char idtext[256] = "";
19055    int total = 0;
19056 
19057    if (!ast_strlen_zero(id))
19058       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
19059 
19060    astman_send_listack(s, m, "Registrations will follow", "start");
19061 
19062    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
19063       ASTOBJ_RDLOCK(iterator);
19064       astman_append(s,
19065          "Event: RegistryEntry\r\n"
19066          "%s"
19067          "Host: %s\r\n"
19068          "Port: %d\r\n"
19069          "Username: %s\r\n"
19070          "Domain: %s\r\n"
19071          "DomainPort: %d\r\n"
19072          "Refresh: %d\r\n"
19073          "State: %s\r\n"
19074          "RegistrationTime: %ld\r\n"
19075          "\r\n",
19076          idtext,
19077          iterator->hostname,
19078          iterator->portno ? iterator->portno : STANDARD_SIP_PORT,
19079          iterator->username,
19080          S_OR(iterator->regdomain,iterator->hostname),
19081          iterator->regdomainport ? iterator->regdomainport : STANDARD_SIP_PORT,
19082          iterator->refresh,
19083          regstate2str(iterator->regstate),
19084          (long) iterator->regtime.tv_sec);
19085       ASTOBJ_UNLOCK(iterator);
19086       total++;
19087    } while(0));
19088 
19089    astman_append(s,
19090       "Event: RegistrationsComplete\r\n"
19091       "EventList: Complete\r\n"
19092       "ListItems: %d\r\n"
19093       "%s"
19094       "\r\n", total, idtext);
19095    
19096    return 0;
19097 }
19098 
19099 /*! \brief  Show SIP peers in the manager API */
19100 /*    Inspired from chan_iax2 */
19101 static int manager_sip_show_peers(struct mansession *s, const struct message *m)
19102 {
19103    const char *id = astman_get_header(m, "ActionID");
19104    const char *a[] = {"sip", "show", "peers"};
19105    char idtext[256] = "";
19106    int total = 0;
19107 
19108    if (!ast_strlen_zero(id))
19109       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
19110 
19111    astman_send_listack(s, m, "Peer status list will follow", "start");
19112    /* List the peers in separate manager events */
19113    _sip_show_peers(-1, &total, s, m, 3, a);
19114    /* Send final confirmation */
19115    astman_append(s,
19116    "Event: PeerlistComplete\r\n"
19117    "EventList: Complete\r\n"
19118    "ListItems: %d\r\n"
19119    "%s"
19120    "\r\n", total, idtext);
19121    return 0;
19122 }
19123 
19124 /*! \brief  CLI Show Peers command */
19125 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19126 {
19127    switch (cmd) {
19128    case CLI_INIT:
19129       e->command = "sip show peers";
19130       e->usage =
19131          "Usage: sip show peers [like <pattern>]\n"
19132          "       Lists all known SIP peers.\n"
19133          "       Optional regular expression pattern is used to filter the peer list.\n";
19134       return NULL;
19135    case CLI_GENERATE:
19136       return NULL;
19137    }
19138 
19139    return _sip_show_peers(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
19140 }
19141 
19142 int peercomparefunc(const void *a, const void *b);
19143 
19144 int peercomparefunc(const void *a, const void *b)
19145 {
19146    struct sip_peer **ap = (struct sip_peer **)a;
19147    struct sip_peer **bp = (struct sip_peer **)b;
19148    return strcmp((*ap)->name, (*bp)->name);
19149 }
19150 
19151 /* the last argument is left-aligned, so we don't need a size anyways */
19152 #define PEERS_FORMAT2 "%-25.25s %-39.39s %-3.3s %-10.10s %-10.10s %-3.3s %-8s %-11s %-32.32s %s\n"
19153 
19154 /*! \brief Used in the sip_show_peers functions to pass parameters */
19155 struct show_peers_context {
19156    regex_t regexbuf;
19157    int havepattern;
19158    char idtext[256];
19159    int realtimepeers;
19160    int peers_mon_online;
19161    int peers_mon_offline;
19162    int peers_unmon_offline;
19163    int peers_unmon_online;
19164 };
19165 
19166 /*! \brief Execute sip show peers command */
19167 static char *_sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
19168 {
19169    struct show_peers_context cont = {
19170       .havepattern = FALSE,
19171       .idtext = "",
19172 
19173       .peers_mon_online = 0,
19174       .peers_mon_offline = 0,
19175       .peers_unmon_online = 0,
19176       .peers_unmon_offline = 0,
19177    };
19178 
19179    struct sip_peer *peer;
19180    struct ao2_iterator* it_peers;
19181 
19182    int total_peers = 0;
19183    const char *id;
19184    struct sip_peer **peerarray;
19185    int k;
19186 
19187    cont.realtimepeers = ast_check_realtime("sippeers");
19188 
19189    if (s) { /* Manager - get ActionID */
19190       id = astman_get_header(m, "ActionID");
19191       if (!ast_strlen_zero(id)) {
19192          snprintf(cont.idtext, sizeof(cont.idtext), "ActionID: %s\r\n", id);
19193       }
19194    }
19195 
19196    switch (argc) {
19197    case 5:
19198       if (!strcasecmp(argv[3], "like")) {
19199          if (regcomp(&cont.regexbuf, argv[4], REG_EXTENDED | REG_NOSUB)) {
19200             return CLI_SHOWUSAGE;
19201          }
19202          cont.havepattern = TRUE;
19203       } else {
19204          return CLI_SHOWUSAGE;
19205       }
19206    case 3:
19207       break;
19208    default:
19209       return CLI_SHOWUSAGE;
19210    }
19211 
19212    if (!s) {
19213       /* Normal list */
19214       ast_cli(fd, PEERS_FORMAT2, "Name/username", "Host", "Dyn", "Forcerport", "Comedia", "ACL", "Port", "Status", "Description", (cont.realtimepeers ? "Realtime" : ""));
19215    }
19216 
19217    ao2_lock(peers);
19218    if (!(it_peers = ao2_callback(peers, OBJ_MULTIPLE, NULL, NULL))) {
19219       ast_log(AST_LOG_ERROR, "Unable to create iterator for peers container for sip show peers\n");
19220       ao2_unlock(peers);
19221       return CLI_FAILURE;
19222    }
19223    if (!(peerarray = ast_calloc(sizeof(struct sip_peer *), ao2_container_count(peers)))) {
19224       ast_log(AST_LOG_ERROR, "Unable to allocate peer array for sip show peers\n");
19225       ao2_iterator_destroy(it_peers);
19226       ao2_unlock(peers);
19227       return CLI_FAILURE;
19228    }
19229    ao2_unlock(peers);
19230 
19231    while ((peer = ao2_t_iterator_next(it_peers, "iterate thru peers table"))) {
19232       ao2_lock(peer);
19233 
19234       if (!(peer->type & SIP_TYPE_PEER)) {
19235          ao2_unlock(peer);
19236          sip_unref_peer(peer, "unref peer because it's actually a user");
19237          continue;
19238       }
19239 
19240       if (cont.havepattern && regexec(&cont.regexbuf, peer->name, 0, NULL, 0)) {
19241          ao2_unlock(peer);
19242          sip_unref_peer(peer, "toss iterator peer ptr before continue");
19243          continue;
19244       }
19245 
19246       peerarray[total_peers++] = peer;
19247       ao2_unlock(peer);
19248    }
19249    ao2_iterator_destroy(it_peers);
19250 
19251    qsort(peerarray, total_peers, sizeof(struct sip_peer *), peercomparefunc);
19252 
19253    for(k = 0; k < total_peers; k++) {
19254       peerarray[k] = _sip_show_peers_one(fd, s, &cont, peerarray[k]);
19255    }
19256 
19257    if (!s) {
19258       ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
19259               total_peers, cont.peers_mon_online, cont.peers_mon_offline, cont.peers_unmon_online, cont.peers_unmon_offline);
19260    }
19261 
19262    if (cont.havepattern) {
19263       regfree(&cont.regexbuf);
19264    }
19265 
19266    if (total) {
19267       *total = total_peers;
19268    }
19269 
19270    ast_free(peerarray);
19271 
19272    return CLI_SUCCESS;
19273 }
19274 
19275 /*! \brief Emit informations for one peer during sip show peers command */
19276 static struct sip_peer *_sip_show_peers_one(int fd, struct mansession *s, struct show_peers_context *cont, struct sip_peer *peer)
19277 {
19278    /* _sip_show_peers_one() is separated from _sip_show_peers() to properly free the ast_strdupa
19279     * (this is executed in a loop in _sip_show_peers() )
19280     */
19281 
19282    char name[256];
19283    char status[20] = "";
19284    char pstatus;
19285 
19286    /*
19287     * tmp_port and tmp_host store copies of ast_sockaddr_stringify strings since the
19288     * string pointers for that function aren't valid between subsequent calls to
19289     * ast_sockaddr_stringify functions
19290     */
19291    char *tmp_port;
19292    char *tmp_host;
19293 
19294    tmp_port = ast_sockaddr_isnull(&peer->addr) ?
19295       "0" : ast_strdupa(ast_sockaddr_stringify_port(&peer->addr));
19296 
19297    tmp_host = ast_sockaddr_isnull(&peer->addr) ?
19298       "(Unspecified)" : ast_strdupa(ast_sockaddr_stringify_addr(&peer->addr));
19299 
19300    ao2_lock(peer);
19301    if (cont->havepattern && regexec(&cont->regexbuf, peer->name, 0, NULL, 0)) {
19302       ao2_unlock(peer);
19303       return sip_unref_peer(peer, "toss iterator peer ptr no match");
19304    }
19305 
19306    if (!ast_strlen_zero(peer->username) && !s) {
19307       snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
19308    } else {
19309       ast_copy_string(name, peer->name, sizeof(name));
19310    }
19311 
19312    pstatus = peer_status(peer, status, sizeof(status));
19313    if (pstatus == 1) {
19314       cont->peers_mon_online++;
19315    } else if (pstatus == 0) {
19316       cont->peers_mon_offline++;
19317    } else {
19318       if (ast_sockaddr_isnull(&peer->addr) ||
19319           !ast_sockaddr_port(&peer->addr)) {
19320          cont->peers_unmon_offline++;
19321       } else {
19322          cont->peers_unmon_online++;
19323       }
19324    }
19325 
19326    if (!s) { /* Normal CLI list */
19327       ast_cli(fd, PEERS_FORMAT2, name,
19328       tmp_host,
19329       peer->host_dynamic ? " D " : "   ", /* Dynamic or not? */
19330       force_rport_string(peer->flags),
19331       comedia_string(peer->flags),
19332       (!ast_acl_list_is_empty(peer->acl)) ? " A " : "   ",       /* permit/deny */
19333       tmp_port, status,
19334       peer->description ? peer->description : "",
19335       cont->realtimepeers ? (peer->is_realtime ? "Cached RT" : "") : "");
19336    } else { /* Manager format */
19337       /* The names here need to be the same as other channels */
19338       astman_append(s,
19339       "Event: PeerEntry\r\n%s"
19340       "Channeltype: SIP\r\n"
19341       "ObjectName: %s\r\n"
19342       "ChanObjectType: peer\r\n" /* "peer" or "user" */
19343       "IPaddress: %s\r\n"
19344       "IPport: %s\r\n"
19345       "Dynamic: %s\r\n"
19346       "AutoForcerport: %s\r\n"
19347       "Forcerport: %s\r\n"
19348       "AutoComedia: %s\r\n"
19349       "Comedia: %s\r\n"
19350       "VideoSupport: %s\r\n"
19351       "TextSupport: %s\r\n"
19352       "ACL: %s\r\n"
19353       "Status: %s\r\n"
19354       "RealtimeDevice: %s\r\n"
19355       "Description: %s\r\n\r\n",
19356       cont->idtext,
19357       peer->name,
19358       ast_sockaddr_isnull(&peer->addr) ? "-none-" : tmp_host,
19359       ast_sockaddr_isnull(&peer->addr) ? "0" : tmp_port,
19360       peer->host_dynamic ? "yes" : "no",  /* Dynamic or not? */
19361       ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_RPORT) ? "yes" : "no",
19362       ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? "yes" : "no",
19363       ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_COMEDIA) ? "yes" : "no",
19364       ast_test_flag(&peer->flags[1], SIP_PAGE2_SYMMETRICRTP) ? "yes" : "no",
19365       ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no",  /* VIDEOSUPPORT=yes? */
19366       ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "yes" : "no",   /* TEXTSUPPORT=yes? */
19367       ast_acl_list_is_empty(peer->acl) ? "no" : "yes",       /* permit/deny/acl */
19368       status,
19369       cont->realtimepeers ? (peer->is_realtime ? "yes" : "no") : "no",
19370       peer->description);
19371    }
19372    ao2_unlock(peer);
19373 
19374    return sip_unref_peer(peer, "toss iterator peer ptr");
19375 }
19376 #undef PEERS_FORMAT2
19377 
19378 static int peer_dump_func(void *userobj, void *arg, int flags)
19379 {
19380    struct sip_peer *peer = userobj;
19381    int refc = ao2_t_ref(userobj, 0, "");
19382    struct ast_cli_args *a = (struct ast_cli_args *) arg;
19383    
19384    ast_cli(a->fd, "name: %s\ntype: peer\nobjflags: %d\nrefcount: %d\n\n",
19385       peer->name, 0, refc);
19386    return 0;
19387 }
19388 
19389 static int dialog_dump_func(void *userobj, void *arg, int flags)
19390 {
19391    struct sip_pvt *pvt = userobj;
19392    int refc = ao2_t_ref(userobj, 0, "");
19393    struct ast_cli_args *a = (struct ast_cli_args *) arg;
19394    
19395    ast_cli(a->fd, "name: %s\ntype: dialog\nobjflags: %d\nrefcount: %d\n\n",
19396       pvt->callid, 0, refc);
19397    return 0;
19398 }
19399 
19400 
19401 /*! \brief List all allocated SIP Objects (realtime or static) */
19402 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19403 {
19404    char tmp[256];
19405    
19406    switch (cmd) {
19407    case CLI_INIT:
19408       e->command = "sip show objects";
19409       e->usage =
19410          "Usage: sip show objects\n"
19411          "       Lists status of known SIP objects\n";
19412       return NULL;
19413    case CLI_GENERATE:
19414       return NULL;
19415    }  
19416 
19417    if (a->argc != 3)
19418       return CLI_SHOWUSAGE;
19419    ast_cli(a->fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
19420    ao2_t_callback(peers, OBJ_NODATA, peer_dump_func, a, "initiate ao2_callback to dump peers");
19421    ast_cli(a->fd, "-= Peer objects by IP =-\n\n"); 
19422    ao2_t_callback(peers_by_ip, OBJ_NODATA, peer_dump_func, a, "initiate ao2_callback to dump peers_by_ip");
19423    ast_cli(a->fd, "-= Registry objects: %d =-\n\n", regobjs);
19424    ASTOBJ_CONTAINER_DUMP(a->fd, tmp, sizeof(tmp), &regl);
19425    ast_cli(a->fd, "-= Dialog objects:\n\n");
19426    ao2_t_callback(dialogs, OBJ_NODATA, dialog_dump_func, a, "initiate ao2_callback to dump dialogs");
19427    return CLI_SUCCESS;
19428 }
19429 /*! \brief Print call group and pickup group */
19430 static void print_group(int fd, ast_group_t group, int crlf)
19431 {
19432    char buf[256];
19433    ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
19434 }
19435 
19436 /*! \brief Print named call groups and pickup groups */
19437 static void print_named_groups(int fd, struct ast_namedgroups *group, int crlf)
19438 {
19439    struct ast_str *buf = ast_str_create(1024);
19440    if (buf) {
19441       ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_namedgroups(&buf, group) );
19442       ast_free(buf);
19443    }
19444 }
19445 
19446 /*! \brief mapping between dtmf flags and strings */
19447 static const struct _map_x_s dtmfstr[] = {
19448    { SIP_DTMF_RFC2833,     "rfc2833" },
19449    { SIP_DTMF_INFO,        "info" },
19450    { SIP_DTMF_SHORTINFO,   "shortinfo" },
19451    { SIP_DTMF_INBAND,      "inband" },
19452    { SIP_DTMF_AUTO,        "auto" },
19453    { -1,                   NULL }, /* terminator */
19454 };
19455 
19456 /*! \brief Convert DTMF mode to printable string */
19457 static const char *dtmfmode2str(int mode)
19458 {
19459    return map_x_s(dtmfstr, mode, "<error>");
19460 }
19461 
19462 /*! \brief maps a string to dtmfmode, returns -1 on error */
19463 static int str2dtmfmode(const char *str)
19464 {
19465    return map_s_x(dtmfstr, str, -1);
19466 }
19467 
19468 static const struct _map_x_s insecurestr[] = {
19469    { SIP_INSECURE_PORT,    "port" },
19470    { SIP_INSECURE_INVITE,  "invite" },
19471    { SIP_INSECURE_PORT | SIP_INSECURE_INVITE, "port,invite" },
19472    { 0,                    "no" },
19473    { -1,                   NULL }, /* terminator */
19474 };
19475 
19476 /*! \brief Convert Insecure setting to printable string */
19477 static const char *insecure2str(int mode)
19478 {
19479    return map_x_s(insecurestr, mode, "<error>");
19480 }
19481 
19482 static const struct _map_x_s allowoverlapstr[] = {
19483    { SIP_PAGE2_ALLOWOVERLAP_YES,   "Yes" },
19484    { SIP_PAGE2_ALLOWOVERLAP_DTMF,  "DTMF" },
19485    { SIP_PAGE2_ALLOWOVERLAP_NO,    "No" },
19486    { -1,                           NULL }, /* terminator */
19487 };
19488 
19489 /*! \brief Convert AllowOverlap setting to printable string */
19490 static const char *allowoverlap2str(int mode)
19491 {
19492    return map_x_s(allowoverlapstr, mode, "<error>");
19493 }
19494 
19495 static const struct _map_x_s trust_id_outboundstr[] = {
19496    { SIP_PAGE2_TRUST_ID_OUTBOUND_LEGACY,  "Legacy" },
19497    { SIP_PAGE2_TRUST_ID_OUTBOUND_NO,      "No" },
19498    { SIP_PAGE2_TRUST_ID_OUTBOUND_YES,     "Yes" },
19499    { -1,                                  NULL }, /* terminator */
19500 };
19501 
19502 static const char *trust_id_outbound2str(int mode)
19503 {
19504    return map_x_s(trust_id_outboundstr, mode, "<error>");
19505 }
19506 
19507 /*! \brief Destroy disused contexts between reloads
19508    Only used in reload_config so the code for regcontext doesn't get ugly
19509 */
19510 static void cleanup_stale_contexts(char *new, char *old)
19511 {
19512    char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
19513 
19514    while ((oldcontext = strsep(&old, "&"))) {
19515       stalecontext = '\0';
19516       ast_copy_string(newlist, new, sizeof(newlist));
19517       stringp = newlist;
19518       while ((newcontext = strsep(&stringp, "&"))) {
19519          if (!strcmp(newcontext, oldcontext)) {
19520             /* This is not the context you're looking for */
19521             stalecontext = '\0';
19522             break;
19523          } else if (strcmp(newcontext, oldcontext)) {
19524             stalecontext = oldcontext;
19525          }
19526          
19527       }
19528       if (stalecontext)
19529          ast_context_destroy(ast_context_find(stalecontext), "SIP");
19530    }
19531 }
19532 
19533 /*!
19534  * \brief Check RTP Timeout on dialogs
19535  *
19536  * \details This is used with ao2_callback to check rtptimeout
19537  * rtponholdtimeout and send rtpkeepalive packets.
19538  *
19539  * \return CMP_MATCH for items to be unlinked from dialogs_rtpcheck.
19540  */
19541 static int dialog_checkrtp_cb(void *dialogobj, void *arg, int flags)
19542 {
19543    struct sip_pvt *dialog = dialogobj;
19544    time_t *t = arg;
19545    int match_status;
19546 
19547    if (sip_pvt_trylock(dialog)) {
19548       return 0;
19549    }
19550 
19551    if (dialog->rtp || dialog->vrtp) {
19552       match_status = check_rtp_timeout(dialog, *t);
19553    } else {
19554       /* Dialog has no active RTP or VRTP. unlink it from dialogs_rtpcheck. */
19555       match_status = CMP_MATCH;
19556    }
19557    sip_pvt_unlock(dialog);
19558 
19559    return match_status;
19560 }
19561 
19562 /*!
19563  * \brief Match dialogs that need to be destroyed
19564  *
19565  * \details This is used with ao2_callback to unlink/delete all dialogs that
19566  * are marked needdestroy.
19567  *
19568  * \todo Re-work this to improve efficiency.  Currently, this function is called
19569  * on _every_ dialog after processing _every_ incoming SIP/UDP packet, or
19570  * potentially even more often when the scheduler has entries to run.
19571  */
19572 static int dialog_needdestroy(void *dialogobj, void *arg, int flags)
19573 {
19574    struct sip_pvt *dialog = dialogobj;
19575 
19576    if (sip_pvt_trylock(dialog)) {
19577       /* Don't block the monitor thread.  This function is called often enough
19578        * that we can wait for the next time around. */
19579       return 0;
19580    }
19581 
19582    /* If we have sessions that needs to be destroyed, do it now */
19583    /* Check if we have outstanding requests not responsed to or an active call
19584       - if that's the case, wait with destruction */
19585    if (dialog->needdestroy && !dialog->packets && !dialog->owner) {
19586       /* We absolutely cannot destroy the rtp struct while a bridge is active or we WILL crash */
19587       if (dialog->rtp && ast_rtp_instance_get_bridged(dialog->rtp)) {
19588          ast_debug(2, "Bridge still active.  Delaying destruction of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
19589          sip_pvt_unlock(dialog);
19590          return 0;
19591       }
19592 
19593       if (dialog->vrtp && ast_rtp_instance_get_bridged(dialog->vrtp)) {
19594          ast_debug(2, "Bridge still active.  Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
19595          sip_pvt_unlock(dialog);
19596          return 0;
19597       }
19598 
19599       sip_pvt_unlock(dialog);
19600       /* no, the unlink should handle this: dialog_unref(dialog, "needdestroy: one more refcount decrement to allow dialog to be destroyed"); */
19601       /* the CMP_MATCH will unlink this dialog from the dialog hash table */
19602       dialog_unlink_all(dialog);
19603       return 0; /* the unlink_all should unlink this from the table, so.... no need to return a match */
19604    }
19605 
19606    sip_pvt_unlock(dialog);
19607 
19608    return 0;
19609 }
19610 
19611 /*! \brief Remove temporary realtime objects from memory (CLI) */
19612 /*! \todo XXXX Propably needs an overhaul after removal of the devices */
19613 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19614 {
19615    struct sip_peer *peer, *pi;
19616    int prunepeer = FALSE;
19617    int multi = FALSE;
19618    const char *name = NULL;
19619    regex_t regexbuf;
19620    int havepattern = 0;
19621    struct ao2_iterator i;
19622    static const char * const choices[] = { "all", "like", NULL };
19623    char *cmplt;
19624    
19625    if (cmd == CLI_INIT) {
19626       e->command = "sip prune realtime [peer|all]";
19627       e->usage =
19628          "Usage: sip prune realtime [peer [<name>|all|like <pattern>]|all]\n"
19629          "       Prunes object(s) from the cache.\n"
19630          "       Optional regular expression pattern is used to filter the objects.\n";
19631       return NULL;
19632    } else if (cmd == CLI_GENERATE) {
19633       if (a->pos == 4 && !strcasecmp(a->argv[3], "peer")) {
19634          cmplt = ast_cli_complete(a->word, choices, a->n);
19635          if (!cmplt)
19636             cmplt = complete_sip_peer(a->word, a->n - sizeof(choices), SIP_PAGE2_RTCACHEFRIENDS);
19637          return cmplt;
19638       }
19639       if (a->pos == 5 && !strcasecmp(a->argv[4], "like"))
19640          return complete_sip_peer(a->word, a->n, SIP_PAGE2_RTCACHEFRIENDS);
19641       return NULL;
19642    }
19643    switch (a->argc) {
19644    case 4:
19645       name = a->argv[3];
19646       /* we accept a name in position 3, but keywords are not good. */
19647       if (!strcasecmp(name, "peer") || !strcasecmp(name, "like"))
19648          return CLI_SHOWUSAGE;
19649       prunepeer = TRUE;
19650       if (!strcasecmp(name, "all")) {
19651          multi = TRUE;
19652          name = NULL;
19653       }
19654       /* else a single name, already set */
19655       break;
19656    case 5:
19657       /* sip prune realtime {peer|like} name */
19658       name = a->argv[4];
19659       if (!strcasecmp(a->argv[3], "peer"))
19660          prunepeer = TRUE;
19661       else if (!strcasecmp(a->argv[3], "like")) {
19662          prunepeer = TRUE;
19663          multi = TRUE;
19664       } else
19665          return CLI_SHOWUSAGE;
19666       if (!strcasecmp(name, "like"))
19667          return CLI_SHOWUSAGE;
19668       if (!multi && !strcasecmp(name, "all")) {
19669          multi = TRUE;
19670          name = NULL;
19671       }
19672       break;
19673    case 6:
19674       name = a->argv[5];
19675       multi = TRUE;
19676       /* sip prune realtime {peer} like name */
19677       if (strcasecmp(a->argv[4], "like"))
19678          return CLI_SHOWUSAGE;
19679       if (!strcasecmp(a->argv[3], "peer")) {
19680          prunepeer = TRUE;
19681       } else
19682          return CLI_SHOWUSAGE;
19683       break;
19684    default:
19685       return CLI_SHOWUSAGE;
19686    }
19687 
19688    if (multi && name) {
19689       if (regcomp(&regexbuf, name, REG_EXTENDED | REG_NOSUB)) {
19690          return CLI_SHOWUSAGE;
19691       }
19692       havepattern = 1;
19693    }
19694 
19695    if (multi) {
19696       if (prunepeer) {
19697          int pruned = 0;
19698          
19699          i = ao2_iterator_init(peers, 0);
19700          while ((pi = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
19701             ao2_lock(pi);
19702             if (name && regexec(&regexbuf, pi->name, 0, NULL, 0)) {
19703                ao2_unlock(pi);
19704                sip_unref_peer(pi, "toss iterator peer ptr before continue");
19705                continue;
19706             };
19707             if (ast_test_flag(&pi->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
19708                pi->the_mark = 1;
19709                pruned++;
19710             }
19711             ao2_unlock(pi);
19712             sip_unref_peer(pi, "toss iterator peer ptr");
19713          }
19714          ao2_iterator_destroy(&i);
19715          if (pruned) {
19716             unlink_marked_peers_from_tables();
19717             ast_cli(a->fd, "%d peers pruned.\n", pruned);
19718          } else
19719             ast_cli(a->fd, "No peers found to prune.\n");
19720       }
19721    } else {
19722       if (prunepeer) {
19723          struct sip_peer tmp;
19724          ast_copy_string(tmp.name, name, sizeof(tmp.name));
19725          if ((peer = ao2_t_find(peers, &tmp, OBJ_POINTER | OBJ_UNLINK, "finding to unlink from peers"))) {
19726             if (!ast_sockaddr_isnull(&peer->addr)) {
19727                ao2_t_unlink(peers_by_ip, peer, "unlinking peer from peers_by_ip also");
19728             }
19729             if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
19730                ast_cli(a->fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
19731                /* put it back! */
19732                ao2_t_link(peers, peer, "link peer into peer table");
19733                if (!ast_sockaddr_isnull(&peer->addr)) {
19734                   ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
19735                }
19736             } else
19737                ast_cli(a->fd, "Peer '%s' pruned.\n", name);
19738             sip_unref_peer(peer, "sip_prune_realtime: sip_unref_peer: tossing temp peer ptr");
19739          } else
19740             ast_cli(a->fd, "Peer '%s' not found.\n", name);
19741       }
19742    }
19743 
19744    if (havepattern) {
19745       regfree(&regexbuf);
19746    }
19747 
19748    return CLI_SUCCESS;
19749 }
19750 
19751 /*! \brief Print codec list from preference to CLI/manager */
19752 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
19753 {
19754    int x;
19755    struct ast_format codec;
19756 
19757    for(x = 0; x < AST_CODEC_PREF_SIZE; x++) {
19758       if (!(ast_codec_pref_index(pref, x, &codec))) {
19759          break;
19760       }
19761       ast_cli(fd, "%s", ast_getformatname(&codec));
19762       ast_cli(fd, ":%d", pref->framing[x]);
19763       if (x < 31 && ast_codec_pref_index(pref, x + 1, &codec))
19764          ast_cli(fd, ",");
19765    }
19766    if (!x)
19767       ast_cli(fd, "none");
19768 }
19769 
19770 /*! \brief Print domain mode to cli */
19771 static const char *domain_mode_to_text(const enum domain_mode mode)
19772 {
19773    switch (mode) {
19774    case SIP_DOMAIN_AUTO:
19775       return "[Automatic]";
19776    case SIP_DOMAIN_CONFIG:
19777       return "[Configured]";
19778    }
19779 
19780    return "";
19781 }
19782 
19783 /*! \brief CLI command to list local domains */
19784 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19785 {
19786    struct domain *d;
19787 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
19788 
19789    switch (cmd) {
19790    case CLI_INIT:
19791       e->command = "sip show domains";
19792       e->usage =
19793          "Usage: sip show domains\n"
19794          "       Lists all configured SIP local domains.\n"
19795          "       Asterisk only responds to SIP messages to local domains.\n";
19796       return NULL;
19797    case CLI_GENERATE:
19798       return NULL;
19799    }
19800 
19801    if (AST_LIST_EMPTY(&domain_list)) {
19802       ast_cli(a->fd, "SIP Domain support not enabled.\n\n");
19803       return CLI_SUCCESS;
19804    } else {
19805       ast_cli(a->fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
19806       AST_LIST_LOCK(&domain_list);
19807       AST_LIST_TRAVERSE(&domain_list, d, list)
19808          ast_cli(a->fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
19809             domain_mode_to_text(d->mode));
19810       AST_LIST_UNLOCK(&domain_list);
19811       ast_cli(a->fd, "\n");
19812       return CLI_SUCCESS;
19813    }
19814 }
19815 #undef FORMAT
19816 
19817 /*! \brief Show SIP peers in the manager API  */
19818 static int manager_sip_show_peer(struct mansession *s, const struct message *m)
19819 {
19820    const char *a[4];
19821    const char *peer;
19822 
19823    peer = astman_get_header(m, "Peer");
19824    if (ast_strlen_zero(peer)) {
19825       astman_send_error(s, m, "Peer: <name> missing.");
19826       return 0;
19827    }
19828    a[0] = "sip";
19829    a[1] = "show";
19830    a[2] = "peer";
19831    a[3] = peer;
19832 
19833    _sip_show_peer(1, -1, s, m, 4, a);
19834    astman_append(s, "\r\n" );
19835    return 0;
19836 }
19837 
19838 /*! \brief Show one peer in detail */
19839 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19840 {
19841    switch (cmd) {
19842    case CLI_INIT:
19843       e->command = "sip show peer";
19844       e->usage =
19845          "Usage: sip show peer <name> [load]\n"
19846          "       Shows all details on one SIP peer and the current status.\n"
19847          "       Option \"load\" forces lookup of peer in realtime storage.\n";
19848       return NULL;
19849    case CLI_GENERATE:
19850       return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
19851    }
19852    return _sip_show_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
19853 }
19854 
19855 static void send_manager_peer_status(struct mansession *s, struct sip_peer *peer, const char *idText)
19856 {
19857    char time[128] = "";
19858    char status[128] = "";
19859    if (peer->maxms) {
19860       if (peer->lastms < 0) {
19861          snprintf(status, sizeof(status), "PeerStatus: Unreachable\r\n");
19862       } else if (peer->lastms > peer->maxms) {
19863          snprintf(status, sizeof(status), "PeerStatus: Lagged\r\n");
19864          snprintf(time, sizeof(time), "Time: %d\r\n", peer->lastms);
19865       } else if (peer->lastms) {
19866          snprintf(status, sizeof(status), "PeerStatus: Reachable\r\n");
19867          snprintf(time, sizeof(time), "Time: %d\r\n", peer->lastms);
19868       } else {
19869          snprintf(status, sizeof(status), "PeerStatus: Unknown\r\n");
19870       }
19871    } else {
19872       snprintf(status, sizeof(status), "PeerStatus: Unmonitored\r\n");
19873    }
19874 
19875    astman_append(s,
19876    "Event: PeerStatus\r\n"
19877    "Privilege: System\r\n"
19878    "ChannelType: SIP\r\n"
19879    "Peer: SIP/%s\r\n"
19880    "%s"
19881    "%s"
19882    "%s"
19883    "\r\n",
19884    peer->name, status, time, idText);
19885 }
19886 
19887 /*! \brief Show SIP peers in the manager API  */
19888 static int manager_sip_peer_status(struct mansession *s, const struct message *m)
19889 {
19890    const char *id = astman_get_header(m,"ActionID");
19891    const char *peer_name = astman_get_header(m,"Peer");
19892    char idText[256] = "";
19893    struct sip_peer *peer = NULL;
19894 
19895    if (!ast_strlen_zero(id)) {
19896       snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
19897    }
19898 
19899    if (!ast_strlen_zero(peer_name)) {
19900       /* strip SIP/ from the begining of the peer name */
19901       if (strlen(peer_name) >= 4 && !strncasecmp("SIP/", peer_name, 4)) {
19902          peer_name += 4;
19903       }
19904 
19905       peer = sip_find_peer(peer_name, NULL, TRUE, FINDPEERS, FALSE, 0);
19906       if (!peer) {
19907          astman_send_error(s, m, "No such peer");
19908          return 0;
19909       }
19910    }
19911 
19912    astman_send_ack(s, m, "Peer status will follow");
19913 
19914    if (!peer) {
19915       struct ao2_iterator i = ao2_iterator_init(peers, 0);
19916       while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table for SIPpeerstatus"))) {
19917          ao2_lock(peer);
19918          send_manager_peer_status(s, peer, idText);
19919          ao2_unlock(peer);
19920          sip_unref_peer(peer, "unref peer for SIPpeerstatus");
19921       }
19922       ao2_iterator_destroy(&i);
19923    } else {
19924       ao2_lock(peer);
19925       send_manager_peer_status(s, peer, idText);
19926       ao2_unlock(peer);
19927       sip_unref_peer(peer, "unref peer for SIPpeerstatus");
19928    }
19929 
19930 
19931    astman_append(s,
19932    "Event: SIPpeerstatusComplete\r\n"
19933    "%s"
19934    "\r\n",
19935    idText);
19936 
19937    return 0;
19938 }
19939 
19940 
19941 /*! \brief Send qualify message to peer from cli or manager. Mostly for debugging. */
19942 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
19943 {
19944    struct sip_peer *peer;
19945    int load_realtime;
19946 
19947    if (argc < 4)
19948       return CLI_SHOWUSAGE;
19949 
19950    load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
19951    if ((peer = sip_find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0))) {
19952       sip_poke_peer(peer, 1);
19953       sip_unref_peer(peer, "qualify: done with peer");
19954    } else if (type == 0) {
19955       ast_cli(fd, "Peer '%s' not found\n", argv[3]);
19956    } else {
19957       astman_send_error(s, m, "Peer not found");
19958    }
19959    return CLI_SUCCESS;
19960 }
19961 
19962 /*! \brief Qualify SIP peers in the manager API  */
19963 static int manager_sip_qualify_peer(struct mansession *s, const struct message *m)
19964 {
19965    const char *a[4];
19966    const char *peer;
19967 
19968    peer = astman_get_header(m, "Peer");
19969    if (ast_strlen_zero(peer)) {
19970       astman_send_error(s, m, "Peer: <name> missing.");
19971       return 0;
19972    }
19973    a[0] = "sip";
19974    a[1] = "qualify";
19975    a[2] = "peer";
19976    a[3] = peer;
19977 
19978    _sip_qualify_peer(1, -1, s, m, 4, a);
19979    astman_append(s, "\r\n\r\n" );
19980    return 0;
19981 }
19982 
19983 /*! \brief Send an OPTIONS packet to a SIP peer */
19984 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19985 {
19986    switch (cmd) {
19987    case CLI_INIT:
19988       e->command = "sip qualify peer";
19989       e->usage =
19990          "Usage: sip qualify peer <name> [load]\n"
19991          "       Requests a response from one SIP peer and the current status.\n"
19992          "       Option \"load\" forces lookup of peer in realtime storage.\n";
19993       return NULL;
19994    case CLI_GENERATE:
19995       return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
19996    }
19997    return _sip_qualify_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
19998 }
19999 
20000 /*! \brief list peer mailboxes to CLI */
20001 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer)
20002 {
20003    struct sip_mailbox *mailbox;
20004 
20005    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
20006       ast_str_append(mailbox_str, 0, "%s%s%s%s",
20007          mailbox->mailbox,
20008          ast_strlen_zero(mailbox->context) ? "" : "@",
20009          S_OR(mailbox->context, ""),
20010          AST_LIST_NEXT(mailbox, entry) ? "," : "");
20011    }
20012 }
20013 
20014 static struct _map_x_s faxecmodes[] = {
20015    { SIP_PAGE2_T38SUPPORT_UDPTL,       "None"},
20016    { SIP_PAGE2_T38SUPPORT_UDPTL_FEC,      "FEC"},
20017    { SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY,  "Redundancy"},
20018    { -1,                NULL},
20019 };
20020 
20021 static const char *faxec2str(int faxec)
20022 {
20023    return map_x_s(faxecmodes, faxec, "Unknown");
20024 }
20025 
20026 /*! \brief Show one peer in detail (main function) */
20027 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
20028 {
20029    char status[30] = "";
20030    char cbuf[256];
20031    struct sip_peer *peer;
20032    char codec_buf[512];
20033    struct ast_codec_pref *pref;
20034    struct ast_variable *v;
20035    int x = 0, load_realtime;
20036    struct ast_format codec;
20037    int realtimepeers;
20038 
20039    realtimepeers = ast_check_realtime("sippeers");
20040 
20041    if (argc < 4)
20042       return CLI_SHOWUSAGE;
20043 
20044    load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
20045    peer = sip_find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0);
20046 
20047    if (s) {    /* Manager */
20048       if (peer) {
20049          const char *id = astman_get_header(m, "ActionID");
20050 
20051          astman_append(s, "Response: Success\r\n");
20052          if (!ast_strlen_zero(id))
20053             astman_append(s, "ActionID: %s\r\n", id);
20054       } else {
20055          snprintf (cbuf, sizeof(cbuf), "Peer %s not found.", argv[3]);
20056          astman_send_error(s, m, cbuf);
20057          return CLI_SUCCESS;
20058       }
20059    }
20060    if (peer && type==0 ) { /* Normal listing */
20061       struct ast_str *mailbox_str = ast_str_alloca(512);
20062       struct sip_auth_container *credentials;
20063 
20064       ao2_lock(peer);
20065       credentials = peer->auth;
20066       if (credentials) {
20067          ao2_t_ref(credentials, +1, "Ref peer auth for show");
20068       }
20069       ao2_unlock(peer);
20070 
20071       ast_cli(fd, "\n\n");
20072       ast_cli(fd, "  * Name       : %s\n", peer->name);
20073       ast_cli(fd, "  Description  : %s\n", peer->description);
20074       if (realtimepeers) { /* Realtime is enabled */
20075          ast_cli(fd, "  Realtime peer: %s\n", peer->is_realtime ? "Yes, cached" : "No");
20076       }
20077       ast_cli(fd, "  Secret       : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
20078       ast_cli(fd, "  MD5Secret    : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
20079       ast_cli(fd, "  Remote Secret: %s\n", ast_strlen_zero(peer->remotesecret)?"<Not set>":"<Set>");
20080       if (credentials) {
20081          struct sip_auth *auth;
20082 
20083          AST_LIST_TRAVERSE(&credentials->list, auth, node) {
20084             ast_cli(fd, "  Realm-auth   : Realm %-15.15s User %-10.20s %s\n",
20085                auth->realm,
20086                auth->username,
20087                !ast_strlen_zero(auth->secret)
20088                   ? "<Secret set>"
20089                   : (!ast_strlen_zero(auth->md5secret)
20090                      ? "<MD5secret set>" : "<Not set>"));
20091          }
20092          ao2_t_ref(credentials, -1, "Unref peer auth for show");
20093       }
20094       ast_cli(fd, "  Context      : %s\n", peer->context);
20095       ast_cli(fd, "  Record On feature : %s\n", peer->record_on_feature);
20096       ast_cli(fd, "  Record Off feature : %s\n", peer->record_off_feature);
20097       ast_cli(fd, "  Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
20098       ast_cli(fd, "  Language     : %s\n", peer->language);
20099       ast_cli(fd, "  Tonezone     : %s\n", peer->zone[0] != '\0' ? peer->zone : "<Not set>");
20100       if (!ast_strlen_zero(peer->accountcode))
20101          ast_cli(fd, "  Accountcode  : %s\n", peer->accountcode);
20102       ast_cli(fd, "  AMA flags    : %s\n", ast_cdr_flags2str(peer->amaflags));
20103       ast_cli(fd, "  Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
20104       ast_cli(fd, "  CallingPres  : %s\n", ast_describe_caller_presentation(peer->callingpres));
20105       if (!ast_strlen_zero(peer->fromuser))
20106          ast_cli(fd, "  FromUser     : %s\n", peer->fromuser);
20107       if (!ast_strlen_zero(peer->fromdomain))
20108          ast_cli(fd, "  FromDomain   : %s Port %d\n", peer->fromdomain, (peer->fromdomainport) ? peer->fromdomainport : STANDARD_SIP_PORT);
20109       ast_cli(fd, "  Callgroup    : ");
20110       print_group(fd, peer->callgroup, 0);
20111       ast_cli(fd, "  Pickupgroup  : ");
20112       print_group(fd, peer->pickupgroup, 0);
20113       ast_cli(fd, "  Named Callgr : ");
20114       print_named_groups(fd, peer->named_callgroups, 0);
20115       ast_cli(fd, "  Nam. Pickupgr: ");
20116       print_named_groups(fd, peer->named_pickupgroups, 0);
20117       peer_mailboxes_to_str(&mailbox_str, peer);
20118       ast_cli(fd, "  MOH Suggest  : %s\n", peer->mohsuggest);
20119       ast_cli(fd, "  Mailbox      : %s\n", ast_str_buffer(mailbox_str));
20120       ast_cli(fd, "  VM Extension : %s\n", peer->vmexten);
20121       ast_cli(fd, "  LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
20122       ast_cli(fd, "  Call limit   : %d\n", peer->call_limit);
20123       ast_cli(fd, "  Max forwards : %d\n", peer->maxforwards);
20124       if (peer->busy_level)
20125          ast_cli(fd, "  Busy level   : %d\n", peer->busy_level);
20126       ast_cli(fd, "  Dynamic      : %s\n", AST_CLI_YESNO(peer->host_dynamic));
20127       ast_cli(fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
20128       ast_cli(fd, "  MaxCallBR    : %d kbps\n", peer->maxcallbitrate);
20129       ast_cli(fd, "  Expire       : %ld\n", ast_sched_when(sched, peer->expire));
20130       ast_cli(fd, "  Insecure     : %s\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
20131       ast_cli(fd, "  Force rport  : %s\n", force_rport_string(peer->flags));
20132       ast_cli(fd, "  Symmetric RTP: %s\n", comedia_string(peer->flags));
20133       ast_cli(fd, "  ACL          : %s\n", AST_CLI_YESNO(ast_acl_list_is_empty(peer->acl) == 0));
20134       ast_cli(fd, "  DirectMedACL : %s\n", AST_CLI_YESNO(ast_acl_list_is_empty(peer->directmediaacl) == 0));
20135       ast_cli(fd, "  T.38 support : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
20136       ast_cli(fd, "  T.38 EC mode : %s\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
20137       ast_cli(fd, "  T.38 MaxDtgrm: %u\n", peer->t38_maxdatagram);
20138       ast_cli(fd, "  DirectMedia  : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)));
20139       ast_cli(fd, "  PromiscRedir : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)));
20140       ast_cli(fd, "  User=Phone   : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)));
20141       ast_cli(fd, "  Video Support: %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) || ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS)));
20142       ast_cli(fd, "  Text Support : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)));
20143       ast_cli(fd, "  Ign SDP ver  : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_IGNORESDPVERSION)));
20144       ast_cli(fd, "  Trust RPID   : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_TRUSTRPID)));
20145       ast_cli(fd, "  Send RPID    : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_SENDRPID)));
20146       ast_cli(fd, "  TrustIDOutbnd: %s\n", trust_id_outbound2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND)));
20147       ast_cli(fd, "  Subscriptions: %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
20148       ast_cli(fd, "  Overlap dial : %s\n", allowoverlap2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP)));
20149       if (peer->outboundproxy)
20150          ast_cli(fd, "  Outb. proxy  : %s %s\n", ast_strlen_zero(peer->outboundproxy->name) ? "<not set>" : peer->outboundproxy->name,
20151                      peer->outboundproxy->force ? "(forced)" : "");
20152 
20153       /* - is enumerated */
20154       ast_cli(fd, "  DTMFmode     : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
20155       ast_cli(fd, "  Timer T1     : %d\n", peer->timer_t1);
20156       ast_cli(fd, "  Timer B      : %d\n", peer->timer_b);
20157       ast_cli(fd, "  ToHost       : %s\n", peer->tohost);
20158       ast_cli(fd, "  Addr->IP     : %s\n", ast_sockaddr_stringify(&peer->addr));
20159       ast_cli(fd, "  Defaddr->IP  : %s\n", ast_sockaddr_stringify(&peer->defaddr));
20160       ast_cli(fd, "  Prim.Transp. : %s\n", sip_get_transport(peer->socket.type));
20161       ast_cli(fd, "  Allowed.Trsp : %s\n", get_transport_list(peer->transports));
20162       if (!ast_strlen_zero(sip_cfg.regcontext))
20163          ast_cli(fd, "  Reg. exten   : %s\n", peer->regexten);
20164       ast_cli(fd, "  Def. Username: %s\n", peer->username);
20165       ast_cli(fd, "  SIP Options  : ");
20166       if (peer->sipoptions) {
20167          int lastoption = -1;
20168          for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
20169             if (sip_options[x].id != lastoption) {
20170                if (peer->sipoptions & sip_options[x].id)
20171                   ast_cli(fd, "%s ", sip_options[x].text);
20172                lastoption = x;
20173             }
20174          }
20175       } else
20176          ast_cli(fd, "(none)");
20177 
20178       ast_cli(fd, "\n");
20179       ast_cli(fd, "  Codecs       : ");
20180       ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->caps);
20181       ast_cli(fd, "%s\n", codec_buf);
20182       ast_cli(fd, "  Codec Order  : (");
20183       print_codec_to_cli(fd, &peer->prefs);
20184       ast_cli(fd, ")\n");
20185 
20186       ast_cli(fd, "  Auto-Framing : %s\n", AST_CLI_YESNO(peer->autoframing));
20187       ast_cli(fd, "  Status       : ");
20188       peer_status(peer, status, sizeof(status));
20189       ast_cli(fd, "%s\n", status);
20190       ast_cli(fd, "  Useragent    : %s\n", peer->useragent);
20191       ast_cli(fd, "  Reg. Contact : %s\n", peer->fullcontact);
20192       ast_cli(fd, "  Qualify Freq : %d ms\n", peer->qualifyfreq);
20193       ast_cli(fd, "  Keepalive    : %d ms\n", peer->keepalive * 1000);
20194       if (peer->chanvars) {
20195          ast_cli(fd, "  Variables    :\n");
20196          for (v = peer->chanvars ; v ; v = v->next)
20197             ast_cli(fd, "                 %s = %s\n", v->name, v->value);
20198       }
20199 
20200       ast_cli(fd, "  Sess-Timers  : %s\n", stmode2str(peer->stimer.st_mode_oper));
20201       ast_cli(fd, "  Sess-Refresh : %s\n", strefresherparam2str(peer->stimer.st_ref));
20202       ast_cli(fd, "  Sess-Expires : %d secs\n", peer->stimer.st_max_se);
20203       ast_cli(fd, "  Min-Sess     : %d secs\n", peer->stimer.st_min_se);
20204       ast_cli(fd, "  RTP Engine   : %s\n", peer->engine);
20205       ast_cli(fd, "  Parkinglot   : %s\n", peer->parkinglot);
20206       ast_cli(fd, "  Use Reason   : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_Q850_REASON)));
20207       ast_cli(fd, "  Encryption   : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP)));
20208       ast_cli(fd, "\n");
20209       peer = sip_unref_peer(peer, "sip_show_peer: sip_unref_peer: done with peer ptr");
20210    } else  if (peer && type == 1) { /* manager listing */
20211       char buffer[256];
20212       struct ast_str *tmp_str = ast_str_alloca(512);
20213       astman_append(s, "Channeltype: SIP\r\n");
20214       astman_append(s, "ObjectName: %s\r\n", peer->name);
20215       astman_append(s, "ChanObjectType: peer\r\n");
20216       astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
20217       astman_append(s, "RemoteSecretExist: %s\r\n", ast_strlen_zero(peer->remotesecret)?"N":"Y");
20218       astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
20219       astman_append(s, "Context: %s\r\n", peer->context);
20220       astman_append(s, "Language: %s\r\n", peer->language);
20221       astman_append(s, "ToneZone: %s\r\n", peer->zone[0] != '\0' ? peer->zone : "<Not set>");
20222       if (!ast_strlen_zero(peer->accountcode))
20223          astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
20224       astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
20225       astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
20226       if (!ast_strlen_zero(peer->fromuser))
20227          astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
20228       if (!ast_strlen_zero(peer->fromdomain))
20229          astman_append(s, "SIP-FromDomain: %s\r\nSip-FromDomain-Port: %d\r\n", peer->fromdomain, (peer->fromdomainport) ? peer->fromdomainport : STANDARD_SIP_PORT);
20230       astman_append(s, "Callgroup: ");
20231       astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->callgroup));
20232       astman_append(s, "Pickupgroup: ");
20233       astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->pickupgroup));
20234       astman_append(s, "Named Callgroup: ");
20235       astman_append(s, "%s\r\n", ast_print_namedgroups(&tmp_str, peer->named_callgroups));
20236       ast_str_reset(tmp_str);
20237       astman_append(s, "Named Pickupgroup: ");
20238       astman_append(s, "%s\r\n", ast_print_namedgroups(&tmp_str, peer->named_pickupgroups));
20239       ast_str_reset(tmp_str);
20240       astman_append(s, "MOHSuggest: %s\r\n", peer->mohsuggest);
20241       peer_mailboxes_to_str(&tmp_str, peer);
20242       astman_append(s, "VoiceMailbox: %s\r\n", ast_str_buffer(tmp_str));
20243       astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
20244       astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
20245       astman_append(s, "Maxforwards: %d\r\n", peer->maxforwards);
20246       astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
20247       astman_append(s, "Busy-level: %d\r\n", peer->busy_level);
20248       astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
20249       astman_append(s, "Dynamic: %s\r\n", peer->host_dynamic?"Y":"N");
20250       astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
20251       astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched, peer->expire));
20252       astman_append(s, "SIP-AuthInsecure: %s\r\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
20253       astman_append(s, "SIP-Forcerport: %s\r\n", ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_RPORT) ?
20254             (ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? "A" : "a") :
20255             (ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? "Y" : "N"));
20256       astman_append(s, "SIP-Comedia: %s\r\n", ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_COMEDIA) ?
20257             (ast_test_flag(&peer->flags[1], SIP_PAGE2_SYMMETRICRTP) ? "A" : "a") :
20258             (ast_test_flag(&peer->flags[1], SIP_PAGE2_SYMMETRICRTP) ? "Y" : "N"));
20259       astman_append(s, "ACL: %s\r\n", (ast_acl_list_is_empty(peer->acl) ? "N" : "Y"));
20260       astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
20261       astman_append(s, "SIP-DirectMedia: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
20262       astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
20263       astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
20264       astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
20265       astman_append(s, "SIP-TextSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)?"Y":"N"));
20266       astman_append(s, "SIP-T.38Support: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)?"Y":"N"));
20267       astman_append(s, "SIP-T.38EC: %s\r\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
20268       astman_append(s, "SIP-T.38MaxDtgrm: %u\r\n", peer->t38_maxdatagram);
20269       astman_append(s, "SIP-Sess-Timers: %s\r\n", stmode2str(peer->stimer.st_mode_oper));
20270       astman_append(s, "SIP-Sess-Refresh: %s\r\n", strefresherparam2str(peer->stimer.st_ref));
20271       astman_append(s, "SIP-Sess-Expires: %d\r\n", peer->stimer.st_max_se);
20272       astman_append(s, "SIP-Sess-Min: %d\r\n", peer->stimer.st_min_se);
20273       astman_append(s, "SIP-RTP-Engine: %s\r\n", peer->engine);
20274       astman_append(s, "SIP-Encryption: %s\r\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP) ? "Y" : "N");
20275 
20276       /* - is enumerated */
20277       astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
20278       astman_append(s, "ToHost: %s\r\n", peer->tohost);
20279       astman_append(s, "Address-IP: %s\r\nAddress-Port: %d\r\n", ast_sockaddr_stringify_addr(&peer->addr), ast_sockaddr_port(&peer->addr));
20280       astman_append(s, "Default-addr-IP: %s\r\nDefault-addr-port: %d\r\n", ast_sockaddr_stringify_addr(&peer->defaddr), ast_sockaddr_port(&peer->defaddr));
20281       astman_append(s, "Default-Username: %s\r\n", peer->username);
20282       if (!ast_strlen_zero(sip_cfg.regcontext))
20283          astman_append(s, "RegExtension: %s\r\n", peer->regexten);
20284       astman_append(s, "Codecs: ");
20285       ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->caps);
20286       astman_append(s, "%s\r\n", codec_buf);
20287       astman_append(s, "CodecOrder: ");
20288       pref = &peer->prefs;
20289       for(x = 0; x < AST_CODEC_PREF_SIZE ; x++) {
20290          if (!(ast_codec_pref_index(pref, x, &codec))) {
20291             break;
20292          }
20293          astman_append(s, "%s", ast_getformatname(&codec));
20294          if ((x < (AST_CODEC_PREF_SIZE - 1)) && ast_codec_pref_index(pref, x+1, &codec))
20295             astman_append(s, ",");
20296       }
20297 
20298       astman_append(s, "\r\n");
20299       astman_append(s, "Status: ");
20300       peer_status(peer, status, sizeof(status));
20301       astman_append(s, "%s\r\n", status);
20302       astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
20303       astman_append(s, "Reg-Contact: %s\r\n", peer->fullcontact);
20304       astman_append(s, "QualifyFreq: %d ms\r\n", peer->qualifyfreq);
20305       astman_append(s, "Parkinglot: %s\r\n", peer->parkinglot);
20306       if (peer->chanvars) {
20307          for (v = peer->chanvars ; v ; v = v->next) {
20308             astman_append(s, "ChanVariable: %s=%s\r\n", v->name, v->value);
20309          }
20310       }
20311       astman_append(s, "SIP-Use-Reason-Header: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_Q850_REASON)) ? "Y" : "N");
20312       astman_append(s, "Description: %s\r\n", peer->description);
20313 
20314       peer = sip_unref_peer(peer, "sip_show_peer: sip_unref_peer: done with peer");
20315 
20316    } else {
20317       ast_cli(fd, "Peer %s not found.\n", argv[3]);
20318       ast_cli(fd, "\n");
20319    }
20320 
20321    return CLI_SUCCESS;
20322 }
20323 
20324 /*! \brief Do completion on user name */
20325 static char *complete_sip_user(const char *word, int state)
20326 {
20327    char *result = NULL;
20328    int wordlen = strlen(word);
20329    int which = 0;
20330    struct ao2_iterator user_iter;
20331    struct sip_peer *user;
20332 
20333    user_iter = ao2_iterator_init(peers, 0);
20334    while ((user = ao2_t_iterator_next(&user_iter, "iterate thru peers table"))) {
20335       ao2_lock(user);
20336       if (!(user->type & SIP_TYPE_USER)) {
20337          ao2_unlock(user);
20338          sip_unref_peer(user, "complete sip user");
20339          continue;
20340       }
20341       /* locking of the object is not required because only the name and flags are being compared */
20342       if (!strncasecmp(word, user->name, wordlen) && ++which > state) {
20343          result = ast_strdup(user->name);
20344       }
20345       ao2_unlock(user);
20346       sip_unref_peer(user, "complete sip user");
20347       if (result) {
20348          break;
20349       }
20350    }
20351    ao2_iterator_destroy(&user_iter);
20352    return result;
20353 }
20354 /*! \brief Support routine for 'sip show user' CLI */
20355 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
20356 {
20357    if (pos == 3)
20358       return complete_sip_user(word, state);
20359 
20360    return NULL;
20361 }
20362 
20363 /*! \brief Show one user in detail */
20364 static char *sip_show_user(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
20365 {
20366    char cbuf[256];
20367    struct sip_peer *user;
20368    struct ast_variable *v;
20369    int load_realtime;
20370 
20371    switch (cmd) {
20372    case CLI_INIT:
20373       e->command = "sip show user";
20374       e->usage =
20375          "Usage: sip show user <name> [load]\n"
20376          "       Shows all details on one SIP user and the current status.\n"
20377          "       Option \"load\" forces lookup of peer in realtime storage.\n";
20378       return NULL;
20379    case CLI_GENERATE:
20380       return complete_sip_show_user(a->line, a->word, a->pos, a->n);
20381    }
20382 
20383    if (a->argc < 4)
20384       return CLI_SHOWUSAGE;
20385 
20386    /* Load from realtime storage? */
20387    load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? TRUE : FALSE;
20388 
20389    if ((user = sip_find_peer(a->argv[3], NULL, load_realtime, FINDUSERS, FALSE, 0))) {
20390       ao2_lock(user);
20391       ast_cli(a->fd, "\n\n");
20392       ast_cli(a->fd, "  * Name       : %s\n", user->name);
20393       ast_cli(a->fd, "  Secret       : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
20394       ast_cli(a->fd, "  MD5Secret    : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
20395       ast_cli(a->fd, "  Context      : %s\n", user->context);
20396       ast_cli(a->fd, "  Language     : %s\n", user->language);
20397       if (!ast_strlen_zero(user->accountcode))
20398          ast_cli(a->fd, "  Accountcode  : %s\n", user->accountcode);
20399       ast_cli(a->fd, "  AMA flags    : %s\n", ast_cdr_flags2str(user->amaflags));
20400       ast_cli(a->fd, "  Tonezone     : %s\n", user->zone[0] != '\0' ? user->zone : "<Not set>");
20401       ast_cli(a->fd, "  Transfer mode: %s\n", transfermode2str(user->allowtransfer));
20402       ast_cli(a->fd, "  MaxCallBR    : %d kbps\n", user->maxcallbitrate);
20403       ast_cli(a->fd, "  CallingPres  : %s\n", ast_describe_caller_presentation(user->callingpres));
20404       ast_cli(a->fd, "  Call limit   : %d\n", user->call_limit);
20405       ast_cli(a->fd, "  Callgroup    : ");
20406       print_group(a->fd, user->callgroup, 0);
20407       ast_cli(a->fd, "  Pickupgroup  : ");
20408       print_group(a->fd, user->pickupgroup, 0);
20409       ast_cli(a->fd, "  Named Callgr : ");
20410       print_named_groups(a->fd, user->named_callgroups, 0);
20411       ast_cli(a->fd, "  Nam. Pickupgr: ");
20412       print_named_groups(a->fd, user->named_pickupgroups, 0);
20413       ast_cli(a->fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
20414       ast_cli(a->fd, "  ACL          : %s\n", AST_CLI_YESNO(ast_acl_list_is_empty(user->acl) == 0));
20415       ast_cli(a->fd, "  Sess-Timers  : %s\n", stmode2str(user->stimer.st_mode_oper));
20416       ast_cli(a->fd, "  Sess-Refresh : %s\n", strefresherparam2str(user->stimer.st_ref));
20417       ast_cli(a->fd, "  Sess-Expires : %d secs\n", user->stimer.st_max_se);
20418       ast_cli(a->fd, "  Sess-Min-SE  : %d secs\n", user->stimer.st_min_se);
20419       ast_cli(a->fd, "  RTP Engine   : %s\n", user->engine);
20420 
20421       ast_cli(a->fd, "  Codec Order  : (");
20422       print_codec_to_cli(a->fd, &user->prefs);
20423       ast_cli(a->fd, ")\n");
20424 
20425       ast_cli(a->fd, "  Auto-Framing:  %s \n", AST_CLI_YESNO(user->autoframing));
20426       if (user->chanvars) {
20427          ast_cli(a->fd, "  Variables    :\n");
20428          for (v = user->chanvars ; v ; v = v->next)
20429             ast_cli(a->fd, "                 %s = %s\n", v->name, v->value);
20430       }
20431 
20432       ast_cli(a->fd, "\n");
20433 
20434       ao2_unlock(user);
20435       sip_unref_peer(user, "sip show user");
20436    } else {
20437       ast_cli(a->fd, "User %s not found.\n", a->argv[3]);
20438       ast_cli(a->fd, "\n");
20439    }
20440 
20441    return CLI_SUCCESS;
20442 }
20443 
20444 
20445 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
20446 {
20447    struct ast_str *cbuf;
20448    struct ast_cb_names cbnames = {9, { "retrans_pkt",
20449                                         "__sip_autodestruct",
20450                                         "expire_register",
20451                                         "auto_congest",
20452                                         "sip_reg_timeout",
20453                                         "sip_poke_peer_s",
20454                                         "sip_poke_noanswer",
20455                                         "sip_reregister",
20456                                         "sip_reinvite_retry"},
20457                            { retrans_pkt,
20458                                      __sip_autodestruct,
20459                                      expire_register,
20460                                      auto_congest,
20461                                      sip_reg_timeout,
20462                                      sip_poke_peer_s,
20463                                      sip_poke_noanswer,
20464                                      sip_reregister,
20465                                      sip_reinvite_retry}};
20466    
20467    switch (cmd) {
20468    case CLI_INIT:
20469       e->command = "sip show sched";
20470       e->usage =
20471          "Usage: sip show sched\n"
20472          "       Shows stats on what's in the sched queue at the moment\n";
20473       return NULL;
20474    case CLI_GENERATE:
20475       return NULL;
20476    }
20477 
20478    cbuf = ast_str_alloca(2048);
20479 
20480    ast_cli(a->fd, "\n");
20481    ast_sched_report(sched, &cbuf, &cbnames);
20482    ast_cli(a->fd, "%s", ast_str_buffer(cbuf));
20483 
20484    return CLI_SUCCESS;
20485 }
20486 
20487 /*! \brief  Show SIP Registry (registrations with other SIP proxies */
20488 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
20489 {
20490 #define FORMAT2 "%-39.39s %-6.6s %-12.12s  %8.8s %-20.20s %-25.25s\n"
20491 #define FORMAT  "%-39.39s %-6.6s %-12.12s  %8d %-20.20s %-25.25s\n"
20492    char host[80];
20493    char user[80];
20494    char tmpdat[256];
20495    struct ast_tm tm;
20496    int counter = 0;
20497 
20498    switch (cmd) {
20499    case CLI_INIT:
20500       e->command = "sip show registry";
20501       e->usage =
20502          "Usage: sip show registry\n"
20503          "       Lists all registration requests and status.\n";
20504       return NULL;
20505    case CLI_GENERATE:
20506       return NULL;
20507    }
20508 
20509    if (a->argc != 3)
20510       return CLI_SHOWUSAGE;
20511    ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Refresh", "State", "Reg.Time");
20512    
20513    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
20514       ASTOBJ_RDLOCK(iterator);
20515       snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
20516       snprintf(user, sizeof(user), "%s", iterator->username);
20517       if (!ast_strlen_zero(iterator->regdomain)) {
20518          snprintf(tmpdat, sizeof(tmpdat), "%s", user);
20519          snprintf(user, sizeof(user), "%s@%s", tmpdat, iterator->regdomain);}
20520       if (iterator->regdomainport) {
20521          snprintf(tmpdat, sizeof(tmpdat), "%s", user);
20522          snprintf(user, sizeof(user), "%s:%d", tmpdat, iterator->regdomainport);}
20523       if (iterator->regtime.tv_sec) {
20524          ast_localtime(&iterator->regtime, &tm, NULL);
20525          ast_strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
20526       } else
20527          tmpdat[0] = '\0';
20528       ast_cli(a->fd, FORMAT, host, (iterator->dnsmgr) ? "Y" : "N", user, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
20529       ASTOBJ_UNLOCK(iterator);
20530       counter++;
20531    } while(0));
20532    ast_cli(a->fd, "%d SIP registrations.\n", counter);
20533    return CLI_SUCCESS;
20534 #undef FORMAT
20535 #undef FORMAT2
20536 }
20537 
20538 /*! \brief Unregister (force expiration) a SIP peer in the registry via CLI
20539    \note This function does not tell the SIP device what's going on,
20540    so use it with great care.
20541 */
20542 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
20543 {
20544    struct sip_peer *peer;
20545    int load_realtime = 0;
20546 
20547    switch (cmd) {
20548    case CLI_INIT:
20549       e->command = "sip unregister";
20550       e->usage =
20551          "Usage: sip unregister <peer>\n"
20552          "       Unregister (force expiration) a SIP peer from the registry\n";
20553       return NULL;
20554    case CLI_GENERATE:
20555       return complete_sip_unregister(a->line, a->word, a->pos, a->n);
20556    }
20557    
20558    if (a->argc != 3)
20559       return CLI_SHOWUSAGE;
20560    
20561    if ((peer = sip_find_peer(a->argv[2], NULL, load_realtime, FINDPEERS, TRUE, 0))) {
20562       if (peer->expire > 0) {
20563          AST_SCHED_DEL_UNREF(sched, peer->expire,
20564             sip_unref_peer(peer, "remove register expire ref"));
20565          expire_register(sip_ref_peer(peer, "ref for expire_register"));
20566          ast_cli(a->fd, "Unregistered peer \'%s\'\n\n", a->argv[2]);
20567       } else {
20568          ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
20569       }
20570       sip_unref_peer(peer, "sip_unregister: sip_unref_peer via sip_unregister: done with peer from sip_find_peer call");
20571    } else {
20572       ast_cli(a->fd, "Peer unknown: \'%s\'. Not unregistered.\n", a->argv[2]);
20573    }
20574    
20575    return CLI_SUCCESS;
20576 }
20577 
20578 /*! \brief Callback for show_chanstats */
20579 static int show_chanstats_cb(void *__cur, void *__arg, int flags)
20580 {
20581 #define FORMAT2 "%-15.15s  %-11.11s  %-8.8s %-10.10s  %-10.10s (     %%) %-6.6s %-10.10s  %-10.10s (     %%) %-6.6s\n"
20582 #define FORMAT  "%-15.15s  %-11.11s  %-8.8s %-10.10u%-1.1s %-10.10u (%5.2f%%) %-6.4lf %-10.10u%-1.1s %-10.10u (%5.2f%%) %-6.4lf\n"
20583    struct sip_pvt *cur = __cur;
20584    struct ast_rtp_instance_stats stats;
20585    char durbuf[10];
20586    int duration;
20587    int durh, durm, durs;
20588    struct ast_channel *c;
20589    struct __show_chan_arg *arg = __arg;
20590    int fd = arg->fd;
20591 
20592    sip_pvt_lock(cur);
20593    c = cur->owner;
20594 
20595    if (cur->subscribed != NONE) {
20596       /* Subscriptions */
20597       sip_pvt_unlock(cur);
20598       return 0;   /* don't care, we scan all channels */
20599    }
20600 
20601    if (!cur->rtp) {
20602       if (sipdebug) {
20603          ast_cli(fd, "%-15.15s  %-11.11s (inv state: %s) -- %s\n",
20604             ast_sockaddr_stringify_addr(&cur->sa), cur->callid,
20605             invitestate2string[cur->invitestate].desc,
20606             "-- No RTP active");
20607       }
20608       sip_pvt_unlock(cur);
20609       return 0;   /* don't care, we scan all channels */
20610    }
20611 
20612    if (ast_rtp_instance_get_stats(cur->rtp, &stats, AST_RTP_INSTANCE_STAT_ALL)) {
20613       sip_pvt_unlock(cur);
20614       ast_log(LOG_WARNING, "Could not get RTP stats.\n");
20615       return 0;
20616    }
20617 
20618    if (c && ast_channel_cdr(c) && !ast_tvzero(ast_channel_cdr(c)->start)) {
20619       duration = (int)(ast_tvdiff_ms(ast_tvnow(), ast_channel_cdr(c)->start) / 1000);
20620       durh = duration / 3600;
20621       durm = (duration % 3600) / 60;
20622       durs = duration % 60;
20623       snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
20624    } else {
20625       durbuf[0] = '\0';
20626    }
20627 
20628    ast_cli(fd, FORMAT,
20629       ast_sockaddr_stringify_addr(&cur->sa),
20630       cur->callid,
20631       durbuf,
20632       stats.rxcount > (unsigned int) 100000 ? (unsigned int) (stats.rxcount)/(unsigned int) 1000 : stats.rxcount,
20633       stats.rxcount > (unsigned int) 100000 ? "K":" ",
20634       stats.rxploss,
20635       (stats.rxcount + stats.rxploss) > 0 ? (double) stats.rxploss / (stats.rxcount + stats.rxploss) * 100 : 0,
20636       stats.rxjitter,
20637       stats.txcount > (unsigned int) 100000 ? (unsigned int) (stats.txcount)/(unsigned int) 1000 : stats.txcount,
20638       stats.txcount > (unsigned int) 100000 ? "K":" ",
20639       stats.txploss,
20640       stats.txcount > 0 ? (double) stats.txploss / stats.txcount * 100 : 0,
20641       stats.txjitter
20642    );
20643    arg->numchans++;
20644    sip_pvt_unlock(cur);
20645 
20646    return 0;   /* don't care, we scan all channels */
20647 }
20648 
20649 /*! \brief SIP show channelstats CLI (main function) */
20650 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
20651 {
20652    struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
20653 
20654    switch (cmd) {
20655    case CLI_INIT:
20656       e->command = "sip show channelstats";
20657       e->usage =
20658          "Usage: sip show channelstats\n"
20659          "       Lists all currently active SIP channel's RTCP statistics.\n"
20660          "       Note that calls in the much optimized RTP P2P bridge mode will not show any packets here.";
20661       return NULL;
20662    case CLI_GENERATE:
20663       return NULL;
20664    }
20665 
20666    if (a->argc != 3)
20667       return CLI_SHOWUSAGE;
20668 
20669    ast_cli(a->fd, FORMAT2, "Peer", "Call ID", "Duration", "Recv: Pack", "Lost", "Jitter", "Send: Pack", "Lost", "Jitter");
20670    /* iterate on the container and invoke the callback on each item */
20671    ao2_t_callback(dialogs, OBJ_NODATA, show_chanstats_cb, &arg, "callback to sip show chanstats");
20672    ast_cli(a->fd, "%d active SIP channel%s\n", arg.numchans, (arg.numchans != 1) ? "s" : "");
20673    return CLI_SUCCESS;
20674 }
20675 #undef FORMAT
20676 #undef FORMAT2
20677 
20678 /*! \brief List global settings for the SIP channel */
20679 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
20680 {
20681    int realtimepeers;
20682    int realtimeregs;
20683    char codec_buf[SIPBUFSIZE];
20684    const char *msg;  /* temporary msg pointer */
20685    struct sip_auth_container *credentials;
20686 
20687    switch (cmd) {
20688    case CLI_INIT:
20689       e->command = "sip show settings";
20690       e->usage =
20691          "Usage: sip show settings\n"
20692          "       Provides detailed list of the configuration of the SIP channel.\n";
20693       return NULL;
20694    case CLI_GENERATE:
20695       return NULL;
20696    }
20697 
20698    if (a->argc != 3)
20699       return CLI_SHOWUSAGE;
20700 
20701    realtimepeers = ast_check_realtime("sippeers");
20702    realtimeregs = ast_check_realtime("sipregs");
20703 
20704    ast_mutex_lock(&authl_lock);
20705    credentials = authl;
20706    if (credentials) {
20707       ao2_t_ref(credentials, +1, "Ref global auth for show");
20708    }
20709    ast_mutex_unlock(&authl_lock);
20710 
20711    ast_cli(a->fd, "\n\nGlobal Settings:\n");
20712    ast_cli(a->fd, "----------------\n");
20713    ast_cli(a->fd, "  UDP Bindaddress:        %s\n", ast_sockaddr_stringify(&bindaddr));
20714    if (ast_sockaddr_is_ipv6(&bindaddr) && ast_sockaddr_is_any(&bindaddr)) {
20715       ast_cli(a->fd, "  ** Additional Info:\n");
20716       ast_cli(a->fd, "     [::] may include IPv4 in addition to IPv6, if such a feature is enabled in the OS.\n");
20717    }
20718    ast_cli(a->fd, "  TCP SIP Bindaddress:    %s\n",
20719       sip_cfg.tcp_enabled != FALSE ?
20720             ast_sockaddr_stringify(&sip_tcp_desc.local_address) :
20721             "Disabled");
20722    ast_cli(a->fd, "  TLS SIP Bindaddress:    %s\n",
20723       default_tls_cfg.enabled != FALSE ?
20724             ast_sockaddr_stringify(&sip_tls_desc.local_address) :
20725             "Disabled");
20726    ast_cli(a->fd, "  Videosupport:           %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT)));
20727    ast_cli(a->fd, "  Textsupport:            %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT)));
20728    ast_cli(a->fd, "  Ignore SDP sess. ver.:  %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION)));
20729    ast_cli(a->fd, "  AutoCreate Peer:        %s\n", autocreatepeer2str(sip_cfg.autocreatepeer));
20730    ast_cli(a->fd, "  Match Auth Username:    %s\n", AST_CLI_YESNO(global_match_auth_username));
20731    ast_cli(a->fd, "  Allow unknown access:   %s\n", AST_CLI_YESNO(sip_cfg.allowguest));
20732    ast_cli(a->fd, "  Allow subscriptions:    %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
20733    ast_cli(a->fd, "  Allow overlap dialing:  %s\n", allowoverlap2str(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)));
20734    ast_cli(a->fd, "  Allow promisc. redir:   %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_PROMISCREDIR)));
20735    ast_cli(a->fd, "  Enable call counters:   %s\n", AST_CLI_YESNO(global_callcounter));
20736    ast_cli(a->fd, "  SIP domain support:     %s\n", AST_CLI_YESNO(!AST_LIST_EMPTY(&domain_list)));
20737    ast_cli(a->fd, "  Realm. auth:            %s\n", AST_CLI_YESNO(credentials != NULL));
20738    if (credentials) {
20739       struct sip_auth *auth;
20740 
20741       AST_LIST_TRAVERSE(&credentials->list, auth, node) {
20742          ast_cli(a->fd, "  Realm. auth entry:      Realm %-15.15s User %-10.20s %s\n",
20743             auth->realm,
20744             auth->username,
20745             !ast_strlen_zero(auth->secret)
20746                ? "<Secret set>"
20747                : (!ast_strlen_zero(auth->md5secret)
20748                   ? "<MD5secret set>" : "<Not set>"));
20749       }
20750       ao2_t_ref(credentials, -1, "Unref global auth for show");
20751    }
20752    ast_cli(a->fd, "  Our auth realm          %s\n", sip_cfg.realm);
20753    ast_cli(a->fd, "  Use domains as realms:  %s\n", AST_CLI_YESNO(sip_cfg.domainsasrealm));
20754    ast_cli(a->fd, "  Call to non-local dom.: %s\n", AST_CLI_YESNO(sip_cfg.allow_external_domains));
20755    ast_cli(a->fd, "  URI user is phone no:   %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_USEREQPHONE)));
20756    ast_cli(a->fd, "  Always auth rejects:    %s\n", AST_CLI_YESNO(sip_cfg.alwaysauthreject));
20757    ast_cli(a->fd, "  Direct RTP setup:       %s\n", AST_CLI_YESNO(sip_cfg.directrtpsetup));
20758    ast_cli(a->fd, "  User Agent:             %s\n", global_useragent);
20759    ast_cli(a->fd, "  SDP Session Name:       %s\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
20760    ast_cli(a->fd, "  SDP Owner Name:         %s\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner);
20761    ast_cli(a->fd, "  Reg. context:           %s\n", S_OR(sip_cfg.regcontext, "(not set)"));
20762    ast_cli(a->fd, "  Regexten on Qualify:    %s\n", AST_CLI_YESNO(sip_cfg.regextenonqualify));
20763    ast_cli(a->fd, "  Trust RPID:             %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_TRUSTRPID)));
20764    ast_cli(a->fd, "  Send RPID:              %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_SENDRPID)));
20765    ast_cli(a->fd, "  Legacy userfield parse: %s\n", AST_CLI_YESNO(sip_cfg.legacy_useroption_parsing));
20766    ast_cli(a->fd, "  Send Diversion:         %s\n", AST_CLI_YESNO(sip_cfg.send_diversion));
20767    ast_cli(a->fd, "  Caller ID:              %s\n", default_callerid);
20768    if ((default_fromdomainport) && (default_fromdomainport != STANDARD_SIP_PORT)) {
20769       ast_cli(a->fd, "  From: Domain:           %s:%d\n", default_fromdomain, default_fromdomainport);
20770    } else {
20771       ast_cli(a->fd, "  From: Domain:           %s\n", default_fromdomain);
20772    }
20773    ast_cli(a->fd, "  Record SIP history:     %s\n", AST_CLI_ONOFF(recordhistory));
20774    ast_cli(a->fd, "  Call Events:            %s\n", AST_CLI_ONOFF(sip_cfg.callevents));
20775    ast_cli(a->fd, "  Auth. Failure Events:   %s\n", AST_CLI_ONOFF(global_authfailureevents));
20776 
20777    ast_cli(a->fd, "  T.38 support:           %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
20778    ast_cli(a->fd, "  T.38 EC mode:           %s\n", faxec2str(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
20779    ast_cli(a->fd, "  T.38 MaxDtgrm:          %u\n", global_t38_maxdatagram);
20780    if (!realtimepeers && !realtimeregs)
20781       ast_cli(a->fd, "  SIP realtime:           Disabled\n" );
20782    else
20783       ast_cli(a->fd, "  SIP realtime:           Enabled\n" );
20784    ast_cli(a->fd, "  Qualify Freq :          %d ms\n", global_qualifyfreq);
20785    ast_cli(a->fd, "  Q.850 Reason header:    %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_Q850_REASON)));
20786    ast_cli(a->fd, "  Store SIP_CAUSE:        %s\n", AST_CLI_YESNO(global_store_sip_cause));
20787    ast_cli(a->fd, "\nNetwork QoS Settings:\n");
20788    ast_cli(a->fd, "---------------------------\n");
20789    ast_cli(a->fd, "  IP ToS SIP:             %s\n", ast_tos2str(global_tos_sip));
20790    ast_cli(a->fd, "  IP ToS RTP audio:       %s\n", ast_tos2str(global_tos_audio));
20791    ast_cli(a->fd, "  IP ToS RTP video:       %s\n", ast_tos2str(global_tos_video));
20792    ast_cli(a->fd, "  IP ToS RTP text:        %s\n", ast_tos2str(global_tos_text));
20793    ast_cli(a->fd, "  802.1p CoS SIP:         %u\n", global_cos_sip);
20794    ast_cli(a->fd, "  802.1p CoS RTP audio:   %u\n", global_cos_audio);
20795    ast_cli(a->fd, "  802.1p CoS RTP video:   %u\n", global_cos_video);
20796    ast_cli(a->fd, "  802.1p CoS RTP text:    %u\n", global_cos_text);
20797    ast_cli(a->fd, "  Jitterbuffer enabled:   %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_ENABLED)));
20798    if (ast_test_flag(&global_jbconf, AST_JB_ENABLED)) {
20799       ast_cli(a->fd, "  Jitterbuffer forced:    %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_FORCED)));
20800       ast_cli(a->fd, "  Jitterbuffer max size:  %ld\n", global_jbconf.max_size);
20801       ast_cli(a->fd, "  Jitterbuffer resync:    %ld\n", global_jbconf.resync_threshold);
20802       ast_cli(a->fd, "  Jitterbuffer impl:      %s\n", global_jbconf.impl);
20803       if (!strcasecmp(global_jbconf.impl, "adaptive")) {
20804          ast_cli(a->fd, "  Jitterbuffer tgt extra: %ld\n", global_jbconf.target_extra);
20805       }
20806       ast_cli(a->fd, "  Jitterbuffer log:       %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_LOG)));
20807    }
20808 
20809    ast_cli(a->fd, "\nNetwork Settings:\n");
20810    ast_cli(a->fd, "---------------------------\n");
20811    /* determine if/how SIP address can be remapped */
20812    if (localaddr == NULL)
20813       msg = "Disabled, no localnet list";
20814    else if (ast_sockaddr_isnull(&externaddr))
20815       msg = "Disabled";
20816    else if (!ast_strlen_zero(externhost))
20817       msg = "Enabled using externhost";
20818    else
20819       msg = "Enabled using externaddr";
20820    ast_cli(a->fd, "  SIP address remapping:  %s\n", msg);
20821    ast_cli(a->fd, "  Externhost:             %s\n", S_OR(externhost, "<none>"));
20822    ast_cli(a->fd, "  Externaddr:             %s\n", ast_sockaddr_stringify(&externaddr));
20823    ast_cli(a->fd, "  Externrefresh:          %d\n", externrefresh);
20824    {
20825       struct ast_ha *d;
20826       const char *prefix = "Localnet:";
20827 
20828       for (d = localaddr; d ; prefix = "", d = d->next) {
20829          const char *addr = ast_strdupa(ast_sockaddr_stringify_addr(&d->addr));
20830          const char *mask = ast_strdupa(ast_sockaddr_stringify_addr(&d->netmask));
20831          ast_cli(a->fd, "  %-24s%s/%s\n", prefix, addr, mask);
20832       }
20833    }
20834    ast_cli(a->fd, "\nGlobal Signalling Settings:\n");
20835    ast_cli(a->fd, "---------------------------\n");
20836    ast_cli(a->fd, "  Codecs:                 ");
20837    ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, sip_cfg.caps);
20838    ast_cli(a->fd, "%s\n", codec_buf);
20839    ast_cli(a->fd, "  Codec Order:            ");
20840    print_codec_to_cli(a->fd, &default_prefs);
20841    ast_cli(a->fd, "\n");
20842    ast_cli(a->fd, "  Relax DTMF:             %s\n", AST_CLI_YESNO(global_relaxdtmf));
20843    ast_cli(a->fd, "  RFC2833 Compensation:   %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE)));
20844    ast_cli(a->fd, "  Symmetric RTP:          %s\n", comedia_string(global_flags));
20845    ast_cli(a->fd, "  Compact SIP headers:    %s\n", AST_CLI_YESNO(sip_cfg.compactheaders));
20846    ast_cli(a->fd, "  RTP Keepalive:          %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
20847    ast_cli(a->fd, "  RTP Timeout:            %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
20848    ast_cli(a->fd, "  RTP Hold Timeout:       %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
20849    ast_cli(a->fd, "  MWI NOTIFY mime type:   %s\n", default_notifymime);
20850    ast_cli(a->fd, "  DNS SRV lookup:         %s\n", AST_CLI_YESNO(sip_cfg.srvlookup));
20851    ast_cli(a->fd, "  Pedantic SIP support:   %s\n", AST_CLI_YESNO(sip_cfg.pedanticsipchecking));
20852    ast_cli(a->fd, "  Reg. min duration       %d secs\n", min_expiry);
20853    ast_cli(a->fd, "  Reg. max duration:      %d secs\n", max_expiry);
20854    ast_cli(a->fd, "  Reg. default duration:  %d secs\n", default_expiry);
20855    ast_cli(a->fd, "  Sub. min duration       %d secs\n", min_subexpiry);
20856    ast_cli(a->fd, "  Sub. max duration:      %d secs\n", max_subexpiry);
20857    ast_cli(a->fd, "  Outbound reg. timeout:  %d secs\n", global_reg_timeout);
20858    ast_cli(a->fd, "  Outbound reg. attempts: %d\n", global_regattempts_max);
20859    ast_cli(a->fd, "  Outbound reg. retry 403:%d\n", global_reg_retry_403);
20860    ast_cli(a->fd, "  Notify ringing state:   %s\n", AST_CLI_YESNO(sip_cfg.notifyringing));
20861    if (sip_cfg.notifyringing) {
20862       ast_cli(a->fd, "    Include CID:          %s%s\n",
20863             AST_CLI_YESNO(sip_cfg.notifycid),
20864             sip_cfg.notifycid == IGNORE_CONTEXT ? " (Ignoring context)" : "");
20865    }
20866    ast_cli(a->fd, "  Notify hold state:      %s\n", AST_CLI_YESNO(sip_cfg.notifyhold));
20867    ast_cli(a->fd, "  SIP Transfer mode:      %s\n", transfermode2str(sip_cfg.allowtransfer));
20868    ast_cli(a->fd, "  Max Call Bitrate:       %d kbps\n", default_maxcallbitrate);
20869    ast_cli(a->fd, "  Auto-Framing:           %s\n", AST_CLI_YESNO(global_autoframing));
20870    ast_cli(a->fd, "  Outb. proxy:            %s %s\n", ast_strlen_zero(sip_cfg.outboundproxy.name) ? "<not set>" : sip_cfg.outboundproxy.name,
20871                      sip_cfg.outboundproxy.force ? "(forced)" : "");
20872    ast_cli(a->fd, "  Session Timers:         %s\n", stmode2str(global_st_mode));
20873    ast_cli(a->fd, "  Session Refresher:      %s\n", strefresherparam2str(global_st_refresher));
20874    ast_cli(a->fd, "  Session Expires:        %d secs\n", global_max_se);
20875    ast_cli(a->fd, "  Session Min-SE:         %d secs\n", global_min_se);
20876    ast_cli(a->fd, "  Timer T1:               %d\n", global_t1);
20877    ast_cli(a->fd, "  Timer T1 minimum:       %d\n", global_t1min);
20878    ast_cli(a->fd, "  Timer B:                %d\n", global_timer_b);
20879    ast_cli(a->fd, "  No premature media:     %s\n", AST_CLI_YESNO(global_prematuremediafilter));
20880    ast_cli(a->fd, "  Max forwards:           %d\n", sip_cfg.default_max_forwards);
20881 
20882    ast_cli(a->fd, "\nDefault Settings:\n");
20883    ast_cli(a->fd, "-----------------\n");
20884    ast_cli(a->fd, "  Allowed transports:     %s\n", get_transport_list(default_transports));
20885    ast_cli(a->fd, "  Outbound transport:    %s\n", sip_get_transport(default_primary_transport));
20886    ast_cli(a->fd, "  Context:                %s\n", sip_cfg.default_context);
20887    ast_cli(a->fd, "  Record on feature:      %s\n", sip_cfg.default_record_on_feature);
20888    ast_cli(a->fd, "  Record off feature:     %s\n", sip_cfg.default_record_off_feature);
20889    ast_cli(a->fd, "  Force rport:            %s\n", force_rport_string(global_flags));
20890    ast_cli(a->fd, "  DTMF:                   %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
20891    ast_cli(a->fd, "  Qualify:                %d\n", default_qualify);
20892    ast_cli(a->fd, "  Keepalive:              %d\n", default_keepalive);
20893    ast_cli(a->fd, "  Use ClientCode:         %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_USECLIENTCODE)));
20894    ast_cli(a->fd, "  Progress inband:        %s\n", (ast_test_flag(&global_flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER) ? "Never" : (AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_NO)));
20895    ast_cli(a->fd, "  Language:               %s\n", default_language);
20896    ast_cli(a->fd, "  Tone zone:              %s\n", default_zone[0] != '\0' ? default_zone : "<Not set>");
20897    ast_cli(a->fd, "  MOH Interpret:          %s\n", default_mohinterpret);
20898    ast_cli(a->fd, "  MOH Suggest:            %s\n", default_mohsuggest);
20899    ast_cli(a->fd, "  Voice Mail Extension:   %s\n", default_vmexten);
20900 
20901    
20902    if (realtimepeers || realtimeregs) {
20903       ast_cli(a->fd, "\nRealtime SIP Settings:\n");
20904       ast_cli(a->fd, "----------------------\n");
20905       ast_cli(a->fd, "  Realtime Peers:         %s\n", AST_CLI_YESNO(realtimepeers));
20906       ast_cli(a->fd, "  Realtime Regs:          %s\n", AST_CLI_YESNO(realtimeregs));
20907       ast_cli(a->fd, "  Cache Friends:          %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)));
20908       ast_cli(a->fd, "  Update:                 %s\n", AST_CLI_YESNO(sip_cfg.peer_rtupdate));
20909       ast_cli(a->fd, "  Ignore Reg. Expire:     %s\n", AST_CLI_YESNO(sip_cfg.ignore_regexpire));
20910       ast_cli(a->fd, "  Save sys. name:         %s\n", AST_CLI_YESNO(sip_cfg.rtsave_sysname));
20911       ast_cli(a->fd, "  Auto Clear:             %d (%s)\n", sip_cfg.rtautoclear, ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR) ? "Enabled" : "Disabled");
20912    }
20913    ast_cli(a->fd, "\n----\n");
20914    return CLI_SUCCESS;
20915 }
20916 
20917 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
20918 {
20919 #define FORMAT  "%-30.30s  %-12.12s  %-10.10s  %-10.10s\n"
20920    char host[80];
20921    
20922    switch (cmd) {
20923    case CLI_INIT:
20924       e->command = "sip show mwi";
20925       e->usage =
20926          "Usage: sip show mwi\n"
20927          "       Provides a list of MWI subscriptions and status.\n";
20928       return NULL;
20929    case CLI_GENERATE:
20930       return NULL;
20931    }
20932    
20933    ast_cli(a->fd, FORMAT, "Host", "Username", "Mailbox", "Subscribed");
20934    
20935    ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
20936       ASTOBJ_RDLOCK(iterator);
20937       snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
20938       ast_cli(a->fd, FORMAT, host, iterator->username, iterator->mailbox, AST_CLI_YESNO(iterator->subscribed));
20939       ASTOBJ_UNLOCK(iterator);
20940    } while(0));
20941 
20942    return CLI_SUCCESS;
20943 #undef FORMAT
20944 }
20945 
20946 
20947 /*! \brief Show subscription type in string format */
20948 static const char *subscription_type2str(enum subscriptiontype subtype)
20949 {
20950    int i;
20951 
20952    for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
20953       if (subscription_types[i].type == subtype) {
20954          return subscription_types[i].text;
20955       }
20956    }
20957    return subscription_types[0].text;
20958 }
20959 
20960 /*! \brief Find subscription type in array */
20961 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
20962 {
20963    int i;
20964 
20965    for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
20966       if (subscription_types[i].type == subtype) {
20967          return &subscription_types[i];
20968       }
20969    }
20970    return &subscription_types[0];
20971 }
20972 
20973 /*
20974  * We try to structure all functions that loop on data structures as
20975  * a handler for individual entries, and a mainloop that iterates
20976  * on the main data structure. This way, moving the code to containers
20977  * that support iteration through callbacks will be a lot easier.
20978  */
20979 
20980 #define FORMAT4 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-13.13s  %-15.15s %-10.10s %-6.6d\n"
20981 #define FORMAT3 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-13.13s  %-15.15s %-10.10s %-6.6s\n"
20982 #define FORMAT2 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-7.7s  %-15.15s %-10.10s %-10.10s\n"
20983 #define FORMAT  "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-3.3s %-3.3s  %-15.15s %-10.10s %-10.10s\n"
20984 
20985 /*! \brief callback for show channel|subscription */
20986 static int show_channels_cb(void *__cur, void *__arg, int flags)
20987 {
20988    struct sip_pvt *cur = __cur;
20989    struct __show_chan_arg *arg = __arg;
20990    const struct ast_sockaddr *dst;
20991 
20992    sip_pvt_lock(cur);
20993    dst = sip_real_dst(cur);
20994 
20995    /* XXX indentation preserved to reduce diff. Will be fixed later */
20996    if (cur->subscribed == NONE && !arg->subscriptions) {
20997       /* set if SIP transfer in progress */
20998       const char *referstatus = cur->refer ? referstatus2str(cur->refer->status) : "";
20999       char formatbuf[SIPBUFSIZE/2];
21000       
21001       ast_cli(arg->fd, FORMAT, ast_sockaddr_stringify_addr(dst),
21002             S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
21003             cur->callid,
21004             cur->owner ? ast_getformatname_multiple(formatbuf, sizeof(formatbuf), ast_channel_nativeformats(cur->owner)) : "(nothing)",
21005             AST_CLI_YESNO(ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD)),
21006             cur->needdestroy ? "(d)" : "",
21007             cur->lastmsg ,
21008             referstatus,
21009             cur->relatedpeer ? cur->relatedpeer->name : "<guest>"
21010          );
21011       arg->numchans++;
21012    }
21013    if (cur->subscribed != NONE && arg->subscriptions) {
21014       struct ast_str *mailbox_str = ast_str_alloca(512);
21015       if (cur->subscribed == MWI_NOTIFICATION && cur->relatedpeer)
21016          peer_mailboxes_to_str(&mailbox_str, cur->relatedpeer);
21017       ast_cli(arg->fd, FORMAT4, ast_sockaddr_stringify_addr(dst),
21018             S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
21019                cur->callid,
21020             /* the 'complete' exten/context is hidden in the refer_to field for subscriptions */
21021             cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
21022             cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate),
21023             subscription_type2str(cur->subscribed),
21024             cur->subscribed == MWI_NOTIFICATION ? S_OR(ast_str_buffer(mailbox_str), "<none>") : "<none>",
21025             cur->expiry
21026          );
21027       arg->numchans++;
21028    }
21029    sip_pvt_unlock(cur);
21030    return 0;   /* don't care, we scan all channels */
21031 }
21032 
21033 /*! \brief CLI for show channels or subscriptions.
21034  * This is a new-style CLI handler so a single function contains
21035  * the prototype for the function, the 'generator' to produce multiple
21036  * entries in case it is required, and the actual handler for the command.
21037  */
21038 static char *sip_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
21039 {
21040    struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
21041 
21042 
21043    if (cmd == CLI_INIT) {
21044       e->command = "sip show {channels|subscriptions}";
21045       e->usage =
21046          "Usage: sip show channels\n"
21047          "       Lists all currently active SIP calls (dialogs).\n"
21048          "Usage: sip show subscriptions\n"
21049          "       Lists active SIP subscriptions.\n";
21050       return NULL;
21051    } else if (cmd == CLI_GENERATE)
21052       return NULL;
21053 
21054    if (a->argc != e->args)
21055       return CLI_SHOWUSAGE;
21056    arg.subscriptions = !strcasecmp(a->argv[e->args - 1], "subscriptions");
21057    if (!arg.subscriptions)
21058       ast_cli(arg.fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Format", "Hold", "Last Message", "Expiry", "Peer");
21059    else
21060       ast_cli(arg.fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox", "Expiry");
21061 
21062    /* iterate on the container and invoke the callback on each item */
21063    ao2_t_callback(dialogs, OBJ_NODATA, show_channels_cb, &arg, "callback to show channels");
21064    
21065    /* print summary information */
21066    ast_cli(arg.fd, "%d active SIP %s%s\n", arg.numchans,
21067       (arg.subscriptions ? "subscription" : "dialog"),
21068       ESS(arg.numchans));  /* ESS(n) returns an "s" if n>1 */
21069    return CLI_SUCCESS;
21070 #undef FORMAT
21071 #undef FORMAT2
21072 #undef FORMAT3
21073 }
21074 
21075 /*! \brief Support routine for 'sip show channel' and 'sip show history' CLI
21076  * This is in charge of generating all strings that match a prefix in the
21077  * given position. As many functions of this kind, each invokation has
21078  * O(state) time complexity so be careful in using it.
21079  */
21080 static char *complete_sipch(const char *line, const char *word, int pos, int state)
21081 {
21082    int which=0;
21083    struct sip_pvt *cur;
21084    char *c = NULL;
21085    int wordlen = strlen(word);
21086    struct ao2_iterator i;
21087 
21088    if (pos != 3) {
21089       return NULL;
21090    }
21091 
21092    i = ao2_iterator_init(dialogs, 0);
21093    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
21094       sip_pvt_lock(cur);
21095       if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
21096          c = ast_strdup(cur->callid);
21097          sip_pvt_unlock(cur);
21098          dialog_unref(cur, "drop ref in iterator loop break");
21099          break;
21100       }
21101       sip_pvt_unlock(cur);
21102       dialog_unref(cur, "drop ref in iterator loop");
21103    }
21104    ao2_iterator_destroy(&i);
21105    return c;
21106 }
21107 
21108 
21109 /*! \brief Do completion on peer name */
21110 static char *complete_sip_peer(const char *word, int state, int flags2)
21111 {
21112    char *result = NULL;
21113    int wordlen = strlen(word);
21114    int which = 0;
21115    struct ao2_iterator i = ao2_iterator_init(peers, 0);
21116    struct sip_peer *peer;
21117 
21118    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
21119       /* locking of the object is not required because only the name and flags are being compared */
21120       if (!strncasecmp(word, peer->name, wordlen) &&
21121             (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
21122             ++which > state)
21123          result = ast_strdup(peer->name);
21124       sip_unref_peer(peer, "toss iterator peer ptr before break");
21125       if (result) {
21126          break;
21127       }
21128    }
21129    ao2_iterator_destroy(&i);
21130    return result;
21131 }
21132 
21133 /*! \brief Do completion on registered peer name */
21134 static char *complete_sip_registered_peer(const char *word, int state, int flags2)
21135 {
21136        char *result = NULL;
21137        int wordlen = strlen(word);
21138        int which = 0;
21139        struct ao2_iterator i;
21140        struct sip_peer *peer;
21141        
21142        i = ao2_iterator_init(peers, 0);
21143        while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
21144           if (!strncasecmp(word, peer->name, wordlen) &&
21145          (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
21146          ++which > state && peer->expire > 0)
21147              result = ast_strdup(peer->name);
21148           if (result) {
21149              sip_unref_peer(peer, "toss iterator peer ptr before break");
21150              break;
21151           }
21152           sip_unref_peer(peer, "toss iterator peer ptr");
21153        }
21154        ao2_iterator_destroy(&i);
21155        return result;
21156 }
21157 
21158 /*! \brief Support routine for 'sip show history' CLI */
21159 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state)
21160 {
21161    if (pos == 3)
21162       return complete_sipch(line, word, pos, state);
21163 
21164    return NULL;
21165 }
21166 
21167 /*! \brief Support routine for 'sip show peer' CLI */
21168 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
21169 {
21170    if (pos == 3) {
21171       return complete_sip_peer(word, state, 0);
21172    }
21173 
21174    return NULL;
21175 }
21176 
21177 /*! \brief Support routine for 'sip unregister' CLI */
21178 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state)
21179 {
21180        if (pos == 2)
21181                return complete_sip_registered_peer(word, state, 0);
21182 
21183        return NULL;
21184 }
21185 
21186 /*! \brief Support routine for 'sip notify' CLI */
21187 static char *complete_sip_notify(const char *line, const char *word, int pos, int state)
21188 {
21189    char *c = NULL;
21190 
21191    if (pos == 2) {
21192       int which = 0;
21193       char *cat = NULL;
21194       int wordlen = strlen(word);
21195 
21196       /* do completion for notify type */
21197 
21198       if (!notify_types)
21199          return NULL;
21200       
21201       while ( (cat = ast_category_browse(notify_types, cat)) ) {
21202          if (!strncasecmp(word, cat, wordlen) && ++which > state) {
21203             c = ast_strdup(cat);
21204             break;
21205          }
21206       }
21207       return c;
21208    }
21209 
21210    if (pos > 2)
21211       return complete_sip_peer(word, state, 0);
21212 
21213    return NULL;
21214 }
21215 
21216 static const char *transport2str(enum sip_transport transport)
21217 {
21218    switch (transport) {
21219    case SIP_TRANSPORT_TLS:
21220       return "TLS";
21221    case SIP_TRANSPORT_UDP:
21222       return "UDP";
21223    case SIP_TRANSPORT_TCP:
21224       return "TCP";
21225    case SIP_TRANSPORT_WS:
21226       return "WS";
21227    case SIP_TRANSPORT_WSS:
21228       return "WSS";
21229    }
21230 
21231    return "Undefined";
21232 }
21233 
21234 /*! \brief Show details of one active dialog */
21235 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
21236 {
21237    struct sip_pvt *cur;
21238    size_t len;
21239    int found = 0;
21240    struct ao2_iterator i;
21241 
21242    switch (cmd) {
21243    case CLI_INIT:
21244       e->command = "sip show channel";
21245       e->usage =
21246          "Usage: sip show channel <call-id>\n"
21247          "       Provides detailed status on a given SIP dialog (identified by SIP call-id).\n";
21248       return NULL;
21249    case CLI_GENERATE:
21250       return complete_sipch(a->line, a->word, a->pos, a->n);
21251    }
21252 
21253    if (a->argc != 4)
21254       return CLI_SHOWUSAGE;
21255    len = strlen(a->argv[3]);
21256    
21257    i = ao2_iterator_init(dialogs, 0);
21258    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
21259       sip_pvt_lock(cur);
21260 
21261       if (!strncasecmp(cur->callid, a->argv[3], len)) {
21262          char formatbuf[SIPBUFSIZE/2];
21263          ast_cli(a->fd, "\n");
21264          if (cur->subscribed != NONE) {
21265             ast_cli(a->fd, "  * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
21266          } else {
21267             ast_cli(a->fd, "  * SIP Call\n");
21268          }
21269          ast_cli(a->fd, "  Curr. trans. direction:  %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
21270          ast_cli(a->fd, "  Call-ID:                %s\n", cur->callid);
21271          ast_cli(a->fd, "  Owner channel ID:       %s\n", cur->owner ? ast_channel_name(cur->owner) : "<none>");
21272          ast_cli(a->fd, "  Our Codec Capability:   %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->caps));
21273          ast_cli(a->fd, "  Non-Codec Capability (DTMF):   %d\n", cur->noncodeccapability);
21274          ast_cli(a->fd, "  Their Codec Capability:   %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->peercaps));
21275          ast_cli(a->fd, "  Joint Codec Capability:   %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->jointcaps));
21276          ast_cli(a->fd, "  Format:                 %s\n", cur->owner ? ast_getformatname_multiple(formatbuf, sizeof(formatbuf), ast_channel_nativeformats(cur->owner)) : "(nothing)" );
21277          ast_cli(a->fd, "  T.38 support            %s\n", AST_CLI_YESNO(cur->udptl != NULL));
21278          ast_cli(a->fd, "  Video support           %s\n", AST_CLI_YESNO(cur->vrtp != NULL));
21279          ast_cli(a->fd, "  MaxCallBR:              %d kbps\n", cur->maxcallbitrate);
21280          ast_cli(a->fd, "  Theoretical Address:    %s\n", ast_sockaddr_stringify(&cur->sa));
21281          ast_cli(a->fd, "  Received Address:       %s\n", ast_sockaddr_stringify(&cur->recv));
21282          ast_cli(a->fd, "  SIP Transfer mode:      %s\n", transfermode2str(cur->allowtransfer));
21283          ast_cli(a->fd, "  Force rport:            %s\n", force_rport_string(cur->flags));
21284          if (ast_sockaddr_isnull(&cur->redirip)) {
21285             ast_cli(a->fd,
21286                "  Audio IP:               %s (local)\n",
21287                ast_sockaddr_stringify_addr(&cur->ourip));
21288          } else {
21289             ast_cli(a->fd,
21290                "  Audio IP:               %s (Outside bridge)\n",
21291                ast_sockaddr_stringify_addr(&cur->redirip));
21292          }
21293          ast_cli(a->fd, "  Our Tag:                %s\n", cur->tag);
21294          ast_cli(a->fd, "  Their Tag:              %s\n", cur->theirtag);
21295          ast_cli(a->fd, "  SIP User agent:         %s\n", cur->useragent);
21296          if (!ast_strlen_zero(cur->username)) {
21297             ast_cli(a->fd, "  Username:               %s\n", cur->username);
21298          }
21299          if (!ast_strlen_zero(cur->peername)) {
21300             ast_cli(a->fd, "  Peername:               %s\n", cur->peername);
21301          }
21302          if (!ast_strlen_zero(cur->uri)) {
21303             ast_cli(a->fd, "  Original uri:           %s\n", cur->uri);
21304          }
21305          if (!ast_strlen_zero(cur->cid_num)) {
21306             ast_cli(a->fd, "  Caller-ID:              %s\n", cur->cid_num);
21307          }
21308          ast_cli(a->fd, "  Need Destroy:           %s\n", AST_CLI_YESNO(cur->needdestroy));
21309          ast_cli(a->fd, "  Last Message:           %s\n", cur->lastmsg);
21310          ast_cli(a->fd, "  Promiscuous Redir:      %s\n", AST_CLI_YESNO(ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR)));
21311          ast_cli(a->fd, "  Route:                  ");
21312          if (cur->route) {
21313             struct sip_route *route;
21314             int first = 1;
21315 
21316             for (route = cur->route; route; route = route->next) {
21317                ast_cli(a->fd, "%s<%s>", first ? "" : ", ", route->hop);
21318                first = 0;
21319             }
21320             ast_cli(a->fd, "\n");
21321          } else {
21322             ast_cli(a->fd, "N/A\n");
21323          }
21324          ast_cli(a->fd, "  DTMF Mode:              %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
21325          ast_cli(a->fd, "  SIP Options:            ");
21326          if (cur->sipoptions) {
21327             int x;
21328             for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
21329                if (cur->sipoptions & sip_options[x].id)
21330                   ast_cli(a->fd, "%s ", sip_options[x].text);
21331             }
21332             ast_cli(a->fd, "\n");
21333          } else {
21334             ast_cli(a->fd, "(none)\n");
21335          }
21336 
21337          if (!cur->stimer) {
21338             ast_cli(a->fd, "  Session-Timer:          Uninitiallized\n");
21339          } else {
21340             ast_cli(a->fd, "  Session-Timer:          %s\n", cur->stimer->st_active ? "Active" : "Inactive");
21341             if (cur->stimer->st_active == TRUE) {
21342                ast_cli(a->fd, "  S-Timer Interval:       %d\n", cur->stimer->st_interval);
21343                ast_cli(a->fd, "  S-Timer Refresher:      %s\n", strefresher2str(cur->stimer->st_ref));
21344                ast_cli(a->fd, "  S-Timer Sched Id:       %d\n", cur->stimer->st_schedid);
21345                ast_cli(a->fd, "  S-Timer Peer Sts:       %s\n", cur->stimer->st_active_peer_ua ? "Active" : "Inactive");
21346                ast_cli(a->fd, "  S-Timer Cached Min-SE:  %d\n", cur->stimer->st_cached_min_se);
21347                ast_cli(a->fd, "  S-Timer Cached SE:      %d\n", cur->stimer->st_cached_max_se);
21348                ast_cli(a->fd, "  S-Timer Cached Ref:     %s\n", strefresherparam2str(cur->stimer->st_cached_ref));
21349                ast_cli(a->fd, "  S-Timer Cached Mode:    %s\n", stmode2str(cur->stimer->st_cached_mode));
21350             }
21351          }
21352 
21353          /* add transport and media types */
21354          ast_cli(a->fd, "  Transport:              %s\n", transport2str(cur->socket.type));
21355          ast_cli(a->fd, "  Media:                  %s\n", cur->srtp ? "SRTP" : cur->rtp ? "RTP" : "None");
21356 
21357          ast_cli(a->fd, "\n\n");
21358 
21359          found++;
21360       }
21361 
21362       sip_pvt_unlock(cur);
21363 
21364       ao2_t_ref(cur, -1, "toss dialog ptr set by iterator_next");
21365    }
21366    ao2_iterator_destroy(&i);
21367 
21368    if (!found) {
21369       ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
21370    }
21371 
21372    return CLI_SUCCESS;
21373 }
21374 
21375 /*! \brief Show history details of one dialog */
21376 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
21377 {
21378    struct sip_pvt *cur;
21379    size_t len;
21380    int found = 0;
21381    struct ao2_iterator i;
21382 
21383    switch (cmd) {
21384    case CLI_INIT:
21385       e->command = "sip show history";
21386       e->usage =
21387          "Usage: sip show history <call-id>\n"
21388          "       Provides detailed dialog history on a given SIP call (specified by call-id).\n";
21389       return NULL;
21390    case CLI_GENERATE:
21391       return complete_sip_show_history(a->line, a->word, a->pos, a->n);
21392    }
21393 
21394    if (a->argc != 4) {
21395       return CLI_SHOWUSAGE;
21396    }
21397 
21398    if (!recordhistory) {
21399       ast_cli(a->fd, "\n***Note: History recording is currently DISABLED.  Use 'sip set history on' to ENABLE.\n");
21400    }
21401 
21402    len = strlen(a->argv[3]);
21403 
21404    i = ao2_iterator_init(dialogs, 0);
21405    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
21406       sip_pvt_lock(cur);
21407       if (!strncasecmp(cur->callid, a->argv[3], len)) {
21408          struct sip_history *hist;
21409          int x = 0;
21410 
21411          ast_cli(a->fd, "\n");
21412          if (cur->subscribed != NONE) {
21413             ast_cli(a->fd, "  * Subscription\n");
21414          } else {
21415             ast_cli(a->fd, "  * SIP Call\n");
21416          }
21417          if (cur->history) {
21418             AST_LIST_TRAVERSE(cur->history, hist, list)
21419                ast_cli(a->fd, "%d. %s\n", ++x, hist->event);
21420          }
21421          if (x == 0) {
21422             ast_cli(a->fd, "Call '%s' has no history\n", cur->callid);
21423          }
21424          found++;
21425       }
21426       sip_pvt_unlock(cur);
21427       ao2_t_ref(cur, -1, "toss dialog ptr from iterator_next");
21428    }
21429    ao2_iterator_destroy(&i);
21430 
21431    if (!found) {
21432       ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
21433    }
21434 
21435    return CLI_SUCCESS;
21436 }
21437 
21438 /*! \brief Dump SIP history to debug log file at end of lifespan for SIP dialog */
21439 static void sip_dump_history(struct sip_pvt *dialog)
21440 {
21441    int x = 0;
21442    struct sip_history *hist;
21443    static int errmsg = 0;
21444 
21445    if (!dialog) {
21446       return;
21447    }
21448 
21449    if (!option_debug && !sipdebug) {
21450       if (!errmsg) {
21451          ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
21452          errmsg = 1;
21453       }
21454       return;
21455    }
21456 
21457    ast_debug(1, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
21458    if (dialog->subscribed) {
21459       ast_debug(1, "  * Subscription\n");
21460    } else {
21461       ast_debug(1, "  * SIP Call\n");
21462    }
21463    if (dialog->history) {
21464       AST_LIST_TRAVERSE(dialog->history, hist, list)
21465          ast_debug(1, "  %-3.3d. %s\n", ++x, hist->event);
21466    }
21467    if (!x) {
21468       ast_debug(1, "Call '%s' has no history\n", dialog->callid);
21469    }
21470    ast_debug(1, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
21471 }
21472 
21473 
21474 /*! \brief  Receive SIP INFO Message */
21475 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
21476 {
21477    const char *buf = "";
21478    unsigned int event;
21479    const char *c = sip_get_header(req, "Content-Type");
21480 
21481    /* Need to check the media/type */
21482    if (!strcasecmp(c, "application/dtmf-relay") ||
21483        !strcasecmp(c, "application/vnd.nortelnetworks.digits") ||
21484        !strcasecmp(c, "application/dtmf")) {
21485       unsigned int duration = 0;
21486 
21487       if (!p->owner) {  /* not a PBX call */
21488          transmit_response(p, "481 Call leg/transaction does not exist", req);
21489          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21490          return;
21491       }
21492 
21493       /* If dtmf-relay or vnd.nortelnetworks.digits, parse the signal and duration;
21494        * otherwise use the body as the signal */
21495       if (strcasecmp(c, "application/dtmf")) {
21496          const char *tmp;
21497 
21498          if (ast_strlen_zero(buf = get_content_line(req, "Signal", '='))
21499             && ast_strlen_zero(buf = get_content_line(req, "d", '='))) {
21500             ast_log(LOG_WARNING, "Unable to retrieve DTMF signal for INFO message on "
21501                   "call %s\n", p->callid);
21502             transmit_response(p, "200 OK", req);
21503             return;
21504          }
21505          if (!ast_strlen_zero((tmp = get_content_line(req, "Duration", '=')))) {
21506             sscanf(tmp, "%30u", &duration);
21507          }
21508       } else {
21509          /* Type is application/dtmf, simply use what's in the message body */
21510          buf = get_content(req);
21511       }
21512 
21513       /* An empty message body requires us to send a 200 OK */
21514       if (ast_strlen_zero(buf)) {
21515          transmit_response(p, "200 OK", req);
21516          return;
21517       }
21518 
21519       if (!duration) {
21520          duration = 100; /* 100 ms */
21521       }
21522 
21523       if (buf[0] == '*') {
21524          event = 10;
21525       } else if (buf[0] == '#') {
21526          event = 11;
21527       } else if (buf[0] == '!') {
21528          event = 16;
21529       } else if ('A' <= buf[0] && buf[0] <= 'D') {
21530          event = 12 + buf[0] - 'A';
21531       } else if ('a' <= buf[0] && buf[0] <= 'd') {
21532          event = 12 + buf[0] - 'a';
21533       } else if ((sscanf(buf, "%30u", &event) != 1) || event > 16) {
21534          ast_log(AST_LOG_WARNING, "Unable to convert DTMF event signal code to a valid "
21535                "value for INFO message on call %s\n", p->callid);
21536          transmit_response(p, "200 OK", req);
21537          return;
21538       }
21539 
21540       if (event == 16) {
21541          /* send a FLASH event */
21542          struct ast_frame f = { AST_FRAME_CONTROL, { AST_CONTROL_FLASH, } };
21543          ast_queue_frame(p->owner, &f);
21544          if (sipdebug) {
21545             ast_verbose("* DTMF-relay event received: FLASH\n");
21546          }
21547       } else {
21548          /* send a DTMF event */
21549          struct ast_frame f = { AST_FRAME_DTMF, };
21550          if (event < 10) {
21551             f.subclass.integer = '0' + event;
21552          } else if (event == 10) {
21553             f.subclass.integer = '*';
21554          } else if (event == 11) {
21555             f.subclass.integer = '#';
21556          } else {
21557             f.subclass.integer = 'A' + (event - 12);
21558          }
21559          f.len = duration;
21560          ast_queue_frame(p->owner, &f);
21561          if (sipdebug) {
21562             ast_verbose("* DTMF-relay event received: %c\n", (int) f.subclass.integer);
21563          }
21564       }
21565       transmit_response(p, "200 OK", req);
21566       return;
21567    } else if (!strcasecmp(c, "application/media_control+xml")) {
21568       /* Eh, we'll just assume it's a fast picture update for now */
21569       if (p->owner) {
21570          ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
21571       }
21572       transmit_response(p, "200 OK", req);
21573       return;
21574    } else if (!ast_strlen_zero(c = sip_get_header(req, "X-ClientCode"))) {
21575       /* Client code (from SNOM phone) */
21576       if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
21577          if (p->owner && ast_channel_cdr(p->owner)) {
21578             ast_cdr_setuserfield(p->owner, c);
21579          }
21580          if (p->owner && ast_bridged_channel(p->owner) && ast_channel_cdr(ast_bridged_channel(p->owner))) {
21581             ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
21582          }
21583          transmit_response(p, "200 OK", req);
21584       } else {
21585          transmit_response(p, "403 Forbidden", req);
21586       }
21587       return;
21588    } else if (!ast_strlen_zero(c = sip_get_header(req, "Record"))) {
21589       /* INFO messages generated by some phones to start/stop recording
21590        * on phone calls.
21591        */
21592 
21593       struct ast_call_feature *feat = NULL;
21594       int j;
21595       struct ast_frame f = { AST_FRAME_DTMF, };
21596       int suppress_warning = 0; /* Supress warning if the feature is blank */
21597 
21598       if (!p->owner) {        /* not a PBX call */
21599          transmit_response(p, "481 Call leg/transaction does not exist", req);
21600          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21601          return;
21602       }
21603 
21604       /* first, get the feature string, if it exists */
21605       ast_rdlock_call_features();
21606       if (p->relatedpeer) {
21607          if (!strcasecmp(c, "on")) {
21608             if (ast_strlen_zero(p->relatedpeer->record_on_feature)) {
21609                suppress_warning = 1;
21610             } else {
21611                feat = ast_find_call_feature(p->relatedpeer->record_on_feature);
21612             }
21613          } else if (!strcasecmp(c, "off")) {
21614             if (ast_strlen_zero(p->relatedpeer->record_off_feature)) {
21615                suppress_warning = 1;
21616             } else {
21617                feat = ast_find_call_feature(p->relatedpeer->record_off_feature);
21618             }
21619          } else {
21620             ast_log(LOG_ERROR, "Received INFO requesting to record with invalid value: %s\n", c);
21621          }
21622       }
21623       if (!feat || ast_strlen_zero(feat->exten)) {
21624          if (!suppress_warning) {
21625             ast_log(LOG_WARNING, "Recording requested, but no One Touch Monitor registered. (See features.conf)\n");
21626          }
21627          /* 403 means that we don't support this feature, so don't request it again */
21628          transmit_response(p, "403 Forbidden", req);
21629          ast_unlock_call_features();
21630          return;
21631       }
21632       /* Send the feature code to the PBX as DTMF, just like the handset had sent it */
21633       f.len = 100;
21634       for (j=0; j < strlen(feat->exten); j++) {
21635          f.subclass.integer = feat->exten[j];
21636          ast_queue_frame(p->owner, &f);
21637          if (sipdebug) {
21638             ast_verbose("* DTMF-relay event faked: %c\n", f.subclass.integer);
21639          }
21640       }
21641       ast_unlock_call_features();
21642 
21643       ast_debug(1, "Got a Request to Record the channel, state %s\n", c);
21644       transmit_response(p, "200 OK", req);
21645       return;
21646    } else if (ast_strlen_zero(c = sip_get_header(req, "Content-Length")) || !strcasecmp(c, "0")) {
21647       /* This is probably just a packet making sure the signalling is still up, just send back a 200 OK */
21648       transmit_response(p, "200 OK", req);
21649       return;
21650    }
21651 
21652    /* Other type of INFO message, not really understood by Asterisk */
21653 
21654    ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
21655    transmit_response(p, "415 Unsupported media type", req);
21656    return;
21657 }
21658 
21659 /*! \brief Enable SIP Debugging for a single IP */
21660 static char *sip_do_debug_ip(int fd, const char *arg)
21661 {
21662    if (ast_sockaddr_resolve_first_af(&debugaddr, arg, 0, 0)) {
21663       return CLI_SHOWUSAGE;
21664    }
21665 
21666    ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_sockaddr_stringify_addr(&debugaddr));
21667    sipdebug |= sip_debug_console;
21668 
21669    return CLI_SUCCESS;
21670 }
21671 
21672 /*! \brief  Turn on SIP debugging for a given peer */
21673 static char *sip_do_debug_peer(int fd, const char *arg)
21674 {
21675    struct sip_peer *peer = sip_find_peer(arg, NULL, TRUE, FINDPEERS, FALSE, 0);
21676    if (!peer) {
21677       ast_cli(fd, "No such peer '%s'\n", arg);
21678    } else if (ast_sockaddr_isnull(&peer->addr)) {
21679       ast_cli(fd, "Unable to get IP address of peer '%s'\n", arg);
21680    } else {
21681       ast_sockaddr_copy(&debugaddr, &peer->addr);
21682       ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_sockaddr_stringify_addr(&debugaddr));
21683       sipdebug |= sip_debug_console;
21684    }
21685    if (peer) {
21686       sip_unref_peer(peer, "sip_do_debug_peer: sip_unref_peer, from sip_find_peer call");
21687    }
21688    return CLI_SUCCESS;
21689 }
21690 
21691 /*! \brief Turn on SIP debugging (CLI command) */
21692 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
21693 {
21694    int oldsipdebug = sipdebug & sip_debug_console;
21695    const char *what;
21696 
21697    if (cmd == CLI_INIT) {
21698       e->command = "sip set debug {on|off|ip|peer}";
21699       e->usage =
21700          "Usage: sip set debug {off|on|ip addr[:port]|peer peername}\n"
21701          "       Globally disables dumping of SIP packets,\n"
21702          "       or enables it either globally or for a (single)\n"
21703          "       IP address or registered peer.\n";
21704       return NULL;
21705    } else if (cmd == CLI_GENERATE) {
21706       if (a->pos == 4 && !strcasecmp(a->argv[3], "peer"))
21707          return complete_sip_peer(a->word, a->n, 0);
21708       return NULL;
21709         }
21710 
21711    what = a->argv[e->args-1];      /* guaranteed to exist */
21712    if (a->argc == e->args) {       /* on/off */
21713       if (!strcasecmp(what, "on")) {
21714          sipdebug |= sip_debug_console;
21715          sipdebug_text = 1;   /*! \note this can be a special debug command - "sip debug text" or something */
21716          memset(&debugaddr, 0, sizeof(debugaddr));
21717          ast_cli(a->fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
21718          return CLI_SUCCESS;
21719       } else if (!strcasecmp(what, "off")) {
21720          sipdebug &= ~sip_debug_console;
21721          sipdebug_text = 0;
21722          ast_cli(a->fd, "SIP Debugging Disabled\n");
21723          return CLI_SUCCESS;
21724       }
21725    } else if (a->argc == e->args +1) {/* ip/peer */
21726       if (!strcasecmp(what, "ip"))
21727          return sip_do_debug_ip(a->fd, a->argv[e->args]);
21728       else if (!strcasecmp(what, "peer"))
21729          return sip_do_debug_peer(a->fd, a->argv[e->args]);
21730    }
21731    return CLI_SHOWUSAGE;   /* default, failure */
21732 }
21733 
21734 /*! \brief Cli command to send SIP notify to peer */
21735 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
21736 {
21737    struct ast_variable *varlist;
21738    int i;
21739 
21740    switch (cmd) {
21741    case CLI_INIT:
21742       e->command = "sip notify";
21743       e->usage =
21744          "Usage: sip notify <type> <peer> [<peer>...]\n"
21745          "       Send a NOTIFY message to a SIP peer or peers\n"
21746          "       Message types are defined in sip_notify.conf\n";
21747       return NULL;
21748    case CLI_GENERATE:
21749       return complete_sip_notify(a->line, a->word, a->pos, a->n);
21750    }
21751 
21752    if (a->argc < 4)
21753       return CLI_SHOWUSAGE;
21754 
21755    if (!notify_types) {
21756       ast_cli(a->fd, "No %s file found, or no types listed there\n", notify_config);
21757       return CLI_FAILURE;
21758    }
21759 
21760    varlist = ast_variable_browse(notify_types, a->argv[2]);
21761 
21762    if (!varlist) {
21763       ast_cli(a->fd, "Unable to find notify type '%s'\n", a->argv[2]);
21764       return CLI_FAILURE;
21765    }
21766 
21767    for (i = 3; i < a->argc; i++) {
21768       struct sip_pvt *p;
21769       char buf[512];
21770       struct ast_variable *header, *var;
21771 
21772       if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL, NULL))) {
21773          ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
21774          return CLI_FAILURE;
21775       }
21776 
21777       if (create_addr(p, a->argv[i], NULL, 1)) {
21778          /* Maybe they're not registered, etc. */
21779          dialog_unlink_all(p);
21780          dialog_unref(p, "unref dialog inside for loop" );
21781          /* sip_destroy(p); */
21782          ast_cli(a->fd, "Could not create address for '%s'\n", a->argv[i]);
21783          continue;
21784       }
21785 
21786       /* Notify is outgoing call */
21787       ast_set_flag(&p->flags[0], SIP_OUTGOING);
21788       sip_notify_alloc(p);
21789       p->notify->headers = header = ast_variable_new("Subscription-State", "terminated", "");
21790 
21791       for (var = varlist; var; var = var->next) {
21792          ast_copy_string(buf, var->value, sizeof(buf));
21793          ast_unescape_semicolon(buf);
21794 
21795          if (!strcasecmp(var->name, "Content")) {
21796             if (ast_str_strlen(p->notify->content))
21797                ast_str_append(&p->notify->content, 0, "\r\n");
21798             ast_str_append(&p->notify->content, 0, "%s", buf);
21799          } else if (!strcasecmp(var->name, "Content-Length")) {
21800             ast_log(LOG_WARNING, "it is not necessary to specify Content-Length in sip_notify.conf, ignoring\n");
21801          } else {
21802             header->next = ast_variable_new(var->name, buf, "");
21803             header = header->next;
21804          }
21805       }
21806 
21807       /* Now that we have the peer's address, set our ip and change callid */
21808       ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
21809       build_via(p);
21810 
21811       change_callid_pvt(p, NULL);
21812 
21813       ast_cli(a->fd, "Sending NOTIFY of type '%s' to '%s'\n", a->argv[2], a->argv[i]);
21814       sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
21815       transmit_invite(p, SIP_NOTIFY, 0, 2, NULL);
21816       dialog_unref(p, "bump down the count of p since we're done with it.");
21817    }
21818 
21819    return CLI_SUCCESS;
21820 }
21821 
21822 /*! \brief Enable/Disable SIP History logging (CLI) */
21823 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
21824 {
21825    switch (cmd) {
21826    case CLI_INIT:
21827       e->command = "sip set history {on|off}";
21828       e->usage =
21829          "Usage: sip set history {on|off}\n"
21830          "       Enables/Disables recording of SIP dialog history for debugging purposes.\n"
21831          "       Use 'sip show history' to view the history of a call number.\n";
21832       return NULL;
21833    case CLI_GENERATE:
21834       return NULL;
21835    }
21836 
21837    if (a->argc != e->args)
21838       return CLI_SHOWUSAGE;
21839 
21840    if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
21841       recordhistory = TRUE;
21842       ast_cli(a->fd, "SIP History Recording Enabled (use 'sip show history')\n");
21843    } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
21844       recordhistory = FALSE;
21845       ast_cli(a->fd, "SIP History Recording Disabled\n");
21846    } else {
21847       return CLI_SHOWUSAGE;
21848    }
21849    return CLI_SUCCESS;
21850 }
21851 
21852 /*! \brief Authenticate for outbound registration */
21853 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code)
21854 {
21855    char *header, *respheader;
21856    char digest[1024];
21857 
21858    p->authtries++;
21859    sip_auth_headers(code, &header, &respheader);
21860    memset(digest, 0, sizeof(digest));
21861    if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
21862       /* There's nothing to use for authentication */
21863       /* No digest challenge in request */
21864       if (sip_debug_test_pvt(p) && p->registry)
21865          ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
21866          /* No old challenge */
21867       return -1;
21868    }
21869    if (p->do_history)
21870       append_history(p, "RegistryAuth", "Try: %d", p->authtries);
21871    if (sip_debug_test_pvt(p) && p->registry)
21872       ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
21873    return transmit_register(p->registry, SIP_REGISTER, digest, respheader);
21874 }
21875 
21876 /*! \brief Add authentication on outbound SIP packet */
21877 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code, int sipmethod, int init)
21878 {
21879    char *header, *respheader;
21880    char digest[1024];
21881 
21882    if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
21883       return -2;
21884 
21885    p->authtries++;
21886    sip_auth_headers(code, &header, &respheader);
21887    ast_debug(2, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
21888    memset(digest, 0, sizeof(digest));
21889    if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
21890       /* No way to authenticate */
21891       return -1;
21892    }
21893    /* Now we have a reply digest */
21894    p->options->auth = digest;
21895    p->options->authheader = respheader;
21896    return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init, NULL);
21897 }
21898 
21899 /*! \brief  reply to authentication for outbound registrations
21900 \return  Returns -1 if we have no auth
21901 \note This is used for register= servers in sip.conf, SIP proxies we register
21902    with  for receiving calls from.  */
21903 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod,  char *digest, int digest_len)
21904 {
21905    char tmp[512];
21906    char *c;
21907    char oldnonce[256];
21908 
21909    /* table of recognised keywords, and places where they should be copied */
21910    const struct x {
21911       const char *key;
21912       const ast_string_field *field;
21913    } *i, keys[] = {
21914       { "realm=", &p->realm },
21915       { "nonce=", &p->nonce },
21916       { "opaque=", &p->opaque },
21917       { "qop=", &p->qop },
21918       { "domain=", &p->domain },
21919       { NULL, 0 },
21920    };
21921 
21922    ast_copy_string(tmp, sip_get_header(req, header), sizeof(tmp));
21923    if (ast_strlen_zero(tmp))
21924       return -1;
21925    if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
21926       ast_log(LOG_WARNING, "missing Digest.\n");
21927       return -1;
21928    }
21929    c = tmp + strlen("Digest ");
21930    ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
21931    while (c && *(c = ast_skip_blanks(c))) {  /* lookup for keys */
21932       for (i = keys; i->key != NULL; i++) {
21933          char *src, *separator;
21934          if (strncasecmp(c, i->key, strlen(i->key)) != 0)
21935             continue;
21936          /* Found. Skip keyword, take text in quotes or up to the separator. */
21937          c += strlen(i->key);
21938          if (*c == '"') {
21939             src = ++c;
21940             separator = "\"";
21941          } else {
21942             src = c;
21943             separator = ",";
21944          }
21945          strsep(&c, separator); /* clear separator and move ptr */
21946          ast_string_field_ptr_set(p, i->field, src);
21947          break;
21948       }
21949       if (i->key == NULL) /* not found, try ',' */
21950          strsep(&c, ",");
21951    }
21952    /* Reset nonce count */
21953    if (strcmp(p->nonce, oldnonce))
21954       p->noncecount = 0;
21955 
21956    /* Save auth data for following registrations */
21957    if (p->registry) {
21958       struct sip_registry *r = p->registry;
21959 
21960       if (strcmp(r->nonce, p->nonce)) {
21961          ast_string_field_set(r, realm, p->realm);
21962          ast_string_field_set(r, nonce, p->nonce);
21963          ast_string_field_set(r, authdomain, p->domain);
21964          ast_string_field_set(r, opaque, p->opaque);
21965          ast_string_field_set(r, qop, p->qop);
21966          r->noncecount = 0;
21967       }
21968    }
21969    return build_reply_digest(p, sipmethod, digest, digest_len);
21970 }
21971 
21972 /*! \brief  Build reply digest
21973 \return  Returns -1 if we have no auth
21974 \note Build digest challenge for authentication of registrations and calls
21975    Also used for authentication of BYE
21976 */
21977 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
21978 {
21979    char a1[256];
21980    char a2[256];
21981    char a1_hash[256];
21982    char a2_hash[256];
21983    char resp[256];
21984    char resp_hash[256];
21985    char uri[256];
21986    char opaque[256] = "";
21987    char cnonce[80];
21988    const char *username;
21989    const char *secret;
21990    const char *md5secret;
21991    struct sip_auth *auth;  /* Realm authentication credential */
21992    struct sip_auth_container *credentials;
21993 
21994    if (!ast_strlen_zero(p->domain))
21995       snprintf(uri, sizeof(uri), "%s:%s", p->socket.type == SIP_TRANSPORT_TLS ? "sips" : "sip", p->domain);
21996    else if (!ast_strlen_zero(p->uri))
21997       ast_copy_string(uri, p->uri, sizeof(uri));
21998    else
21999       snprintf(uri, sizeof(uri), "%s:%s@%s", p->socket.type == SIP_TRANSPORT_TLS ? "sips" : "sip", p->username, ast_sockaddr_stringify_host_remote(&p->sa));
22000 
22001    snprintf(cnonce, sizeof(cnonce), "%08lx", (unsigned long)ast_random());
22002 
22003    /* Check if we have peer credentials */
22004    ao2_lock(p);
22005    credentials = p->peerauth;
22006    if (credentials) {
22007       ao2_t_ref(credentials, +1, "Ref peer auth for digest");
22008    }
22009    ao2_unlock(p);
22010    auth = find_realm_authentication(credentials, p->realm);
22011    if (!auth) {
22012       /* If not, check global credentials */
22013       if (credentials) {
22014          ao2_t_ref(credentials, -1, "Unref peer auth for digest");
22015       }
22016       ast_mutex_lock(&authl_lock);
22017       credentials = authl;
22018       if (credentials) {
22019          ao2_t_ref(credentials, +1, "Ref global auth for digest");
22020       }
22021       ast_mutex_unlock(&authl_lock);
22022       auth = find_realm_authentication(credentials, p->realm);
22023    }
22024 
22025    if (auth) {
22026       ast_debug(3, "use realm [%s] from peer [%s][%s]\n", auth->username, p->peername, p->username);
22027       username = auth->username;
22028       secret = auth->secret;
22029       md5secret = auth->md5secret;
22030       if (sipdebug)
22031          ast_debug(1, "Using realm %s authentication for call %s\n", p->realm, p->callid);
22032    } else {
22033       /* No authentication, use peer or register= config */
22034       username = p->authname;
22035       secret = p->relatedpeer 
22036          && !ast_strlen_zero(p->relatedpeer->remotesecret)
22037             ? p->relatedpeer->remotesecret : p->peersecret;
22038       md5secret = p->peermd5secret;
22039    }
22040    if (ast_strlen_zero(username)) {
22041       /* We have no authentication */
22042       if (credentials) {
22043          ao2_t_ref(credentials, -1, "Unref auth for digest");
22044       }
22045       return -1;
22046    }
22047 
22048    /* Calculate SIP digest response */
22049    snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
22050    snprintf(a2, sizeof(a2), "%s:%s", sip_methods[method].text, uri);
22051    if (!ast_strlen_zero(md5secret))
22052       ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
22053    else
22054       ast_md5_hash(a1_hash, a1);
22055    ast_md5_hash(a2_hash, a2);
22056 
22057    p->noncecount++;
22058    if (!ast_strlen_zero(p->qop))
22059       snprintf(resp, sizeof(resp), "%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, (unsigned)p->noncecount, cnonce, "auth", a2_hash);
22060    else
22061       snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, p->nonce, a2_hash);
22062    ast_md5_hash(resp_hash, resp);
22063 
22064    /* only include the opaque string if it's set */
22065    if (!ast_strlen_zero(p->opaque)) {
22066       snprintf(opaque, sizeof(opaque), ", opaque=\"%s\"", p->opaque);
22067    }
22068 
22069    /* XXX We hard code our qop to "auth" for now.  XXX */
22070    if (!ast_strlen_zero(p->qop))
22071       snprintf(digest, digest_len, "Digest username=\"%s\", realm=\"%s\", algorithm=MD5, uri=\"%s\", nonce=\"%s\", response=\"%s\"%s, qop=auth, cnonce=\"%s\", nc=%08x", username, p->realm, uri, p->nonce, resp_hash, opaque, cnonce, (unsigned)p->noncecount);
22072    else
22073       snprintf(digest, digest_len, "Digest username=\"%s\", realm=\"%s\", algorithm=MD5, uri=\"%s\", nonce=\"%s\", response=\"%s\"%s", username, p->realm, uri, p->nonce, resp_hash, opaque);
22074 
22075    append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);
22076 
22077    if (credentials) {
22078       ao2_t_ref(credentials, -1, "Unref auth for digest");
22079    }
22080    return 0;
22081 }
22082    
22083 /*! \brief Read SIP header (dialplan function) */
22084 static int func_header_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len)
22085 {
22086    struct sip_pvt *p;
22087    const char *content = NULL;
22088    AST_DECLARE_APP_ARGS(args,
22089       AST_APP_ARG(header);
22090       AST_APP_ARG(number);
22091    );
22092    int i, number, start = 0;
22093 
22094    if (!chan) {
22095       ast_log(LOG_WARNING, "No channel was provided to %s function.\n", function);
22096       return -1;
22097    }
22098 
22099    if (ast_strlen_zero(data)) {
22100       ast_log(LOG_WARNING, "This function requires a header name.\n");
22101       return -1;
22102    }
22103 
22104    ast_channel_lock(chan);
22105    if (!IS_SIP_TECH(ast_channel_tech(chan))) {
22106       ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
22107       ast_channel_unlock(chan);
22108       return -1;
22109    }
22110 
22111    AST_STANDARD_APP_ARGS(args, data);
22112    if (!args.number) {
22113       number = 1;
22114    } else {
22115       sscanf(args.number, "%30d", &number);
22116       if (number < 1)
22117          number = 1;
22118    }
22119 
22120    p = ast_channel_tech_pvt(chan);
22121 
22122    /* If there is no private structure, this channel is no longer alive */
22123    if (!p) {
22124       ast_channel_unlock(chan);
22125       return -1;
22126    }
22127 
22128    for (i = 0; i < number; i++)
22129       content = __get_header(&p->initreq, args.header, &start);
22130 
22131    if (ast_strlen_zero(content)) {
22132       ast_channel_unlock(chan);
22133       return -1;
22134    }
22135 
22136    ast_copy_string(buf, content, len);
22137    ast_channel_unlock(chan);
22138 
22139    return 0;
22140 }
22141 
22142 static struct ast_custom_function sip_header_function = {
22143    .name = "SIP_HEADER",
22144    .read = func_header_read,
22145 };
22146 
22147 /*! \brief  Dial plan function to check if domain is local */
22148 static int func_check_sipdomain(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
22149 {
22150    if (ast_strlen_zero(data)) {
22151       ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
22152       return -1;
22153    }
22154    if (check_sip_domain(data, NULL, 0))
22155       ast_copy_string(buf, data, len);
22156    else
22157       buf[0] = '\0';
22158    return 0;
22159 }
22160 
22161 static struct ast_custom_function checksipdomain_function = {
22162    .name = "CHECKSIPDOMAIN",
22163    .read = func_check_sipdomain,
22164 };
22165 
22166 /*! \brief  ${SIPPEER()} Dialplan function - reads peer data */
22167 static int function_sippeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
22168 {
22169    struct sip_peer *peer;
22170    char *colname;
22171 
22172    if ((colname = strchr(data, ':'))) {   /*! \todo Will be deprecated after 1.4 */
22173       static int deprecation_warning = 0;
22174       *colname++ = '\0';
22175       if (deprecation_warning++ % 10 == 0)
22176          ast_log(LOG_WARNING, "SIPPEER(): usage of ':' to separate arguments is deprecated.  Please use ',' instead.\n");
22177    } else if ((colname = strchr(data, ',')))
22178       *colname++ = '\0';
22179    else
22180       colname = "ip";
22181 
22182    if (!(peer = sip_find_peer(data, NULL, TRUE, FINDPEERS, FALSE, 0)))
22183       return -1;
22184 
22185    if (!strcasecmp(colname, "ip")) {
22186       ast_copy_string(buf, ast_sockaddr_stringify_addr(&peer->addr), len);
22187    } else  if (!strcasecmp(colname, "port")) {
22188       snprintf(buf, len, "%d", ast_sockaddr_port(&peer->addr));
22189    } else  if (!strcasecmp(colname, "status")) {
22190       peer_status(peer, buf, len);
22191    } else  if (!strcasecmp(colname, "language")) {
22192       ast_copy_string(buf, peer->language, len);
22193    } else  if (!strcasecmp(colname, "regexten")) {
22194       ast_copy_string(buf, peer->regexten, len);
22195    } else  if (!strcasecmp(colname, "limit")) {
22196       snprintf(buf, len, "%d", peer->call_limit);
22197    } else  if (!strcasecmp(colname, "busylevel")) {
22198       snprintf(buf, len, "%d", peer->busy_level);
22199    } else  if (!strcasecmp(colname, "curcalls")) {
22200       snprintf(buf, len, "%d", peer->inuse);
22201    } else if (!strcasecmp(colname, "maxforwards")) {
22202       snprintf(buf, len, "%d", peer->maxforwards);
22203    } else  if (!strcasecmp(colname, "accountcode")) {
22204       ast_copy_string(buf, peer->accountcode, len);
22205    } else  if (!strcasecmp(colname, "callgroup")) {
22206       ast_print_group(buf, len, peer->callgroup);
22207    } else  if (!strcasecmp(colname, "pickupgroup")) {
22208       ast_print_group(buf, len, peer->pickupgroup);
22209    } else  if (!strcasecmp(colname, "namedcallgroup")) {
22210       struct ast_str *tmp_str = ast_str_create(1024);
22211       if (tmp_str) {
22212          ast_copy_string(buf, ast_print_namedgroups(&tmp_str, peer->named_callgroups), len);
22213          ast_free(tmp_str);
22214       }
22215    } else  if (!strcasecmp(colname, "namedpickupgroup")) {
22216       struct ast_str *tmp_str = ast_str_create(1024);
22217       if (tmp_str) {
22218          ast_copy_string(buf, ast_print_namedgroups(&tmp_str, peer->named_pickupgroups), len);
22219          ast_free(tmp_str);
22220       }
22221    } else  if (!strcasecmp(colname, "useragent")) {
22222       ast_copy_string(buf, peer->useragent, len);
22223    } else  if (!strcasecmp(colname, "mailbox")) {
22224       struct ast_str *mailbox_str = ast_str_alloca(512);
22225       peer_mailboxes_to_str(&mailbox_str, peer);
22226       ast_copy_string(buf, ast_str_buffer(mailbox_str), len);
22227    } else  if (!strcasecmp(colname, "context")) {
22228       ast_copy_string(buf, peer->context, len);
22229    } else  if (!strcasecmp(colname, "expire")) {
22230       snprintf(buf, len, "%d", peer->expire);
22231    } else  if (!strcasecmp(colname, "dynamic")) {
22232       ast_copy_string(buf, peer->host_dynamic ? "yes" : "no", len);
22233    } else  if (!strcasecmp(colname, "callerid_name")) {
22234       ast_copy_string(buf, peer->cid_name, len);
22235    } else  if (!strcasecmp(colname, "callerid_num")) {
22236       ast_copy_string(buf, peer->cid_num, len);
22237    } else  if (!strcasecmp(colname, "codecs")) {
22238       ast_getformatname_multiple(buf, len -1, peer->caps);
22239    } else if (!strcasecmp(colname, "encryption")) {
22240       snprintf(buf, len, "%u", ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP));
22241    } else  if (!strncasecmp(colname, "chanvar[", 8)) {
22242       char *chanvar=colname + 8;
22243       struct ast_variable *v;
22244 
22245       chanvar = strsep(&chanvar, "]");
22246       for (v = peer->chanvars ; v ; v = v->next) {
22247          if (!strcasecmp(v->name, chanvar)) {
22248             ast_copy_string(buf, v->value, len);
22249          }
22250       }
22251    } else  if (!strncasecmp(colname, "codec[", 6)) {
22252       char *codecnum;
22253       struct ast_format codec;
22254 
22255       codecnum = colname + 6; /* move past the '[' */
22256       codecnum = strsep(&codecnum, "]"); /* trim trailing ']' if any */
22257       if((ast_codec_pref_index(&peer->prefs, atoi(codecnum), &codec))) {
22258          ast_copy_string(buf, ast_getformatname(&codec), len);
22259       } else {
22260          buf[0] = '\0';
22261       }
22262    } else {
22263       buf[0] = '\0';
22264    }
22265 
22266    sip_unref_peer(peer, "sip_unref_peer from function_sippeer, just before return");
22267 
22268    return 0;
22269 }
22270 
22271 /*! \brief Structure to declare a dialplan function: SIPPEER */
22272 static struct ast_custom_function sippeer_function = {
22273    .name = "SIPPEER",
22274    .read = function_sippeer,
22275 };
22276 
22277 /*! \brief ${SIPCHANINFO()} Dialplan function - reads sip channel data */
22278 static int function_sipchaninfo_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
22279 {
22280    struct sip_pvt *p;
22281    static int deprecated = 0;
22282 
22283    *buf = 0;
22284 
22285    if (!chan) {
22286       ast_log(LOG_WARNING, "No channel was provided to %s function.\n", cmd);
22287       return -1;
22288    }
22289 
22290    if (!data) {
22291       ast_log(LOG_WARNING, "This function requires a parameter name.\n");
22292       return -1;
22293    }
22294 
22295    ast_channel_lock(chan);
22296    if (!IS_SIP_TECH(ast_channel_tech(chan))) {
22297       ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
22298       ast_channel_unlock(chan);
22299       return -1;
22300    }
22301 
22302    if (deprecated++ % 20 == 0) {
22303       /* Deprecated in 1.6.1 */
22304       ast_log(LOG_WARNING, "SIPCHANINFO() is deprecated.  Please transition to using CHANNEL().\n");
22305    }
22306 
22307    p = ast_channel_tech_pvt(chan);
22308 
22309    /* If there is no private structure, this channel is no longer alive */
22310    if (!p) {
22311       ast_channel_unlock(chan);
22312       return -1;
22313    }
22314 
22315    if (!strcasecmp(data, "peerip")) {
22316       ast_copy_string(buf, ast_sockaddr_stringify_addr(&p->sa), len);
22317    } else  if (!strcasecmp(data, "recvip")) {
22318       ast_copy_string(buf, ast_sockaddr_stringify_addr(&p->recv), len);
22319    } else  if (!strcasecmp(data, "from")) {
22320       ast_copy_string(buf, p->from, len);
22321    } else  if (!strcasecmp(data, "uri")) {
22322       ast_copy_string(buf, p->uri, len);
22323    } else  if (!strcasecmp(data, "useragent")) {
22324       ast_copy_string(buf, p->useragent, len);
22325    } else  if (!strcasecmp(data, "peername")) {
22326       ast_copy_string(buf, p->peername, len);
22327    } else if (!strcasecmp(data, "t38passthrough")) {
22328       if ((p->t38.state == T38_DISABLED) || (p->t38.state == T38_REJECTED)) {
22329          ast_copy_string(buf, "0", len);
22330       } else { /* T38 is offered or enabled in this call */
22331          ast_copy_string(buf, "1", len);
22332       }
22333    } else {
22334       ast_channel_unlock(chan);
22335       return -1;
22336    }
22337    ast_channel_unlock(chan);
22338 
22339    return 0;
22340 }
22341 
22342 /*! \brief Structure to declare a dialplan function: SIPCHANINFO */
22343 static struct ast_custom_function sipchaninfo_function = {
22344    .name = "SIPCHANINFO",
22345    .read = function_sipchaninfo_read,
22346 };
22347 
22348 /*! \brief update redirecting information for a channel based on headers
22349  *
22350  */
22351 static void change_redirecting_information(struct sip_pvt *p, struct sip_request *req,
22352    struct ast_party_redirecting *redirecting,
22353    struct ast_set_party_redirecting *update_redirecting, int set_call_forward)
22354 {
22355    char *redirecting_from_name = NULL;
22356    char *redirecting_from_number = NULL;
22357    char *redirecting_to_name = NULL;
22358    char *redirecting_to_number = NULL;
22359    int reason = AST_REDIRECTING_REASON_UNCONDITIONAL;
22360    int is_response = req->method == SIP_RESPONSE;
22361    int res = 0;
22362 
22363    res = get_rdnis(p, req, &redirecting_from_name, &redirecting_from_number, &reason);
22364    if (res == -1) {
22365       if (is_response) {
22366          get_name_and_number(sip_get_header(req, "TO"), &redirecting_from_name, &redirecting_from_number);
22367       } else {
22368          return;
22369       }
22370    }
22371 
22372    /* At this point, all redirecting "from" info should be filled in appropriately
22373     * on to the "to" info
22374     */
22375 
22376    if (is_response) {
22377       parse_moved_contact(p, req, &redirecting_to_name, &redirecting_to_number, set_call_forward);
22378    } else {
22379       get_name_and_number(sip_get_header(req, "TO"), &redirecting_to_name, &redirecting_to_number);
22380    }
22381 
22382    if (!ast_strlen_zero(redirecting_from_number)) {
22383       ast_debug(3, "Got redirecting from number %s\n", redirecting_from_number);
22384       update_redirecting->from.number = 1;
22385       redirecting->from.number.valid = 1;
22386       ast_free(redirecting->from.number.str);
22387       redirecting->from.number.str = redirecting_from_number;
22388    }
22389    if (!ast_strlen_zero(redirecting_from_name)) {
22390       ast_debug(3, "Got redirecting from name %s\n", redirecting_from_name);
22391       update_redirecting->from.name = 1;
22392       redirecting->from.name.valid = 1;
22393       ast_free(redirecting->from.name.str);
22394       redirecting->from.name.str = redirecting_from_name;
22395    }
22396    if (!ast_strlen_zero(p->cid_tag)) {
22397       ast_free(redirecting->from.tag);
22398       redirecting->from.tag = ast_strdup(p->cid_tag);
22399       ast_free(redirecting->to.tag);
22400       redirecting->to.tag = ast_strdup(p->cid_tag);
22401    }
22402    if (!ast_strlen_zero(redirecting_to_number)) {
22403       ast_debug(3, "Got redirecting to number %s\n", redirecting_to_number);
22404       update_redirecting->to.number = 1;
22405       redirecting->to.number.valid = 1;
22406       ast_free(redirecting->to.number.str);
22407       redirecting->to.number.str = redirecting_to_number;
22408    }
22409    if (!ast_strlen_zero(redirecting_to_name)) {
22410       ast_debug(3, "Got redirecting to name %s\n", redirecting_from_number);
22411       update_redirecting->to.name = 1;
22412       redirecting->to.name.valid = 1;
22413       ast_free(redirecting->to.name.str);
22414       redirecting->to.name.str = redirecting_to_name;
22415    }
22416    redirecting->reason = reason;
22417 }
22418 
22419 /*! \brief Parse 302 Moved temporalily response
22420    \todo XXX Doesn't redirect over TLS on sips: uri's.
22421       If we get a redirect to a SIPS: uri, this needs to be going back to the
22422       dialplan (this is a request for a secure signalling path).
22423       Note that transport=tls is deprecated, but we need to support it on incoming requests.
22424 */
22425 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward)
22426 {
22427    char contact[SIPBUFSIZE];
22428    char *contact_name = NULL;
22429    char *contact_number = NULL;
22430    char *separator, *trans;
22431    char *domain;
22432    enum sip_transport transport = SIP_TRANSPORT_UDP;
22433 
22434    ast_copy_string(contact, sip_get_header(req, "Contact"), sizeof(contact));
22435    if ((separator = strchr(contact, ',')))
22436       *separator = '\0';
22437 
22438    contact_number = get_in_brackets(contact);
22439    if ((trans = strcasestr(contact_number, ";transport="))) {
22440       trans += 11;
22441 
22442       if ((separator = strchr(trans, ';')))
22443          *separator = '\0';
22444 
22445       if (!strncasecmp(trans, "tcp", 3))
22446          transport = SIP_TRANSPORT_TCP;
22447       else if (!strncasecmp(trans, "tls", 3))
22448          transport = SIP_TRANSPORT_TLS;
22449       else {
22450          if (strncasecmp(trans, "udp", 3))
22451             ast_debug(1, "received contact with an invalid transport, '%s'\n", contact_number);
22452          /* This will assume UDP for all unknown transports */
22453          transport = SIP_TRANSPORT_UDP;
22454       }
22455    }
22456    contact_number = remove_uri_parameters(contact_number);
22457 
22458    if (p->socket.tcptls_session) {
22459       ao2_ref(p->socket.tcptls_session, -1);
22460       p->socket.tcptls_session = NULL;
22461    } else if (p->socket.ws_session) {
22462       ast_websocket_unref(p->socket.ws_session);
22463       p->socket.ws_session = NULL;
22464    }
22465 
22466    set_socket_transport(&p->socket, transport);
22467 
22468    if (set_call_forward && ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
22469       char *host = NULL;
22470       if (!strncasecmp(contact_number, "sip:", 4))
22471          contact_number += 4;
22472       else if (!strncasecmp(contact_number, "sips:", 5))
22473          contact_number += 5;
22474       separator = strchr(contact_number, '/');
22475       if (separator)
22476          *separator = '\0';
22477       if ((host = strchr(contact_number, '@'))) {
22478          *host++ = '\0';
22479          ast_debug(2, "Found promiscuous redirection to 'SIP/%s::::%s@%s'\n", contact_number, sip_get_transport(transport), host);
22480          if (p->owner)
22481             ast_channel_call_forward_build(p->owner, "SIP/%s::::%s@%s", contact_number, sip_get_transport(transport), host);
22482       } else {
22483          ast_debug(2, "Found promiscuous redirection to 'SIP/::::%s@%s'\n", sip_get_transport(transport), contact_number);
22484          if (p->owner)
22485             ast_channel_call_forward_build(p->owner, "SIP/::::%s@%s", sip_get_transport(transport), contact_number);
22486       }
22487    } else {
22488       separator = strchr(contact, '@');
22489       if (separator) {
22490          *separator++ = '\0';
22491          domain = separator;
22492       } else {
22493          /* No username part */
22494          domain = contact;
22495       }
22496       separator = strchr(contact, '/');   /* WHEN do we hae a forward slash in the URI? */
22497       if (separator)
22498          *separator = '\0';
22499 
22500       if (!strncasecmp(contact_number, "sip:", 4))
22501          contact_number += 4;
22502       else if (!strncasecmp(contact_number, "sips:", 5))
22503          contact_number += 5;
22504       separator = strchr(contact_number, ';');  /* And username ; parameters? */
22505       if (separator)
22506          *separator = '\0';
22507       ast_uri_decode(contact_number, ast_uri_sip_user);
22508       if (set_call_forward) {
22509          ast_debug(2, "Received 302 Redirect to extension '%s' (domain %s)\n", contact_number, domain);
22510          if (p->owner) {
22511             pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
22512             ast_channel_call_forward_set(p->owner, contact_number);
22513          }
22514       }
22515    }
22516 
22517    /* We've gotten the number for the contact, now get the name */
22518 
22519    if (*contact == '\"') {
22520       contact_name = contact + 1;
22521       if (!(separator = (char *)find_closing_quote(contact_name, NULL))) {
22522          ast_log(LOG_NOTICE, "No closing quote on name in Contact header? %s\n", contact);
22523       }
22524       *separator = '\0';
22525    }
22526 
22527    if (name && !ast_strlen_zero(contact_name)) {
22528       *name = ast_strdup(contact_name);
22529    }
22530    if (number) {
22531       *number = ast_strdup(contact_number);
22532    }
22533 }
22534 
22535 /*! \brief Check pending actions on SIP call 
22536  *
22537  * \note both sip_pvt and sip_pvt's owner channel (if present)
22538  *  must be locked for this function.
22539  */
22540 static void check_pendings(struct sip_pvt *p)
22541 {
22542    if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
22543       if (p->reinviteid > -1) {
22544          /* Outstanding p->reinviteid timeout, so wait... */
22545          return;
22546       } else if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA) {
22547          /* if we can't BYE, then this is really a pending CANCEL */
22548          p->invitestate = INV_CANCELLED;
22549          transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
22550          /* If the cancel occurred on an initial invite, cancel the pending BYE */
22551          if (!ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
22552             ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);
22553          }
22554          /* Actually don't destroy us yet, wait for the 487 on our original
22555             INVITE, but do set an autodestruct just in case we never get it. */
22556       } else {
22557          /* We have a pending outbound invite, don't send something
22558           * new in-transaction, unless it is a pending reinvite, then
22559           * by the time we are called here, we should probably just hang up. */
22560          if (p->pendinginvite && !p->ongoing_reinvite)
22561             return;
22562 
22563          if (p->owner) {
22564             ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
22565          }
22566          /* Perhaps there is an SD change INVITE outstanding */
22567          transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
22568          ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);
22569       }
22570       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22571    } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
22572       /* if we can't REINVITE, hold it for later */
22573       if (p->pendinginvite || p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA || p->waitid > 0) {
22574          ast_debug(2, "NOT Sending pending reinvite (yet) on '%s'\n", p->callid);
22575       } else {
22576          ast_debug(2, "Sending pending reinvite on '%s'\n", p->callid);
22577          /* Didn't get to reinvite yet, so do it now */
22578          transmit_reinvite_with_sdp(p, (p->t38.state == T38_LOCAL_REINVITE ? TRUE : FALSE), FALSE);
22579          ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
22580       }
22581    }
22582 }
22583 
22584 /*! \brief Reset the NEEDREINVITE flag after waiting when we get 491 on a Re-invite
22585    to avoid race conditions between asterisk servers.
22586    Called from the scheduler.
22587 */
22588 static int sip_reinvite_retry(const void *data)
22589 {
22590    struct sip_pvt *p = (struct sip_pvt *) data;
22591    struct ast_channel *owner;
22592 
22593    sip_pvt_lock(p); /* called from schedule thread which requires a lock */
22594    while ((owner = p->owner) && ast_channel_trylock(owner)) {
22595       sip_pvt_unlock(p);
22596       usleep(1);
22597       sip_pvt_lock(p);
22598    }
22599    ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
22600    p->waitid = -1;
22601    check_pendings(p);
22602    sip_pvt_unlock(p);
22603    if (owner) {
22604       ast_channel_unlock(owner);
22605    }
22606    dialog_unref(p, "unref the dialog ptr from sip_reinvite_retry, because it held a dialog ptr");
22607    return 0;
22608 }
22609 
22610 /*!
22611  * \brief Handle authentication challenge for SIP UPDATE
22612  *
22613  * This function is only called upon the receipt of a 401/407 response to an UPDATE.
22614  */
22615 static void handle_response_update(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
22616 {
22617    if (p->options) {
22618       p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
22619    }
22620    if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, SIP_UPDATE, 1)) {
22621       ast_log(LOG_NOTICE, "Failed to authenticate on UPDATE to '%s'\n", sip_get_header(&p->initreq, "From"));
22622    }
22623 }
22624 
22625 static void cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry)
22626 {
22627    struct cc_epa_entry *cc_entry = epa_entry->instance_data;
22628    struct sip_monitor_instance *monitor_instance = ao2_callback(sip_monitor_instances, 0,
22629          find_sip_monitor_instance_by_suspension_entry, epa_entry);
22630    const char *min_expires;
22631 
22632    if (!monitor_instance) {
22633       ast_log(LOG_WARNING, "Can't find monitor_instance corresponding to epa_entry %p.\n", epa_entry);
22634       return;
22635    }
22636 
22637    if (resp != 423) {
22638       ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
22639             "Received error response to our PUBLISH");
22640       ao2_ref(monitor_instance, -1);
22641       return;
22642    }
22643 
22644    /* Allrighty, the other end doesn't like our Expires value. They think it's
22645     * too small, so let's see if they've provided a more sensible value. If they
22646     * haven't, then we'll just double our Expires value and see if they like that
22647     * instead.
22648     *
22649     * XXX Ideally this logic could be placed into its own function so that SUBSCRIBE,
22650     * PUBLISH, and REGISTER could all benefit from the same shared code.
22651     */
22652    min_expires = sip_get_header(req, "Min-Expires");
22653    if (ast_strlen_zero(min_expires)) {
22654       pvt->expiry *= 2;
22655       if (pvt->expiry < 0) {
22656          /* You dork! You overflowed! */
22657          ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
22658                "PUBLISH expiry overflowed");
22659          ao2_ref(monitor_instance, -1);
22660          return;
22661       }
22662    } else if (sscanf(min_expires, "%30d", &pvt->expiry) != 1) {
22663       ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
22664             "Min-Expires has non-numeric value");
22665       ao2_ref(monitor_instance, -1);
22666       return;
22667    }
22668    /* At this point, we have most certainly changed pvt->expiry, so try transmitting
22669     * again
22670     */
22671    transmit_invite(pvt, SIP_PUBLISH, FALSE, 0, NULL);
22672    ao2_ref(monitor_instance, -1);
22673 }
22674 
22675 static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
22676 {
22677    struct sip_epa_entry *epa_entry = p->epa_entry;
22678    const char *etag = sip_get_header(req, "Sip-ETag");
22679 
22680    ast_assert(epa_entry != NULL);
22681 
22682    if (resp == 401 || resp == 407) {
22683       ast_string_field_set(p, theirtag, NULL);
22684       if (p->options) {
22685          p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
22686       }
22687       if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, SIP_PUBLISH, 0)) {
22688          ast_log(LOG_NOTICE, "Failed to authenticate on PUBLISH to '%s'\n", sip_get_header(&p->initreq, "From"));
22689          pvt_set_needdestroy(p, "Failed to authenticate on PUBLISH");
22690          sip_alreadygone(p);
22691       }
22692       return;
22693    }
22694 
22695    if (resp == 501 || resp == 405) {
22696       mark_method_unallowed(&p->allowed_methods, SIP_PUBLISH);
22697    }
22698 
22699    if (resp == 200) {
22700       p->authtries = 0;
22701       /* If I've read section 6, item 6 of RFC 3903 correctly,
22702        * an ESC will only generate a new etag when it sends a 200 OK
22703        */
22704       if (!ast_strlen_zero(etag)) {
22705          ast_copy_string(epa_entry->entity_tag, etag, sizeof(epa_entry->entity_tag));
22706       }
22707       /* The nominal case. Everything went well. Everybody is happy.
22708        * Each EPA will have a specific action to take as a result of this
22709        * development, so ... callbacks!
22710        */
22711       if (epa_entry->static_data->handle_ok) {
22712          epa_entry->static_data->handle_ok(p, req, epa_entry);
22713       }
22714    } else {
22715       /* Rather than try to make individual callbacks for each error
22716        * type, there is just a single error callback. The callback
22717        * can distinguish between error messages and do what it needs to
22718        */
22719       if (epa_entry->static_data->handle_error) {
22720          epa_entry->static_data->handle_error(p, resp, req, epa_entry);
22721       }
22722    }
22723 }
22724 
22725 /*!
22726  * \internal
22727  * \brief Set hangup source and cause.
22728  *
22729  * \param p SIP private.
22730  * \param cause Hangup cause to queue.  Zero if no cause.
22731  *
22732  * \pre p and p->owner are locked.
22733  *
22734  * \return Nothing
22735  */
22736 static void sip_queue_hangup_cause(struct sip_pvt *p, int cause)
22737 {
22738    struct ast_channel *owner = p->owner;
22739    const char *name = ast_strdupa(ast_channel_name(owner));
22740 
22741    /* Cannot hold any channel/private locks when calling. */
22742    ast_channel_ref(owner);
22743    ast_channel_unlock(owner);
22744    sip_pvt_unlock(p);
22745    ast_set_hangupsource(owner, name, 0);
22746    if (cause) {
22747       ast_queue_hangup_with_cause(owner, cause);
22748    } else {
22749       ast_queue_hangup(owner);
22750    }
22751    ast_channel_unref(owner);
22752 
22753    /* Relock things. */
22754    owner = sip_pvt_lock_full(p);
22755    if (owner) {
22756       ast_channel_unref(owner);
22757    }
22758 }
22759 
22760 /*! \brief Handle SIP response to INVITE dialogue */
22761 static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
22762 {
22763    int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
22764    int res = 0;
22765    int xmitres = 0;
22766    int reinvite = ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
22767    char *p_hdrval;
22768    int rtn;
22769    struct ast_party_connected_line connected;
22770    struct ast_set_party_connected_line update_connected;
22771 
22772    if (reinvite) {
22773       ast_debug(4, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
22774    } else {
22775       ast_debug(4, "SIP response %d to standard invite\n", resp);
22776    }
22777 
22778    if (p->alreadygone) { /* This call is already gone */
22779       ast_debug(1, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
22780       return;
22781    }
22782 
22783    /* Acknowledge sequence number - This only happens on INVITE from SIP-call */
22784    /* Don't auto congest anymore since we've gotten something useful back */
22785    AST_SCHED_DEL_UNREF(sched, p->initid, dialog_unref(p, "when you delete the initid sched, you should dec the refcount for the stored dialog ptr"));
22786 
22787    /* RFC3261 says we must treat every 1xx response (but not 100)
22788       that we don't recognize as if it was 183.
22789    */
22790    if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 181 && resp != 182 && resp != 183) {
22791       resp = 183;
22792    }
22793 
22794    /* For INVITE, treat all 2XX responses as we would a 200 response */
22795    if ((resp >= 200) && (resp < 300)) {
22796       resp = 200;
22797    }
22798 
22799    /* Any response between 100 and 199 is PROCEEDING */
22800    if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING) {
22801       p->invitestate = INV_PROCEEDING;
22802    }
22803 
22804    /* Final response, not 200 ? */
22805    if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA )) {
22806       p->invitestate = INV_COMPLETED;
22807    }
22808    
22809    if ((resp >= 200 && reinvite)) {
22810       p->ongoing_reinvite = 0;
22811       if (p->reinviteid > -1) {
22812          AST_SCHED_DEL_UNREF(sched, p->reinviteid, dialog_unref(p, "unref dialog for reinvite timeout because of a final response"));
22813       }
22814    }
22815 
22816    /* Final response, clear out pending invite */
22817    if ((resp == 200 || resp >= 300) && p->pendinginvite && seqno == p->pendinginvite) {
22818       p->pendinginvite = 0;
22819    }
22820 
22821    /* If this is a response to our initial INVITE, we need to set what we can use
22822     * for this peer.
22823     */
22824    if (!reinvite) {
22825       set_pvt_allowed_methods(p, req);
22826    }
22827 
22828    switch (resp) {
22829    case 100:   /* Trying */
22830    case 101:   /* Dialog establishment */
22831       if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p)) {
22832          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
22833       }
22834       check_pendings(p);
22835       break;
22836 
22837    case 180:   /* 180 Ringing */
22838    case 182:       /* 182 Queued */
22839       if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p)) {
22840          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
22841       }
22842       /* Store Route-set from provisional SIP responses so
22843        * early-dialog request can be routed properly
22844        * */
22845       parse_ok_contact(p, req);
22846       if (!reinvite) {
22847          build_route(p, req, 1, resp);
22848       }
22849       if (!req->ignore && p->owner) {
22850          if (get_rpid(p, req)) {
22851             /* Queue a connected line update */
22852             ast_party_connected_line_init(&connected);
22853             memset(&update_connected, 0, sizeof(update_connected));
22854 
22855             update_connected.id.number = 1;
22856             connected.id.number.valid = 1;
22857             connected.id.number.str = (char *) p->cid_num;
22858             connected.id.number.presentation = p->callingpres;
22859 
22860             update_connected.id.name = 1;
22861             connected.id.name.valid = 1;
22862             connected.id.name.str = (char *) p->cid_name;
22863             connected.id.name.presentation = p->callingpres;
22864 
22865             /* Invalidate any earlier private connected id representation */
22866             ast_set_party_id_all(&update_connected.priv);
22867 
22868             connected.id.tag = (char *) p->cid_tag;
22869             connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
22870             ast_channel_queue_connected_line_update(p->owner, &connected,
22871                &update_connected);
22872          }
22873          sip_handle_cc(p, req, AST_CC_CCNR);
22874          ast_queue_control(p->owner, AST_CONTROL_RINGING);
22875          if (ast_channel_state(p->owner) != AST_STATE_UP) {
22876             ast_setstate(p->owner, AST_STATE_RINGING);
22877          }
22878       }
22879       if (find_sdp(req)) {
22880          if (p->invitestate != INV_CANCELLED) {
22881             p->invitestate = INV_EARLY_MEDIA;
22882          }
22883          res = process_sdp(p, req, SDP_T38_NONE);
22884          if (!req->ignore && p->owner) {
22885             /* Queue a progress frame only if we have SDP in 180 or 182 */
22886             ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
22887          }
22888          ast_rtp_instance_activate(p->rtp);
22889       }
22890       check_pendings(p);
22891       break;
22892 
22893    case 181:   /* Call Is Being Forwarded */
22894       if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
22895          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
22896       /* Store Route-set from provisional SIP responses so
22897        * early-dialog request can be routed properly
22898        * */
22899       parse_ok_contact(p, req);
22900       if (!reinvite) {
22901          build_route(p, req, 1, resp);
22902       }
22903       if (!req->ignore && p->owner) {
22904          struct ast_party_redirecting redirecting;
22905          struct ast_set_party_redirecting update_redirecting;
22906 
22907          ast_party_redirecting_init(&redirecting);
22908          memset(&update_redirecting, 0, sizeof(update_redirecting));
22909          change_redirecting_information(p, req, &redirecting, &update_redirecting,
22910             FALSE);
22911 
22912          /* Invalidate any earlier private redirecting id representations */
22913          ast_set_party_id_all(&update_redirecting.priv_orig);
22914          ast_set_party_id_all(&update_redirecting.priv_from);
22915          ast_set_party_id_all(&update_redirecting.priv_to);
22916 
22917          ast_channel_queue_redirecting_update(p->owner, &redirecting,
22918             &update_redirecting);
22919          ast_party_redirecting_free(&redirecting);
22920          sip_handle_cc(p, req, AST_CC_CCNR);
22921       }
22922       check_pendings(p);
22923       break;
22924 
22925    case 183:   /* Session progress */
22926       if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p)) {
22927          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
22928       }
22929       /* Store Route-set from provisional SIP responses so
22930        * early-dialog request can be routed properly
22931        * */
22932       parse_ok_contact(p, req);
22933       if (!reinvite) {
22934          build_route(p, req, 1, resp);
22935       }
22936       if (!req->ignore && p->owner) {
22937          if (get_rpid(p, req)) {
22938             /* Queue a connected line update */
22939             ast_party_connected_line_init(&connected);
22940             memset(&update_connected, 0, sizeof(update_connected));
22941 
22942             update_connected.id.number = 1;
22943             connected.id.number.valid = 1;
22944             connected.id.number.str = (char *) p->cid_num;
22945             connected.id.number.presentation = p->callingpres;
22946 
22947             update_connected.id.name = 1;
22948             connected.id.name.valid = 1;
22949             connected.id.name.str = (char *) p->cid_name;
22950             connected.id.name.presentation = p->callingpres;
22951 
22952             /* Invalidate any earlier private connected id representation */
22953             ast_set_party_id_all(&update_connected.priv);
22954 
22955             connected.id.tag = (char *) p->cid_tag;
22956             connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
22957             ast_channel_queue_connected_line_update(p->owner, &connected,
22958                &update_connected);
22959          }
22960          sip_handle_cc(p, req, AST_CC_CCNR);
22961       }
22962       if (find_sdp(req)) {
22963          if (p->invitestate != INV_CANCELLED) {
22964             p->invitestate = INV_EARLY_MEDIA;
22965          }
22966          res = process_sdp(p, req, SDP_T38_NONE);
22967          if (!req->ignore && p->owner) {
22968             /* Queue a progress frame */
22969             ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
22970          }
22971          ast_rtp_instance_activate(p->rtp);
22972       } else {
22973          /* Alcatel PBXs are known to send 183s with no SDP after sending
22974           * a 100 Trying response. We're just going to treat this sort of thing
22975           * the same as we would treat a 180 Ringing
22976           */
22977          if (!req->ignore && p->owner) {
22978             ast_queue_control(p->owner, AST_CONTROL_RINGING);
22979          }
22980       }
22981       check_pendings(p);
22982       break;
22983 
22984    case 200:   /* 200 OK on invite - someone's answering our call */
22985       if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p)) {
22986          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
22987       }
22988       p->authtries = 0;
22989       if (find_sdp(req)) {
22990          if ((res = process_sdp(p, req, SDP_T38_ACCEPT)) && !req->ignore) {
22991             if (!reinvite) {
22992                /* This 200 OK's SDP is not acceptable, so we need to ack, then hangup */
22993                /* For re-invites, we try to recover */
22994                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
22995                p->hangupcause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
22996                if (p->owner) {
22997                   ast_channel_hangupcause_set(p->owner, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
22998                   sip_queue_hangup_cause(p, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
22999                }
23000             }
23001          }
23002          ast_rtp_instance_activate(p->rtp);
23003       } else if (!reinvite) {
23004          struct ast_sockaddr remote_address = {{0,}};
23005 
23006          ast_rtp_instance_get_remote_address(p->rtp, &remote_address);
23007          if (ast_sockaddr_isnull(&remote_address) || (!ast_strlen_zero(p->theirprovtag) && strcmp(p->theirtag, p->theirprovtag))) {
23008             ast_log(LOG_WARNING, "Received response: \"200 OK\" from '%s' without SDP\n", p->relatedpeer->name);
23009             ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
23010             ast_rtp_instance_activate(p->rtp);
23011          }
23012       }
23013 
23014       if (!req->ignore && p->owner) {
23015          int rpid_changed;
23016 
23017          rpid_changed = get_rpid(p, req);
23018          if (rpid_changed || !reinvite) {
23019             /* Queue a connected line update */
23020             ast_party_connected_line_init(&connected);
23021             memset(&update_connected, 0, sizeof(update_connected));
23022             if (rpid_changed
23023                || !ast_strlen_zero(p->cid_num)
23024                || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
23025                update_connected.id.number = 1;
23026                connected.id.number.valid = 1;
23027                connected.id.number.str = (char *) p->cid_num;
23028                connected.id.number.presentation = p->callingpres;
23029             }
23030             if (rpid_changed
23031                || !ast_strlen_zero(p->cid_name)
23032                || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
23033                update_connected.id.name = 1;
23034                connected.id.name.valid = 1;
23035                connected.id.name.str = (char *) p->cid_name;
23036                connected.id.name.presentation = p->callingpres;
23037             }
23038             if (update_connected.id.number || update_connected.id.name) {
23039                /* Invalidate any earlier private connected id representation */
23040                ast_set_party_id_all(&update_connected.priv);
23041 
23042                connected.id.tag = (char *) p->cid_tag;
23043                connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
23044                ast_channel_queue_connected_line_update(p->owner, &connected,
23045                   &update_connected);
23046             }
23047          }
23048       }
23049 
23050       /* Parse contact header for continued conversation */
23051       /* When we get 200 OK, we know which device (and IP) to contact for this call */
23052       /* This is important when we have a SIP proxy between us and the phone */
23053       if (outgoing) {
23054          update_call_counter(p, DEC_CALL_RINGING);
23055          parse_ok_contact(p, req);
23056          /* Save Record-Route for any later requests we make on this dialogue */
23057          if (!reinvite) {
23058             build_route(p, req, 1, resp);
23059          }
23060          if(set_address_from_contact(p)) {
23061             /* Bad contact - we don't know how to reach this device */
23062             /* We need to ACK, but then send a bye */
23063             if (!p->route && !req->ignore) {
23064                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
23065             }
23066          }
23067 
23068       }
23069 
23070       if (!req->ignore && p->owner) {
23071          if (!reinvite && !res) {
23072             ast_queue_control(p->owner, AST_CONTROL_ANSWER);
23073             if (sip_cfg.callevents) {
23074                manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
23075                   "Channel: %s\r\nChanneltype: %s\r\nUniqueid: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
23076                   ast_channel_name(p->owner), "SIP", ast_channel_uniqueid(p->owner), p->callid, p->fullcontact, p->peername);
23077             }
23078          } else { /* RE-invite */
23079             if (p->t38.state == T38_DISABLED || p->t38.state == T38_REJECTED) {
23080                ast_queue_control(p->owner, AST_CONTROL_UPDATE_RTP_PEER);
23081             } else {
23082                ast_queue_frame(p->owner, &ast_null_frame);
23083             }
23084          }
23085       } else {
23086           /* It's possible we're getting an 200 OK after we've tried to disconnect
23087               by sending CANCEL */
23088          /* First send ACK, then send bye */
23089          if (!req->ignore) {
23090             ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
23091          }
23092       }
23093 
23094       /* Check for Session-Timers related headers */
23095       if (st_get_mode(p, 0) != SESSION_TIMER_MODE_REFUSE) {
23096          p_hdrval = (char*)sip_get_header(req, "Session-Expires");
23097          if (!ast_strlen_zero(p_hdrval)) {
23098             /* UAS supports Session-Timers */
23099             enum st_refresher_param st_ref_param;
23100             int tmp_st_interval = 0;
23101             rtn = parse_session_expires(p_hdrval, &tmp_st_interval, &st_ref_param);
23102             if (rtn != 0) {
23103                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
23104             } else if (tmp_st_interval < st_get_se(p, FALSE)) {
23105                ast_log(LOG_WARNING, "Got Session-Expires less than local Min-SE in 200 OK, tearing down call\n");
23106                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
23107             }
23108             if (st_ref_param == SESSION_TIMER_REFRESHER_PARAM_UAC) {
23109                p->stimer->st_ref = SESSION_TIMER_REFRESHER_US;
23110             } else if (st_ref_param == SESSION_TIMER_REFRESHER_PARAM_UAS) {
23111                p->stimer->st_ref = SESSION_TIMER_REFRESHER_THEM;
23112             } else {
23113                ast_log(LOG_WARNING, "Unknown refresher on %s\n", p->callid);
23114             }
23115             if (tmp_st_interval) {
23116                p->stimer->st_interval = tmp_st_interval;
23117             }
23118             p->stimer->st_active = TRUE;
23119             p->stimer->st_active_peer_ua = TRUE;
23120             start_session_timer(p);
23121          } else {
23122             /* UAS doesn't support Session-Timers */
23123             if (st_get_mode(p, 0) == SESSION_TIMER_MODE_ORIGINATE) {
23124                p->stimer->st_ref = SESSION_TIMER_REFRESHER_US;
23125                p->stimer->st_active_peer_ua = FALSE;
23126                start_session_timer(p);
23127             }
23128          }
23129       }
23130 
23131 
23132       /* If I understand this right, the branch is different for a non-200 ACK only */
23133       p->invitestate = INV_TERMINATED;
23134       ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
23135       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
23136       check_pendings(p);
23137       break;
23138 
23139    case 407: /* Proxy authentication */
23140    case 401: /* Www auth */
23141       /* First we ACK */
23142       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
23143       if (p->options) {
23144          p->options->auth_type = resp;
23145       }
23146 
23147       /* Then we AUTH */
23148       ast_string_field_set(p, theirtag, NULL);  /* forget their old tag, so we don't match tags when getting response */
23149       if (!req->ignore) {
23150          if (p->authtries < MAX_AUTHTRIES) {
23151             p->invitestate = INV_CALLING;
23152          }
23153          if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, SIP_INVITE, 1)) {
23154             ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", sip_get_header(&p->initreq, "From"));
23155             pvt_set_needdestroy(p, "failed to authenticate on INVITE");
23156             sip_alreadygone(p);
23157             if (p->owner) {
23158                ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
23159             }
23160          }
23161       }
23162       break;
23163 
23164    case 403: /* Forbidden */
23165       /* First we ACK */
23166       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
23167       ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", sip_get_header(&p->initreq, "From"));
23168       if (!req->ignore && p->owner) {
23169          sip_queue_hangup_cause(p, hangup_sip2cause(resp));
23170       }
23171       break;
23172 
23173    case 404: /* Not found */
23174       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
23175       if (p->owner && !req->ignore) {
23176          sip_queue_hangup_cause(p, hangup_sip2cause(resp));
23177       }
23178       break;
23179 
23180    case 481: /* Call leg does not exist */
23181       /* Could be REFER caused INVITE with replaces */
23182       ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
23183       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
23184       if (p->owner) {
23185          ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
23186       }
23187       break;
23188 
23189    case 422: /* Session-Timers: Session interval too small */
23190       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
23191       ast_string_field_set(p, theirtag, NULL);
23192       proc_422_rsp(p, req);
23193       break;
23194 
23195    case 428: /* Use identity header - rfc 4474 - not supported by Asterisk yet */
23196       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
23197       append_history(p, "Identity", "SIP identity is required. Not supported by Asterisk.");
23198       ast_log(LOG_WARNING, "SIP identity required by proxy. SIP dialog '%s'. Giving up.\n", p->callid);
23199       if (p->owner && !req->ignore) {
23200          ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
23201       }
23202       break;
23203 
23204    case 487: /* Cancelled transaction */
23205       /* We have sent CANCEL on an outbound INVITE
23206          This transaction is already scheduled to be killed by sip_hangup().
23207       */
23208       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
23209       if (p->owner && !req->ignore) {
23210          ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_CLEARING);
23211          append_history(p, "Hangup", "Got 487 on CANCEL request from us. Queued AST hangup request");
23212       } else if (!req->ignore) {
23213          update_call_counter(p, DEC_CALL_LIMIT);
23214          append_history(p, "Hangup", "Got 487 on CANCEL request from us on call without owner. Killing this dialog.");
23215       }
23216       check_pendings(p);
23217       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23218       break;
23219    case 415: /* Unsupported media type */
23220    case 488: /* Not acceptable here */
23221    case 606: /* Not Acceptable */
23222       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
23223       if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
23224          change_t38_state(p, T38_REJECTED);
23225          /* Try to reset RTP timers */
23226          /* XXX Why is this commented away??? */
23227          //ast_rtp_set_rtptimers_onhold(p->rtp);
23228 
23229          /* Trigger a reinvite back to audio */
23230          transmit_reinvite_with_sdp(p, FALSE, FALSE);
23231       } else {
23232          /* We can't set up this call, so give up */
23233          if (p->owner && !req->ignore) {
23234             ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
23235          }
23236       }
23237       break;
23238    case 491: /* Pending */
23239       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
23240       if (p->owner && !req->ignore) {
23241          if (ast_channel_state(p->owner) != AST_STATE_UP) {
23242             ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
23243          } else {
23244             /* This is a re-invite that failed. */
23245             /* Reset the flag after a while
23246              */
23247             int wait;
23248             /* RFC 3261, if owner of call, wait between 2.1 to 4 seconds,
23249              * if not owner of call, wait 0 to 2 seconds */
23250             if (p->outgoing_call) {
23251                wait = 2100 + ast_random() % 2000;
23252             } else {
23253                wait = ast_random() % 2000;
23254             }
23255             p->waitid = ast_sched_add(sched, wait, sip_reinvite_retry, dialog_ref(p, "passing dialog ptr into sched structure based on waitid for sip_reinvite_retry."));
23256             ast_debug(2, "Reinvite race. Scheduled sip_reinvite_retry in %d secs in handle_response_invite (waitid %d, dialog '%s')\n",
23257                   wait, p->waitid, p->callid);
23258          }
23259       }
23260       break;
23261 
23262    case 408: /* Request timeout */
23263    case 405: /* Not allowed */
23264    case 501: /* Not implemented */
23265       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
23266       if (p->owner) {
23267          ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
23268       }
23269       break;
23270    }
23271    if (xmitres == XMIT_ERROR) {
23272       ast_log(LOG_WARNING, "Could not transmit message in dialog %s\n", p->callid);
23273    }
23274 }
23275 
23276 /* \brief Handle SIP response in NOTIFY transaction
23277        We've sent a NOTIFY, now handle responses to it
23278   */
23279 static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
23280 {
23281    switch (resp) {
23282    case 200:   /* Notify accepted */
23283       /* They got the notify, this is the end */
23284       if (p->owner) {
23285          if (p->refer) {
23286             ast_log(LOG_NOTICE, "Got OK on REFER Notify message\n");
23287          } else {
23288             ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", ast_channel_name(p->owner));
23289          }
23290       } else {
23291          if (p->subscribed == NONE && !p->refer) {
23292             ast_debug(4, "Got 200 accepted on NOTIFY %s\n", p->callid);
23293             pvt_set_needdestroy(p, "received 200 response");
23294          }
23295          if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
23296             struct state_notify_data data = {
23297                .state = p->laststate,
23298                .device_state_info = p->last_device_state_info,
23299                .presence_state = p->last_presence_state,
23300                .presence_subtype = p->last_presence_subtype,
23301                .presence_message = p->last_presence_message,
23302             };
23303             /* Ready to send the next state we have on queue */
23304             ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
23305             extensionstate_update(p->context, p->exten, &data, p, TRUE);
23306          }
23307       }
23308       break;
23309    case 401:   /* Not www-authorized on SIP method */
23310    case 407:   /* Proxy auth */
23311       if (!p->notify) {
23312          break; /* Only device notify can use NOTIFY auth */
23313       }
23314       ast_string_field_set(p, theirtag, NULL);
23315       if (ast_strlen_zero(p->authname)) {
23316          ast_log(LOG_WARNING, "Asked to authenticate NOTIFY to %s but we have no matching peer or realm auth!\n", ast_sockaddr_stringify(&p->recv));
23317          pvt_set_needdestroy(p, "unable to authenticate NOTIFY");
23318       }
23319       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_NOTIFY, 0)) {
23320          ast_log(LOG_NOTICE, "Failed to authenticate on NOTIFY to '%s'\n", sip_get_header(&p->initreq, "From"));
23321          pvt_set_needdestroy(p, "failed to authenticate NOTIFY");
23322       }
23323       break;
23324    case 481: /* Call leg does not exist */
23325       pvt_set_needdestroy(p, "Received 481 response for NOTIFY");
23326       break;
23327    }
23328 }
23329 
23330 /* \brief Handle SIP response in SUBSCRIBE transaction */
23331 static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
23332 {
23333    if (p->subscribed == CALL_COMPLETION) {
23334       struct sip_monitor_instance *monitor_instance;
23335 
23336       if (resp < 300) {
23337          return;
23338       }
23339 
23340       /* Final failure response received. */
23341       monitor_instance = ao2_callback(sip_monitor_instances, 0,
23342          find_sip_monitor_instance_by_subscription_pvt, p);
23343       if (monitor_instance) {
23344          ast_cc_monitor_failed(monitor_instance->core_id,
23345             monitor_instance->device_name,
23346             "Received error response to our SUBSCRIBE");
23347       }
23348       return;
23349    }
23350 
23351    if (p->subscribed != MWI_NOTIFICATION) {
23352       return;
23353    }
23354    if (!p->mwi) {
23355       return;
23356    }
23357 
23358    switch (resp) {
23359    case 200: /* Subscription accepted */
23360       ast_debug(3, "Got 200 OK on subscription for MWI\n");
23361       set_pvt_allowed_methods(p, req);
23362       if (p->options) {
23363          if (p->options->outboundproxy) {
23364             ao2_ref(p->options->outboundproxy, -1);
23365          }
23366          ast_free(p->options);
23367          p->options = NULL;
23368       }
23369       p->mwi->subscribed = 1;
23370       if ((p->mwi->resub = ast_sched_add(sched, mwi_expiry * 1000, sip_subscribe_mwi_do, ASTOBJ_REF(p->mwi))) < 0) {
23371          ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
23372       }
23373       break;
23374    case 401:
23375    case 407:
23376       ast_string_field_set(p, theirtag, NULL);
23377       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_SUBSCRIBE, 0)) {
23378          ast_log(LOG_NOTICE, "Failed to authenticate on SUBSCRIBE to '%s'\n", sip_get_header(&p->initreq, "From"));
23379          p->mwi->call = NULL;
23380          ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
23381          pvt_set_needdestroy(p, "failed to authenticate SUBSCRIBE");
23382       }
23383       break;
23384    case 403:
23385       transmit_response_with_date(p, "200 OK", req);
23386       ast_log(LOG_WARNING, "Authentication failed while trying to subscribe for MWI.\n");
23387       p->mwi->call = NULL;
23388       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
23389       pvt_set_needdestroy(p, "received 403 response");
23390       sip_alreadygone(p);
23391       break;
23392    case 404:
23393       ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that a mailbox may not have been configured.\n");
23394       p->mwi->call = NULL;
23395       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
23396       pvt_set_needdestroy(p, "received 404 response");
23397       break;
23398    case 481:
23399       ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that our dialog did not exist.\n");
23400       p->mwi->call = NULL;
23401       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
23402       pvt_set_needdestroy(p, "received 481 response");
23403       break;
23404    case 500:
23405    case 501:
23406       ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side may have suffered a heart attack.\n");
23407       p->mwi->call = NULL;
23408       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
23409       pvt_set_needdestroy(p, "received 500/501 response");
23410       break;
23411    }
23412 }
23413 
23414 /* \brief Handle SIP response in REFER transaction
23415    We've sent a REFER, now handle responses to it
23416   */
23417 static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
23418 {
23419    enum ast_control_transfer message = AST_TRANSFER_FAILED;
23420 
23421    /* If no refer structure exists, then do nothing */
23422    if (!p->refer)
23423       return;
23424 
23425    switch (resp) {
23426    case 202:   /* Transfer accepted */
23427       /* We need  to do something here */
23428       /* The transferee is now sending INVITE to target */
23429       p->refer->status = REFER_ACCEPTED;
23430       /* Now wait for next message */
23431       ast_debug(3, "Got 202 accepted on transfer\n");
23432       /* We should hang along, waiting for NOTIFY's here */
23433       break;
23434 
23435    case 401:   /* Not www-authorized on SIP method */
23436    case 407:   /* Proxy auth */
23437       if (ast_strlen_zero(p->authname)) {
23438          ast_log(LOG_WARNING, "Asked to authenticate REFER to %s but we have no matching peer or realm auth!\n",
23439             ast_sockaddr_stringify(&p->recv));
23440          if (p->owner) {
23441             ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
23442          }
23443          pvt_set_needdestroy(p, "unable to authenticate REFER");
23444       }
23445       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_REFER, 0)) {
23446          ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", sip_get_header(&p->initreq, "From"));
23447          p->refer->status = REFER_NOAUTH;
23448          if (p->owner) {
23449             ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
23450          }
23451          pvt_set_needdestroy(p, "failed to authenticate REFER");
23452       }
23453       break;
23454    
23455    case 405:   /* Method not allowed */
23456       /* Return to the current call onhold */
23457       /* Status flag needed to be reset */
23458       ast_log(LOG_NOTICE, "SIP transfer to %s failed, REFER not allowed. \n", p->refer->refer_to);
23459       pvt_set_needdestroy(p, "received 405 response");
23460       p->refer->status = REFER_FAILED;
23461       if (p->owner) {
23462          ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
23463       }
23464       break;
23465 
23466    case 481: /* Call leg does not exist */
23467 
23468       /* A transfer with Replaces did not work */
23469       /* OEJ: We should Set flag, cancel the REFER, go back
23470       to original call - but right now we can't */
23471       ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
23472       if (p->owner)
23473          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
23474       pvt_set_needdestroy(p, "received 481 response");
23475       break;
23476 
23477    case 500:   /* Server error */
23478    case 501:   /* Method not implemented */
23479       /* Return to the current call onhold */
23480       /* Status flag needed to be reset */
23481       ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
23482       pvt_set_needdestroy(p, "received 500/501 response");
23483       p->refer->status = REFER_FAILED;
23484       if (p->owner) {
23485          ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
23486       }
23487       break;
23488    case 603:   /* Transfer declined */
23489       ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
23490       p->refer->status = REFER_FAILED;
23491       pvt_set_needdestroy(p, "received 603 response");
23492       if (p->owner) {
23493          ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
23494       }
23495       break;
23496    default:
23497       /* We should treat unrecognized 9xx as 900.  400 is actually
23498          specified as a possible response, but any 4-6xx is 
23499          theoretically possible. */
23500 
23501       if (resp < 299) { /* 1xx cases don't get here */
23502          ast_log(LOG_WARNING, "SIP transfer to %s had unxpected 2xx response (%d), confusion is possible. \n", p->refer->refer_to, resp);
23503       } else {
23504          ast_log(LOG_WARNING, "SIP transfer to %s with response (%d). \n", p->refer->refer_to, resp);
23505       }
23506 
23507       p->refer->status = REFER_FAILED;
23508       pvt_set_needdestroy(p, "received failure response");
23509       if (p->owner) {
23510          ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
23511       }
23512       break;
23513    }
23514 }
23515 
23516 /*! \brief Handle responses on REGISTER to services */
23517 static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
23518 {
23519    int expires, expires_ms;
23520    struct sip_registry *r;
23521    r=p->registry;
23522    
23523    switch (resp) {
23524    case 401:   /* Unauthorized */
23525       if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
23526          ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
23527          pvt_set_needdestroy(p, "failed to authenticate REGISTER");
23528       }
23529       break;
23530    case 403:   /* Forbidden */
23531       if (global_reg_retry_403) {
23532          ast_log(LOG_NOTICE, "Treating 403 response to REGISTER as non-fatal for %s@%s\n",
23533             p->registry->username, p->registry->hostname);
23534          ast_string_field_set(r, nonce, "");
23535          ast_string_field_set(p, nonce, "");
23536          break;
23537       }
23538       ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
23539       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 403"));
23540       r->regstate = REG_STATE_NOAUTH;
23541       pvt_set_needdestroy(p, "received 403 response");
23542       break;
23543    case 404:   /* Not found */
23544       ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username, p->registry->hostname);
23545       pvt_set_needdestroy(p, "received 404 response");
23546       if (r->call)
23547          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 404");
23548       r->regstate = REG_STATE_REJECTED;
23549       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 404"));
23550       break;
23551    case 407:   /* Proxy auth */
23552       if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
23553          ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", sip_get_header(&p->initreq, "From"), p->authtries);
23554          pvt_set_needdestroy(p, "failed to authenticate REGISTER");
23555       }
23556       break;
23557    case 408:   /* Request timeout */
23558       /* Got a timeout response, so reset the counter of failed responses */
23559       if (r) {
23560          r->regattempts = 0;
23561       } else {
23562          ast_log(LOG_WARNING, "Got a 408 response to our REGISTER on call %s after we had destroyed the registry object\n", p->callid);
23563       }
23564       break;
23565    case 423:   /* Interval too brief */
23566       r->expiry = atoi(sip_get_header(req, "Min-Expires"));
23567       ast_log(LOG_WARNING, "Got 423 Interval too brief for service %s@%s, minimum is %d seconds\n", p->registry->username, p->registry->hostname, r->expiry);
23568       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 423"));
23569       if (r->call) {
23570          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 423");
23571          pvt_set_needdestroy(p, "received 423 response");
23572       }
23573       if (r->expiry > max_expiry) {
23574          ast_log(LOG_WARNING, "Required expiration time from %s@%s is too high, giving up\n", p->registry->username, p->registry->hostname);
23575          r->expiry = r->configured_expiry;
23576          r->regstate = REG_STATE_REJECTED;
23577       } else {
23578          r->regstate = REG_STATE_UNREGISTERED;
23579          transmit_register(r, SIP_REGISTER, NULL, NULL);
23580       }
23581       manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: SIP\r\nUsername: %s\r\nDomain: %s\r\nStatus: %s\r\n", r->username, r->hostname, regstate2str(r->regstate));
23582       break;
23583    case 479:   /* SER: Not able to process the URI - address is wrong in register*/
23584       ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username, p->registry->hostname);
23585       pvt_set_needdestroy(p, "received 479 response");
23586       if (r->call)
23587          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 479");
23588       r->regstate = REG_STATE_REJECTED;
23589       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 479"));
23590       break;
23591    case 200:   /* 200 OK */
23592       if (!r) {
23593          ast_log(LOG_WARNING, "Got 200 OK on REGISTER, but there isn't a registry entry for '%s' (we probably already got the OK)\n", S_OR(p->peername, p->username));
23594          pvt_set_needdestroy(p, "received erroneous 200 response");
23595          return 0;
23596       }
23597 
23598       r->regstate = REG_STATE_REGISTERED;
23599       r->regtime = ast_tvnow();     /* Reset time of last successful registration */
23600       manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: SIP\r\nUsername: %s\r\nDomain: %s\r\nStatus: %s\r\n", r->username, r->hostname, regstate2str(r->regstate));
23601       r->regattempts = 0;
23602       ast_debug(1, "Registration successful\n");
23603       if (r->timeout > -1) {
23604          ast_debug(1, "Cancelling timeout %d\n", r->timeout);
23605       }
23606       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 200"));
23607       if (r->call)
23608          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 200");
23609       p->registry = registry_unref(p->registry, "unref registry entry p->registry");
23610 
23611       /* destroy dialog now to avoid interference with next register */
23612       pvt_set_needdestroy(p, "Registration successfull");
23613 
23614       /* set us up for re-registering
23615        * figure out how long we got registered for
23616        * according to section 6.13 of RFC, contact headers override
23617        * expires headers, so check those first */
23618       expires = 0;
23619 
23620       /* XXX todo: try to save the extra call */
23621       if (!ast_strlen_zero(sip_get_header(req, "Contact"))) {
23622          const char *contact = NULL;
23623          const char *tmptmp = NULL;
23624          int start = 0;
23625          for(;;) {
23626             contact = __get_header(req, "Contact", &start);
23627             /* this loop ensures we get a contact header about our register request */
23628             if(!ast_strlen_zero(contact)) {
23629                if( (tmptmp=strstr(contact, p->our_contact))) {
23630                   contact=tmptmp;
23631                   break;
23632                }
23633             } else
23634                break;
23635          }
23636          tmptmp = strcasestr(contact, "expires=");
23637          if (tmptmp) {
23638             if (sscanf(tmptmp + 8, "%30d", &expires) != 1) {
23639                expires = 0;
23640             }
23641          }
23642          
23643       }
23644       if (!expires)
23645          expires=atoi(sip_get_header(req, "expires"));
23646       if (!expires)
23647          expires=default_expiry;
23648       
23649       expires_ms = expires * 1000;
23650       if (expires <= EXPIRY_GUARD_LIMIT)
23651          expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT), EXPIRY_GUARD_MIN);
23652       else
23653          expires_ms -= EXPIRY_GUARD_SECS * 1000;
23654       if (sipdebug)
23655          ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000);
23656       
23657       r->refresh= (int) expires_ms / 1000;
23658       
23659       /* Schedule re-registration before we expire */
23660       AST_SCHED_REPLACE_UNREF(r->expire, sched, expires_ms, sip_reregister, r,
23661                         registry_unref(_data,"unref in REPLACE del fail"),
23662                         registry_unref(r,"unref in REPLACE add fail"),
23663                         registry_addref(r,"The Addition side of REPLACE"));
23664    }
23665    return 1;
23666 }
23667 
23668 /*! \brief Handle qualification responses (OPTIONS) */
23669 static void handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
23670 {
23671    struct sip_peer *peer = /* sip_ref_peer( */ p->relatedpeer /* , "bump refcount on p, as it is being used in this function(handle_response_peerpoke)")*/ ; /* hope this is already refcounted! */
23672    int statechanged, is_reachable, was_reachable;
23673    int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);
23674 
23675    /*
23676     * Compute the response time to a ping (goes in peer->lastms.)
23677     * -1 means did not respond, 0 means unknown,
23678     * 1..maxms is a valid response, >maxms means late response.
23679     */
23680    if (pingtime < 1) {  /* zero = unknown, so round up to 1 */
23681       pingtime = 1;
23682    }
23683 
23684    if (!peer->maxms) { /* this should never happens */
23685       pvt_set_needdestroy(p, "got OPTIONS response but qualify is not enabled");
23686       return;
23687    }
23688 
23689    /* Now determine new state and whether it has changed.
23690     * Use some helper variables to simplify the writing
23691     * of the expressions.
23692     */
23693    was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
23694    is_reachable = pingtime <= peer->maxms;
23695    statechanged = peer->lastms == 0 /* yes, unknown before */
23696       || was_reachable != is_reachable;
23697 
23698    peer->lastms = pingtime;
23699    peer->call = dialog_unref(peer->call, "unref dialog peer->call");
23700    if (statechanged) {
23701       const char *s = is_reachable ? "Reachable" : "Lagged";
23702       char str_lastms[20];
23703       snprintf(str_lastms, sizeof(str_lastms), "%d", pingtime);
23704 
23705       ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
23706          peer->name, s, pingtime, peer->maxms);
23707       ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", peer->name);
23708       if (sip_cfg.peer_rtupdate) {
23709          ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", str_lastms, SENTINEL);
23710       }
23711       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
23712          "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
23713          peer->name, s, pingtime);
23714       if (is_reachable && sip_cfg.regextenonqualify)
23715          register_peer_exten(peer, TRUE);
23716    }
23717 
23718    pvt_set_needdestroy(p, "got OPTIONS response");
23719 
23720    /* Try again eventually */
23721    AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
23722          is_reachable ? peer->qualifyfreq : DEFAULT_FREQ_NOTOK,
23723          sip_poke_peer_s, peer,
23724          sip_unref_peer(_data, "removing poke peer ref"),
23725          sip_unref_peer(peer, "removing poke peer ref"),
23726          sip_ref_peer(peer, "adding poke peer ref"));
23727 }
23728 
23729 /*!
23730  * \internal
23731  * \brief Handle responses to INFO messages
23732  *
23733  * \note The INFO method MUST NOT change the state of calls or
23734  * related sessions (RFC 2976).
23735  */
23736 static void handle_response_info(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
23737 {
23738    int sipmethod = SIP_INFO;
23739 
23740    switch (resp) {
23741    case 401: /* Not www-authorized on SIP method */
23742    case 407: /* Proxy auth required */
23743       ast_log(LOG_WARNING, "Host '%s' requests authentication (%d) for '%s'\n",
23744          ast_sockaddr_stringify(&p->sa), resp, sip_methods[sipmethod].text);
23745       break;
23746    case 405: /* Method not allowed */
23747    case 501: /* Not Implemented */
23748       mark_method_unallowed(&p->allowed_methods, sipmethod);
23749       if (p->relatedpeer) {
23750          mark_method_allowed(&p->relatedpeer->disallowed_methods, sipmethod);
23751       }
23752       ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n",
23753          ast_sockaddr_stringify(&p->sa), sip_methods[sipmethod].text);
23754       break;
23755    default:
23756       if (300 <= resp && resp < 700) {
23757          ast_verb(3, "Got SIP %s response %d \"%s\" back from host '%s'\n",
23758             sip_methods[sipmethod].text, resp, rest, ast_sockaddr_stringify(&p->sa));
23759       }
23760       break;
23761    }
23762 }
23763 
23764 /*!
23765  * \internal
23766  * \brief Handle auth requests to a MESSAGE request
23767  * \return TRUE if authentication failed.
23768  */
23769 static int do_message_auth(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
23770 {
23771    char *header;
23772    char *respheader;
23773    char digest[1024];
23774 
23775    if (p->options) {
23776       p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
23777    }
23778 
23779    if (p->authtries == MAX_AUTHTRIES) {
23780       ast_log(LOG_NOTICE, "Failed to authenticate MESSAGE with host '%s'\n",
23781          ast_sockaddr_stringify(&p->sa));
23782       return -1;
23783    }
23784 
23785    ++p->authtries;
23786    sip_auth_headers((resp == 401 ? WWW_AUTH : PROXY_AUTH), &header, &respheader);
23787    memset(digest, 0, sizeof(digest));
23788    if (reply_digest(p, req, header, SIP_MESSAGE, digest, sizeof(digest))) {
23789       /* There's nothing to use for authentication */
23790       ast_debug(1, "Nothing to use for MESSAGE authentication\n");
23791       return -1;
23792    }
23793 
23794    if (p->do_history) {
23795       append_history(p, "MessageAuth", "Try: %d", p->authtries);
23796    }
23797 
23798    transmit_message(p, 0, 1);
23799    return 0;
23800 }
23801 
23802 /*!
23803  * \internal
23804  * \brief Handle responses to MESSAGE messages
23805  *
23806  * \note The MESSAGE method should not change the state of calls
23807  * or related sessions if associated with a dialog. (Implied by
23808  * RFC 3428 Section 2).
23809  */
23810 static void handle_response_message(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
23811 {
23812    int sipmethod = SIP_MESSAGE;
23813    int in_dialog = ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
23814 
23815    switch (resp) {
23816    case 401: /* Not www-authorized on SIP method */
23817    case 407: /* Proxy auth required */
23818       if (do_message_auth(p, resp, rest, req, seqno) && !in_dialog) {
23819          pvt_set_needdestroy(p, "MESSAGE authentication failed");
23820       }
23821       break;
23822    case 405: /* Method not allowed */
23823    case 501: /* Not Implemented */
23824       mark_method_unallowed(&p->allowed_methods, sipmethod);
23825       if (p->relatedpeer) {
23826          mark_method_allowed(&p->relatedpeer->disallowed_methods, sipmethod);
23827       }
23828       ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n",
23829          ast_sockaddr_stringify(&p->sa), sip_methods[sipmethod].text);
23830       if (!in_dialog) {
23831          pvt_set_needdestroy(p, "MESSAGE not implemented or allowed");
23832       }
23833       break;
23834    default:
23835       if (100 <= resp && resp < 200) {
23836          /* Must allow provisional responses for out-of-dialog requests. */
23837       } else if (200 <= resp && resp < 300) {
23838          p->authtries = 0; /* Reset authentication counter */
23839          if (!in_dialog) {
23840             pvt_set_needdestroy(p, "MESSAGE delivery accepted");
23841          }
23842       } else if (300 <= resp && resp < 700) {
23843          ast_verb(3, "Got SIP %s response %d \"%s\" back from host '%s'\n",
23844             sip_methods[sipmethod].text, resp, rest, ast_sockaddr_stringify(&p->sa));
23845          if (!in_dialog) {
23846             pvt_set_needdestroy(p, (300 <= resp && resp < 600)
23847                ? "MESSAGE delivery failed" : "MESSAGE delivery refused");
23848          }
23849       }
23850       break;
23851    }
23852 }
23853 
23854 /*! \brief Immediately stop RTP, VRTP and UDPTL as applicable */
23855 static void stop_media_flows(struct sip_pvt *p)
23856 {
23857    /* Immediately stop RTP, VRTP and UDPTL as applicable */
23858    if (p->rtp)
23859       ast_rtp_instance_stop(p->rtp);
23860    if (p->vrtp)
23861       ast_rtp_instance_stop(p->vrtp);
23862    if (p->trtp)
23863       ast_rtp_instance_stop(p->trtp);
23864    if (p->udptl)
23865       ast_udptl_stop(p->udptl);
23866 }
23867 
23868 /*! \brief Handle SIP response in dialogue
23869    \note only called by handle_incoming */
23870 static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
23871 {
23872    struct ast_channel *owner;
23873    int sipmethod;
23874    const char *c = sip_get_header(req, "Cseq");
23875    /* GCC 4.2 complains if I try to cast c as a char * when passing it to ast_skip_nonblanks, so make a copy of it */
23876    char *c_copy = ast_strdupa(c);
23877    /* Skip the Cseq and its subsequent spaces */
23878    const char *msg = ast_skip_blanks(ast_skip_nonblanks(c_copy));
23879 
23880    if (!msg)
23881       msg = "";
23882 
23883    sipmethod = find_sip_method(msg);
23884 
23885    owner = p->owner;
23886    if (owner) {
23887       const char *rp = NULL, *rh = NULL;
23888 
23889       ast_channel_hangupcause_set(owner, 0);
23890       if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON) && (rh = sip_get_header(req, "Reason"))) {
23891          rh = ast_skip_blanks(rh);
23892          if (!strncasecmp(rh, "Q.850", 5)) {
23893             int cause = ast_channel_hangupcause(owner);
23894             rp = strstr(rh, "cause=");
23895             if (rp && sscanf(rp + 6, "%30d", &cause) == 1) {
23896                ast_channel_hangupcause_set(owner, cause & 0x7f);
23897                if (req->debug)
23898                   ast_verbose("Using Reason header for cause code: %d\n", ast_channel_hangupcause(owner));
23899             }
23900          }
23901       }
23902 
23903       if (!ast_channel_hangupcause(owner))
23904          ast_channel_hangupcause_set(owner, hangup_sip2cause(resp));
23905    }
23906 
23907    if (p->socket.type == SIP_TRANSPORT_UDP) {
23908       int ack_res = FALSE;
23909 
23910       /* Acknowledge whatever it is destined for */
23911       if ((resp >= 100) && (resp <= 199)) {
23912          /* NON-INVITE messages do not ack a 1XX response. RFC 3261 section 17.1.2.2 */
23913          if (sipmethod == SIP_INVITE) {
23914             ack_res = __sip_semi_ack(p, seqno, 0, sipmethod);
23915          }
23916       } else {
23917          ack_res = __sip_ack(p, seqno, 0, sipmethod);
23918       }
23919 
23920       if (ack_res == FALSE) {
23921          /* RFC 3261 13.2.2.4 and 17.1.1.2 - We must re-send ACKs to re-transmitted final responses */
23922          if (sipmethod == SIP_INVITE && resp >= 200) {
23923             transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, resp < 300 ? TRUE: FALSE);
23924          }
23925 
23926          append_history(p, "Ignore", "Ignoring this retransmit\n");
23927          return;
23928       }
23929    }
23930 
23931    /* If this is a NOTIFY for a subscription clear the flag that indicates that we have a NOTIFY pending */
23932    if (!p->owner && sipmethod == SIP_NOTIFY && p->pendinginvite) {
23933       p->pendinginvite = 0;
23934    }
23935 
23936    /* Get their tag if we haven't already */
23937    if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
23938       char tag[128];
23939 
23940       gettag(req, "To", tag, sizeof(tag));
23941       ast_string_field_set(p, theirtag, tag);
23942    } else {
23943       /* Store theirtag to track for changes when 200 responses to invites are received without SDP */
23944       ast_string_field_set(p, theirprovtag, p->theirtag);
23945    }
23946 
23947    /* This needs to be configurable on a channel/peer level,
23948       not mandatory for all communication. Sadly enough, NAT implementations
23949       are not so stable so we can always rely on these headers.
23950       Temporarily disabled, while waiting for fix.
23951       Fix assigned to Rizzo :-)
23952    */
23953    /* check_via_response(p, req); */
23954 
23955    /* RFC 3261 Section 15 specifies that if we receive a 408 or 481
23956     * in response to a BYE, then we should end the current dialog
23957     * and session.  It is known that at least one phone manufacturer
23958     * potentially will send a 404 in response to a BYE, so we'll be
23959     * liberal in what we accept and end the dialog and session if we
23960     * receive any of those responses to a BYE.
23961     */
23962    if ((resp == 404 || resp == 408 || resp == 481) && sipmethod == SIP_BYE) {
23963       pvt_set_needdestroy(p, "received 4XX response to a BYE");
23964       return;
23965    }
23966 
23967    if (p->relatedpeer && sipmethod == SIP_OPTIONS) {
23968       /* We don't really care what the response is, just that it replied back.
23969          Well, as long as it's not a 100 response...  since we might
23970          need to hang around for something more "definitive" */
23971       if (resp != 100)
23972          handle_response_peerpoke(p, resp, req);
23973    } else if (sipmethod == SIP_REFER && resp >= 200) {
23974       handle_response_refer(p, resp, rest, req, seqno);
23975    } else if (sipmethod == SIP_PUBLISH) {
23976       /* SIP PUBLISH transcends this morass of doodoo and instead
23977        * we just always call the response handler. Good gravy!
23978        */
23979       handle_response_publish(p, resp, rest, req, seqno);
23980    } else if (sipmethod == SIP_INFO) {
23981       /* More good gravy! */
23982       handle_response_info(p, resp, rest, req, seqno);
23983    } else if (sipmethod == SIP_MESSAGE) {
23984       /* More good gravy! */
23985       handle_response_message(p, resp, rest, req, seqno);
23986    } else if (sipmethod == SIP_NOTIFY) {
23987       /* The gravy train continues to roll */
23988       handle_response_notify(p, resp, rest, req, seqno);
23989    } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
23990       switch(resp) {
23991       case 100:   /* 100 Trying */
23992       case 101:   /* 101 Dialog establishment */
23993       case 183:   /* 183 Session Progress */
23994       case 180:   /* 180 Ringing */
23995       case 182:   /* 182 Queued */
23996       case 181:   /* 181 Call Is Being Forwarded */
23997          if (sipmethod == SIP_INVITE)
23998             handle_response_invite(p, resp, rest, req, seqno);
23999          break;
24000       case 200:   /* 200 OK */
24001          p->authtries = 0; /* Reset authentication counter */
24002          if (sipmethod == SIP_INVITE) {
24003             handle_response_invite(p, resp, rest, req, seqno);
24004          } else if (sipmethod == SIP_REGISTER) {
24005             handle_response_register(p, resp, rest, req, seqno);
24006          } else if (sipmethod == SIP_SUBSCRIBE) {
24007             ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
24008             handle_response_subscribe(p, resp, rest, req, seqno);
24009          } else if (sipmethod == SIP_BYE) {     /* Ok, we're ready to go */
24010             pvt_set_needdestroy(p, "received 200 response");
24011             ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
24012          }
24013          break;
24014       case 401: /* Not www-authorized on SIP method */
24015       case 407: /* Proxy auth required */
24016          if (sipmethod == SIP_INVITE)
24017             handle_response_invite(p, resp, rest, req, seqno);
24018          else if (sipmethod == SIP_SUBSCRIBE)
24019             handle_response_subscribe(p, resp, rest, req, seqno);
24020          else if (p->registry && sipmethod == SIP_REGISTER)
24021             handle_response_register(p, resp, rest, req, seqno);
24022          else if (sipmethod == SIP_UPDATE) {
24023             handle_response_update(p, resp, rest, req, seqno);
24024          } else if (sipmethod == SIP_BYE) {
24025             if (p->options)
24026                p->options->auth_type = resp;
24027             if (ast_strlen_zero(p->authname)) {
24028                ast_log(LOG_WARNING, "Asked to authenticate %s, to %s but we have no matching peer!\n",
24029                      msg, ast_sockaddr_stringify(&p->recv));
24030                pvt_set_needdestroy(p, "unable to authenticate BYE");
24031             } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp,  sipmethod, 0)) {
24032                ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, sip_get_header(&p->initreq, "From"));
24033                pvt_set_needdestroy(p, "failed to authenticate BYE");
24034             }
24035          } else {
24036             ast_log(LOG_WARNING, "Got authentication request (%d) on %s to '%s'\n", resp, sip_methods[sipmethod].text, sip_get_header(req, "To"));
24037             pvt_set_needdestroy(p, "received 407 response");
24038          }
24039          break;
24040       case 403: /* Forbidden - we failed authentication */
24041          if (sipmethod == SIP_INVITE)
24042             handle_response_invite(p, resp, rest, req, seqno);
24043          else if (sipmethod == SIP_SUBSCRIBE)
24044             handle_response_subscribe(p, resp, rest, req, seqno);
24045          else if (p->registry && sipmethod == SIP_REGISTER)
24046             handle_response_register(p, resp, rest, req, seqno);
24047          else {
24048             ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
24049             pvt_set_needdestroy(p, "received 403 response");
24050          }
24051          break;
24052       case 404: /* Not found */
24053          if (p->registry && sipmethod == SIP_REGISTER)
24054             handle_response_register(p, resp, rest, req, seqno);
24055          else if (sipmethod == SIP_INVITE)
24056             handle_response_invite(p, resp, rest, req, seqno);
24057          else if (sipmethod == SIP_SUBSCRIBE)
24058             handle_response_subscribe(p, resp, rest, req, seqno);
24059          else if (owner)
24060             ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
24061          break;
24062       case 423: /* Interval too brief */
24063          if (sipmethod == SIP_REGISTER)
24064             handle_response_register(p, resp, rest, req, seqno);
24065          break;
24066       case 408: /* Request timeout - terminate dialog */
24067          if (sipmethod == SIP_INVITE)
24068             handle_response_invite(p, resp, rest, req, seqno);
24069          else if (sipmethod == SIP_REGISTER)
24070             handle_response_register(p, resp, rest, req, seqno);
24071          else if (sipmethod == SIP_BYE) {
24072             pvt_set_needdestroy(p, "received 408 response");
24073             ast_debug(4, "Got timeout on bye. Thanks for the answer. Now, kill this call\n");
24074          } else {
24075             if (owner)
24076                ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
24077             pvt_set_needdestroy(p, "received 408 response");
24078          }
24079          break;
24080 
24081       case 428:
24082       case 422: /* Session-Timers: Session Interval Too Small */
24083          if (sipmethod == SIP_INVITE) {
24084             handle_response_invite(p, resp, rest, req, seqno);
24085          }
24086          break;
24087 
24088       case 481: /* Call leg does not exist */
24089          if (sipmethod == SIP_INVITE) {
24090             handle_response_invite(p, resp, rest, req, seqno);
24091          } else if (sipmethod == SIP_SUBSCRIBE) {
24092             handle_response_subscribe(p, resp, rest, req, seqno);
24093          } else if (sipmethod == SIP_BYE) {
24094             /* The other side has no transaction to bye,
24095             just assume it's all right then */
24096             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
24097          } else if (sipmethod == SIP_CANCEL) {
24098             /* The other side has no transaction to cancel,
24099             just assume it's all right then */
24100             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
24101          } else {
24102             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
24103             /* Guessing that this is not an important request */
24104          }
24105          break;
24106       case 487:
24107          if (sipmethod == SIP_INVITE)
24108             handle_response_invite(p, resp, rest, req, seqno);
24109          break;
24110       case 415: /* Unsupported media type */
24111       case 488: /* Not acceptable here - codec error */
24112       case 606: /* Not Acceptable */
24113          if (sipmethod == SIP_INVITE)
24114             handle_response_invite(p, resp, rest, req, seqno);
24115          break;
24116       case 491: /* Pending */
24117          if (sipmethod == SIP_INVITE)
24118             handle_response_invite(p, resp, rest, req, seqno);
24119          else {
24120             ast_debug(1, "Got 491 on %s, unsupported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
24121             pvt_set_needdestroy(p, "received 491 response");
24122          }
24123          break;
24124       case 405: /* Method not allowed */
24125       case 501: /* Not Implemented */
24126          mark_method_unallowed(&p->allowed_methods, sipmethod);
24127          if (p->relatedpeer) {
24128             mark_method_allowed(&p->relatedpeer->disallowed_methods, sipmethod);
24129          }
24130          if (sipmethod == SIP_INVITE)
24131             handle_response_invite(p, resp, rest, req, seqno);
24132          else
24133             ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_sockaddr_stringify(&p->sa), msg);
24134          break;
24135       default:
24136          if ((resp >= 200) && (resp < 300)) { /* on any 2XX response do the following */
24137             if (sipmethod == SIP_INVITE) {
24138                handle_response_invite(p, resp, rest, req, seqno);
24139             }
24140          } else if ((resp >= 300) && (resp < 700)) {
24141             /* Fatal response */
24142             if ((resp != 487))
24143                ast_verb(3, "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_sockaddr_stringify(&p->sa));
24144    
24145             if (sipmethod == SIP_INVITE)
24146                stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
24147 
24148             /* XXX Locking issues?? XXX */
24149             switch(resp) {
24150             case 300: /* Multiple Choices */
24151             case 301: /* Moved permanently */
24152             case 302: /* Moved temporarily */
24153             case 305: /* Use Proxy */
24154                if (p->owner) {
24155                   struct ast_party_redirecting redirecting;
24156                   struct ast_set_party_redirecting update_redirecting;
24157 
24158                   ast_party_redirecting_init(&redirecting);
24159                   memset(&update_redirecting, 0, sizeof(update_redirecting));
24160                   change_redirecting_information(p, req, &redirecting,
24161                      &update_redirecting, TRUE);
24162                   ast_channel_set_redirecting(p->owner, &redirecting,
24163                      &update_redirecting);
24164                   ast_party_redirecting_free(&redirecting);
24165                }
24166                /* Fall through */
24167             case 486: /* Busy here */
24168             case 600: /* Busy everywhere */
24169             case 603: /* Decline */
24170                if (p->owner) {
24171                   sip_handle_cc(p, req, AST_CC_CCBS);
24172                   ast_queue_control(p->owner, AST_CONTROL_BUSY);
24173                }
24174                break;
24175             case 482: /* Loop Detected */
24176             case 480: /* Temporarily Unavailable */
24177             case 404: /* Not Found */
24178             case 410: /* Gone */
24179             case 400: /* Bad Request */
24180             case 500: /* Server error */
24181                if (sipmethod == SIP_SUBSCRIBE) {
24182                   handle_response_subscribe(p, resp, rest, req, seqno);
24183                   break;
24184                }
24185                /* Fall through */
24186             case 502: /* Bad gateway */
24187             case 503: /* Service Unavailable */
24188             case 504: /* Server Timeout */
24189                if (owner)
24190                   ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
24191                break;
24192             case 484: /* Address Incomplete */
24193                if (owner && sipmethod != SIP_BYE) {
24194                   switch (ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)) {
24195                   case SIP_PAGE2_ALLOWOVERLAP_YES:
24196                      ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
24197                      break;
24198                   default:
24199                      ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(404));
24200                      break;
24201                   }
24202                }
24203                break;
24204             default:
24205                /* Send hangup */ 
24206                if (owner && sipmethod != SIP_BYE)
24207                   ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
24208                break;
24209             }
24210             /* ACK on invite */
24211             if (sipmethod == SIP_INVITE)
24212                transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
24213             sip_alreadygone(p);
24214             if (!p->owner) {
24215                pvt_set_needdestroy(p, "transaction completed");
24216             }
24217          } else if ((resp >= 100) && (resp < 200)) {
24218             if (sipmethod == SIP_INVITE) {
24219                if (!req->ignore && sip_cancel_destroy(p))
24220                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
24221                if (find_sdp(req))
24222                   process_sdp(p, req, SDP_T38_NONE);
24223                if (p->owner) {
24224                   /* Queue a progress frame */
24225                   ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
24226                }
24227             }
24228          } else
24229             ast_log(LOG_NOTICE, "Don't know how to handle a %d %s response from %s\n", resp, rest, p->owner ? ast_channel_name(p->owner) : ast_sockaddr_stringify(&p->sa));
24230       }
24231    } else { 
24232       /* Responses to OUTGOING SIP requests on INCOMING calls
24233          get handled here. As well as out-of-call message responses */
24234       if (req->debug)
24235          ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
24236 
24237       if (sipmethod == SIP_INVITE && resp == 200) {
24238          /* Tags in early session is replaced by the tag in 200 OK, which is
24239          the final reply to our INVITE */
24240          char tag[128];
24241 
24242          gettag(req, "To", tag, sizeof(tag));
24243          ast_string_field_set(p, theirtag, tag);
24244       }
24245 
24246       switch(resp) {
24247       case 200:
24248          if (sipmethod == SIP_INVITE) {
24249             handle_response_invite(p, resp, rest, req, seqno);
24250          } else if (sipmethod == SIP_CANCEL) {
24251             ast_debug(1, "Got 200 OK on CANCEL\n");
24252 
24253             /* Wait for 487, then destroy */
24254          } else if (sipmethod == SIP_BYE) {
24255             pvt_set_needdestroy(p, "transaction completed");
24256          }
24257          break;
24258       case 401:   /* www-auth */
24259       case 407:
24260          if (sipmethod == SIP_INVITE)
24261             handle_response_invite(p, resp, rest, req, seqno);
24262          else if (sipmethod == SIP_BYE) {
24263             if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, sipmethod, 0)) {
24264                ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, sip_get_header(&p->initreq, "From"));
24265                pvt_set_needdestroy(p, "failed to authenticate BYE");
24266             }
24267          }
24268          break;
24269       case 481:   /* Call leg does not exist */
24270          if (sipmethod == SIP_INVITE) {
24271             /* Re-invite failed */
24272             handle_response_invite(p, resp, rest, req, seqno);
24273          } else if (sipmethod == SIP_BYE) {
24274             pvt_set_needdestroy(p, "received 481 response");
24275          } else if (sipdebug) {
24276             ast_debug(1, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
24277          }
24278          break;
24279       case 501: /* Not Implemented */
24280          if (sipmethod == SIP_INVITE)
24281             handle_response_invite(p, resp, rest, req, seqno);
24282          break;
24283       default: /* Errors without handlers */
24284          if ((resp >= 100) && (resp < 200)) {
24285             if (sipmethod == SIP_INVITE) {   /* re-invite */
24286                if (!req->ignore && sip_cancel_destroy(p))
24287                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
24288             }
24289          } else if ((resp >= 200) && (resp < 300)) { /* on any unrecognized 2XX response do the following */
24290             if (sipmethod == SIP_INVITE) {
24291                handle_response_invite(p, resp, rest, req, seqno);
24292             }
24293          } else if ((resp >= 300) && (resp < 700)) {
24294             if ((resp != 487))
24295                ast_verb(3, "Incoming call: Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_sockaddr_stringify(&p->sa));
24296             switch(resp) {
24297             case 415: /* Unsupported media type */
24298             case 488: /* Not acceptable here - codec error */
24299             case 603: /* Decline */
24300             case 500: /* Server error */
24301             case 502: /* Bad gateway */
24302             case 503: /* Service Unavailable */
24303             case 504: /* Server timeout */
24304 
24305                /* re-invite failed */
24306                if (sipmethod == SIP_INVITE && sip_cancel_destroy(p))
24307                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
24308                break;
24309             }
24310          }
24311          break;
24312       }
24313    }
24314 }
24315 
24316 
24317 /*! \brief Park SIP call support function
24318    Starts in a new thread, then parks the call
24319    XXX Should we add a wait period after streaming audio and before hangup?? Sometimes the
24320       audio can't be heard before hangup
24321 */
24322 static void *sip_park_thread(void *stuff)
24323 {
24324    struct ast_channel *transferee, *transferer; /* Chan1: The transferee, Chan2: The transferer */
24325    struct sip_pvt *transferer_pvt;
24326    struct sip_dual *d;
24327    int ext;
24328    int res;
24329 
24330    d = stuff;
24331    transferee = d->chan1;
24332    transferer = d->chan2;
24333    transferer_pvt = ast_channel_tech_pvt(transferer);
24334 
24335    ast_debug(4, "SIP Park: Transferer channel %s, Transferee %s\n", ast_channel_name(transferer), ast_channel_name(transferee));
24336 
24337    res = ast_park_call_exten(transferee, transferer, d->park_exten, d->park_context, 0, &ext);
24338 
24339    sip_pvt_lock(transferer_pvt);
24340 #ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
24341    if (res) {
24342       destroy_msg_headers(transferer_pvt);
24343       ast_string_field_set(transferer_pvt, msg_body, "Unable to park call.");
24344       transmit_message(transferer_pvt, 0, 0);
24345    } else {
24346       /* Then tell the transferer what happened */
24347       destroy_msg_headers(transferer_pvt);
24348       sprintf(buf, "Call parked on extension '%d'.", ext);
24349       ast_string_field_set(transferer_pvt, msg_body, buf);
24350       transmit_message(transferer_pvt, 0, 0);
24351    }
24352 #endif
24353 
24354    /* Any way back to the current call??? */
24355    /* Transmit response to the REFER request */
24356    ast_set_flag(&transferer_pvt->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
24357    if (!res)   {
24358       /* Transfer succeeded */
24359       append_history(transferer_pvt, "SIPpark", "Parked call on %d", ext);
24360       transmit_notify_with_sipfrag(transferer_pvt, d->seqno, "200 OK", TRUE);
24361       sip_pvt_unlock(transferer_pvt);
24362       ast_channel_hangupcause_set(transferer, AST_CAUSE_NORMAL_CLEARING);
24363       ast_debug(1, "SIP Call parked on extension '%d'\n", ext);
24364    } else {
24365       transmit_notify_with_sipfrag(transferer_pvt, d->seqno, "503 Service Unavailable", TRUE);
24366       append_history(transferer_pvt, "SIPpark", "Parking failed\n");
24367       sip_pvt_unlock(transferer_pvt);
24368       ast_log(AST_LOG_NOTICE, "SIP Call parked failed for %s\n", ast_channel_name(transferee));
24369       ast_hangup(transferee);
24370    }
24371    ast_hangup(transferer);
24372 
24373    deinit_req(&d->req);
24374    ast_free(d->park_exten);
24375    ast_free(d->park_context);
24376    ast_free(d);
24377    return NULL;
24378 }
24379 
24380 /*! DO NOT hold any locks while calling sip_park */
24381 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, uint32_t seqno, const char *park_exten, const char *park_context)
24382 {
24383    struct sip_dual *d;
24384    struct ast_channel *transferee, *transferer;
24385    pthread_t th;
24386 
24387    transferee = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, ast_channel_accountcode(chan1), ast_channel_exten(chan1), ast_channel_context(chan1), ast_channel_linkedid(chan1), ast_channel_amaflags(chan1), "Parking/%s", ast_channel_name(chan1));
24388    transferer = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, ast_channel_accountcode(chan2), ast_channel_exten(chan2), ast_channel_context(chan2), ast_channel_linkedid(chan2), ast_channel_amaflags(chan2), "SIPPeer/%s", ast_channel_name(chan2));
24389    d = ast_calloc(1, sizeof(*d));
24390    if (!transferee || !transferer || !d) {
24391       if (transferee) {
24392          ast_hangup(transferee);
24393       }
24394       if (transferer) {
24395          ast_hangup(transferer);
24396       }
24397       ast_free(d);
24398       return -1;
24399    }
24400    d->park_exten = ast_strdup(park_exten);
24401    d->park_context = ast_strdup(park_context);
24402    if (!d->park_exten || !d->park_context) {
24403       ast_hangup(transferee);
24404       ast_hangup(transferer);
24405       ast_free(d->park_exten);
24406       ast_free(d->park_context);
24407       ast_free(d);
24408       return -1;
24409    }
24410 
24411    /* Make formats okay */
24412    ast_format_copy(ast_channel_readformat(transferee), ast_channel_readformat(chan1));
24413    ast_format_copy(ast_channel_writeformat(transferee), ast_channel_writeformat(chan1));
24414 
24415    /* Prepare for taking over the channel */
24416    if (ast_channel_masquerade(transferee, chan1)) {
24417       ast_hangup(transferee);
24418       ast_hangup(transferer);
24419       ast_free(d->park_exten);
24420       ast_free(d->park_context);
24421       ast_free(d);
24422       return -1;
24423    }
24424 
24425    /* Setup the extensions and such */
24426    ast_channel_context_set(transferee, ast_channel_context(chan1));
24427    ast_channel_exten_set(transferee, ast_channel_exten(chan1));
24428    ast_channel_priority_set(transferee, ast_channel_priority(chan1));
24429 
24430    ast_do_masquerade(transferee);
24431 
24432    /* We make a clone of the peer channel too, so we can play
24433       back the announcement */
24434 
24435    /* Make formats okay */
24436    ast_format_copy(ast_channel_readformat(transferer), ast_channel_readformat(chan2));
24437    ast_format_copy(ast_channel_writeformat(transferer), ast_channel_writeformat(chan2));
24438    ast_channel_parkinglot_set(transferer, ast_channel_parkinglot(chan2));
24439 
24440    /* Prepare for taking over the channel */
24441    if (ast_channel_masquerade(transferer, chan2)) {
24442       ast_hangup(transferee);
24443       ast_hangup(transferer);
24444       ast_free(d->park_exten);
24445       ast_free(d->park_context);
24446       ast_free(d);
24447       return -1;
24448    }
24449 
24450    /* Setup the extensions and such */
24451    ast_channel_context_set(transferer, ast_channel_context(chan2));
24452    ast_channel_exten_set(transferer, ast_channel_exten(chan2));
24453    ast_channel_priority_set(transferer, ast_channel_priority(chan2));
24454 
24455    ast_do_masquerade(transferer);
24456 
24457    /* Save original request for followup */
24458    copy_request(&d->req, req);
24459    d->chan1 = transferee;  /* Transferee */
24460    d->chan2 = transferer;  /* Transferer */
24461    d->seqno = seqno;
24462    if (ast_pthread_create_detached_background(&th, NULL, sip_park_thread, d) < 0) {
24463       /* Could not start thread */
24464       ast_hangup(transferer);
24465       ast_hangup(transferee);
24466       deinit_req(&d->req);
24467       ast_free(d->park_exten);
24468       ast_free(d->park_context);
24469       ast_free(d);   /* We don't need it anymore. If thread is created, d will be free'd
24470                by sip_park_thread() */
24471       return -1;
24472    }
24473    return 0;
24474 }
24475 
24476 
24477 /*! \brief SIP pickup support function
24478  * Starts in a new thread, then pickup the call
24479  */
24480 static void *sip_pickup_thread(void *stuff)
24481 {
24482    struct ast_channel *chan;
24483    chan = stuff;
24484 
24485    if (ast_pickup_call(chan)) {
24486       ast_channel_hangupcause_set(chan, AST_CAUSE_CALL_REJECTED);
24487    } else {
24488       ast_channel_hangupcause_set(chan, AST_CAUSE_NORMAL_CLEARING);
24489    }
24490    ast_hangup(chan);
24491    ast_channel_unref(chan);
24492    chan = NULL;
24493    return NULL;
24494 }
24495 
24496 /*! \brief Pickup a call using the subsystem in features.c
24497  * This is executed in a separate thread
24498  */
24499 static int sip_pickup(struct ast_channel *chan)
24500 {
24501    pthread_t threadid;
24502 
24503    ast_channel_ref(chan);
24504 
24505    if (ast_pthread_create_detached_background(&threadid, NULL, sip_pickup_thread, chan)) {
24506       ast_debug(1, "Unable to start Group pickup thread on channel %s\n", ast_channel_name(chan));
24507       ast_channel_unref(chan);
24508       return -1;
24509    }
24510    ast_debug(1, "Started Group pickup thread on channel %s\n", ast_channel_name(chan));
24511    return 0;
24512 }
24513 
24514 
24515 /*! \brief Turn off generator data
24516    XXX Does this function belong in the SIP channel?
24517 */
24518 static void ast_quiet_chan(struct ast_channel *chan)
24519 {
24520    if (chan && ast_channel_state(chan) == AST_STATE_UP) {
24521       if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_MOH))
24522          ast_moh_stop(chan);
24523       else if (ast_channel_generatordata(chan))
24524          ast_deactivate_generator(chan);
24525    }
24526 }
24527 
24528 /*! \brief Attempt transfer of SIP call
24529    This fix for attended transfers on a local PBX */
24530 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target)
24531 {
24532    int res = 0;
24533    struct ast_channel *peera = NULL,
24534       *peerb = NULL,
24535       *peerc = NULL,
24536       *peerd = NULL;
24537 
24538 
24539    /* We will try to connect the transferee with the target and hangup
24540       all channels to the transferer */
24541    ast_debug(4, "Sip transfer:--------------------\n");
24542    if (transferer->chan1)
24543       ast_debug(4, "-- Transferer to PBX channel: %s State %s\n", ast_channel_name(transferer->chan1), ast_state2str(ast_channel_state(transferer->chan1)));
24544    else
24545       ast_debug(4, "-- No transferer first channel - odd??? \n");
24546    if (target->chan1)
24547       ast_debug(4, "-- Transferer to PBX second channel (target): %s State %s\n", ast_channel_name(target->chan1), ast_state2str(ast_channel_state(target->chan1)));
24548    else
24549       ast_debug(4, "-- No target first channel ---\n");
24550    if (transferer->chan2)
24551       ast_debug(4, "-- Bridged call to transferee: %s State %s\n", ast_channel_name(transferer->chan2), ast_state2str(ast_channel_state(transferer->chan2)));
24552    else
24553       ast_debug(4, "-- No bridged call to transferee\n");
24554    if (target->chan2)
24555       ast_debug(4, "-- Bridged call to transfer target: %s State %s\n", target->chan2 ? ast_channel_name(target->chan2) : "<none>", target->chan2 ? ast_state2str(ast_channel_state(target->chan2)) : "(none)");
24556    else
24557       ast_debug(4, "-- No target second channel ---\n");
24558    ast_debug(4, "-- END Sip transfer:--------------------\n");
24559    if (transferer->chan2) { /* We have a bridge on the transferer's channel */
24560       peera = transferer->chan1; /* Transferer - PBX -> transferee channel * the one we hangup */
24561       peerb = target->chan1;     /* Transferer - PBX -> target channel - This will get lost in masq */
24562       peerc = transferer->chan2; /* Asterisk to Transferee */
24563       peerd = target->chan2;     /* Asterisk to Target */
24564       ast_debug(3, "SIP transfer: Four channels to handle\n");
24565    } else if (target->chan2) {   /* Transferer has no bridge (IVR), but transferee */
24566       peera = target->chan1;     /* Transferer to PBX -> target channel */
24567       peerb = transferer->chan1; /* Transferer to IVR*/
24568       peerc = target->chan2;     /* Asterisk to Target */
24569       peerd = transferer->chan2; /* Nothing */
24570       ast_debug(3, "SIP transfer: Three channels to handle\n");
24571    }
24572 
24573    if (peera && peerb && peerc && (peerb != peerc)) {
24574       ast_quiet_chan(peera);     /* Stop generators */
24575       /* no need to quiet peerb since it should be hungup after the
24576          transfer and the masquerade needs to be able to see if MOH is
24577          playing on it */
24578       ast_quiet_chan(peerc);
24579       if (peerd)
24580          ast_quiet_chan(peerd);
24581 
24582       ast_debug(4, "SIP transfer: trying to masquerade %s into %s\n", ast_channel_name(peerc), ast_channel_name(peerb));
24583       if (ast_channel_masquerade(peerb, peerc)) {
24584          ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", ast_channel_name(peerb), ast_channel_name(peerc));
24585          res = -1;
24586       } else
24587          ast_debug(4, "SIP transfer: Succeeded to masquerade channels.\n");
24588       return res;
24589    } else {
24590       ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
24591       if (transferer->chan1)
24592          ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
24593       if (target->chan1)
24594          ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
24595       return -1;
24596    }
24597    return 0;
24598 }
24599 
24600 /*! \brief Get tag from packet
24601  *
24602  * \return Returns the pointer to the provided tag buffer,
24603  *         or NULL if the tag was not found.
24604  */
24605 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
24606 {
24607    const char *thetag;
24608 
24609    if (!tagbuf)
24610       return NULL;
24611    tagbuf[0] = '\0';    /* reset the buffer */
24612    thetag = sip_get_header(req, header);
24613    thetag = strcasestr(thetag, ";tag=");
24614    if (thetag) {
24615       thetag += 5;
24616       ast_copy_string(tagbuf, thetag, tagbufsize);
24617       return strsep(&tagbuf, ";");
24618    }
24619    return NULL;
24620 }
24621 
24622 static int handle_cc_notify(struct sip_pvt *pvt, struct sip_request *req)
24623 {
24624    struct sip_monitor_instance *monitor_instance = ao2_callback(sip_monitor_instances, 0,
24625          find_sip_monitor_instance_by_subscription_pvt, pvt);
24626    const char *status = get_content_line(req, "cc-state", ':');
24627    struct cc_epa_entry *cc_entry;
24628    char *uri;
24629 
24630    if (!monitor_instance) {
24631       transmit_response(pvt, "400 Bad Request", req);
24632       return -1;
24633    }
24634 
24635    if (ast_strlen_zero(status)) {
24636       ao2_ref(monitor_instance, -1);
24637       transmit_response(pvt, "400 Bad Request", req);
24638       return -1;
24639    }
24640 
24641    if (!strcmp(status, "queued")) {
24642       /* We've been told that we're queued. This is the endpoint's way of telling
24643        * us that it has accepted our CC request. We need to alert the core of this
24644        * development
24645        */
24646       ast_cc_monitor_request_acked(monitor_instance->core_id, "SIP endpoint %s accepted request", monitor_instance->device_name);
24647       transmit_response(pvt, "200 OK", req);
24648       ao2_ref(monitor_instance, -1);
24649       return 0;
24650    }
24651 
24652    /* It's open! Yay! */
24653    uri = get_content_line(req, "cc-URI", ':');
24654    if (ast_strlen_zero(uri)) {
24655       uri = get_in_brackets((char *)sip_get_header(req, "From"));
24656    }
24657 
24658    ast_string_field_set(monitor_instance, notify_uri, uri);
24659    if (monitor_instance->suspension_entry) {
24660       cc_entry = monitor_instance->suspension_entry->instance_data;
24661       if (cc_entry->current_state == CC_CLOSED) {
24662          /* If we've created a suspension entry and the current state is closed, then that means
24663           * we got a notice from the CC core earlier to suspend monitoring, but because this particular
24664           * call leg had not yet notified us that it was ready for recall, it meant that we
24665           * could not yet send a PUBLISH. Now, however, we can.
24666           */
24667          construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body,
24668                sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
24669          transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_INITIAL, monitor_instance->notify_uri);
24670       } else {
24671          ast_cc_monitor_callee_available(monitor_instance->core_id, "SIP monitored callee has become available");
24672       }
24673    } else {
24674       ast_cc_monitor_callee_available(monitor_instance->core_id, "SIP monitored callee has become available");
24675    }
24676    ao2_ref(monitor_instance, -1);
24677    transmit_response(pvt, "200 OK", req);
24678 
24679    return 0;
24680 }
24681 
24682 /*! \brief Handle incoming notifications */
24683 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e)
24684 {
24685    /* This is mostly a skeleton for future improvements */
24686    /* Mostly created to return proper answers on notifications on outbound REFER's */
24687    int res = 0;
24688    const char *event = sip_get_header(req, "Event");
24689    char *sep;
24690 
24691    if( (sep = strchr(event, ';')) ) {  /* XXX bug here - overwriting string ? */
24692       *sep++ = '\0';
24693    }
24694 
24695    if (sipdebug)
24696       ast_debug(2, "Got NOTIFY Event: %s\n", event);
24697 
24698    if (!strcmp(event, "refer")) {
24699       /* Save nesting depth for now, since there might be other events we will
24700          support in the future */
24701 
24702       /* Handle REFER notifications */
24703       char *buf, *cmd, *code;
24704       int respcode;
24705       int success = TRUE;
24706 
24707       /* EventID for each transfer... EventID is basically the REFER cseq
24708 
24709        We are getting notifications on a call that we transferred
24710        We should hangup when we are getting a 200 OK in a sipfrag
24711        Check if we have an owner of this event */
24712 
24713       /* Check the content type */
24714       if (strncasecmp(sip_get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
24715          /* We need a sipfrag */
24716          transmit_response(p, "400 Bad request", req);
24717          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
24718          return -1;
24719       }
24720 
24721       /* Get the text of the attachment */
24722       if (ast_strlen_zero(buf = get_content(req))) {
24723          ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
24724          transmit_response(p, "400 Bad request", req);
24725          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
24726          return -1;
24727       }
24728 
24729       /*
24730       From the RFC...
24731       A minimal, but complete, implementation can respond with a single
24732       NOTIFY containing either the body:
24733          SIP/2.0 100 Trying
24734       
24735       if the subscription is pending, the body:
24736          SIP/2.0 200 OK
24737       if the reference was successful, the body:
24738          SIP/2.0 503 Service Unavailable
24739       if the reference failed, or the body:
24740          SIP/2.0 603 Declined
24741 
24742       if the REFER request was accepted before approval to follow the
24743       reference could be obtained and that approval was subsequently denied
24744       (see Section 2.4.7).
24745       
24746       If there are several REFERs in the same dialog, we need to
24747       match the ID of the event header...
24748       */
24749       ast_debug(3, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
24750       cmd = ast_skip_blanks(buf);
24751       code = cmd;
24752       /* We are at SIP/2.0 */
24753       while(*code && (*code > 32)) {   /* Search white space */
24754          code++;
24755       }
24756       *code++ = '\0';
24757       code = ast_skip_blanks(code);
24758       sep = code;
24759       sep++;
24760       while(*sep && (*sep > 32)) {  /* Search white space */
24761          sep++;
24762       }
24763       *sep++ = '\0';       /* Response string */
24764       respcode = atoi(code);
24765       switch (respcode) {
24766       case 200:   /* OK: The new call is up, hangup this call */
24767          /* Hangup the call that we are replacing */
24768          break;
24769       case 301: /* Moved permenantly */
24770       case 302: /* Moved temporarily */
24771          /* Do we get the header in the packet in this case? */
24772          success = FALSE;
24773          break;
24774       case 503:   /* Service Unavailable: The new call failed */
24775       case 603:   /* Declined: Not accepted */
24776             /* Cancel transfer, continue the current call */
24777          success = FALSE;
24778          break;
24779       case 0:     /* Parse error */
24780             /* Cancel transfer, continue the current call */
24781          ast_log(LOG_NOTICE, "Error parsing sipfrag in NOTIFY in response to REFER.\n");
24782          success = FALSE;
24783          break;
24784       default:
24785          if (respcode < 200) {
24786             /* ignore provisional responses */
24787             success = -1;
24788          } else {
24789             ast_log(LOG_NOTICE, "Got unknown code '%d' in NOTIFY in response to REFER.\n", respcode);
24790             success = FALSE;
24791          }
24792          break;
24793       }
24794       if (success == FALSE) {
24795          ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
24796       }
24797 
24798       if (p->owner && success != -1) {
24799          enum ast_control_transfer message = success ? AST_TRANSFER_SUCCESS : AST_TRANSFER_FAILED;
24800          ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
24801       }
24802       /* Confirm that we received this packet */
24803       transmit_response(p, "200 OK", req);
24804    } else if (!strcmp(event, "message-summary")) {
24805       const char *mailbox = NULL;
24806       char *c = ast_strdupa(get_content_line(req, "Voice-Message", ':'));
24807 
24808       if (!p->mwi) {
24809          struct sip_peer *peer = sip_find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
24810 
24811          if (peer) {
24812             mailbox = ast_strdupa(peer->unsolicited_mailbox);
24813             sip_unref_peer(peer, "removing unsolicited mwi ref");
24814          }
24815       } else {
24816          mailbox = p->mwi->mailbox;
24817       }
24818 
24819       if (!ast_strlen_zero(mailbox) && !ast_strlen_zero(c)) {
24820          char *old = strsep(&c, " ");
24821          char *new = strsep(&old, "/");
24822          struct ast_event *event;
24823 
24824          if ((event = ast_event_new(AST_EVENT_MWI,
24825                      AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
24826                      AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, "SIP_Remote",
24827                      AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(new),
24828                      AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(old),
24829                      AST_EVENT_IE_END))) {
24830             ast_event_queue_and_cache(event);
24831          }
24832          transmit_response(p, "200 OK", req);
24833       } else {
24834          transmit_response(p, "489 Bad event", req);
24835          res = -1;
24836       }
24837    } else if (!strcmp(event, "keep-alive")) {
24838        /* Used by Sipura/Linksys for NAT pinhole,
24839         * just confirm that we received the packet. */
24840       transmit_response(p, "200 OK", req);
24841    } else if (!strcmp(event, "call-completion")) {
24842       res = handle_cc_notify(p, req);
24843    } else {
24844       /* We don't understand this event. */
24845       transmit_response(p, "489 Bad event", req);
24846       res = -1;
24847    }
24848 
24849    if (!p->lastinvite)
24850       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
24851 
24852    return res;
24853 }
24854 
24855 /*! \brief Handle incoming OPTIONS request
24856    An OPTIONS request should be answered like an INVITE from the same UA, including SDP
24857 */
24858 static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e)
24859 {
24860    const char *msg;
24861    enum sip_get_dest_result gotdest;
24862    int res;
24863 
24864    if (p->lastinvite) {
24865       /* if this is a request in an active dialog, just confirm that the dialog exists. */
24866       transmit_response_with_allow(p, "200 OK", req, 0);
24867       return 0;
24868    }
24869 
24870    if (sip_cfg.auth_options_requests) {
24871       /* Do authentication if this OPTIONS request began the dialog */
24872       copy_request(&p->initreq, req);
24873       set_pvt_allowed_methods(p, req);
24874       res = check_user(p, req, SIP_OPTIONS, e, XMIT_UNRELIABLE, addr);
24875       if (res == AUTH_CHALLENGE_SENT) {
24876          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
24877          return 0;
24878       }
24879       if (res < 0) { /* Something failed in authentication */
24880          ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", sip_get_header(req, "From"));
24881          transmit_response(p, "403 Forbidden", req);
24882          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
24883          return 0;
24884       }
24885    }
24886 
24887    /* must go through authentication before getting here */
24888    gotdest = get_destination(p, req, NULL);
24889    build_contact(p);
24890 
24891    if (ast_strlen_zero(p->context))
24892       ast_string_field_set(p, context, sip_cfg.default_context);
24893 
24894    if (ast_shutting_down()) {
24895       msg = "503 Unavailable";
24896    } else {
24897       msg = "404 Not Found";
24898       switch (gotdest) {
24899       case SIP_GET_DEST_INVALID_URI:
24900          msg = "416 Unsupported URI scheme";
24901          break;
24902       case SIP_GET_DEST_EXTEN_MATCHMORE:
24903       case SIP_GET_DEST_REFUSED:
24904       case SIP_GET_DEST_EXTEN_NOT_FOUND:
24905          //msg = "404 Not Found";
24906          break;
24907       case SIP_GET_DEST_EXTEN_FOUND:
24908          msg = "200 OK";
24909          break;
24910       }
24911    }
24912    transmit_response_with_allow(p, msg, req, 0);
24913 
24914    /* Destroy if this OPTIONS was the opening request, but not if
24915       it's in the middle of a normal call flow. */
24916    sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
24917 
24918    return 0;
24919 }
24920 
24921 /*! \brief Handle the transfer part of INVITE with a replaces: header,
24922     meaning a target pickup or an attended transfer.
24923     Used only once.
24924    XXX 'ignore' is unused.
24925 
24926    \note this function is called by handle_request_invite(). Four locks
24927    held at the beginning of this function, p, p->owner, p->refer->refer_call and
24928    p->refere->refer_call->owner.  only p's lock should remain at the end of this
24929    function.  p's lock as well as the channel p->owner's lock are held by
24930    handle_request_do(), we unlock p->owner before the masq.  By setting nounlock
24931    we are indicating to handle_request_do() that we have already unlocked the owner.
24932  */
24933 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, int *nounlock)
24934 {
24935    int earlyreplace = 0;
24936    int oneleggedreplace = 0;     /* Call with no bridge, propably IVR or voice message */
24937    struct ast_channel *c = p->owner;   /* Our incoming call */
24938    struct ast_channel *replacecall = p->refer->refer_call->owner; /* The channel we're about to take over */
24939    struct ast_channel *targetcall;     /* The bridge to the take-over target */
24940 
24941    /* Check if we're in ring state */
24942    if (ast_channel_state(replacecall) == AST_STATE_RING)
24943       earlyreplace = 1;
24944 
24945    /* Check if we have a bridge */
24946    if (!(targetcall = ast_bridged_channel(replacecall))) {
24947       /* We have no bridge */
24948       if (!earlyreplace) {
24949          ast_debug(2, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", ast_channel_name(replacecall));
24950          oneleggedreplace = 1;
24951       }
24952    }
24953    if (targetcall && ast_channel_state(targetcall) == AST_STATE_RINGING)
24954       ast_debug(4, "SIP transfer: Target channel is in ringing state\n");
24955 
24956    if (targetcall)
24957       ast_debug(4, "SIP transfer: Invite Replace incoming channel should bridge to channel %s while hanging up channel %s\n", ast_channel_name(targetcall), ast_channel_name(replacecall));
24958    else
24959       ast_debug(4, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", ast_channel_name(replacecall));
24960 
24961    if (req->ignore) {
24962       ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
24963       /* We should answer something here. If we are here, the
24964          call we are replacing exists, so an accepted
24965          can't harm */
24966       transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE, FALSE);
24967       /* Do something more clever here */
24968       if (c) {
24969          *nounlock = 1;
24970          ast_channel_unlock(c);
24971       }
24972       ast_channel_unlock(replacecall);
24973       sip_pvt_unlock(p->refer->refer_call);
24974       return 1;
24975    }
24976    if (!c) {
24977       /* What to do if no channel ??? */
24978       ast_log(LOG_ERROR, "Unable to create new channel.  Invite/replace failed.\n");
24979       transmit_response_reliable(p, "503 Service Unavailable", req);
24980       append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
24981       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
24982       ast_channel_unlock(replacecall);
24983       sip_pvt_unlock(p->refer->refer_call);
24984       return 1;
24985    }
24986    append_history(p, "Xfer", "INVITE/Replace received");
24987    /* We have three channels to play with
24988       channel c: New incoming call
24989       targetcall: Call from PBX to target
24990       p->refer->refer_call: SIP pvt dialog from transferer to pbx.
24991       replacecall: The owner of the previous
24992       We need to masq C into refer_call to connect to
24993       targetcall;
24994       If we are talking to internal audio stream, target call is null.
24995    */
24996 
24997    /* Fake call progress */
24998    transmit_response(p, "100 Trying", req);
24999    ast_setstate(c, AST_STATE_RING);
25000 
25001    /* Masquerade the new call into the referred call to connect to target call
25002       Targetcall is not touched by the masq */
25003 
25004    /* Answer the incoming call and set channel to UP state */
25005    transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE, FALSE);
25006 
25007    /* Is this a call pickup? */
25008    if (earlyreplace || oneleggedreplace) {
25009       /* Report pickup event, in this order: PICKUP, CHAN_UP, ANSWER */
25010       ast_cel_report_event(replacecall, AST_CEL_PICKUP, NULL, NULL, c);
25011       ast_setstate(c, AST_STATE_UP);
25012       ast_cel_report_event(c, AST_CEL_ANSWER, NULL, NULL, NULL);
25013    } else {
25014       ast_setstate(c, AST_STATE_UP);
25015    }
25016 
25017    /* Stop music on hold and other generators */
25018    ast_quiet_chan(replacecall);
25019    ast_quiet_chan(targetcall);
25020    ast_debug(4, "Invite/Replaces: preparing to masquerade %s into %s\n", ast_channel_name(c), ast_channel_name(replacecall));
25021 
25022    /* Make sure that the masq does not free our PVT for the old call */
25023    if (! earlyreplace && ! oneleggedreplace )
25024       ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER);  /* Delay hangup */
25025 
25026    /* Prepare the masquerade - if this does not happen, we will be gone */
25027    if(ast_channel_masquerade(replacecall, c))
25028       ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
25029    else
25030       ast_debug(4, "Invite/Replaces: Going to masquerade %s into %s\n", ast_channel_name(c), ast_channel_name(replacecall));
25031 
25032    /* C should now be in place of replacecall. all channel locks and pvt locks should be removed
25033     * before issuing the masq.  Since we are unlocking both the pvt (p) and its owner channel (c)
25034     * it is possible for channel c to be destroyed on us.  To prevent this, we must give c a reference
25035     * before any unlocking takes place and remove it only once we are completely done with it */
25036    ast_channel_ref(c);
25037    ast_channel_unlock(replacecall);
25038    ast_channel_unlock(c);
25039    sip_pvt_unlock(p->refer->refer_call);
25040    sip_pvt_unlock(p);
25041    if (ast_do_masquerade(replacecall)) {
25042       ast_log(LOG_WARNING, "Failed to perform masquerade with INVITE replaces\n");
25043    }
25044    if (earlyreplace || oneleggedreplace ) {
25045       ast_channel_lock(c);
25046       ast_channel_hangupcause_set(c, AST_CAUSE_SWITCH_CONGESTION);
25047       ast_channel_unlock(c);
25048    }
25049 
25050    /* c and c's tech pvt must be unlocked at this point for ast_hangup */
25051    ast_hangup(c);
25052    /* this indicates to handle_request_do that the owner channel has already been unlocked */
25053    *nounlock = 1;
25054    /* lock PVT structure again after hangup */
25055    sip_pvt_lock(p);
25056    ast_channel_unref(c);
25057    return 0;
25058 }
25059 
25060 /*! \note No channel or pvt locks should be held while calling this function. */
25061 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context)
25062 {
25063    struct ast_str *str = ast_str_alloca(AST_MAX_EXTENSION + AST_MAX_CONTEXT + 2);
25064    struct ast_app *pickup = pbx_findapp("Pickup");
25065 
25066    if (!pickup) {
25067       ast_log(LOG_ERROR, "Unable to perform pickup: Application 'Pickup' not loaded (app_directed_pickup.so).\n");
25068       return -1;
25069    }
25070 
25071    ast_str_set(&str, 0, "%s@%s", extension, sip_cfg.notifycid == IGNORE_CONTEXT ? "PICKUPMARK" : context);
25072 
25073    ast_debug(2, "About to call Pickup(%s)\n", ast_str_buffer(str));
25074 
25075    /* There is no point in capturing the return value since pickup_exec
25076       doesn't return anything meaningful unless the passed data is an empty
25077       string (which in our case it will not be) */
25078    pbx_exec(channel, pickup, ast_str_buffer(str));
25079 
25080    return 0;
25081 }
25082 
25083 /*! \brief Called to deny a T38 reinvite if the core does not respond to our request */
25084 static int sip_t38_abort(const void *data)
25085 {
25086    struct sip_pvt *p = (struct sip_pvt *) data;
25087 
25088    sip_pvt_lock(p);
25089    /* an application may have taken ownership of the T.38 negotiation on this
25090     * channel while we were waiting to grab the lock... if it did, the scheduler
25091     * id will have been reset to -1, which is our indication that we do *not*
25092     * want to abort the negotiation process
25093     */
25094    if (p->t38id != -1) {
25095       change_t38_state(p, T38_REJECTED);
25096       transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
25097       p->t38id = -1;
25098       dialog_unref(p, "unref the dialog ptr from sip_t38_abort, because it held a dialog ptr");
25099    }
25100    sip_pvt_unlock(p);
25101    return 0;
25102 }
25103 
25104 /*!
25105  * \brief bare-bones support for SIP UPDATE
25106  *
25107  * XXX This is not even close to being RFC 3311-compliant. We don't advertise
25108  * that we support the UPDATE method, so no one should ever try sending us
25109  * an UPDATE anyway. However, Asterisk can send an UPDATE to change connected
25110  * line information, so we need to be prepared to handle this. The way we distinguish
25111  * such an UPDATE is through the X-Asterisk-rpid-update header.
25112  *
25113  * Actually updating the media session may be some future work.
25114  */
25115 static int handle_request_update(struct sip_pvt *p, struct sip_request *req)
25116 {
25117    if (ast_strlen_zero(sip_get_header(req, "X-Asterisk-rpid-update"))) {
25118       transmit_response(p, "501 Method Not Implemented", req);
25119       return 0;
25120    }
25121    if (!p->owner) {
25122       transmit_response(p, "481 Call/Transaction Does Not Exist", req);
25123       return 0;
25124    }
25125    if (get_rpid(p, req)) {
25126       struct ast_party_connected_line connected;
25127       struct ast_set_party_connected_line update_connected;
25128 
25129       ast_party_connected_line_init(&connected);
25130       memset(&update_connected, 0, sizeof(update_connected));
25131 
25132       update_connected.id.number = 1;
25133       connected.id.number.valid = 1;
25134       connected.id.number.str = (char *) p->cid_num;
25135       connected.id.number.presentation = p->callingpres;
25136 
25137       update_connected.id.name = 1;
25138       connected.id.name.valid = 1;
25139       connected.id.name.str = (char *) p->cid_name;
25140       connected.id.name.presentation = p->callingpres;
25141 
25142       /* Invalidate any earlier private connected id representation */
25143       ast_set_party_id_all(&update_connected.priv);
25144 
25145       connected.id.tag = (char *) p->cid_tag;
25146       connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
25147       ast_channel_queue_connected_line_update(p->owner, &connected, &update_connected);
25148    }
25149    transmit_response(p, "200 OK", req);
25150    return 0;
25151 }
25152 
25153 /*
25154  * \internal \brief Check Session Timers for an INVITE request
25155  *
25156  * \retval 0 ok
25157  * \retval -1 failure
25158  */
25159 static int handle_request_invite_st(struct sip_pvt *p, struct sip_request *req,
25160       const char *required, int reinvite)
25161 {
25162    const char *p_uac_se_hdr;       /* UAC's Session-Expires header string                      */
25163    const char *p_uac_min_se;       /* UAC's requested Min-SE interval (char string)            */
25164    int uac_max_se = -1;            /* UAC's Session-Expires in integer format                  */
25165    int uac_min_se = -1;            /* UAC's Min-SE in integer format                           */
25166    int st_active = FALSE;          /* Session-Timer on/off boolean                             */
25167    int st_interval = 0;            /* Session-Timer negotiated refresh interval                */
25168    enum st_refresher tmp_st_ref = SESSION_TIMER_REFRESHER_AUTO; /* Session-Timer refresher     */
25169    int dlg_min_se = -1;
25170    int dlg_max_se = global_max_se;
25171    int rtn;
25172 
25173    /* Session-Timers */
25174    if ((p->sipoptions & SIP_OPT_TIMER)) {
25175       enum st_refresher_param st_ref_param = SESSION_TIMER_REFRESHER_PARAM_UNKNOWN;
25176 
25177       /* The UAC has requested session-timers for this session. Negotiate
25178       the session refresh interval and who will be the refresher */
25179       ast_debug(2, "Incoming INVITE with 'timer' option supported\n");
25180 
25181       /* Allocate Session-Timers struct w/in the dialog */
25182       if (!p->stimer) {
25183          sip_st_alloc(p);
25184       }
25185 
25186       /* Parse the Session-Expires header */
25187       p_uac_se_hdr = sip_get_header(req, "Session-Expires");
25188       if (!ast_strlen_zero(p_uac_se_hdr)) {
25189          ast_debug(2, "INVITE also has \"Session-Expires\" header.\n");
25190          rtn = parse_session_expires(p_uac_se_hdr, &uac_max_se, &st_ref_param);
25191          tmp_st_ref = (st_ref_param == SESSION_TIMER_REFRESHER_PARAM_UAC) ? SESSION_TIMER_REFRESHER_THEM : SESSION_TIMER_REFRESHER_US;
25192          if (rtn != 0) {
25193             transmit_response_reliable(p, "400 Session-Expires Invalid Syntax", req);
25194             return -1;
25195          }
25196       }
25197 
25198       /* Parse the Min-SE header */
25199       p_uac_min_se = sip_get_header(req, "Min-SE");
25200       if (!ast_strlen_zero(p_uac_min_se)) {
25201          ast_debug(2, "INVITE also has \"Min-SE\" header.\n");
25202          rtn = parse_minse(p_uac_min_se, &uac_min_se);
25203          if (rtn != 0) {
25204             transmit_response_reliable(p, "400 Min-SE Invalid Syntax", req);
25205             return -1;
25206          }
25207       }
25208 
25209       dlg_min_se = st_get_se(p, FALSE);
25210       switch (st_get_mode(p, 1)) {
25211       case SESSION_TIMER_MODE_ACCEPT:
25212       case SESSION_TIMER_MODE_ORIGINATE:
25213          if (uac_max_se > 0 && uac_max_se < dlg_min_se) {
25214             transmit_response_with_minse(p, "422 Session Interval Too Small", req, dlg_min_se);
25215             return -1;
25216          }
25217 
25218          p->stimer->st_active_peer_ua = TRUE;
25219          st_active = TRUE;
25220          if (st_ref_param == SESSION_TIMER_REFRESHER_PARAM_UNKNOWN) {
25221             tmp_st_ref = st_get_refresher(p);
25222          }
25223 
25224          dlg_max_se = st_get_se(p, TRUE);
25225          if (uac_max_se > 0) {
25226             if (dlg_max_se >= uac_min_se) {
25227                st_interval = (uac_max_se < dlg_max_se) ? uac_max_se : dlg_max_se;
25228             } else {
25229                st_interval = uac_max_se;
25230             }
25231          } else if (uac_min_se > 0) {
25232             st_interval = MAX(dlg_max_se, uac_min_se);
25233          } else {
25234             st_interval = dlg_max_se;
25235          }
25236          break;
25237 
25238       case SESSION_TIMER_MODE_REFUSE:
25239          if (p->reqsipoptions & SIP_OPT_TIMER) {
25240             transmit_response_with_unsupported(p, "420 Option Disabled", req, required);
25241             ast_log(LOG_WARNING, "Received SIP INVITE with supported but disabled option: %s\n", required);
25242             return -1;
25243          }
25244          break;
25245 
25246       default:
25247          ast_log(LOG_ERROR, "Internal Error %u at %s:%d\n", st_get_mode(p, 1), __FILE__, __LINE__);
25248          break;
25249       }
25250    } else {
25251       /* The UAC did not request session-timers.  Asterisk (UAS), will now decide
25252       (based on session-timer-mode in sip.conf) whether to run session-timers for
25253       this session or not. */
25254       switch (st_get_mode(p, 1)) {
25255       case SESSION_TIMER_MODE_ORIGINATE:
25256          st_active = TRUE;
25257          st_interval = st_get_se(p, TRUE);
25258          tmp_st_ref = SESSION_TIMER_REFRESHER_US;
25259          p->stimer->st_active_peer_ua = (p->sipoptions & SIP_OPT_TIMER) ? TRUE : FALSE;
25260          break;
25261 
25262       default:
25263          break;
25264       }
25265    }
25266 
25267    if (reinvite == 0) {
25268       /* Session-Timers: Start session refresh timer based on negotiation/config */
25269       if (st_active == TRUE) {
25270          p->stimer->st_active = TRUE;
25271          p->stimer->st_interval = st_interval;
25272          p->stimer->st_ref = tmp_st_ref;
25273       }
25274    } else {
25275       if (p->stimer->st_active == TRUE) {
25276          /* Session-Timers:  A re-invite request sent within a dialog will serve as
25277          a refresh request, no matter whether the re-invite was sent for refreshing
25278          the session or modifying it.*/
25279          ast_debug (2, "Restarting session-timers on a refresh - %s\n", p->callid);
25280 
25281          /* The UAC may be adjusting the session-timers mid-session */
25282          if (st_interval > 0) {
25283             p->stimer->st_interval = st_interval;
25284             p->stimer->st_ref      = tmp_st_ref;
25285          }
25286       }
25287    }
25288 
25289    return 0;
25290 }
25291 
25292 /*!
25293  * \brief Handle incoming INVITE request
25294  * \note If the INVITE has a Replaces header, it is part of an
25295  * attended transfer. If so, we do not go through the dial
25296  * plan but try to find the active call and masquerade
25297  * into it
25298  */
25299 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)
25300 {
25301    int res = INV_REQ_SUCCESS;
25302    int gotdest;
25303    const char *p_replaces;
25304    char *replace_id = NULL;
25305    int refer_locked = 0;
25306    const char *required;
25307    unsigned int required_profile = 0;
25308    struct ast_channel *c = NULL;    /* New channel */
25309    struct sip_peer *authpeer = NULL;   /* Matching Peer */
25310    int reinvite = 0;
25311    struct ast_party_redirecting redirecting;
25312    struct ast_set_party_redirecting update_redirecting;
25313 
25314    struct {
25315       char exten[AST_MAX_EXTENSION];
25316       char context[AST_MAX_CONTEXT];
25317    } pickup = {
25318          .exten = "",
25319    };
25320 
25321    /* Find out what they support */
25322    if (!p->sipoptions) {
25323       const char *supported = sip_get_header(req, "Supported");
25324       if (!ast_strlen_zero(supported)) {
25325          p->sipoptions = parse_sip_options(supported, NULL, 0);
25326       }
25327    }
25328 
25329    /* Find out what they require */
25330    required = sip_get_header(req, "Require");
25331    if (!ast_strlen_zero(required)) {
25332       char unsupported[256] = { 0, };
25333       required_profile = parse_sip_options(required, unsupported, ARRAY_LEN(unsupported));
25334 
25335       /* If there are any options required that we do not support,
25336        * then send a 420 with only those unsupported options listed */
25337       if (!ast_strlen_zero(unsupported)) {
25338          transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, unsupported);
25339          ast_log(LOG_WARNING, "Received SIP INVITE with unsupported required extension: required:%s unsupported:%s\n", required, unsupported);
25340          p->invitestate = INV_COMPLETED;
25341          if (!p->lastinvite)
25342             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25343          res = INV_REQ_ERROR;
25344          goto request_invite_cleanup;
25345       }
25346    }
25347 
25348    /* The option tags may be present in Supported: or Require: headers.
25349    Include the Require: option tags for further processing as well */
25350    p->sipoptions |= required_profile;
25351    p->reqsipoptions = required_profile;
25352 
25353    /* Check if this is a loop */
25354    if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && p->owner && (p->invitestate != INV_TERMINATED && p->invitestate != INV_CONFIRMED) && ast_channel_state(p->owner) != AST_STATE_UP) {
25355       /* This is a call to ourself.  Send ourselves an error code and stop
25356          processing immediately, as SIP really has no good mechanism for
25357          being able to call yourself */
25358       /* If pedantic is on, we need to check the tags. If they're different, this is
25359          in fact a forked call through a SIP proxy somewhere. */
25360       int different;
25361       const char *initial_rlpart2 = REQ_OFFSET_TO_STR(&p->initreq, rlpart2);
25362       const char *this_rlpart2 = REQ_OFFSET_TO_STR(req, rlpart2);
25363       if (sip_cfg.pedanticsipchecking)
25364          different = sip_uri_cmp(initial_rlpart2, this_rlpart2);
25365       else
25366          different = strcmp(initial_rlpart2, this_rlpart2);
25367       if (!different) {
25368          transmit_response(p, "482 Loop Detected", req);
25369          p->invitestate = INV_COMPLETED;
25370          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25371          res = INV_REQ_FAILED;
25372          goto request_invite_cleanup;
25373       } else {
25374          /*! This is a spiral. What we need to do is to just change the outgoing INVITE
25375           * so that it now routes to the new Request URI. Since we created the INVITE ourselves
25376           * that should be all we need to do.
25377           *
25378           * \todo XXX This needs to be reviewed.  YOu don't change the request URI really, you route the packet
25379           * correctly instead...
25380           */
25381          char *uri = ast_strdupa(this_rlpart2);
25382          char *at = strchr(uri, '@');
25383          char *peerorhost;
25384          ast_debug(2, "Potential spiral detected. Original RURI was %s, new RURI is %s\n", initial_rlpart2, this_rlpart2);
25385          transmit_response(p, "100 Trying", req);
25386          if (at) {
25387             *at = '\0';
25388          }
25389          /* Parse out "sip:" */
25390          if ((peerorhost = strchr(uri, ':'))) {
25391             *peerorhost++ = '\0';
25392          }
25393          ast_string_field_set(p, theirtag, NULL);
25394          /* Treat this as if there were a call forward instead...
25395           */
25396          ast_channel_call_forward_set(p->owner, peerorhost);
25397          ast_queue_control(p->owner, AST_CONTROL_BUSY);
25398          res = INV_REQ_FAILED;
25399          goto request_invite_cleanup;
25400       }
25401    }
25402 
25403    if (!req->ignore && p->pendinginvite) {
25404       if (!ast_test_flag(&p->flags[0], SIP_OUTGOING) && (p->invitestate == INV_COMPLETED || p->invitestate == INV_TERMINATED)) {
25405          /* What do these circumstances mean? We have received an INVITE for an "incoming" dialog for which we
25406           * have sent a final response. We have not yet received an ACK, though (which is why p->pendinginvite is non-zero).
25407           * We also know that the INVITE is not a retransmission, because otherwise the "ignore" flag would be set.
25408           * This means that either we are receiving a reinvite for a terminated dialog, or we are receiving an INVITE with
25409           * credentials based on one we challenged earlier.
25410           *
25411           * The action to take in either case is to treat the INVITE as though it contains an implicit ACK for the previous
25412           * transaction. Calling __sip_ack will take care of this by clearing the p->pendinginvite and removing the response
25413           * from the previous transaction from the list of outstanding packets.
25414           */
25415          __sip_ack(p, p->pendinginvite, 1, 0);
25416       } else {
25417          /* We already have a pending invite. Sorry. You are on hold. */
25418          p->glareinvite = seqno;
25419          if (p->rtp && find_sdp(req)) {
25420             struct ast_sockaddr addr;
25421             if (get_ip_and_port_from_sdp(req, SDP_AUDIO, &addr)) {
25422                ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Audio may not work properly on this call.\n");
25423             } else {
25424                ast_rtp_instance_set_alt_remote_address(p->rtp, &addr);
25425             }
25426             if (p->vrtp) {
25427                if (get_ip_and_port_from_sdp(req, SDP_VIDEO, &addr)) {
25428                   ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Video may not work properly on this call.\n");
25429                } else {
25430                   ast_rtp_instance_set_alt_remote_address(p->vrtp, &addr);
25431                }
25432             }
25433          }
25434          transmit_response_reliable(p, "491 Request Pending", req);
25435          check_via(p, req);
25436          ast_debug(1, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
25437          /* Don't destroy dialog here */
25438          res = INV_REQ_FAILED;
25439          goto request_invite_cleanup;
25440       }
25441    }
25442 
25443    p_replaces = sip_get_header(req, "Replaces");
25444    if (!ast_strlen_zero(p_replaces)) {
25445       /* We have a replaces header */
25446       char *ptr;
25447       char *fromtag = NULL;
25448       char *totag = NULL;
25449       char *start, *to;
25450       int error = 0;
25451 
25452       if (p->owner) {
25453          ast_debug(3, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
25454          transmit_response_reliable(p, "400 Bad request", req);   /* The best way to not not accept the transfer */
25455          check_via(p, req);
25456          copy_request(&p->initreq, req);
25457          /* Do not destroy existing call */
25458          res = INV_REQ_ERROR;
25459          goto request_invite_cleanup;
25460       }
25461 
25462       if (sipdebug)
25463          ast_debug(3, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
25464       /* Create a buffer we can manipulate */
25465       replace_id = ast_strdupa(p_replaces);
25466       ast_uri_decode(replace_id, ast_uri_sip_user);
25467 
25468       if (!p->refer && !sip_refer_alloc(p)) {
25469          transmit_response_reliable(p, "500 Server Internal Error", req);
25470          append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
25471          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25472          p->invitestate = INV_COMPLETED;
25473          res = INV_REQ_ERROR;
25474          check_via(p, req);
25475          copy_request(&p->initreq, req);
25476          goto request_invite_cleanup;
25477       }
25478 
25479       /*  Todo: (When we find phones that support this)
25480          if the replaces header contains ";early-only"
25481          we can only replace the call in early
25482          stage, not after it's up.
25483 
25484          If it's not in early mode, 486 Busy.
25485       */
25486 
25487       /* Skip leading whitespace */
25488       replace_id = ast_skip_blanks(replace_id);
25489 
25490       start = replace_id;
25491       while ( (ptr = strsep(&start, ";")) ) {
25492          ptr = ast_skip_blanks(ptr); /* XXX maybe unnecessary ? */
25493          if ( (to = strcasestr(ptr, "to-tag=") ) )
25494             totag = to + 7;   /* skip the keyword */
25495          else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
25496             fromtag = to + 9; /* skip the keyword */
25497             fromtag = strsep(&fromtag, "&"); /* trim what ? */
25498          }
25499       }
25500 
25501       if (sipdebug)
25502          ast_debug(4, "Invite/replaces: Will use Replace-Call-ID : %s Fromtag: %s Totag: %s\n",
25503                  replace_id,
25504                  fromtag ? fromtag : "<no from tag>",
25505                  totag ? totag : "<no to tag>");
25506 
25507       /* Try to find call that we are replacing.
25508          If we have a Replaces header, we need to cancel that call if we succeed with this call.
25509          First we cheat a little and look for a magic call-id from phones that support
25510          dialog-info+xml so we can do technology independent pickup... */
25511       if (strncmp(replace_id, "pickup-", 7) == 0) {
25512          struct sip_pvt *subscription = NULL;
25513          replace_id += 7; /* Worst case we are looking at \0 */
25514 
25515          if ((subscription = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
25516             ast_log(LOG_NOTICE, "Unable to find subscription with call-id: %s\n", replace_id);
25517             transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
25518             error = 1;
25519          } else {
25520             ast_log(LOG_NOTICE, "Trying to pick up %s@%s\n", subscription->exten, subscription->context);
25521             ast_copy_string(pickup.exten, subscription->exten, sizeof(pickup.exten));
25522             ast_copy_string(pickup.context, subscription->context, sizeof(pickup.context));
25523             sip_pvt_unlock(subscription);
25524             if (subscription->owner) {
25525                ast_channel_unlock(subscription->owner);
25526             }
25527             subscription = dialog_unref(subscription, "unref dialog subscription");
25528          }
25529       }
25530 
25531       /* This locks both refer_call pvt and refer_call pvt's owner!!!*/
25532       if (!error && ast_strlen_zero(pickup.exten) && (p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
25533          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
25534          transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
25535          error = 1;
25536       } else {
25537          refer_locked = 1;
25538       }
25539 
25540       /* The matched call is the call from the transferer to Asterisk .
25541          We want to bridge the bridged part of the call to the
25542          incoming invite, thus taking over the refered call */
25543 
25544       if (p->refer->refer_call == p) {
25545          ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
25546          transmit_response_reliable(p, "400 Bad request", req);   /* The best way to not not accept the transfer */
25547          error = 1;
25548       }
25549 
25550       if (!error && ast_strlen_zero(pickup.exten) && !p->refer->refer_call->owner) {
25551          /* Oops, someting wrong anyway, no owner, no call */
25552          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
25553          /* Check for better return code */
25554          transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replace)", req);
25555          error = 1;
25556       }
25557 
25558       if (!error && ast_strlen_zero(pickup.exten) && ast_channel_state(p->refer->refer_call->owner) != AST_STATE_RINGING && ast_channel_state(p->refer->refer_call->owner) != AST_STATE_RING && ast_channel_state(p->refer->refer_call->owner) != AST_STATE_UP) {
25559          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
25560          transmit_response_reliable(p, "603 Declined (Replaces)", req);
25561          error = 1;
25562       }
25563 
25564       if (error) {   /* Give up this dialog */
25565          append_history(p, "Xfer", "INVITE/Replace Failed.");
25566          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25567          sip_pvt_unlock(p);
25568          if (p->refer->refer_call) {
25569             sip_pvt_unlock(p->refer->refer_call);
25570             if (p->refer->refer_call->owner) {
25571                ast_channel_unlock(p->refer->refer_call->owner);
25572             }
25573             p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
25574          }
25575          refer_locked = 0;
25576          p->invitestate = INV_COMPLETED;
25577          res = INV_REQ_ERROR;
25578          check_via(p, req);
25579          copy_request(&p->initreq, req);
25580          goto request_invite_cleanup;
25581       }
25582    }
25583 
25584    /* Check if this is an INVITE that sets up a new dialog or
25585       a re-invite in an existing dialog */
25586 
25587    if (!req->ignore) {
25588       int newcall = (p->initreq.headers ? TRUE : FALSE);
25589 
25590       if (sip_cancel_destroy(p))
25591          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
25592       /* This also counts as a pending invite */
25593       p->pendinginvite = seqno;
25594       check_via(p, req);
25595 
25596       copy_request(&p->initreq, req);     /* Save this INVITE as the transaction basis */
25597       if (sipdebug)
25598          ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
25599       if (!p->owner) {  /* Not a re-invite */
25600          if (req->debug)
25601             ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
25602          if (newcall)
25603             append_history(p, "Invite", "New call: %s", p->callid);
25604          parse_ok_contact(p, req);
25605       } else { /* Re-invite on existing call */
25606          ast_clear_flag(&p->flags[0], SIP_OUTGOING);  /* This is now an inbound dialog */
25607          if (get_rpid(p, req)) {
25608             struct ast_party_connected_line connected;
25609             struct ast_set_party_connected_line update_connected;
25610 
25611             ast_party_connected_line_init(&connected);
25612             memset(&update_connected, 0, sizeof(update_connected));
25613 
25614             update_connected.id.number = 1;
25615             connected.id.number.valid = 1;
25616             connected.id.number.str = (char *) p->cid_num;
25617             connected.id.number.presentation = p->callingpres;
25618 
25619             update_connected.id.name = 1;
25620             connected.id.name.valid = 1;
25621             connected.id.name.str = (char *) p->cid_name;
25622             connected.id.name.presentation = p->callingpres;
25623 
25624             /* Invalidate any earlier private connected id representation */
25625             ast_set_party_id_all(&update_connected.priv);
25626 
25627             connected.id.tag = (char *) p->cid_tag;
25628             connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
25629             ast_channel_queue_connected_line_update(p->owner, &connected,
25630                &update_connected);
25631          }
25632          /* Handle SDP here if we already have an owner */
25633          if (find_sdp(req)) {
25634             if (process_sdp(p, req, SDP_T38_INITIATE)) {
25635                if (!ast_strlen_zero(sip_get_header(req, "Content-Encoding"))) {
25636                   /* Asterisk does not yet support any Content-Encoding methods.  Always
25637                    * attempt to process the sdp, but return a 415 if a Content-Encoding header
25638                    * was present after processing failed.  */
25639                   transmit_response_reliable(p, "415 Unsupported Media type", req);
25640                } else {
25641                   transmit_response_reliable(p, "488 Not acceptable here", req);
25642                }
25643                if (!p->lastinvite)
25644                   sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25645                res = INV_REQ_ERROR;
25646                goto request_invite_cleanup;
25647             }
25648             ast_queue_control(p->owner, AST_CONTROL_SRCUPDATE);
25649          } else {
25650             ast_format_cap_copy(p->jointcaps, p->caps);
25651             ast_debug(1, "Hm....  No sdp for the moment\n");
25652             /* Some devices signal they want to be put off hold by sending a re-invite
25653                *without* an SDP, which is supposed to mean "Go back to your state"
25654                and since they put os on remote hold, we go back to off hold */
25655             if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
25656                ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
25657                /* Activate a re-invite */
25658                ast_queue_frame(p->owner, &ast_null_frame);
25659                change_hold_state(p, req, FALSE, 0);
25660             }
25661          }
25662          if (p->do_history) /* This is a response, note what it was for */
25663             append_history(p, "ReInv", "Re-invite received");
25664       }
25665    } else if (req->debug)
25666       ast_verbose("Ignoring this INVITE request\n");
25667 
25668    if (!p->lastinvite && !req->ignore && !p->owner) {
25669       /* This is a new invite */
25670       /* Handle authentication if this is our first invite */
25671       int cc_recall_core_id = -1;
25672       set_pvt_allowed_methods(p, req);
25673       res = check_user_full(p, req, SIP_INVITE, e, XMIT_RELIABLE, addr, &authpeer);
25674       if (res == AUTH_CHALLENGE_SENT) {
25675          p->invitestate = INV_COMPLETED;     /* Needs to restart in another INVITE transaction */
25676          goto request_invite_cleanup;
25677       }
25678       if (res < 0) { /* Something failed in authentication */
25679          ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", sip_get_header(req, "From"));
25680          transmit_response_reliable(p, "403 Forbidden", req);
25681          p->invitestate = INV_COMPLETED;
25682          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25683          goto request_invite_cleanup;
25684       }
25685 
25686       /* Successful authentication and peer matching so record the peer related to this pvt (for easy access to peer settings) */
25687       if (p->relatedpeer) {
25688          p->relatedpeer = sip_unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
25689       }
25690       if (authpeer) {
25691          p->relatedpeer = sip_ref_peer(authpeer, "setting dialog's relatedpeer pointer");
25692       }
25693 
25694       req->authenticated = 1;
25695 
25696       /* We have a successful authentication, process the SDP portion if there is one */
25697       if (find_sdp(req)) {
25698          if (process_sdp(p, req, SDP_T38_INITIATE)) {
25699             /* Asterisk does not yet support any Content-Encoding methods.  Always
25700              * attempt to process the sdp, but return a 415 if a Content-Encoding header
25701              * was present after processing fails. */
25702             if (!ast_strlen_zero(sip_get_header(req, "Content-Encoding"))) {
25703                transmit_response_reliable(p, "415 Unsupported Media type", req);
25704             } else {
25705                /* Unacceptable codecs */
25706                transmit_response_reliable(p, "488 Not acceptable here", req);
25707             }
25708             p->invitestate = INV_COMPLETED;
25709             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25710             ast_debug(1, "No compatible codecs for this SIP call.\n");
25711             res = INV_REQ_ERROR;
25712             goto request_invite_cleanup;
25713          }
25714       } else { /* No SDP in invite, call control session */
25715          ast_format_cap_copy(p->jointcaps, p->caps);
25716          ast_debug(2, "No SDP in Invite, third party call control\n");
25717       }
25718 
25719       /* Initialize the context if it hasn't been already */
25720       if (ast_strlen_zero(p->context))
25721          ast_string_field_set(p, context, sip_cfg.default_context);
25722 
25723 
25724       /* Check number of concurrent calls -vs- incoming limit HERE */
25725       ast_debug(1, "Checking SIP call limits for device %s\n", p->username);
25726       if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
25727          if (res < 0) {
25728             ast_log(LOG_NOTICE, "Failed to place call for device %s, too many calls\n", p->username);
25729             transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
25730             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25731             p->invitestate = INV_COMPLETED;
25732 
25733             res = AUTH_SESSION_LIMIT;
25734          }
25735 
25736          goto request_invite_cleanup;
25737       }
25738       gotdest = get_destination(p, NULL, &cc_recall_core_id);  /* Get destination right away */
25739       extract_uri(p, req);       /* Get the Contact URI */
25740       build_contact(p);       /* Build our contact header */
25741 
25742       if (p->rtp) {
25743          ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
25744          ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
25745       }
25746 
25747       if (!replace_id && (gotdest != SIP_GET_DEST_EXTEN_FOUND)) { /* No matching extension found */
25748          switch(gotdest) {
25749          case SIP_GET_DEST_INVALID_URI:
25750             transmit_response_reliable(p, "416 Unsupported URI scheme", req);
25751             break;
25752          case SIP_GET_DEST_EXTEN_MATCHMORE:
25753             if (ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)
25754                == SIP_PAGE2_ALLOWOVERLAP_YES) {
25755                transmit_response_reliable(p, "484 Address Incomplete", req);
25756                break;
25757             }
25758             /*
25759              * XXX We would have to implement collecting more digits in
25760              * chan_sip for any other schemes of overlap dialing.
25761              *
25762              * For SIP_PAGE2_ALLOWOVERLAP_DTMF it is better to do this in
25763              * the dialplan using the Incomplete application rather than
25764              * having the channel driver do it.
25765              */
25766             /* Fall through */
25767          case SIP_GET_DEST_EXTEN_NOT_FOUND:
25768             {
25769                char *decoded_exten = ast_strdupa(p->exten);
25770                transmit_response_reliable(p, "404 Not Found", req);
25771                ast_uri_decode(decoded_exten, ast_uri_sip_user);
25772                ast_log(LOG_NOTICE, "Call from '%s' (%s) to extension"
25773                   " '%s' rejected because extension not found in context '%s'.\n",
25774                   S_OR(p->username, p->peername), ast_sockaddr_stringify(&p->recv), decoded_exten, p->context);
25775             }
25776             break;
25777          case SIP_GET_DEST_REFUSED:
25778          default:
25779             transmit_response_reliable(p, "403 Forbidden", req);
25780          } /* end switch */
25781 
25782          p->invitestate = INV_COMPLETED;
25783          update_call_counter(p, DEC_CALL_LIMIT);
25784          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25785          res = INV_REQ_FAILED;
25786          goto request_invite_cleanup;
25787       } else {
25788          /* If no extension was specified, use the s one */
25789          /* Basically for calling to IP/Host name only */
25790          if (ast_strlen_zero(p->exten))
25791             ast_string_field_set(p, exten, "s");
25792          /* Initialize our tag */
25793 
25794          make_our_tag(p);
25795 
25796          if (handle_request_invite_st(p, req, required, reinvite)) {
25797             p->invitestate = INV_COMPLETED;
25798             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25799             res = INV_REQ_ERROR;
25800             goto request_invite_cleanup;
25801          }
25802 
25803          /* First invitation - create the channel.  Allocation
25804           * failures are handled below. */
25805 
25806          c = sip_new(p, AST_STATE_DOWN, S_OR(p->peername, NULL), NULL, p->logger_callid);
25807 
25808          if (cc_recall_core_id != -1) {
25809             ast_setup_cc_recall_datastore(c, cc_recall_core_id);
25810             ast_cc_agent_set_interfaces_chanvar(c);
25811          }
25812          *recount = 1;
25813 
25814          /* Save Record-Route for any later requests we make on this dialogue */
25815          build_route(p, req, 0, 0);
25816 
25817          if (c) {
25818             ast_party_redirecting_init(&redirecting);
25819             memset(&update_redirecting, 0, sizeof(update_redirecting));
25820             change_redirecting_information(p, req, &redirecting, &update_redirecting,
25821                FALSE); /*Will return immediately if no Diversion header is present */
25822             ast_channel_set_redirecting(c, &redirecting, &update_redirecting);
25823             ast_party_redirecting_free(&redirecting);
25824          }
25825       }
25826    } else {
25827       ast_party_redirecting_init(&redirecting);
25828       memset(&update_redirecting, 0, sizeof(update_redirecting));
25829       if (sipdebug) {
25830          if (!req->ignore)
25831             ast_debug(2, "Got a SIP re-invite for call %s\n", p->callid);
25832          else
25833             ast_debug(2, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
25834       }
25835       if (!req->ignore)
25836          reinvite = 1;
25837 
25838       if (handle_request_invite_st(p, req, required, reinvite)) {
25839          p->invitestate = INV_COMPLETED;
25840          if (!p->lastinvite) {
25841             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25842          }
25843          res = INV_REQ_ERROR;
25844          goto request_invite_cleanup;
25845       }
25846 
25847       c = p->owner;
25848       change_redirecting_information(p, req, &redirecting, &update_redirecting, FALSE); /*Will return immediately if no Diversion header is present */
25849       if (c) {
25850          ast_channel_set_redirecting(c, &redirecting, &update_redirecting);
25851       }
25852       ast_party_redirecting_free(&redirecting);
25853    }
25854 
25855    /* Check if OLI/ANI-II is present in From: */
25856    parse_oli(req, p->owner);
25857 
25858    if (reinvite && p->stimer->st_active == TRUE) {
25859       restart_session_timer(p);
25860    }
25861 
25862    if (!req->ignore && p)
25863       p->lastinvite = seqno;
25864 
25865    if (c && replace_id) {  /* Attended transfer or call pickup - we're the target */
25866       if (!ast_strlen_zero(pickup.exten)) {
25867          append_history(p, "Xfer", "INVITE/Replace received");
25868 
25869          /* Let the caller know we're giving it a shot */
25870          transmit_response(p, "100 Trying", req);
25871          p->invitestate = INV_PROCEEDING;
25872          ast_setstate(c, AST_STATE_RING);
25873 
25874          /* Do the pickup itself */
25875          ast_channel_unlock(c);
25876          *nounlock = 1;
25877 
25878          /* since p->owner (c) is unlocked, we need to go ahead and unlock pvt for both
25879           * magic pickup and ast_hangup.  Both of these functions will attempt to lock
25880           * p->owner again, which can cause a deadlock if we already hold a lock on p.
25881           * Locking order is, channel then pvt.  Dead lock avoidance must be used if
25882           * called the other way around. */
25883          sip_pvt_unlock(p);
25884          do_magic_pickup(c, pickup.exten, pickup.context);
25885          /* Now we're either masqueraded or we failed to pickup, in either case we... */
25886          ast_hangup(c);
25887          sip_pvt_lock(p); /* pvt is expected to remain locked on return, so re-lock it */
25888 
25889          res = INV_REQ_FAILED;
25890          goto request_invite_cleanup;
25891       } else {
25892          /* Go and take over the target call */
25893          if (sipdebug)
25894             ast_debug(4, "Sending this call to the invite/replcaes handler %s\n", p->callid);
25895          res = handle_invite_replaces(p, req, addr, seqno, nounlock);
25896          refer_locked = 0;
25897          goto request_invite_cleanup;
25898       }
25899    }
25900 
25901 
25902    if (c) { /* We have a call  -either a new call or an old one (RE-INVITE) */
25903       enum ast_channel_state c_state = ast_channel_state(c);
25904 
25905       if (c_state != AST_STATE_UP && reinvite &&
25906          (p->invitestate == INV_TERMINATED || p->invitestate == INV_CONFIRMED)) {
25907          /* If these conditions are true, and the channel is still in the 'ringing'
25908           * state, then this likely means that we have a situation where the initial
25909           * INVITE transaction has completed *but* the channel's state has not yet been
25910           * changed to UP. The reason this could happen is if the reinvite is received
25911           * on the SIP socket prior to an application calling ast_read on this channel
25912           * to read the answer frame we earlier queued on it. In this case, the reinvite
25913           * is completely legitimate so we need to handle this the same as if the channel
25914           * were already UP. Thus we are purposely falling through to the AST_STATE_UP case.
25915           */
25916          c_state = AST_STATE_UP;
25917       }
25918 
25919       switch(c_state) {
25920       case AST_STATE_DOWN:
25921          ast_debug(2, "%s: New call is still down.... Trying... \n", ast_channel_name(c));
25922          transmit_provisional_response(p, "100 Trying", req, 0);
25923          p->invitestate = INV_PROCEEDING;
25924          ast_setstate(c, AST_STATE_RING);
25925          if (strcmp(p->exten, ast_pickup_ext())) { /* Call to extension -start pbx on this call */
25926             enum ast_pbx_result result;
25927 
25928             result = ast_pbx_start(c);
25929 
25930             switch(result) {
25931             case AST_PBX_FAILED:
25932                ast_log(LOG_WARNING, "Failed to start PBX :(\n");
25933                p->invitestate = INV_COMPLETED;
25934                transmit_response_reliable(p, "503 Unavailable", req);
25935                break;
25936             case AST_PBX_CALL_LIMIT:
25937                ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
25938                p->invitestate = INV_COMPLETED;
25939                transmit_response_reliable(p, "480 Temporarily Unavailable", req);
25940                res = AUTH_SESSION_LIMIT;
25941                break;
25942             case AST_PBX_SUCCESS:
25943                /* nothing to do */
25944                break;
25945             }
25946 
25947             if (result) {
25948 
25949                /* Unlock locks so ast_hangup can do its magic */
25950                ast_channel_unlock(c);
25951                *nounlock = 1;
25952                sip_pvt_unlock(p);
25953                ast_hangup(c);
25954                sip_pvt_lock(p);
25955                c = NULL;
25956             }
25957          } else { /* Pickup call in call group */
25958             if (sip_pickup(c)) {
25959                ast_log(LOG_WARNING, "Failed to start Group pickup by %s\n", ast_channel_name(c));
25960                transmit_response_reliable(p, "480 Temporarily Unavailable", req);
25961                sip_alreadygone(p);
25962                ast_channel_hangupcause_set(c, AST_CAUSE_FAILURE);
25963 
25964                /* Unlock locks so ast_hangup can do its magic */
25965                ast_channel_unlock(c);
25966                *nounlock = 1;
25967 
25968                p->invitestate = INV_COMPLETED;
25969                sip_pvt_unlock(p);
25970                ast_hangup(c);
25971                sip_pvt_lock(p);
25972                c = NULL;
25973             }
25974          }
25975          break;
25976       case AST_STATE_RING:
25977          transmit_provisional_response(p, "100 Trying", req, 0);
25978          p->invitestate = INV_PROCEEDING;
25979          break;
25980       case AST_STATE_RINGING:
25981          transmit_provisional_response(p, "180 Ringing", req, 0);
25982          p->invitestate = INV_PROCEEDING;
25983          break;
25984       case AST_STATE_UP:
25985          ast_debug(2, "%s: This call is UP.... \n", ast_channel_name(c));
25986 
25987          transmit_response(p, "100 Trying", req);
25988 
25989          if (p->t38.state == T38_PEER_REINVITE) {
25990             if (p->t38id > -1) {
25991                /* reset t38 abort timer */
25992                AST_SCHED_DEL_UNREF(sched, p->t38id, dialog_unref(p, "remove ref for t38id"));
25993             }
25994             p->t38id = ast_sched_add(sched, 5000, sip_t38_abort, dialog_ref(p, "passing dialog ptr into sched structure based on t38id for sip_t38_abort."));
25995          } else if (p->t38.state == T38_ENABLED) {
25996             ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
25997             transmit_response_with_t38_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ?  XMIT_UNRELIABLE : XMIT_CRITICAL)));
25998          } else if ((p->t38.state == T38_DISABLED) || (p->t38.state == T38_REJECTED)) {
25999             /* If this is not a re-invite or something to ignore - it's critical */
26000             if (p->srtp && !ast_test_flag(p->srtp, SRTP_CRYPTO_OFFER_OK)) {
26001                ast_log(LOG_WARNING, "Target does not support required crypto\n");
26002                transmit_response_reliable(p, "488 Not Acceptable Here (crypto)", req);
26003             } else {
26004                ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
26005                transmit_response_with_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ?  XMIT_UNRELIABLE : XMIT_CRITICAL)), p->session_modify == TRUE ? FALSE : TRUE, FALSE);
26006                ast_queue_control(p->owner, AST_CONTROL_UPDATE_RTP_PEER);
26007             }
26008          }
26009 
26010          p->invitestate = INV_TERMINATED;
26011          break;
26012       default:
26013          ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %u\n", ast_channel_state(c));
26014          transmit_response(p, "100 Trying", req);
26015          break;
26016       }
26017    } else {
26018       if (p && (p->autokillid == -1)) {
26019          const char *msg;
26020 
26021          if ((ast_format_cap_is_empty(p->jointcaps)))
26022             msg = "488 Not Acceptable Here (codec error)";
26023          else {
26024             ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
26025             msg = "503 Unavailable";
26026          }
26027          transmit_response_reliable(p, msg, req);
26028          p->invitestate = INV_COMPLETED;
26029          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
26030       }
26031    }
26032 
26033 request_invite_cleanup:
26034 
26035    if (refer_locked && p->refer && p->refer->refer_call) {
26036       sip_pvt_unlock(p->refer->refer_call);
26037       if (p->refer->refer_call->owner) {
26038          ast_channel_unlock(p->refer->refer_call->owner);
26039       }
26040       p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
26041    }
26042    if (authpeer) {
26043       authpeer = sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_invite authpeer");
26044    }
26045 
26046    return res;
26047 }
26048 
26049 /*! \brief Check for the presence of OLI tag(s) in the From header and set on the channel
26050  */
26051 static void parse_oli(struct sip_request *req, struct ast_channel *chan)
26052 {
26053    const char *from = NULL;
26054    const char *s = NULL;
26055    int ani2 = 0;
26056 
26057    if (!chan || !req) {
26058       /* null pointers are not helpful */
26059       return;
26060    }
26061 
26062    from = sip_get_header(req, "From");
26063    if (ast_strlen_zero(from)) {
26064       /* no From header */
26065       return;
26066    }
26067 
26068    /* Look for the possible OLI tags. */
26069    if ((s = strcasestr(from, ";isup-oli="))) {
26070       s += 10;
26071    } else if ((s = strcasestr(from, ";ss7-oli="))) {
26072       s += 9;
26073    } else if ((s = strcasestr(from, ";oli="))) {
26074       s += 5;
26075    }
26076 
26077    if (ast_strlen_zero(s)) {
26078       /* OLI tag is missing, or present with nothing following the '=' sign */
26079       return;
26080    }
26081 
26082    /* just in case OLI is quoted */
26083    if (*s == '\"') {
26084       s++;
26085    }
26086 
26087    if (sscanf(s, "%d", &ani2)) {
26088       ast_channel_caller(chan)->ani2 = ani2;
26089    }
26090 
26091    return;
26092 }
26093 
26094 /*! \brief  Find all call legs and bridge transferee with target
26095  * called from handle_request_refer
26096  *
26097  * \note this function assumes two locks to begin with, sip_pvt transferer and current.chan1 (the pvt's owner)... 
26098  * 2 additional locks are held at the beginning of the function, targetcall_pvt, and targetcall_pvt's owner
26099  * channel (which is stored in target.chan1).  These 2 locks _MUST_ be let go by the end of the function.  Do
26100  * not be confused into thinking a pvt's owner is the same thing as the channels locked at the beginning of
26101  * this function, after the masquerade this may not be true.  Be consistent and unlock only the exact same
26102  * pointers that were locked to begin with.
26103  *
26104  * If this function is successful, only the transferer pvt lock will remain on return.  Setting nounlock indicates
26105  * to handle_request_do() that the pvt's owner it locked does not require an unlock.
26106  */
26107 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, uint32_t seqno, int *nounlock)
26108 {
26109    struct sip_dual target;    /* Chan 1: Call from tranferer to Asterisk */
26110                /* Chan 2: Call from Asterisk to target */
26111    int res = 0;
26112    struct sip_pvt *targetcall_pvt;
26113    struct ast_party_connected_line connected_to_transferee;
26114    struct ast_party_connected_line connected_to_target;
26115    char transferer_linkedid[32];
26116    struct ast_channel *chans[2];
26117 
26118    /* Check if the call ID of the replaces header does exist locally */
26119    if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag,
26120       transferer->refer->replaces_callid_fromtag))) {
26121       if (transferer->refer->localtransfer) {
26122          /* We did not find the refered call. Sorry, can't accept then */
26123          /* Let's fake a response from someone else in order
26124             to follow the standard */
26125          transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
26126          append_history(transferer, "Xfer", "Refer failed");
26127          ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
26128          transferer->refer->status = REFER_FAILED;
26129          return -1;
26130       }
26131       /* Fall through for remote transfers that we did not find locally */
26132       ast_debug(3, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
26133       return 0;
26134    }
26135 
26136    /* Ok, we can accept this transfer */
26137    append_history(transferer, "Xfer", "Refer accepted");
26138    if (!targetcall_pvt->owner) { /* No active channel */
26139       ast_debug(4, "SIP attended transfer: Error: No owner of target call\n");
26140       /* Cancel transfer */
26141       transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
26142       append_history(transferer, "Xfer", "Refer failed");
26143       ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
26144       transferer->refer->status = REFER_FAILED;
26145       sip_pvt_unlock(targetcall_pvt);
26146       if (targetcall_pvt)
26147          ao2_t_ref(targetcall_pvt, -1, "Drop targetcall_pvt pointer");
26148       return -1;
26149    }
26150 
26151    /* We have a channel, find the bridge */
26152    target.chan1 = ast_channel_ref(targetcall_pvt->owner);            /* Transferer to Asterisk */
26153    target.chan2 = ast_bridged_channel(targetcall_pvt->owner);  /* Asterisk to target */
26154    if (target.chan2) {
26155       ast_channel_ref(target.chan2);
26156    }
26157 
26158    if (!target.chan2 || !(ast_channel_state(target.chan2) == AST_STATE_UP || ast_channel_state(target.chan2) == AST_STATE_RINGING) ) {
26159       /* Wrong state of new channel */
26160       if (target.chan2)
26161          ast_debug(4, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(ast_channel_state(target.chan2)));
26162       else if (ast_channel_state(target.chan1) != AST_STATE_RING)
26163          ast_debug(4, "SIP attended transfer: Error: No target channel\n");
26164       else
26165          ast_debug(4, "SIP attended transfer: Attempting transfer in ringing state\n");
26166    }
26167 
26168    /* Transfer */
26169    if (sipdebug) {
26170       if (current->chan2)  /* We have two bridges */
26171          ast_debug(4, "SIP attended transfer: trying to bridge %s and %s\n", ast_channel_name(target.chan1), ast_channel_name(current->chan2));
26172       else        /* One bridge, propably transfer of IVR/voicemail etc */
26173          ast_debug(4, "SIP attended transfer: trying to make %s take over (masq) %s\n", ast_channel_name(target.chan1), ast_channel_name(current->chan1));
26174    }
26175 
26176    ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);   /* Delay hangup */
26177 
26178    ast_copy_string(transferer_linkedid, ast_channel_linkedid(transferer->owner), sizeof(transferer_linkedid));
26179 
26180    /* Perform the transfer */
26181    chans[0] = transferer->owner;
26182    chans[1] = target.chan1;
26183    ast_manager_event_multichan(EVENT_FLAG_CALL, "Transfer", 2, chans,
26184       "TransferMethod: SIP\r\n"
26185       "TransferType: Attended\r\n"
26186       "Channel: %s\r\n"
26187       "Uniqueid: %s\r\n"
26188       "SIP-Callid: %s\r\n"
26189       "TargetChannel: %s\r\n"
26190       "TargetUniqueid: %s\r\n",
26191       ast_channel_name(transferer->owner),
26192       ast_channel_uniqueid(transferer->owner),
26193       transferer->callid,
26194       ast_channel_name(target.chan1),
26195       ast_channel_uniqueid(target.chan1));
26196    ast_party_connected_line_init(&connected_to_transferee);
26197    ast_party_connected_line_init(&connected_to_target);
26198    /* No need to lock current->chan1 here since it was locked in sipsock_read */
26199    ast_party_connected_line_copy(&connected_to_transferee, ast_channel_connected(current->chan1));
26200    /* No need to lock target.chan1 here since it was locked in get_sip_pvt_byid_locked */
26201    ast_party_connected_line_copy(&connected_to_target, ast_channel_connected(target.chan1));
26202    /* Reset any earlier private connected id representation */
26203    ast_party_id_reset(&connected_to_transferee.priv);
26204    ast_party_id_reset(&connected_to_target.priv);
26205    connected_to_target.source = connected_to_transferee.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
26206    res = attempt_transfer(current, &target);
26207    if (res) {
26208       /* Failed transfer */
26209       transmit_notify_with_sipfrag(transferer, seqno, "486 Busy Here", TRUE);
26210       append_history(transferer, "Xfer", "Refer failed");
26211       ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
26212       /* if transfer failed, go ahead and unlock targetcall_pvt and it's owner channel */
26213       sip_pvt_unlock(targetcall_pvt);
26214       ast_channel_unlock(target.chan1);
26215    } else {
26216       /* Transfer succeeded! */
26217       const char *xfersound = pbx_builtin_getvar_helper(target.chan1, "ATTENDED_TRANSFER_COMPLETE_SOUND");
26218 
26219       /* target.chan1 was locked in get_sip_pvt_byid_locked, do not unlock target.chan1 before this */
26220       ast_cel_report_event(target.chan1, AST_CEL_ATTENDEDTRANSFER, NULL, transferer_linkedid, target.chan2);
26221 
26222       /* Tell transferer that we're done. */
26223       transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
26224       append_history(transferer, "Xfer", "Refer succeeded");
26225       transferer->refer->status = REFER_200OK;
26226       if (target.chan2 && !ast_strlen_zero(xfersound) && ast_streamfile(target.chan2, xfersound, ast_channel_language(target.chan2)) >= 0) {
26227          ast_waitstream(target.chan2, "");
26228       }
26229 
26230       /* By forcing the masquerade, we know that target.chan1 and target.chan2 are bridged. We then
26231        * can queue connected line updates where they need to go.
26232        *
26233        * before a masquerade, all channel and pvt locks must be unlocked.  Any recursive
26234        * channel locks held before this function invalidates channel container locking order.
26235        * Since we are unlocking both the pvt (transferer) and its owner channel (current.chan1)
26236        * it is possible for current.chan1 to be destroyed in the pbx thread.  To prevent this
26237        * we must give c a reference before any unlocking takes place.
26238        */
26239 
26240       ast_channel_ref(current->chan1);
26241       ast_channel_unlock(current->chan1); /* current.chan1 is p->owner before the masq, it was locked by socket_read()*/
26242       ast_channel_unlock(target.chan1);
26243       *nounlock = 1;  /* we just unlocked the dialog's channel and have no plans of locking it again. */
26244       sip_pvt_unlock(targetcall_pvt);
26245       sip_pvt_unlock(transferer);
26246 
26247       ast_do_masquerade(target.chan1);
26248 
26249       if (target.chan2) {
26250          ast_indicate(target.chan2, AST_CONTROL_UNHOLD);
26251       }
26252 
26253       if (current->chan2 && ast_channel_state(current->chan2) == AST_STATE_RING) {
26254          ast_indicate(target.chan1, AST_CONTROL_RINGING);
26255       }
26256 
26257       if (target.chan2) {
26258          ast_channel_queue_connected_line_update(target.chan1, &connected_to_transferee, NULL);
26259          ast_channel_queue_connected_line_update(target.chan2, &connected_to_target, NULL);
26260       } else {
26261          /* Since target.chan1 isn't actually connected to another channel, there is no way for us
26262           * to queue a frame so that its connected line status will be updated.
26263           *
26264           * Instead, we use the somewhat hackish approach of using a special control frame type that
26265           * instructs ast_read to perform a specific action. In this case, the frame we queue tells
26266           * ast_read to call the connected line interception macro configured for target.chan1.
26267           */
26268          struct ast_control_read_action_payload *frame_payload;
26269          int payload_size;
26270          int frame_size;
26271          unsigned char connected_line_data[1024];
26272          payload_size = ast_connected_line_build_data(connected_line_data,
26273             sizeof(connected_line_data), &connected_to_target, NULL);
26274          frame_size = payload_size + sizeof(*frame_payload);
26275          if (payload_size != -1) {
26276             frame_payload = ast_alloca(frame_size);
26277             frame_payload->payload_size = payload_size;
26278             memcpy(frame_payload->payload, connected_line_data, payload_size);
26279             frame_payload->action = AST_FRAME_READ_ACTION_CONNECTED_LINE_MACRO;
26280             ast_queue_control_data(target.chan1, AST_CONTROL_READ_ACTION, frame_payload, frame_size);
26281          }
26282          /* In addition to queueing the read action frame so that target.chan1's connected line info
26283           * will be updated, we also are going to queue a plain old connected line update on target.chan1. This
26284           * way, either Dial or Queue can apply this connected line update to the outgoing ringing channel.
26285           */
26286          ast_channel_queue_connected_line_update(target.chan1, &connected_to_transferee, NULL);
26287 
26288       }
26289       sip_pvt_lock(transferer); /* the transferer pvt is expected to remain locked on return */
26290 
26291       ast_channel_unref(current->chan1);
26292    }
26293 
26294    /* at this point if the transfer is successful only the transferer pvt should be locked. */
26295    ast_party_connected_line_free(&connected_to_target);
26296    ast_party_connected_line_free(&connected_to_transferee);
26297    ast_channel_unref(target.chan1);
26298    if (target.chan2) {
26299       ast_channel_unref(target.chan2);
26300    }
26301    if (targetcall_pvt)
26302       ao2_t_ref(targetcall_pvt, -1, "drop targetcall_pvt");
26303    return 1;
26304 }
26305 
26306 
26307 /*! \brief Handle incoming REFER request */
26308 /*! \page SIP_REFER SIP transfer Support (REFER)
26309 
26310    REFER is used for call transfer in SIP. We get a REFER
26311    to place a new call with an INVITE somwhere and then
26312    keep the transferor up-to-date of the transfer. If the
26313    transfer fails, get back on line with the orginal call.
26314 
26315    - REFER can be sent outside or inside of a dialog.
26316      Asterisk only accepts REFER inside of a dialog.
26317 
26318    - If we get a replaces header, it is an attended transfer
26319 
26320    \par Blind transfers
26321    The transferor provides the transferee
26322    with the transfer targets contact. The signalling between
26323    transferer or transferee should not be cancelled, so the
26324    call is recoverable if the transfer target can not be reached
26325    by the transferee.
26326 
26327    In this case, Asterisk receives a TRANSFER from
26328    the transferor, thus is the transferee. We should
26329    try to set up a call to the contact provided
26330    and if that fails, re-connect the current session.
26331    If the new call is set up, we issue a hangup.
26332    In this scenario, we are following section 5.2
26333    in the SIP CC Transfer draft. (Transfer without
26334    a GRUU)
26335 
26336    \par Transfer with consultation hold
26337    In this case, the transferor
26338    talks to the transfer target before the transfer takes place.
26339    This is implemented with SIP hold and transfer.
26340    Note: The invite From: string could indicate a transfer.
26341    (Section 6. Transfer with consultation hold)
26342    The transferor places the transferee on hold, starts a call
26343    with the transfer target to alert them to the impending
26344    transfer, terminates the connection with the target, then
26345    proceeds with the transfer (as in Blind transfer above)
26346 
26347    \par Attended transfer
26348    The transferor places the transferee
26349    on hold, calls the transfer target to alert them,
26350    places the target on hold, then proceeds with the transfer
26351    using a Replaces header field in the Refer-to header. This
26352    will force the transfee to send an Invite to the target,
26353    with a replaces header that instructs the target to
26354    hangup the call between the transferor and the target.
26355    In this case, the Refer/to: uses the AOR address. (The same
26356    URI that the transferee used to establish the session with
26357    the transfer target (To: ). The Require: replaces header should
26358    be in the INVITE to avoid the wrong UA in a forked SIP proxy
26359    scenario to answer and have no call to replace with.
26360 
26361    The referred-by header is *NOT* required, but if we get it,
26362    can be copied into the INVITE to the transfer target to
26363    inform the target about the transferor
26364 
26365    "Any REFER request has to be appropriately authenticated.".
26366    
26367    We can't destroy dialogs, since we want the call to continue.
26368    
26369    */
26370 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, uint32_t seqno, int *nounlock)
26371 {
26372    /*!
26373     * Chan1: Call between asterisk and transferer
26374     * Chan2: Call between asterisk and transferee
26375     */
26376    struct sip_dual current = { 0, };
26377    struct ast_channel *chans[2] = { 0, };
26378    char *refer_to = NULL;
26379    char *refer_to_domain = NULL;
26380    char *refer_to_context = NULL;
26381    char *referred_by = NULL;
26382    char *callid = NULL;
26383    int localtransfer = 0;
26384    int attendedtransfer = 0;
26385    int res = 0;
26386    struct ast_party_redirecting redirecting;
26387    struct ast_set_party_redirecting update_redirecting;
26388 
26389    if (req->debug) {
26390       ast_verbose("Call %s got a SIP call transfer from %s: (REFER)!\n",
26391          p->callid,
26392          ast_test_flag(&p->flags[0], SIP_OUTGOING) ? "callee" : "caller");
26393    }
26394 
26395    if (!p->owner) {
26396       /* This is a REFER outside of an existing SIP dialog */
26397       /* We can't handle that, so decline it */
26398       ast_debug(3, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
26399       transmit_response(p, "603 Declined (No dialog)", req);
26400       if (!req->ignore) {
26401          append_history(p, "Xfer", "Refer failed. Outside of dialog.");
26402          sip_alreadygone(p);
26403          pvt_set_needdestroy(p, "outside of dialog");
26404       }
26405       res = 0;
26406       goto handle_refer_cleanup;
26407    }
26408 
26409    /* Check if transfer is allowed from this device */
26410    if (p->allowtransfer == TRANSFER_CLOSED ) {
26411       /* Transfer not allowed, decline */
26412       transmit_response(p, "603 Declined (policy)", req);
26413       append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
26414       /* Do not destroy SIP session */
26415       res = 0;
26416       goto handle_refer_cleanup;
26417    }
26418 
26419    if (!req->ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
26420       /* Already have a pending REFER */
26421       transmit_response(p, "491 Request pending", req);
26422       append_history(p, "Xfer", "Refer failed. Request pending.");
26423       res = 0;
26424       goto handle_refer_cleanup;
26425    }
26426 
26427    /* Allocate memory for call transfer data */
26428    if (!p->refer && !sip_refer_alloc(p)) {
26429       transmit_response(p, "500 Internal Server Error", req);
26430       append_history(p, "Xfer", "Refer failed. Memory allocation error.");
26431       res = -3;
26432       goto handle_refer_cleanup;
26433    }
26434 
26435    res = get_refer_info(p, req); /* Extract headers */
26436 
26437    p->refer->status = REFER_SENT;
26438 
26439    if (res != 0) {
26440       switch (res) {
26441       case -2: /* Syntax error */
26442          transmit_response(p, "400 Bad Request (Refer-to missing)", req);
26443          append_history(p, "Xfer", "Refer failed. Refer-to missing.");
26444          if (req->debug) {
26445             ast_debug(1, "SIP transfer to black hole can't be handled (no refer-to: )\n");
26446          }
26447          break;
26448       case -3:
26449          transmit_response(p, "603 Declined (Non sip: uri)", req);
26450          append_history(p, "Xfer", "Refer failed. Non SIP uri");
26451          if (req->debug) {
26452             ast_debug(1, "SIP transfer to non-SIP uri denied\n");
26453          }
26454          break;
26455       default:
26456          /* Refer-to extension not found, fake a failed transfer */
26457          transmit_response(p, "202 Accepted", req);
26458          append_history(p, "Xfer", "Refer failed. Bad extension.");
26459          transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
26460          ast_clear_flag(&p->flags[0], SIP_GOTREFER);
26461          if (req->debug) {
26462             ast_debug(1, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
26463          }
26464          break;
26465       }
26466       res = 0;
26467       goto handle_refer_cleanup;
26468    }
26469    if (ast_strlen_zero(p->context)) {
26470       ast_string_field_set(p, context, sip_cfg.default_context);
26471    }
26472 
26473    /* If we do not support SIP domains, all transfers are local */
26474    if (sip_cfg.allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
26475       p->refer->localtransfer = 1;
26476       if (sipdebug) {
26477          ast_debug(3, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
26478       }
26479    } else if (AST_LIST_EMPTY(&domain_list) || check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
26480       /* This PBX doesn't bother with SIP domains or domain is local, so this transfer is local */
26481       p->refer->localtransfer = 1;
26482    } else if (sipdebug) {
26483       ast_debug(3, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
26484    }
26485 
26486    /* Is this a repeat of a current request? Ignore it */
26487    /* Don't know what else to do right now. */
26488    if (req->ignore) {
26489       goto handle_refer_cleanup;
26490    }
26491 
26492    /* If this is a blind transfer, we have the following
26493    channels to work with:
26494    - chan1, chan2: The current call between transferer and transferee (2 channels)
26495    - target_channel: A new call from the transferee to the target (1 channel)
26496    We need to stay tuned to what happens in order to be able
26497    to bring back the call to the transferer */
26498 
26499    /* If this is a attended transfer, we should have all call legs within reach:
26500    - chan1, chan2: The call between the transferer and transferee (2 channels)
26501    - target_channel, targetcall_pvt: The call between the transferer and the target (2 channels)
26502    We want to bridge chan2 with targetcall_pvt!
26503    
26504    The replaces call id in the refer message points
26505    to the call leg between Asterisk and the transferer.
26506    So we need to connect the target and the transferee channel
26507    and hangup the two other channels silently
26508    
26509    If the target is non-local, the call ID could be on a remote
26510    machine and we need to send an INVITE with replaces to the
26511    target. We basically handle this as a blind transfer
26512    and let the sip_call function catch that we need replaces
26513    header in the INVITE.
26514    */
26515 
26516    /* Get the transferer's channel */
26517    chans[0] = current.chan1 = p->owner;
26518 
26519    /* Find the other part of the bridge (2) - transferee */
26520    chans[1] = current.chan2 = ast_bridged_channel(current.chan1);
26521 
26522    ast_channel_ref(current.chan1);
26523    if (current.chan2) {
26524       ast_channel_ref(current.chan2);
26525    }
26526 
26527    if (sipdebug) {
26528       ast_debug(3, "SIP %s transfer: Transferer channel %s, transferee channel %s\n",
26529          p->refer->attendedtransfer ? "attended" : "blind",
26530          ast_channel_name(current.chan1),
26531          current.chan2 ? ast_channel_name(current.chan2) : "<none>");
26532    }
26533 
26534    if (!current.chan2 && !p->refer->attendedtransfer) {
26535       /* No bridged channel, propably IVR or echo or similar... */
26536       /* Guess we should masquerade or something here */
26537       /* Until we figure it out, refuse transfer of such calls */
26538       if (sipdebug) {
26539          ast_debug(3, "Refused SIP transfer on non-bridged channel.\n");
26540       }
26541       p->refer->status = REFER_FAILED;
26542       append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
26543       transmit_response(p, "603 Declined", req);
26544       res = -1;
26545       goto handle_refer_cleanup;
26546    }
26547 
26548    if (current.chan2) {
26549       if (sipdebug) {
26550          ast_debug(4, "Got SIP transfer, applying to bridged peer '%s'\n", ast_channel_name(current.chan2));
26551       }
26552       ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
26553    }
26554 
26555    ast_set_flag(&p->flags[0], SIP_GOTREFER);
26556 
26557    /* From here on failures will be indicated with NOTIFY requests */
26558    transmit_response(p, "202 Accepted", req);
26559 
26560    /* Attended transfer: Find all call legs and bridge transferee with target*/
26561    if (p->refer->attendedtransfer) {
26562       /* both p and p->owner _MUST_ be locked while calling local_attended_transfer */
26563       if ((res = local_attended_transfer(p, &current, req, seqno, nounlock))) {
26564          goto handle_refer_cleanup; /* We're done with the transfer */
26565       }
26566       /* Fall through for remote transfers that we did not find locally */
26567       if (sipdebug) {
26568          ast_debug(4, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
26569       }
26570       /* Fallthrough if we can't find the call leg internally */
26571    }
26572 
26573    /* Copy data we can not safely access after letting the pvt lock go. */
26574    refer_to = ast_strdupa(p->refer->refer_to);
26575    refer_to_domain = ast_strdupa(p->refer->refer_to_domain);
26576    refer_to_context = ast_strdupa(p->refer->refer_to_context);
26577    referred_by = ast_strdupa(p->refer->referred_by);
26578    callid = ast_strdupa(p->callid);
26579    localtransfer = p->refer->localtransfer;
26580    attendedtransfer = p->refer->attendedtransfer;
26581 
26582    if (!*nounlock) {
26583       ast_channel_unlock(p->owner);
26584       *nounlock = 1;
26585    }
26586    sip_pvt_unlock(p);
26587 
26588    /* Parking a call.  DO NOT hold any locks while calling ast_parking_ext_valid() */
26589    if (localtransfer && ast_parking_ext_valid(refer_to, current.chan1, refer_to_context)) {
26590       sip_pvt_lock(p);
26591       ast_clear_flag(&p->flags[0], SIP_GOTREFER);
26592       p->refer->status = REFER_200OK;
26593       append_history(p, "Xfer", "REFER to call parking.");
26594       sip_pvt_unlock(p);
26595 
26596       ast_manager_event_multichan(EVENT_FLAG_CALL, "Transfer", 2, chans,
26597          "TransferMethod: SIP\r\n"
26598          "TransferType: Blind\r\n"
26599          "Channel: %s\r\n"
26600          "Uniqueid: %s\r\n"
26601          "SIP-Callid: %s\r\n"
26602          "TargetChannel: %s\r\n"
26603          "TargetUniqueid: %s\r\n"
26604          "TransferExten: %s\r\n"
26605          "Transfer2Parking: Yes\r\n",
26606          ast_channel_name(current.chan1),
26607          ast_channel_uniqueid(current.chan1),
26608          callid,
26609          ast_channel_name(current.chan2),
26610          ast_channel_uniqueid(current.chan2),
26611          refer_to);
26612 
26613       if (sipdebug) {
26614          ast_debug(4, "SIP transfer to parking: trying to park %s. Parked by %s\n", ast_channel_name(current.chan2), ast_channel_name(current.chan1));
26615       }
26616 
26617       /* DO NOT hold any locks while calling sip_park */
26618       if (sip_park(current.chan2, current.chan1, req, seqno, refer_to, refer_to_context)) {
26619          sip_pvt_lock(p);
26620          transmit_notify_with_sipfrag(p, seqno, "500 Internal Server Error", TRUE);
26621       } else {
26622          sip_pvt_lock(p);
26623       }
26624       goto handle_refer_cleanup;
26625    }
26626 
26627    /* Blind transfers and remote attended xfers.
26628     * Locks should not be held while calling pbx_builtin_setvar_helper. This function
26629     * locks the channel being passed into it.*/
26630    if (current.chan1 && current.chan2) {
26631       ast_debug(3, "chan1->name: %s\n", ast_channel_name(current.chan1));
26632       pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", ast_channel_name(current.chan2));
26633    }
26634 
26635    if (current.chan2) {
26636       pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", ast_channel_name(current.chan1));
26637       pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", refer_to_domain);
26638       pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
26639       /* One for the new channel */
26640       pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
26641       /* Attended transfer to remote host, prepare headers for the INVITE */
26642       if (!ast_strlen_zero(referred_by)) {
26643          pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", referred_by);
26644       }
26645 
26646       /* When a call is transferred to voicemail from a Digium phone, there may be
26647        * a Diversion header present in the REFER with an appropriate reason parameter
26648        * set. We need to update the redirecting information appropriately.
26649        */
26650       ast_channel_lock(p->owner);
26651       sip_pvt_lock(p);
26652       ast_party_redirecting_init(&redirecting);
26653       memset(&update_redirecting, 0, sizeof(update_redirecting));
26654       change_redirecting_information(p, req, &redirecting, &update_redirecting, FALSE);
26655 
26656       /* Do not hold the pvt lock during a call that causes an indicate or an async_goto.
26657        * Those functions lock channels which will invalidate locking order if the pvt lock
26658        * is held.*/
26659       sip_pvt_unlock(p);
26660       ast_channel_unlock(p->owner);
26661       ast_channel_update_redirecting(current.chan2, &redirecting, &update_redirecting);
26662       ast_party_redirecting_free(&redirecting);
26663    }
26664 
26665    sip_pvt_lock(p);
26666    /* Generate a Replaces string to be used in the INVITE during attended transfer */
26667    if (!ast_strlen_zero(p->refer->replaces_callid)) {
26668       char tempheader[SIPBUFSIZE];
26669       snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid,
26670          p->refer->replaces_callid_totag ? ";to-tag=" : "",
26671          p->refer->replaces_callid_totag,
26672          p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
26673          p->refer->replaces_callid_fromtag);
26674 
26675       if (current.chan2) {
26676          sip_pvt_unlock(p);
26677          pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader);
26678          sip_pvt_lock(p);
26679       }
26680    }
26681 
26682    /* Connect the call */
26683 
26684    /* FAKE ringing if not attended transfer */
26685    if (!p->refer->attendedtransfer) {
26686       transmit_notify_with_sipfrag(p, seqno, "180 Ringing", FALSE);
26687    }
26688 
26689    /* For blind transfer, this will lead to a new call */
26690    /* For attended transfer to remote host, this will lead to
26691       a new SIP call with a replaces header, if the dial plan allows it
26692    */
26693    if (!current.chan2) {
26694       /* We have no bridge, so we're talking with Asterisk somehow */
26695       /* We need to masquerade this call */
26696       /* What to do to fix this situation:
26697          * Set up the new call in a new channel
26698          * Let the new channel masq into this channel
26699          Please add that code here :-)
26700       */
26701       p->refer->status = REFER_FAILED;
26702       transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
26703       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
26704       append_history(p, "Xfer", "Refer failed (only bridged calls).");
26705       res = -1;
26706       goto handle_refer_cleanup;
26707    }
26708    ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);   /* Delay hangup */
26709 
26710    sip_pvt_unlock(p);
26711 
26712    /* For blind transfers, move the call to the new extensions. For attended transfers on multiple
26713     * servers - generate an INVITE with Replaces. Either way, let the dial plan decided
26714     * indicate before masquerade so the indication actually makes it to the real channel
26715     * when using local channels with MOH passthru */
26716    ast_indicate(current.chan2, AST_CONTROL_UNHOLD);
26717    res = ast_async_goto(current.chan2, refer_to_context, refer_to, 1);
26718 
26719    if (!res) {
26720       ast_manager_event_multichan(EVENT_FLAG_CALL, "Transfer", 2, chans,
26721          "TransferMethod: SIP\r\n"
26722          "TransferType: Blind\r\n"
26723          "Channel: %s\r\n"
26724          "Uniqueid: %s\r\n"
26725          "SIP-Callid: %s\r\n"
26726          "TargetChannel: %s\r\n"
26727          "TargetUniqueid: %s\r\n"
26728          "TransferExten: %s\r\n"
26729          "TransferContext: %s\r\n",
26730          ast_channel_name(current.chan1),
26731          ast_channel_uniqueid(current.chan1),
26732          callid,
26733          ast_channel_name(current.chan2),
26734          ast_channel_uniqueid(current.chan2),
26735          refer_to,
26736          refer_to_context);
26737       /* Success  - we have a new channel */
26738       ast_debug(3, "%s transfer succeeded. Telling transferer.\n", attendedtransfer? "Attended" : "Blind");
26739 
26740       /* XXX - what to we put in CEL 'extra' for attended transfers to external systems? NULL for now */
26741       ast_channel_lock(current.chan1);
26742       ast_cel_report_event(current.chan1, p->refer->attendedtransfer? AST_CEL_ATTENDEDTRANSFER : AST_CEL_BLINDTRANSFER, NULL, p->refer->attendedtransfer ? NULL : p->refer->refer_to, current.chan2);
26743       ast_channel_unlock(current.chan1);
26744 
26745       sip_pvt_lock(p);
26746       transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
26747       if (p->refer->localtransfer) {
26748          p->refer->status = REFER_200OK;
26749       }
26750       if (p->owner) {
26751          ast_channel_hangupcause_set(p->owner, AST_CAUSE_NORMAL_CLEARING);
26752       }
26753       append_history(p, "Xfer", "Refer succeeded.");
26754       ast_clear_flag(&p->flags[0], SIP_GOTREFER);
26755       /* Do not hangup call, the other side do that when we say 200 OK */
26756       /* We could possibly implement a timer here, auto congestion */
26757       res = 0;
26758    } else {
26759       sip_pvt_lock(p);
26760       ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Don't delay hangup */
26761       ast_debug(3, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
26762       append_history(p, "Xfer", "Refer failed.");
26763       /* Failure of some kind */
26764       p->refer->status = REFER_FAILED;
26765       transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
26766       ast_clear_flag(&p->flags[0], SIP_GOTREFER);
26767       res = -1;
26768    }
26769 
26770 handle_refer_cleanup:
26771    if (current.chan1) {
26772       ast_channel_unref(current.chan1);
26773    }
26774    if (current.chan2) {
26775       ast_channel_unref(current.chan2);
26776    }
26777 
26778    /* Make sure we exit with the pvt locked */
26779    return res;
26780 }
26781 
26782 /*! \brief Handle incoming CANCEL request */
26783 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
26784 {
26785 
26786    check_via(p, req);
26787    sip_alreadygone(p);
26788 
26789    if (p->owner && ast_channel_state(p->owner) == AST_STATE_UP) {
26790       /* This call is up, cancel is ignored, we need a bye */
26791       transmit_response(p, "200 OK", req);
26792       ast_debug(1, "Got CANCEL on an answered call. Ignoring... \n");
26793       return 0;
26794    }
26795 
26796    /* At this point, we could have cancelled the invite at the same time
26797       as the other side sends a CANCEL. Our final reply with error code
26798       might not have been received by the other side before the CANCEL
26799       was sent, so let's just give up retransmissions and waiting for
26800       ACK on our error code. The call is hanging up any way. */
26801    if (p->invitestate == INV_TERMINATED || p->invitestate == INV_COMPLETED) {
26802       __sip_pretend_ack(p);
26803    }
26804    if (p->invitestate != INV_TERMINATED)
26805       p->invitestate = INV_CANCELLED;
26806 
26807    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD))
26808       update_call_counter(p, DEC_CALL_LIMIT);
26809 
26810    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
26811    if (p->owner) {
26812       sip_queue_hangup_cause(p, 0);
26813    } else {
26814       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
26815    }
26816    if (ast_str_strlen(p->initreq.data) > 0) {
26817       struct sip_pkt *pkt, *prev_pkt;
26818       /* If the CANCEL we are receiving is a retransmission, and we already have scheduled
26819        * a reliable 487, then we don't want to schedule another one on top of the previous
26820        * one.
26821        *
26822        * As odd as this may sound, we can't rely on the previously-transmitted "reliable"
26823        * response in this situation. What if we've sent all of our reliable responses
26824        * already and now all of a sudden, we get this second CANCEL?
26825        *
26826        * The only way to do this correctly is to cancel our previously-scheduled reliably-
26827        * transmitted response and send a new one in its place.
26828        */
26829       for (pkt = p->packets, prev_pkt = NULL; pkt; prev_pkt = pkt, pkt = pkt->next) {
26830          if (pkt->seqno == p->lastinvite && pkt->response_code == 487) {
26831             AST_SCHED_DEL(sched, pkt->retransid);
26832             UNLINK(pkt, p->packets, prev_pkt);
26833             dialog_unref(pkt->owner, "unref packet->owner from dialog");
26834             if (pkt->data) {
26835                ast_free(pkt->data);
26836             }
26837             ast_free(pkt);
26838             break;
26839          }
26840       }
26841       transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
26842       transmit_response(p, "200 OK", req);
26843       return 1;
26844    } else {
26845       transmit_response(p, "481 Call Leg Does Not Exist", req);
26846       return 0;
26847    }
26848 }
26849 
26850 /*! \brief Handle incoming BYE request */
26851 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
26852 {
26853    struct ast_channel *c=NULL;
26854    int res;
26855    struct ast_channel *bridged_to;
26856    const char *required;
26857 
26858    /* If we have an INCOMING invite that we haven't answered, terminate that transaction */
26859    if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !req->ignore) {
26860       transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
26861    }
26862 
26863    __sip_pretend_ack(p);
26864 
26865    p->invitestate = INV_TERMINATED;
26866 
26867    copy_request(&p->initreq, req);
26868    if (sipdebug)
26869       ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
26870    check_via(p, req);
26871    sip_alreadygone(p);
26872 
26873    /* Get RTCP quality before end of call */
26874    if (p->do_history || p->owner) {
26875       char quality_buf[AST_MAX_USER_FIELD], *quality;
26876       struct ast_channel *bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
26877 
26878       /* We need to get the lock on bridge because ast_rtp_instance_set_stats_vars will attempt
26879        * to lock the bridge. This may get hairy...
26880        */
26881       while (bridge && ast_channel_trylock(bridge)) {
26882          ast_channel_unlock(p->owner);
26883          do {
26884             /* Can't use DEADLOCK_AVOIDANCE since p is an ao2 object */
26885             sip_pvt_unlock(p);
26886             usleep(1);
26887             sip_pvt_lock(p);
26888          } while (p->owner && ast_channel_trylock(p->owner));
26889          bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
26890       }
26891 
26892 
26893       if (p->rtp && (quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
26894          if (p->do_history) {
26895             append_history(p, "RTCPaudio", "Quality:%s", quality);
26896 
26897             if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_JITTER, quality_buf, sizeof(quality_buf)))) {
26898                append_history(p, "RTCPaudioJitter", "Quality:%s", quality);
26899             }
26900             if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_LOSS, quality_buf, sizeof(quality_buf)))) {
26901                append_history(p, "RTCPaudioLoss", "Quality:%s", quality);
26902             }
26903             if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_RTT, quality_buf, sizeof(quality_buf)))) {
26904                append_history(p, "RTCPaudioRTT", "Quality:%s", quality);
26905             }
26906          }
26907 
26908          if (p->owner) {
26909             ast_rtp_instance_set_stats_vars(p->owner, p->rtp);
26910          }
26911 
26912       }
26913 
26914       if (bridge) {
26915          struct sip_pvt *q = ast_channel_tech_pvt(bridge);
26916 
26917          if (IS_SIP_TECH(ast_channel_tech(bridge)) && q && q->rtp) {
26918             ast_rtp_instance_set_stats_vars(bridge, q->rtp);
26919          }
26920          ast_channel_unlock(bridge);
26921       }
26922 
26923       if (p->vrtp && (quality = ast_rtp_instance_get_quality(p->vrtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
26924          if (p->do_history) {
26925             append_history(p, "RTCPvideo", "Quality:%s", quality);
26926          }
26927          if (p->owner) {
26928             pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", quality);
26929          }
26930       }
26931       if (p->trtp && (quality = ast_rtp_instance_get_quality(p->trtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
26932          if (p->do_history) {
26933             append_history(p, "RTCPtext", "Quality:%s", quality);
26934          }
26935          if (p->owner) {
26936             pbx_builtin_setvar_helper(p->owner, "RTPTEXTQOS", quality);
26937          }
26938       }
26939    }
26940 
26941    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
26942    if (p->stimer) {
26943       stop_session_timer(p); /* Stop Session-Timer */
26944    }
26945 
26946    if (!ast_strlen_zero(sip_get_header(req, "Also"))) {
26947       ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method.  Ask vendor to support REFER instead\n",
26948          ast_sockaddr_stringify(&p->recv));
26949       if (ast_strlen_zero(p->context))
26950          ast_string_field_set(p, context, sip_cfg.default_context);
26951       res = get_also_info(p, req);
26952       if (!res) {
26953          c = p->owner;
26954          if (c) {
26955             bridged_to = ast_bridged_channel(c);
26956             if (bridged_to) {
26957                /* Don't actually hangup here... */
26958                ast_queue_control(c, AST_CONTROL_UNHOLD);
26959                ast_channel_unlock(c);  /* async_goto can do a masquerade, no locks can be held during a masq */
26960                ast_async_goto(bridged_to, p->context, p->refer->refer_to, 1);
26961                ast_channel_lock(c);
26962             } else
26963                ast_queue_hangup(p->owner);
26964          }
26965       } else {
26966          ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_sockaddr_stringify(&p->recv));
26967          if (p->owner)
26968             ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
26969       }
26970    } else if (p->owner) {
26971       sip_queue_hangup_cause(p, 0);
26972       sip_scheddestroy_final(p, DEFAULT_TRANS_TIMEOUT);
26973       ast_debug(3, "Received bye, issuing owner hangup\n");
26974    } else {
26975       sip_scheddestroy_final(p, DEFAULT_TRANS_TIMEOUT);
26976       ast_debug(3, "Received bye, no owner, selfdestruct soon.\n");
26977    }
26978    ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
26979 
26980    /* Find out what they require */
26981    required = sip_get_header(req, "Require");
26982    if (!ast_strlen_zero(required)) {
26983       char unsupported[256] = { 0, };
26984       parse_sip_options(required, unsupported, ARRAY_LEN(unsupported));
26985       /* If there are any options required that we do not support,
26986        * then send a 420 with only those unsupported options listed */
26987       if (!ast_strlen_zero(unsupported)) {
26988          transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, unsupported);
26989          ast_log(LOG_WARNING, "Received SIP BYE with unsupported required extension: required:%s unsupported:%s\n", required, unsupported);
26990       } else {
26991          transmit_response(p, "200 OK", req);
26992       }
26993    } else {
26994       transmit_response(p, "200 OK", req);
26995    }
26996 
26997    return 1;
26998 }
26999 
27000 /*! \brief Handle incoming MESSAGE request */
27001 static int handle_request_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e)
27002 {
27003    if (!req->ignore) {
27004       if (req->debug)
27005          ast_verbose("Receiving message!\n");
27006       receive_message(p, req, addr, e);
27007    } else
27008       transmit_response(p, "202 Accepted", req);
27009    return 1;
27010 }
27011 
27012 static int sip_msg_send(const struct ast_msg *msg, const char *to, const char *from);
27013 
27014 static const struct ast_msg_tech sip_msg_tech = {
27015    .name = "sip",
27016    .msg_send = sip_msg_send,
27017 };
27018 
27019 /*!
27020  * \internal
27021  * \brief Check if the given header name is blocked.
27022  *
27023  * \details Determine if the given header name from the user is
27024  * blocked for outgoing MESSAGE packets.
27025  *
27026  * \param header_name Name of header to see if it is blocked.
27027  *
27028  * \retval TRUE if the given header is blocked.
27029  */
27030 static int block_msg_header(const char *header_name)
27031 {
27032    int idx;
27033 
27034    /*
27035     * Don't block Content-Type or Max-Forwards headers because the
27036     * user can override them.
27037     */
27038    static const char *hdr[] = {
27039       "To",
27040       "From",
27041       "Via",
27042       "Route",
27043       "Contact",
27044       "Call-ID",
27045       "CSeq",
27046       "Allow",
27047       "Content-Length",
27048       "Request-URI",
27049    };
27050 
27051    for (idx = 0; idx < ARRAY_LEN(hdr); ++idx) {
27052       if (!strcasecmp(header_name, hdr[idx])) {
27053          /* Block addition of this header. */
27054          return 1;
27055       }
27056    }
27057    return 0;
27058 }
27059 
27060 static int sip_msg_send(const struct ast_msg *msg, const char *to, const char *from)
27061 {
27062    struct sip_pvt *pvt;
27063    int res;
27064    char *to_uri;
27065    char *to_host;
27066    char *to_user;
27067    const char *var;
27068    const char *val;
27069    struct ast_msg_var_iterator *iter;
27070    struct sip_peer *peer_ptr;
27071 
27072    if (!(pvt = sip_alloc(NULL, NULL, 0, SIP_MESSAGE, NULL, NULL))) {
27073       return -1;
27074    }
27075 
27076    for (iter = ast_msg_var_iterator_init(msg);
27077       ast_msg_var_iterator_next(msg, iter, &var, &val);
27078       ast_msg_var_unref_current(iter)) {
27079       if (!strcasecmp(var, "Request-URI")) {
27080          ast_string_field_set(pvt, fullcontact, val);
27081          break;
27082       }
27083    }
27084    ast_msg_var_iterator_destroy(iter);
27085 
27086    to_uri = ast_strdupa(to);
27087    to_uri = get_in_brackets(to_uri);
27088    parse_uri(to_uri, "sip:,sips:", &to_user, NULL, &to_host, NULL);
27089 
27090    if (ast_strlen_zero(to_host)) {
27091       ast_log(LOG_WARNING, "MESSAGE(to) is invalid for SIP - '%s'\n", to);
27092       dialog_unlink_all(pvt);
27093       dialog_unref(pvt, "MESSAGE(to) is invalid for SIP");
27094       return -1;
27095    }
27096 
27097    if (!ast_strlen_zero(from)) {
27098       if ((peer_ptr = sip_find_peer(from, NULL, 0, 1, 0, 0))) {
27099          ast_string_field_set(pvt, fromname, S_OR(peer_ptr->cid_name, peer_ptr->name));
27100          ast_string_field_set(pvt, fromuser, S_OR(peer_ptr->cid_num, peer_ptr->name));
27101          sip_unref_peer(peer_ptr, "sip_unref_peer, from sip_msg_send, sip_find_peer");
27102       } else if (strchr(from, '<')) { /* from is callerid-style */
27103          char *sender;
27104          char *name = NULL, *location = NULL, *user = NULL, *domain = NULL;
27105 
27106          sender = ast_strdupa(from);
27107          ast_callerid_parse(sender, &name, &location);
27108          if (ast_strlen_zero(location)) {
27109             /* This can occur if either
27110              *  1) A name-addr style From header does not close the angle brackets
27111              *  properly.
27112              *  2) The From header is not in name-addr style and the content of the
27113              *  From contains characters other than 0-9, *, #, or +.
27114              *
27115              *  In both cases, ast_callerid_parse() should have parsed the From header
27116              *  as a name rather than a number. So we just need to set the location
27117              *  to what was parsed as a name, and set the name NULL since there was
27118              *  no name present.
27119              */
27120             location = name;
27121             name = NULL;
27122          }
27123          ast_string_field_set(pvt, fromname, name);
27124          if (strchr(location, ':')) { /* Must be a URI */
27125             parse_uri(location, "sip:,sips:", &user, NULL, &domain, NULL);
27126             SIP_PEDANTIC_DECODE(user);
27127             SIP_PEDANTIC_DECODE(domain);
27128             extract_host_from_hostport(&domain);
27129             ast_string_field_set(pvt, fromuser, user);
27130             ast_string_field_set(pvt, fromdomain, domain);
27131          } else { /* Treat it as an exten/user */
27132             ast_string_field_set(pvt, fromuser, location);
27133          }
27134       } else { /* assume we just have the name, use defaults for the rest */
27135          ast_string_field_set(pvt, fromname, from);
27136       }
27137    }
27138 
27139    sip_pvt_lock(pvt);
27140 
27141    /* Look up the host to contact */
27142    if (create_addr(pvt, to_host, NULL, TRUE)) {
27143       sip_pvt_unlock(pvt);
27144       dialog_unlink_all(pvt);
27145       dialog_unref(pvt, "create_addr failed sending a MESSAGE");
27146       return -1;
27147    }
27148 
27149    if (!ast_strlen_zero(to_user)) {
27150       ast_string_field_set(pvt, username, to_user);
27151    }
27152    ast_sip_ouraddrfor(&pvt->sa, &pvt->ourip, pvt);
27153    build_via(pvt);
27154    ast_set_flag(&pvt->flags[0], SIP_OUTGOING);
27155 
27156    /* XXX Does pvt->expiry need to be set? */
27157 
27158    /* Save additional MESSAGE headers in case of authentication request. */
27159    for (iter = ast_msg_var_iterator_init(msg);
27160       ast_msg_var_iterator_next(msg, iter, &var, &val);
27161       ast_msg_var_unref_current(iter)) {
27162       if (!strcasecmp(var, "Max-Forwards")) {
27163          /* Decrement Max-Forwards for SIP loop prevention. */
27164          if (sscanf(val, "%30d", &pvt->maxforwards) != 1 || pvt->maxforwards < 1) {
27165             ast_msg_var_iterator_destroy(iter);
27166             sip_pvt_unlock(pvt);
27167             dialog_unlink_all(pvt);
27168             dialog_unref(pvt, "MESSAGE(Max-Forwards) reached zero.");
27169             ast_log(LOG_NOTICE,
27170                "MESSAGE(Max-Forwards) reached zero.  MESSAGE not sent.\n");
27171             return -1;
27172          }
27173          --pvt->maxforwards;
27174          continue;
27175       }
27176       if (block_msg_header(var)) {
27177          /* Block addition of this header. */
27178          continue;
27179       }
27180       add_msg_header(pvt, var, val);
27181    }
27182    ast_msg_var_iterator_destroy(iter);
27183 
27184    ast_string_field_set(pvt, msg_body, ast_msg_get_body(msg));
27185    res = transmit_message(pvt, 1, 0);
27186 
27187    sip_pvt_unlock(pvt);
27188    sip_scheddestroy(pvt, DEFAULT_TRANS_TIMEOUT);
27189    dialog_unref(pvt, "sent a MESSAGE");
27190 
27191    return res;
27192 }
27193 
27194 static enum sip_publish_type determine_sip_publish_type(struct sip_request *req, const char * const event, const char * const etag, const char * const expires, int *expires_int)
27195 {
27196    int etag_present = !ast_strlen_zero(etag);
27197    int body_present = req->lines > 0;
27198 
27199    ast_assert(expires_int != NULL);
27200 
27201    if (ast_strlen_zero(expires)) {
27202       /* Section 6, item 4, second bullet point of RFC 3903 says to
27203        * use a locally-configured default expiration if none is provided
27204        * in the request
27205        */
27206       *expires_int = DEFAULT_PUBLISH_EXPIRES;
27207    } else if (sscanf(expires, "%30d", expires_int) != 1) {
27208       return SIP_PUBLISH_UNKNOWN;
27209    }
27210 
27211    if (*expires_int == 0) {
27212       return SIP_PUBLISH_REMOVE;
27213    } else if (!etag_present && body_present) {
27214       return SIP_PUBLISH_INITIAL;
27215    } else if (etag_present && !body_present) {
27216       return SIP_PUBLISH_REFRESH;
27217    } else if (etag_present && body_present) {
27218       return SIP_PUBLISH_MODIFY;
27219    }
27220 
27221    return SIP_PUBLISH_UNKNOWN;
27222 }
27223 
27224 #ifdef HAVE_LIBXML2
27225 static int pidf_validate_tuple(struct ast_xml_node *tuple_node)
27226 {
27227    const char *id;
27228    int status_found = FALSE;
27229    struct ast_xml_node *tuple_children;
27230    struct ast_xml_node *tuple_children_iterator;
27231    /* Tuples have to have an id attribute or they're invalid */
27232    if (!(id = ast_xml_get_attribute(tuple_node, "id"))) {
27233       ast_log(LOG_WARNING, "Tuple XML element has no attribute 'id'\n");
27234       return FALSE;
27235    }
27236    /* We don't care what it actually is, just that it's there */
27237    ast_xml_free_attr(id);
27238    /* This is a tuple. It must have a status element */
27239    if (!(tuple_children = ast_xml_node_get_children(tuple_node))) {
27240       /* The tuple has no children. It sucks */
27241       ast_log(LOG_WARNING, "Tuple XML element has no child elements\n");
27242       return FALSE;
27243    }
27244    for (tuple_children_iterator = tuple_children; tuple_children_iterator;
27245          tuple_children_iterator = ast_xml_node_get_next(tuple_children_iterator)) {
27246       /* Similar to the wording used regarding tuples, the status element should appear
27247        * first. However, we will once again relax things and accept the status at any
27248        * position. We will enforce that only a single status element can be present.
27249        */
27250       if (strcmp(ast_xml_node_get_name(tuple_children_iterator), "status")) {
27251          /* Not the status, we don't care */
27252          continue;
27253       }
27254       if (status_found == TRUE) {
27255          /* THERE CAN BE ONLY ONE!!! */
27256          ast_log(LOG_WARNING, "Multiple status elements found in tuple. Only one allowed\n");
27257          return FALSE;
27258       }
27259       status_found = TRUE;
27260    }
27261    return status_found;
27262 }
27263 
27264 
27265 static int pidf_validate_presence(struct ast_xml_doc *doc)
27266 {
27267    struct ast_xml_node *presence_node = ast_xml_get_root(doc);
27268    struct ast_xml_node *child_nodes;
27269    struct ast_xml_node *node_iterator;
27270    struct ast_xml_ns *ns;
27271    const char *entity;
27272    const char *namespace;
27273    const char presence_namespace[] = "urn:ietf:params:xml:ns:pidf";
27274 
27275    if (!presence_node) {
27276       ast_log(LOG_WARNING, "Unable to retrieve root node of the XML document\n");
27277       return FALSE;
27278    }
27279    /* Okay, we managed to open the document! YAY! Now, let's start making sure it's all PIDF-ified
27280     * correctly.
27281     */
27282    if (strcmp(ast_xml_node_get_name(presence_node), "presence")) {
27283       ast_log(LOG_WARNING, "Root node of PIDF document is not 'presence'. Invalid\n");
27284       return FALSE;
27285    }
27286 
27287    /* The presence element must have an entity attribute and an xmlns attribute. Furthermore
27288     * the xmlns attribute must be "urn:ietf:params:xml:ns:pidf"
27289     */
27290    if (!(entity = ast_xml_get_attribute(presence_node, "entity"))) {
27291       ast_log(LOG_WARNING, "Presence element of PIDF document has no 'entity' attribute\n");
27292       return FALSE;
27293    }
27294    /* We're not interested in what the entity is, just that it exists */
27295    ast_xml_free_attr(entity);
27296 
27297    if (!(ns = ast_xml_find_namespace(doc, presence_node, NULL))) {
27298       ast_log(LOG_WARNING, "Couldn't find default namespace...\n");
27299       return FALSE;
27300    }
27301 
27302    namespace = ast_xml_get_ns_href(ns);
27303    if (ast_strlen_zero(namespace) || strcmp(namespace, presence_namespace)) {
27304       ast_log(LOG_WARNING, "PIDF document has invalid namespace value %s\n", namespace);
27305       return FALSE;
27306    }
27307 
27308    if (!(child_nodes = ast_xml_node_get_children(presence_node))) {
27309       ast_log(LOG_WARNING, "PIDF document has no elements as children of 'presence'. Invalid\n");
27310       return FALSE;
27311    }
27312 
27313    /* Check for tuple elements. RFC 3863 says that PIDF documents can have any number of
27314     * tuples, including 0. The big thing here is that if there are tuple elements present,
27315     * they have to have a single status element within.
27316     *
27317     * The RFC is worded such that tuples should appear as the first elements as children of
27318     * the presence element. However, we'll be accepting of documents which may place other elements
27319     * before the tuple(s).
27320     */
27321    for (node_iterator = child_nodes; node_iterator;
27322          node_iterator = ast_xml_node_get_next(node_iterator)) {
27323       if (strcmp(ast_xml_node_get_name(node_iterator), "tuple")) {
27324          /* Not a tuple. We don't give a rat's hind quarters */
27325          continue;
27326       }
27327       if (pidf_validate_tuple(node_iterator) == FALSE) {
27328          ast_log(LOG_WARNING, "Unable to validate tuple\n");
27329          return FALSE;
27330       }
27331    }
27332 
27333    return TRUE;
27334 }
27335 
27336 /*!
27337  * \brief Makes sure that body is properly formatted PIDF
27338  *
27339  * Specifically, we check that the document has a "presence" element
27340  * at the root and that within that, there is at least one "tuple" element
27341  * that contains a "status" element.
27342  *
27343  * XXX This function currently assumes a default namespace is used. Of course
27344  * if you're not using a default namespace, you're probably a stupid jerk anyway.
27345  *
27346  * \param req The SIP request to check
27347  * \param[out] pidf_doc The validated PIDF doc.
27348  * \retval FALSE The XML was malformed or the basic PIDF structure was marred
27349  * \retval TRUE The PIDF document is of a valid format
27350  */
27351 static int sip_pidf_validate(struct sip_request *req, struct ast_xml_doc **pidf_doc)
27352 {
27353    struct ast_xml_doc *doc;
27354    const char *content_type = sip_get_header(req, "Content-Type");
27355    char *pidf_body;
27356    int res;
27357 
27358    if (ast_strlen_zero(content_type) || strcmp(content_type, "application/pidf+xml")) {
27359       ast_log(LOG_WARNING, "Content type is not PIDF\n");
27360       return FALSE;
27361    }
27362 
27363    if (!(pidf_body = get_content(req))) {
27364       ast_log(LOG_WARNING, "Unable to get PIDF body\n");
27365       return FALSE;
27366    }
27367 
27368    if (!(doc = ast_xml_read_memory(pidf_body, strlen(pidf_body)))) {
27369       ast_log(LOG_WARNING, "Unable to open XML PIDF document. Is it malformed?\n");
27370       return FALSE;
27371    }
27372 
27373    res = pidf_validate_presence(doc);
27374    if (res == TRUE) {
27375       *pidf_doc = doc;
27376    } else {
27377       ast_xml_close(doc);
27378    }
27379    return res;
27380 }
27381 
27382 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)
27383 {
27384    const char *uri = REQ_OFFSET_TO_STR(req, rlpart2);
27385    struct ast_cc_agent *agent;
27386    struct sip_cc_agent_pvt *agent_pvt;
27387    struct ast_xml_doc *pidf_doc = NULL;
27388    const char *basic_status = NULL;
27389    struct ast_xml_node *presence_node;
27390    struct ast_xml_node *presence_children;
27391    struct ast_xml_node *tuple_node;
27392    struct ast_xml_node *tuple_children;
27393    struct ast_xml_node *status_node;
27394    struct ast_xml_node *status_children;
27395    struct ast_xml_node *basic_node;
27396    int res = 0;
27397 
27398    if (!((agent = find_sip_cc_agent_by_notify_uri(uri)) || (agent = find_sip_cc_agent_by_subscribe_uri(uri)))) {
27399       ast_log(LOG_WARNING, "Could not find agent using uri '%s'\n", uri);
27400       transmit_response(pvt, "412 Conditional Request Failed", req);
27401       return -1;
27402    }
27403 
27404    agent_pvt = agent->private_data;
27405 
27406    if (sip_pidf_validate(req, &pidf_doc) == FALSE) {
27407       res = -1;
27408       goto cc_publish_cleanup;
27409    }
27410 
27411    /* It's important to note that the PIDF validation routine has no knowledge
27412     * of what we specifically want in this instance. A valid PIDF document could
27413     * have no tuples, or it could have tuples whose status element has no basic
27414     * element contained within. While not violating the PIDF spec, these are
27415     * insufficient for our needs in this situation
27416     */
27417    presence_node = ast_xml_get_root(pidf_doc);
27418    if (!(presence_children = ast_xml_node_get_children(presence_node))) {
27419       ast_log(LOG_WARNING, "No tuples within presence element.\n");
27420       res = -1;
27421       goto cc_publish_cleanup;
27422    }
27423 
27424    if (!(tuple_node = ast_xml_find_element(presence_children, "tuple", NULL, NULL))) {
27425       ast_log(LOG_NOTICE, "Couldn't find tuple node?\n");
27426       res = -1;
27427       goto cc_publish_cleanup;
27428    }
27429 
27430    /* We already made sure that the tuple has a status node when we validated the PIDF
27431     * document earlier. So there's no need to enclose this operation in an if statement.
27432     */
27433    tuple_children = ast_xml_node_get_children(tuple_node);
27434    /* coverity[null_returns: FALSE] */
27435    status_node = ast_xml_find_element(tuple_children, "status", NULL, NULL);
27436 
27437    if (!(status_children = ast_xml_node_get_children(status_node))) {
27438       ast_log(LOG_WARNING, "No basic elements within status element.\n");
27439       res = -1;
27440       goto cc_publish_cleanup;
27441    }
27442 
27443    if (!(basic_node = ast_xml_find_element(status_children, "basic", NULL, NULL))) {
27444       ast_log(LOG_WARNING, "Couldn't find basic node?\n");
27445       res = -1;
27446       goto cc_publish_cleanup;
27447    }
27448 
27449    basic_status = ast_xml_get_text(basic_node);
27450 
27451    if (ast_strlen_zero(basic_status)) {
27452       ast_log(LOG_NOTICE, "NOthing in basic node?\n");
27453       res = -1;
27454       goto cc_publish_cleanup;
27455    }
27456 
27457    if (!strcmp(basic_status, "open")) {
27458       agent_pvt->is_available = TRUE;
27459       ast_cc_agent_caller_available(agent->core_id, "Received PUBLISH stating SIP caller %s is available",
27460             agent->device_name);
27461    } else if (!strcmp(basic_status, "closed")) {
27462       agent_pvt->is_available = FALSE;
27463       ast_cc_agent_caller_busy(agent->core_id, "Received PUBLISH stating SIP caller %s is busy",
27464             agent->device_name);
27465    } else {
27466       ast_log(LOG_NOTICE, "Invalid content in basic element: %s\n", basic_status);
27467    }
27468 
27469 cc_publish_cleanup:
27470    if (basic_status) {
27471       ast_xml_free_text(basic_status);
27472    }
27473    if (pidf_doc) {
27474       ast_xml_close(pidf_doc);
27475    }
27476    ao2_ref(agent, -1);
27477    if (res) {
27478       transmit_response(pvt, "400 Bad Request", req);
27479    }
27480    return res;
27481 }
27482 
27483 #endif /* HAVE_LIBXML2 */
27484 
27485 static int handle_sip_publish_initial(struct sip_pvt *p, struct sip_request *req, struct event_state_compositor *esc, const int expires)
27486 {
27487    struct sip_esc_entry *esc_entry = create_esc_entry(esc, req, expires);
27488    int res = 0;
27489 
27490    if (!esc_entry) {
27491       transmit_response(p, "503 Internal Server Failure", req);
27492       return -1;
27493    }
27494 
27495    if (esc->callbacks->initial_handler) {
27496       res = esc->callbacks->initial_handler(p, req, esc, esc_entry);
27497    }
27498 
27499    if (!res) {
27500       transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 0);
27501    }
27502 
27503    ao2_ref(esc_entry, -1);
27504    return res;
27505 }
27506 
27507 static int handle_sip_publish_refresh(struct sip_pvt *p, struct sip_request *req, struct event_state_compositor *esc, const char * const etag, const int expires)
27508 {
27509    struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
27510    int expires_ms = expires * 1000;
27511    int res = 0;
27512 
27513    if (!esc_entry) {
27514       transmit_response(p, "412 Conditional Request Failed", req);
27515       return -1;
27516    }
27517 
27518    AST_SCHED_REPLACE_UNREF(esc_entry->sched_id, sched, expires_ms, publish_expire, esc_entry,
27519          ao2_ref(_data, -1),
27520          ao2_ref(esc_entry, -1),
27521          ao2_ref(esc_entry, +1));
27522 
27523    if (esc->callbacks->refresh_handler) {
27524       res = esc->callbacks->refresh_handler(p, req, esc, esc_entry);
27525    }
27526 
27527    if (!res) {
27528       transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
27529    }
27530 
27531    ao2_ref(esc_entry, -1);
27532    return res;
27533 }
27534 
27535 static int handle_sip_publish_modify(struct sip_pvt *p, struct sip_request *req, struct event_state_compositor *esc, const char * const etag, const int expires)
27536 {
27537    struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
27538    int expires_ms = expires * 1000;
27539    int res = 0;
27540 
27541    if (!esc_entry) {
27542       transmit_response(p, "412 Conditional Request Failed", req);
27543       return -1;
27544    }
27545 
27546    AST_SCHED_REPLACE_UNREF(esc_entry->sched_id, sched, expires_ms, publish_expire, esc_entry,
27547          ao2_ref(_data, -1),
27548          ao2_ref(esc_entry, -1),
27549          ao2_ref(esc_entry, +1));
27550 
27551    if (esc->callbacks->modify_handler) {
27552       res = esc->callbacks->modify_handler(p, req, esc, esc_entry);
27553    }
27554 
27555    if (!res) {
27556       transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
27557    }
27558 
27559    ao2_ref(esc_entry, -1);
27560    return res;
27561 }
27562 
27563 static int handle_sip_publish_remove(struct sip_pvt *p, struct sip_request *req, struct event_state_compositor *esc, const char * const etag)
27564 {
27565    struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
27566    int res = 0;
27567 
27568    if (!esc_entry) {
27569       transmit_response(p, "412 Conditional Request Failed", req);
27570       return -1;
27571    }
27572 
27573    AST_SCHED_DEL(sched, esc_entry->sched_id);
27574    /* Scheduler's ref of the esc_entry */
27575    ao2_ref(esc_entry, -1);
27576 
27577    if (esc->callbacks->remove_handler) {
27578       res = esc->callbacks->remove_handler(p, req, esc, esc_entry);
27579    }
27580 
27581    if (!res) {
27582       transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
27583    }
27584 
27585    /* Ref from finding the esc_entry earlier in function */
27586    ao2_unlink(esc->compositor, esc_entry);
27587    ao2_ref(esc_entry, -1);
27588    return res;
27589 }
27590 
27591 static int handle_request_publish(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const uint32_t seqno, const char *uri)
27592 {
27593    const char *etag = sip_get_header(req, "SIP-If-Match");
27594    const char *event = sip_get_header(req, "Event");
27595    struct event_state_compositor *esc;
27596    enum sip_publish_type publish_type;
27597    const char *expires_str = sip_get_header(req, "Expires");
27598    int expires_int;
27599    int auth_result;
27600    int handler_result = -1;
27601 
27602    if (ast_strlen_zero(event)) {
27603       transmit_response(p, "489 Bad Event", req);
27604       pvt_set_needdestroy(p, "missing Event: header");
27605       return -1;
27606    }
27607 
27608    if (!(esc = get_esc(event))) {
27609       transmit_response(p, "489 Bad Event", req);
27610       pvt_set_needdestroy(p, "unknown event package in publish");
27611       return -1;
27612    }
27613 
27614    auth_result = check_user(p, req, SIP_PUBLISH, uri, XMIT_UNRELIABLE, addr);
27615    if (auth_result == AUTH_CHALLENGE_SENT) {
27616       p->lastinvite = seqno;
27617       return 0;
27618    } else if (auth_result < 0) {
27619       ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", sip_get_header(req, "From"));
27620       transmit_response(p, "403 Forbidden", req);
27621       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
27622       ast_string_field_set(p, theirtag, NULL);
27623       return 0;
27624    } else if (auth_result == AUTH_SUCCESSFUL && p->lastinvite) {
27625       /* We need to stop retransmitting the 401 */
27626       __sip_ack(p, p->lastinvite, 1, 0);
27627    }
27628 
27629    publish_type = determine_sip_publish_type(req, event, etag, expires_str, &expires_int);
27630 
27631    if (expires_int > max_expiry) {
27632       expires_int = max_expiry;
27633    } else if (expires_int < min_expiry && expires_int > 0) {
27634       transmit_response_with_minexpires(p, "423 Interval too small", req, min_expiry);
27635       pvt_set_needdestroy(p, "Expires is less that the min expires allowed.");
27636       return 0;
27637    }
27638    p->expiry = expires_int;
27639 
27640    /* It is the responsibility of these handlers to formulate any response
27641     * sent for a PUBLISH
27642     */
27643    switch (publish_type) {
27644    case SIP_PUBLISH_UNKNOWN:
27645       transmit_response(p, "400 Bad Request", req);
27646       break;
27647    case SIP_PUBLISH_INITIAL:
27648       handler_result = handle_sip_publish_initial(p, req, esc, expires_int);
27649       break;
27650    case SIP_PUBLISH_REFRESH:
27651       handler_result = handle_sip_publish_refresh(p, req, esc, etag, expires_int);
27652       break;
27653    case SIP_PUBLISH_MODIFY:
27654       handler_result = handle_sip_publish_modify(p, req, esc, etag, expires_int);
27655       break;
27656    case SIP_PUBLISH_REMOVE:
27657       handler_result = handle_sip_publish_remove(p, req, esc, etag);
27658       break;
27659    default:
27660       transmit_response(p, "400 Impossible Condition", req);
27661       break;
27662    }
27663    if (!handler_result && p->expiry > 0) {
27664       sip_scheddestroy(p, (p->expiry + 10) * 1000);
27665    } else {
27666       pvt_set_needdestroy(p, "forcing expiration");
27667    }
27668 
27669    return handler_result;
27670 }
27671 
27672 /*! \internal \brief Subscribe to MWI events for the specified peer
27673  * \note The peer cannot be locked during this method.  sip_send_mwi_peer will
27674  * attempt to lock the peer after the event subscription lock is held; if the peer is locked during
27675  * this method then we will attempt to lock the event subscription lock but after the peer, creating
27676  * a locking inversion.
27677  */
27678 static void add_peer_mwi_subs(struct sip_peer *peer)
27679 {
27680    struct sip_mailbox *mailbox;
27681 
27682    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
27683       if (mailbox->event_sub) {
27684          ast_event_unsubscribe(mailbox->event_sub);
27685       }
27686 
27687       mailbox->event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, "SIP mbox event", peer,
27688          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
27689          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
27690          AST_EVENT_IE_END);
27691    }
27692 }
27693 
27694 static int handle_cc_subscribe(struct sip_pvt *p, struct sip_request *req)
27695 {
27696    const char *uri = REQ_OFFSET_TO_STR(req, rlpart2);
27697    char *param_separator;
27698    struct ast_cc_agent *agent;
27699    struct sip_cc_agent_pvt *agent_pvt;
27700    const char *expires_str = sip_get_header(req, "Expires");
27701    int expires = -1; /* Just need it to be non-zero */
27702 
27703    if (!ast_strlen_zero(expires_str)) {
27704       sscanf(expires_str, "%30d", &expires);
27705    }
27706 
27707    if ((param_separator = strchr(uri, ';'))) {
27708       *param_separator = '\0';
27709    }
27710 
27711    p->subscribed = CALL_COMPLETION;
27712 
27713    if (!(agent = find_sip_cc_agent_by_subscribe_uri(uri))) {
27714       if (!expires) {
27715          /* Typically, if a 0 Expires reaches us and we can't find
27716           * the corresponding agent, it means that the CC transaction
27717           * has completed and so the calling side is just trying to
27718           * clean up its subscription. We'll just respond with a
27719           * 200 OK and be done with it
27720           */
27721          transmit_response(p, "200 OK", req);
27722          return 0;
27723       }
27724       ast_log(LOG_WARNING, "Invalid URI '%s' in CC subscribe\n", uri);
27725       transmit_response(p, "404 Not Found", req);
27726       return -1;
27727    }
27728 
27729    agent_pvt = agent->private_data;
27730 
27731    if (!expires) {
27732       /* We got sent a SUBSCRIBE and found an agent. This means that CC
27733        * is being canceled.
27734        */
27735       ast_cc_failed(agent->core_id, "CC is being canceled by %s", agent->device_name);
27736       transmit_response(p, "200 OK", req);
27737       ao2_ref(agent, -1);
27738       return 0;
27739    }
27740 
27741    agent_pvt->subscribe_pvt = dialog_ref(p, "SIP CC agent gains reference to subscription dialog");
27742    ast_cc_agent_accept_request(agent->core_id, "SIP caller %s has requested CC via SUBSCRIBE",
27743          agent->device_name);
27744 
27745    /* We don't send a response here. That is done in the agent's ack callback or in the
27746     * agent destructor, should a failure occur before we have responded
27747     */
27748    ao2_ref(agent, -1);
27749    return 0;
27750 }
27751 
27752 /*! \brief  Handle incoming SUBSCRIBE request */
27753 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e)
27754 {
27755    int res = 0;
27756    struct sip_peer *authpeer = NULL;
27757    char *event = ast_strdupa(sip_get_header(req, "Event")); /* Get Event package name */
27758    int resubscribe = (p->subscribed != NONE) && !req->ignore;
27759    char *options;
27760 
27761    if (p->initreq.headers) {
27762       /* We already have a dialog */
27763       if (p->initreq.method != SIP_SUBSCRIBE) {
27764          /* This is a SUBSCRIBE within another SIP dialog, which we do not support */
27765          /* For transfers, this could happen, but since we haven't seen it happening, let us just refuse this */
27766          transmit_response(p, "403 Forbidden (within dialog)", req);
27767          /* Do not destroy session, since we will break the call if we do */
27768          ast_debug(1, "Got a subscription within the context of another call, can't handle that - %s (Method %s)\n", p->callid, sip_methods[p->initreq.method].text);
27769          return 0;
27770       } else if (req->debug) {
27771          if (resubscribe)
27772             ast_debug(1, "Got a re-subscribe on existing subscription %s\n", p->callid);
27773          else
27774             ast_debug(1, "Got a new subscription %s (possibly with auth) or retransmission\n", p->callid);
27775       }
27776    }
27777 
27778    /* Check if we have a global disallow setting on subscriptions.
27779       if so, we don't have to check peer settings after auth, which saves a lot of processing
27780    */
27781    if (!sip_cfg.allowsubscribe) {
27782       transmit_response(p, "403 Forbidden (policy)", req);
27783       pvt_set_needdestroy(p, "forbidden");
27784       return 0;
27785    }
27786 
27787    if (!req->ignore && !resubscribe) { /* Set up dialog, new subscription */
27788       const char *to = sip_get_header(req, "To");
27789       char totag[128];
27790       set_pvt_allowed_methods(p, req);
27791 
27792       /* Check to see if a tag was provided, if so this is actually a resubscription of a dialog we no longer know about */
27793       if (!ast_strlen_zero(to) && gettag(req, "To", totag, sizeof(totag))) {
27794          if (req->debug)
27795             ast_verbose("Received resubscription for a dialog we no longer know about. Telling remote side to subscribe again.\n");
27796          transmit_response(p, "481 Subscription does not exist", req);
27797          pvt_set_needdestroy(p, "subscription does not exist");
27798          return 0;
27799       }
27800 
27801       /* Use this as the basis */
27802       if (req->debug)
27803          ast_verbose("Creating new subscription\n");
27804 
27805       copy_request(&p->initreq, req);
27806       if (sipdebug)
27807          ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
27808       check_via(p, req);
27809       build_route(p, req, 0, 0);
27810    } else if (req->debug && req->ignore)
27811       ast_verbose("Ignoring this SUBSCRIBE request\n");
27812 
27813    /* Find parameters to Event: header value and remove them for now */
27814    if (ast_strlen_zero(event)) {
27815       transmit_response(p, "489 Bad Event", req);
27816       ast_debug(2, "Received SIP subscribe for unknown event package: <none>\n");
27817       pvt_set_needdestroy(p, "unknown event package in subscribe");
27818       return 0;
27819    }
27820    if ((options = strchr(event, ';')) != NULL) {
27821       *options++ = '\0';
27822    }
27823 
27824    /* Handle authentication if we're new and not a retransmission. We can't just
27825     * use if !req->ignore, because then we'll end up sending
27826     * a 200 OK if someone retransmits without sending auth */
27827    if (p->subscribed == NONE || resubscribe) {
27828       res = check_user_full(p, req, SIP_SUBSCRIBE, e, XMIT_UNRELIABLE, addr, &authpeer);
27829 
27830       /* if an authentication response was sent, we are done here */
27831       if (res == AUTH_CHALLENGE_SENT)  /* authpeer = NULL here */
27832          return 0;
27833       if (res != AUTH_SUCCESSFUL) {
27834          ast_log(LOG_NOTICE, "Failed to authenticate device %s for SUBSCRIBE\n", sip_get_header(req, "From"));
27835          transmit_response(p, "403 Forbidden", req);
27836 
27837          pvt_set_needdestroy(p, "authentication failed");
27838          return 0;
27839       }
27840    }
27841 
27842    /* At this point, we hold a reference to authpeer (if not NULL).  It
27843     * must be released when done.
27844     */
27845 
27846    /* Check if this device  is allowed to subscribe at all */
27847    if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
27848       transmit_response(p, "403 Forbidden (policy)", req);
27849       pvt_set_needdestroy(p, "subscription not allowed");
27850       if (authpeer) {
27851          sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 1)");
27852       }
27853       return 0;
27854    }
27855 
27856    /* Get full contact header - this needs to be used as a request URI in NOTIFY's */
27857    parse_ok_contact(p, req);
27858    build_contact(p);
27859 
27860    /* Initialize tag for new subscriptions */
27861    if (ast_strlen_zero(p->tag)) {
27862       make_our_tag(p);
27863    }
27864 
27865    if (!strcmp(event, "presence") || !strcmp(event, "dialog")) { /* Presence, RFC 3842 */
27866       int gotdest;
27867       const char *accept;
27868       int start = 0;
27869       enum subscriptiontype subscribed = NONE;
27870       const char *unknown_accept = NULL;
27871 
27872                 /* Get destination right away */
27873                 gotdest = get_destination(p, NULL, NULL);
27874       if (gotdest != SIP_GET_DEST_EXTEN_FOUND) {
27875          if (gotdest == SIP_GET_DEST_INVALID_URI) {
27876             transmit_response(p, "416 Unsupported URI scheme", req);
27877          } else {
27878             transmit_response(p, "404 Not Found", req);
27879          }
27880          pvt_set_needdestroy(p, "subscription target not found");
27881          if (authpeer) {
27882             sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 2)");
27883          }
27884          return 0;
27885       }
27886 
27887       /* Header from Xten Eye-beam Accept: multipart/related, application/rlmi+xml, application/pidf+xml, application/xpidf+xml */
27888       accept = __get_header(req, "Accept", &start);
27889       while ((subscribed == NONE) && !ast_strlen_zero(accept)) {
27890          if (strstr(accept, "application/pidf+xml")) {
27891             if (strstr(p->useragent, "Polycom")) {
27892                subscribed = XPIDF_XML; /* Older versions of Polycom firmware will claim pidf+xml, but really they only support xpidf+xml */
27893             } else {
27894                subscribed = PIDF_XML; /* RFC 3863 format */
27895             }
27896          } else if (strstr(accept, "application/dialog-info+xml")) {
27897             subscribed = DIALOG_INFO_XML;
27898             /* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
27899          } else if (strstr(accept, "application/cpim-pidf+xml")) {
27900             subscribed = CPIM_PIDF_XML;    /* RFC 3863 format */
27901          } else if (strstr(accept, "application/xpidf+xml")) {
27902             subscribed = XPIDF_XML;        /* Early pre-RFC 3863 format with MSN additions (Microsoft Messenger) */
27903          } else {
27904             unknown_accept = accept;
27905          }
27906          /* check to see if there is another Accept header present */
27907          accept = __get_header(req, "Accept", &start);
27908       }
27909 
27910       if (!start) {
27911          if (p->subscribed == NONE) { /* if the subscribed field is not already set, and there is no accept header... */
27912             transmit_response(p, "489 Bad Event", req);
27913             ast_log(LOG_WARNING,"SUBSCRIBE failure: no Accept header: pvt: "
27914                "stateid: %d, laststate: %d, dialogver: %u, subscribecont: "
27915                "'%s', subscribeuri: '%s'\n",
27916                p->stateid,
27917                p->laststate,
27918                p->dialogver,
27919                p->subscribecontext,
27920                p->subscribeuri);
27921             pvt_set_needdestroy(p, "no Accept header");
27922             if (authpeer) {
27923                sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 2)");
27924             }
27925             return 0;
27926          }
27927          /* if p->subscribed is non-zero, then accept is not obligatory; according to rfc 3265 section 3.1.3, at least.
27928             so, we'll just let it ride, keeping the value from a previous subscription, and not abort the subscription */
27929       } else if (subscribed == NONE) {
27930          /* Can't find a format for events that we know about */
27931          char buf[200];
27932 
27933          if (!ast_strlen_zero(unknown_accept)) {
27934             snprintf(buf, sizeof(buf), "489 Bad Event (format %s)", unknown_accept);
27935          } else {
27936             snprintf(buf, sizeof(buf), "489 Bad Event");
27937          }
27938          transmit_response(p, buf, req);
27939          ast_log(LOG_WARNING,"SUBSCRIBE failure: unrecognized format:"
27940             "'%s' pvt: subscribed: %d, stateid: %d, laststate: %d,"
27941             "dialogver: %u, subscribecont: '%s', subscribeuri: '%s'\n",
27942             unknown_accept,
27943             (int)p->subscribed,
27944             p->stateid,
27945             p->laststate,
27946             p->dialogver,
27947             p->subscribecontext,
27948             p->subscribeuri);
27949          pvt_set_needdestroy(p, "unrecognized format");
27950          if (authpeer) {
27951             sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 2)");
27952          }
27953          return 0;
27954       } else {
27955          p->subscribed = subscribed;
27956       }
27957    } else if (!strcmp(event, "message-summary")) {
27958       int start = 0;
27959       int found_supported = 0;
27960       const char *accept;
27961 
27962       accept = __get_header(req, "Accept", &start);
27963       while (!found_supported && !ast_strlen_zero(accept)) {
27964          found_supported = strcmp(accept, "application/simple-message-summary") ? 0 : 1;
27965          if (!found_supported && (option_debug > 2)) {
27966             ast_debug(1, "Received SIP mailbox subscription for unknown format: %s\n", accept);
27967          }
27968          accept = __get_header(req, "Accept", &start);
27969       }
27970       if (start && !found_supported) {
27971          /* Format requested that we do not support */
27972          transmit_response(p, "406 Not Acceptable", req);
27973          ast_debug(2, "Received SIP mailbox subscription for unknown format: %s\n", accept);
27974          pvt_set_needdestroy(p, "unknown format");
27975          if (authpeer) {
27976             sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 3)");
27977          }
27978          return 0;
27979       }
27980       /* Looks like they actually want a mailbox status
27981         This version of Asterisk supports mailbox subscriptions
27982         The subscribed URI needs to exist in the dial plan
27983         In most devices, this is configurable to the voicemailmain extension you use
27984       */
27985       if (!authpeer || AST_LIST_EMPTY(&authpeer->mailboxes)) {
27986          if (!authpeer) {
27987             transmit_response(p, "404 Not found", req);
27988          } else {
27989             transmit_response(p, "404 Not found (no mailbox)", req);
27990             ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", S_OR(authpeer->name, ""));
27991          }
27992          pvt_set_needdestroy(p, "received 404 response");
27993 
27994          if (authpeer) {
27995             sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 3)");
27996          }
27997          return 0;
27998       }
27999 
28000       p->subscribed = MWI_NOTIFICATION;
28001       if (ast_test_flag(&authpeer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY)) {
28002          ao2_unlock(p);
28003          add_peer_mwi_subs(authpeer);
28004          ao2_lock(p);
28005       }
28006       if (authpeer->mwipvt != p) {  /* Destroy old PVT if this is a new one */
28007          /* We only allow one subscription per peer */
28008          if (authpeer->mwipvt) {
28009             dialog_unlink_all(authpeer->mwipvt);
28010             authpeer->mwipvt = dialog_unref(authpeer->mwipvt, "unref dialog authpeer->mwipvt");
28011          }
28012          authpeer->mwipvt = dialog_ref(p, "setting peers' mwipvt to p");
28013       }
28014 
28015       if (p->relatedpeer != authpeer) {
28016          if (p->relatedpeer) {
28017             sip_unref_peer(p->relatedpeer, "Unref previously stored relatedpeer ptr");
28018          }
28019          p->relatedpeer = sip_ref_peer(authpeer, "setting dialog's relatedpeer pointer");
28020       }
28021       /* Do not release authpeer here */
28022    } else if (!strcmp(event, "call-completion")) {
28023       handle_cc_subscribe(p, req);
28024    } else { /* At this point, Asterisk does not understand the specified event */
28025       transmit_response(p, "489 Bad Event", req);
28026       ast_debug(2, "Received SIP subscribe for unknown event package: %s\n", event);
28027       pvt_set_needdestroy(p, "unknown event package");
28028       if (authpeer) {
28029          sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 5)");
28030       }
28031       return 0;
28032    }
28033 
28034    if (!req->ignore) {
28035       p->lastinvite = seqno;
28036    }
28037    if (!p->needdestroy) {
28038       p->expiry = atoi(sip_get_header(req, "Expires"));
28039 
28040       /* check if the requested expiry-time is within the approved limits from sip.conf */
28041       if (p->expiry > max_subexpiry) {
28042          p->expiry = max_subexpiry;
28043       } else if (p->expiry < min_subexpiry && p->expiry > 0) {
28044          transmit_response_with_minexpires(p, "423 Interval too small", req, min_subexpiry);
28045          ast_log(LOG_WARNING, "Received subscription for extension \"%s\" context \"%s\" "
28046             "with Expire header less than 'subminexpire' limit. Received \"Expire: %d\" min is %d\n",
28047             p->exten, p->context, p->expiry, min_subexpiry);
28048          pvt_set_needdestroy(p, "Expires is less that the min expires allowed.");
28049          if (authpeer) {
28050             sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 6)");
28051          }
28052          return 0;
28053       }
28054 
28055       if (sipdebug) {
28056          const char *action = p->expiry > 0 ? "Adding" : "Removing";
28057          if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer) {
28058             ast_debug(2, "%s subscription for mailbox notification - peer %s\n",
28059                   action, p->relatedpeer->name);
28060          } else if (p->subscribed == CALL_COMPLETION) {
28061             ast_debug(2, "%s CC subscription for peer %s\n", action, p->username);
28062          } else {
28063             ast_debug(2, "%s subscription for extension %s context %s for peer %s\n",
28064                   action, p->exten, p->context, p->username);
28065          }
28066       }
28067       if (p->autokillid > -1 && sip_cancel_destroy(p))   /* Remove subscription expiry for renewals */
28068          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
28069       if (p->expiry > 0)
28070          sip_scheddestroy(p, (p->expiry + 10) * 1000);   /* Set timer for destruction of call at expiration */
28071 
28072       if (p->subscribed == MWI_NOTIFICATION) {
28073          ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
28074          transmit_response(p, "200 OK", req);
28075          if (p->relatedpeer) {   /* Send first notification */
28076             struct sip_peer *peer = p->relatedpeer;
28077             sip_ref_peer(peer, "ensure a peer ref is held during MWI sending");
28078             ao2_unlock(p);
28079             sip_send_mwi_to_peer(peer, 0);
28080             ao2_lock(p);
28081             sip_unref_peer(peer, "release a peer ref now that MWI is sent");
28082          }
28083       } else if (p->subscribed != CALL_COMPLETION) {
28084          struct state_notify_data data = { 0, };
28085          char *subtype = NULL;
28086          char *message = NULL;
28087          struct ao2_container *device_state_info = NULL;
28088 
28089          if (p->expiry > 0 && !resubscribe) {
28090             /* Add subscription for extension state from the PBX core */
28091             if (p->stateid != -1) {
28092                ast_extension_state_del(p->stateid, cb_extensionstate);
28093             }
28094             dialog_ref(p, "copying dialog ptr into extension state struct");
28095             p->stateid = ast_extension_state_add_destroy_extended(p->context, p->exten, cb_extensionstate, cb_extensionstate_destroy, p);
28096             if (p->stateid == -1) {
28097                dialog_unref(p, "copying dialog ptr into extension state struct failed");
28098             }
28099          }
28100 
28101          sip_pvt_unlock(p);
28102          data.state = ast_extension_state_extended(NULL, p->context, p->exten, &device_state_info);
28103          sip_pvt_lock(p);
28104 
28105          if (data.state < 0) {
28106             ao2_cleanup(device_state_info);
28107             if (p->expiry > 0) {
28108                ast_log(LOG_NOTICE, "Got SUBSCRIBE for extension %s@%s from %s, but there is no hint for that extension.\n", p->exten, p->context, ast_sockaddr_stringify(&p->sa));
28109             }
28110             transmit_response(p, "404 Not found", req);
28111             pvt_set_needdestroy(p, "no extension for SUBSCRIBE");
28112             if (authpeer) {
28113                sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 6)");
28114             }
28115             return 0;
28116          }
28117          if (allow_notify_user_presence(p)) {
28118             data.presence_state = ast_hint_presence_state(NULL, p->context, p->exten, &subtype, &message);
28119             data.presence_subtype = subtype;
28120             data.presence_message = message;
28121          }
28122          ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
28123          transmit_response(p, "200 OK", req);
28124          /* RFC 3265: A notification must be sent on every subscribe, so force it */
28125          data.device_state_info = device_state_info;
28126          if (data.state & AST_EXTENSION_RINGING) {
28127             /* save last_ringing_channel_time if this state really contains a ringing channel
28128              * because extensionstate_update() doesn't do it if forced
28129              */
28130             struct ast_channel *ringing = find_ringing_channel(data.device_state_info, p);
28131             if (ringing) {
28132                p->last_ringing_channel_time = ast_channel_creationtime(ringing);
28133                ao2_ref(ringing, -1);
28134             }
28135             /* If there is no channel, this likely indicates that the ringing indication
28136              * is due to a custom device state. These do not have associated channels.
28137              */
28138          }
28139          extensionstate_update(p->context, p->exten, &data, p, TRUE);
28140          append_history(p, "Subscribestatus", "%s", ast_extension_state2str(data.state));
28141          /* hide the 'complete' exten/context in the refer_to field for later display */
28142          ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
28143          /* Deleted the slow iteration of all sip dialogs to find old subscribes from this peer for exten@context */
28144 
28145          ao2_cleanup(device_state_info);
28146          ast_free(subtype);
28147          ast_free(message);
28148       }
28149       if (!p->expiry) {
28150          pvt_set_needdestroy(p, "forcing expiration");
28151       }
28152    }
28153 
28154    if (authpeer) {
28155       sip_unref_peer(authpeer, "unref pointer into (*authpeer)");
28156    }
28157    return 1;
28158 }
28159 
28160 /*! \brief Handle incoming REGISTER request */
28161 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e)
28162 {
28163    enum check_auth_result res;
28164 
28165    /* If this is not the intial request, and the initial request isn't
28166     * a register, something screwy happened, so bail */
28167    if (p->initreq.headers && p->initreq.method != SIP_REGISTER) {
28168       ast_log(LOG_WARNING, "Ignoring spurious REGISTER with Call-ID: %s\n", p->callid);
28169       return -1;
28170    }
28171 
28172    /* Use this as the basis */
28173    copy_request(&p->initreq, req);
28174    if (sipdebug)
28175       ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
28176    check_via(p, req);
28177 
28178    if ((res = register_verify(p, addr, req, e)) < 0) {
28179       const char *reason;
28180 
28181       switch (res) {
28182       case AUTH_SECRET_FAILED:
28183          reason = "Wrong password";
28184          break;
28185       case AUTH_USERNAME_MISMATCH:
28186          reason = "Username/auth name mismatch";
28187          break;
28188       case AUTH_NOT_FOUND:
28189          reason = "No matching peer found";
28190          break;
28191       case AUTH_UNKNOWN_DOMAIN:
28192          reason = "Not a local domain";
28193          break;
28194       case AUTH_PEER_NOT_DYNAMIC:
28195          reason = "Peer is not supposed to register";
28196          break;
28197       case AUTH_ACL_FAILED:
28198          reason = "Device does not match ACL";
28199          break;
28200       case AUTH_BAD_TRANSPORT:
28201          reason = "Device not configured to use this transport type";
28202          break;
28203       case AUTH_RTP_FAILED:
28204          reason = "RTP initialization failed";
28205          break;
28206       default:
28207          reason = "Unknown failure";
28208          break;
28209       }
28210       ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
28211          sip_get_header(req, "To"), ast_sockaddr_stringify(addr),
28212          reason);
28213       append_history(p, "RegRequest", "Failed : Account %s : %s", sip_get_header(req, "To"), reason);
28214    } else {
28215       req->authenticated = 1;
28216       append_history(p, "RegRequest", "Succeeded : Account %s", sip_get_header(req, "To"));
28217    }
28218 
28219    if (res != AUTH_CHALLENGE_SENT) {
28220       /* Destroy the session, but keep us around for just a bit in case they don't
28221          get our 200 OK */
28222       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
28223    }
28224 
28225    return res;
28226 }
28227 
28228 /*!
28229  * \brief Handle incoming SIP requests (methods)
28230  * \note
28231  * This is where all incoming requests go first.
28232  * \note
28233  * called with p and p->owner locked
28234  */
28235 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock)
28236 {
28237    /* Called with p->lock held, as well as p->owner->lock if appropriate, keeping things
28238       relatively static */
28239    const char *cmd;
28240    const char *cseq;
28241    const char *useragent;
28242    const char *via;
28243    const char *callid;
28244    int via_pos = 0;
28245    uint32_t seqno;
28246    int len;
28247    int respid;
28248    int res = 0;
28249    const char *e;
28250    int error = 0;
28251    int oldmethod = p->method;
28252    int acked = 0;
28253 
28254    /* RFC 3261 - 8.1.1 A valid SIP request must contain To, From, CSeq, Call-ID and Via.
28255     * 8.2.6.2 Response must have To, From, Call-ID CSeq, and Via related to the request,
28256     * so we can check to make sure these fields exist for all requests and responses */
28257    cseq = sip_get_header(req, "Cseq");
28258    cmd = REQ_OFFSET_TO_STR(req, header[0]);
28259    /* Save the via_pos so we can check later that responses only have 1 Via header */
28260    via = __get_header(req, "Via", &via_pos);
28261    /* This must exist already because we've called find_call by now */
28262    callid = sip_get_header(req, "Call-ID");
28263 
28264    /* Must have Cseq */
28265    if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq) || ast_strlen_zero(via)) {
28266       ast_log(LOG_ERROR, "Dropping this SIP message with Call-ID '%s', it's incomplete.\n", callid);
28267       error = 1;
28268    }
28269    if (!error && sscanf(cseq, "%30u%n", &seqno, &len) != 1) {
28270       ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
28271       error = 1;
28272    }
28273    if (error) {
28274       if (!p->initreq.headers) { /* New call */
28275          pvt_set_needdestroy(p, "no headers");
28276       }
28277       return -1;
28278    }
28279    /* Get the command XXX */
28280 
28281    cmd = REQ_OFFSET_TO_STR(req, rlpart1);
28282    e = ast_skip_blanks(REQ_OFFSET_TO_STR(req, rlpart2));
28283 
28284    /* Save useragent of the client */
28285    useragent = sip_get_header(req, "User-Agent");
28286    if (!ast_strlen_zero(useragent))
28287       ast_string_field_set(p, useragent, useragent);
28288 
28289    /* Find out SIP method for incoming request */
28290    if (req->method == SIP_RESPONSE) {  /* Response to our request */
28291       /* ignore means "don't do anything with it" but still have to
28292        * respond appropriately.
28293        * But in this case this is a response already, so we really
28294        * have nothing to do with this message, and even setting the
28295        * ignore flag is pointless.
28296        */
28297       if (ast_strlen_zero(e)) {
28298          return 0;
28299       }
28300       if (sscanf(e, "%30d %n", &respid, &len) != 1) {
28301          ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
28302          return 0;
28303       }
28304       if (respid <= 0) {
28305          ast_log(LOG_WARNING, "Invalid SIP response code: '%d'\n", respid);
28306          return 0;
28307       }
28308       /* RFC 3261 - 8.1.3.3 If more than one Via header field value is present in a reponse
28309        * the UAC SHOULD discard the message. This is not perfect, as it will not catch multiple
28310        * headers joined with a comma. Fixing that would pretty much involve writing a new parser */
28311       if (!ast_strlen_zero(__get_header(req, "via", &via_pos))) {
28312          ast_log(LOG_WARNING, "Misrouted SIP response '%s' with Call-ID '%s', too many vias\n", e, callid);
28313          return 0;
28314       }
28315       if (p->ocseq && (p->ocseq < seqno)) {
28316          ast_debug(1, "Ignoring out of order response %u (expecting %u)\n", seqno, p->ocseq);
28317          return -1;
28318       } else {
28319          if ((respid == 200) || ((respid >= 300) && (respid <= 399))) {
28320             extract_uri(p, req);
28321          }
28322 
28323          if (p->owner) {
28324             struct ast_control_pvt_cause_code *cause_code;
28325             int data_size = sizeof(*cause_code);
28326             /* size of the string making up the cause code is "SIP " + cause length */
28327             data_size += 4 + strlen(REQ_OFFSET_TO_STR(req, rlpart2));
28328             cause_code = ast_alloca(data_size);
28329             memset(cause_code, 0, data_size);
28330 
28331             ast_copy_string(cause_code->chan_name, ast_channel_name(p->owner), AST_CHANNEL_NAME);
28332 
28333             snprintf(cause_code->code, data_size - sizeof(*cause_code) + 1, "SIP %s", REQ_OFFSET_TO_STR(req, rlpart2));
28334 
28335             cause_code->ast_cause = hangup_sip2cause(respid);
28336             if (global_store_sip_cause) {
28337                cause_code->emulate_sip_cause = 1;
28338             }
28339 
28340             ast_queue_control_data(p->owner, AST_CONTROL_PVT_CAUSE_CODE, cause_code, data_size);
28341             ast_channel_hangupcause_hash_set(p->owner, cause_code, data_size);
28342          }
28343 
28344          handle_response(p, respid, e + len, req, seqno);
28345       }
28346       return 0;
28347    }
28348 
28349    /* New SIP request coming in
28350       (could be new request in existing SIP dialog as well...)
28351     */
28352    p->method = req->method;   /* Find out which SIP method they are using */
28353    ast_debug(4, "**** Received %s (%u) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd);
28354 
28355    if (p->icseq && (p->icseq > seqno) ) {
28356       if (p->pendinginvite && seqno == p->pendinginvite && (req->method == SIP_ACK || req->method == SIP_CANCEL)) {
28357          ast_debug(2, "Got CANCEL or ACK on INVITE with transactions in between.\n");
28358       } else {
28359          ast_debug(1, "Ignoring too old SIP packet packet %u (expecting >= %u)\n", seqno, p->icseq);
28360          if (req->method == SIP_INVITE) {
28361             unsigned int ran = (ast_random() % 10) + 1;
28362             char seconds[4];
28363             snprintf(seconds, sizeof(seconds), "%u", ran);
28364             transmit_response_with_retry_after(p, "500 Server error", req, seconds);   /* respond according to RFC 3261 14.2 with Retry-After betwewn 0 and 10 */
28365          } else if (req->method != SIP_ACK) {
28366             transmit_response(p, "500 Server error", req);  /* We must respond according to RFC 3261 sec 12.2 */
28367          }
28368          return -1;
28369       }
28370    } else if (p->icseq &&
28371          p->icseq == seqno &&
28372          req->method != SIP_ACK &&
28373          (p->method != SIP_CANCEL || p->alreadygone)) {
28374       /* ignore means "don't do anything with it" but still have to
28375          respond appropriately.  We do this if we receive a repeat of
28376          the last sequence number  */
28377       req->ignore = 1;
28378       ast_debug(3, "Ignoring SIP message because of retransmit (%s Seqno %u, ours %u)\n", sip_methods[p->method].text, p->icseq, seqno);
28379    }
28380 
28381    /* RFC 3261 section 9. "CANCEL has no effect on a request to which a UAS has
28382     * already given a final response." */
28383    if (!p->pendinginvite && (req->method == SIP_CANCEL)) {
28384       transmit_response(p, "481 Call/Transaction Does Not Exist", req);
28385       return res;
28386    }
28387 
28388    if (seqno >= p->icseq)
28389       /* Next should follow monotonically (but not necessarily
28390          incrementally -- thanks again to the genius authors of SIP --
28391          increasing */
28392       p->icseq = seqno;
28393 
28394    /* Find their tag if we haven't got it */
28395    if (ast_strlen_zero(p->theirtag)) {
28396       char tag[128];
28397 
28398       gettag(req, "From", tag, sizeof(tag));
28399       ast_string_field_set(p, theirtag, tag);
28400    }
28401    snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
28402 
28403    if (sip_cfg.pedanticsipchecking) {
28404       /* If this is a request packet without a from tag, it's not
28405          correct according to RFC 3261  */
28406       /* Check if this a new request in a new dialog with a totag already attached to it,
28407          RFC 3261 - section 12.2 - and we don't want to mess with recovery  */
28408       if (!p->initreq.headers && req->has_to_tag) {
28409          /* If this is a first request and it got a to-tag, it is not for us */
28410          if (!req->ignore && req->method == SIP_INVITE) {
28411             /* Just because we think this is a dialog-starting INVITE with a to-tag
28412              * doesn't mean it actually is. It could be a reinvite for an established, but
28413              * unknown dialog. In such a case, we need to change our tag to the
28414              * incoming INVITE's to-tag so that they will recognize the 481 we send and
28415              * so that we will properly match their incoming ACK.
28416              */
28417             char totag[128];
28418             gettag(req, "To", totag, sizeof(totag));
28419             ast_string_field_set(p, tag, totag);
28420             p->pendinginvite = p->icseq;
28421             transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
28422             /* Will cease to exist after ACK */
28423             return res;
28424          } else if (req->method != SIP_ACK) {
28425             transmit_response(p, "481 Call/Transaction Does Not Exist", req);
28426             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
28427             return res;
28428          }
28429          /* Otherwise, this is an ACK. It will always have a to-tag */
28430       }
28431    }
28432 
28433    if (!e && (p->method == SIP_INVITE || p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_NOTIFY || p->method == SIP_PUBLISH)) {
28434       transmit_response(p, "400 Bad request", req);
28435       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
28436       return -1;
28437    }
28438 
28439    /* Handle various incoming SIP methods in requests */
28440    switch (p->method) {
28441    case SIP_OPTIONS:
28442       res = handle_request_options(p, req, addr, e);
28443       break;
28444    case SIP_INVITE:
28445       res = handle_request_invite(p, req, addr, seqno, recount, e, nounlock);
28446 
28447       if (res < 9) {
28448          sip_report_security_event(p, req, res);
28449       }
28450 
28451       switch (res) {
28452       case INV_REQ_SUCCESS:
28453          res = 1;
28454          break;
28455       case INV_REQ_FAILED:
28456          res = 0;
28457          break;
28458       case INV_REQ_ERROR:
28459          res = -1;
28460          break;
28461       default:
28462          res = 0;
28463          break;
28464       }
28465 
28466       break;
28467    case SIP_REFER:
28468       res = handle_request_refer(p, req, seqno, nounlock);
28469       break;
28470    case SIP_CANCEL:
28471       res = handle_request_cancel(p, req);
28472       break;
28473    case SIP_BYE:
28474       res = handle_request_bye(p, req);
28475       break;
28476    case SIP_MESSAGE:
28477       res = handle_request_message(p, req, addr, e);
28478       break;
28479    case SIP_PUBLISH:
28480       res = handle_request_publish(p, req, addr, seqno, e);
28481       break;
28482    case SIP_SUBSCRIBE:
28483       res = handle_request_subscribe(p, req, addr, seqno, e);
28484       break;
28485    case SIP_REGISTER:
28486       res = handle_request_register(p, req, addr, e);
28487       sip_report_security_event(p, req, res);
28488       break;
28489    case SIP_INFO:
28490       if (req->debug)
28491          ast_verbose("Receiving INFO!\n");
28492       if (!req->ignore)
28493          handle_request_info(p, req);
28494       else  /* if ignoring, transmit response */
28495          transmit_response(p, "200 OK", req);
28496       break;
28497    case SIP_NOTIFY:
28498       res = handle_request_notify(p, req, addr, seqno, e);
28499       break;
28500    case SIP_UPDATE:
28501       res = handle_request_update(p, req);
28502       break;
28503    case SIP_ACK:
28504       /* Make sure we don't ignore this */
28505       if (seqno == p->pendinginvite) {
28506          p->invitestate = INV_TERMINATED;
28507          p->pendinginvite = 0;
28508          acked = __sip_ack(p, seqno, 1 /* response */, 0);
28509          if (p->owner && find_sdp(req)) {
28510             if (process_sdp(p, req, SDP_T38_NONE)) {
28511                return -1;
28512             }
28513             if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
28514                ast_queue_control(p->owner, AST_CONTROL_SRCCHANGE);
28515             }
28516          }
28517          check_pendings(p);
28518       } else if (p->glareinvite == seqno) {
28519          /* handle ack for the 491 pending sent for glareinvite */
28520          p->glareinvite = 0;
28521          acked = __sip_ack(p, seqno, 1, 0);
28522       }
28523       if (!acked) {
28524          /* Got an ACK that did not match anything. Ignore
28525           * silently and restore previous method */
28526          p->method = oldmethod;
28527       }
28528       if (!p->lastinvite && ast_strlen_zero(p->nonce)) {
28529          pvt_set_needdestroy(p, "unmatched ACK");
28530       }
28531       break;
28532    default:
28533       transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
28534       ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n",
28535          cmd, ast_sockaddr_stringify(&p->sa));
28536       /* If this is some new method, and we don't have a call, destroy it now */
28537       if (!p->initreq.headers) {
28538          pvt_set_needdestroy(p, "unimplemented method");
28539       }
28540       break;
28541    }
28542    return res;
28543 }
28544 
28545 /*! \brief Read data from SIP UDP socket
28546 \note sipsock_read locks the owner channel while we are processing the SIP message
28547 \return 1 on error, 0 on success
28548 \note Successful messages is connected to SIP call and forwarded to handle_incoming()
28549 */
28550 static int sipsock_read(int *id, int fd, short events, void *ignore)
28551 {
28552    struct sip_request req;
28553    struct ast_sockaddr addr;
28554    int res;
28555    static char readbuf[65535];
28556 
28557    memset(&req, 0, sizeof(req));
28558    res = ast_recvfrom(fd, readbuf, sizeof(readbuf) - 1, 0, &addr);
28559    if (res < 0) {
28560 #if !defined(__FreeBSD__)
28561       if (errno == EAGAIN)
28562          ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
28563       else
28564 #endif
28565       if (errno != ECONNREFUSED)
28566          ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
28567       return 1;
28568    }
28569 
28570    readbuf[res] = '\0';
28571 
28572    if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
28573       return 1;
28574    }
28575 
28576    if (ast_str_set(&req.data, 0, "%s", readbuf) == AST_DYNSTR_BUILD_FAILED) {
28577       return -1;
28578    }
28579 
28580    req.socket.fd = sipsock;
28581    set_socket_transport(&req.socket, SIP_TRANSPORT_UDP);
28582    req.socket.tcptls_session  = NULL;
28583    req.socket.port = htons(ast_sockaddr_port(&bindaddr));
28584 
28585    handle_request_do(&req, &addr);
28586    deinit_req(&req);
28587 
28588    return 1;
28589 }
28590 
28591 /*! \brief Handle incoming SIP message - request or response
28592 
28593    This is used for all transports (udp, tcp and tcp/tls)
28594 */
28595 static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr)
28596 {
28597    struct sip_pvt *p;
28598    struct ast_channel *owner_chan_ref = NULL;
28599    int recount = 0;
28600    int nounlock = 0;
28601 
28602    if (sip_debug_test_addr(addr))   /* Set the debug flag early on packet level */
28603       req->debug = 1;
28604    if (sip_cfg.pedanticsipchecking)
28605       lws2sws(req->data);  /* Fix multiline headers */
28606    if (req->debug) {
28607       ast_verbose("\n<--- SIP read from %s:%s --->\n%s\n<------------->\n",
28608          sip_get_transport(req->socket.type), ast_sockaddr_stringify(addr), ast_str_buffer(req->data));
28609    }
28610 
28611    if (parse_request(req) == -1) { /* Bad packet, can't parse */
28612       ast_str_reset(req->data); /* nulling this out is NOT a good idea here. */
28613       return 1;
28614    }
28615    req->method = find_sip_method(REQ_OFFSET_TO_STR(req, rlpart1));
28616 
28617    if (req->debug)
28618       ast_verbose("--- (%d headers %d lines)%s ---\n", req->headers, req->lines, (req->headers + req->lines == 0) ? " Nat keepalive" : "");
28619 
28620    if (req->headers < 2) { /* Must have at least two headers */
28621       ast_str_reset(req->data); /* nulling this out is NOT a good idea here. */
28622       return 1;
28623    }
28624    ast_mutex_lock(&netlock);
28625 
28626    /* Find the active SIP dialog or create a new one */
28627    p = find_call(req, addr, req->method); /* returns p with a reference only. _NOT_ locked*/
28628    if (p == NULL) {
28629       ast_debug(1, "Invalid SIP message - rejected , no callid, len %zu\n", ast_str_strlen(req->data));
28630       ast_mutex_unlock(&netlock);
28631       return 1;
28632    }
28633 
28634    if (p->logger_callid) {
28635       ast_callid_threadassoc_add(p->logger_callid);
28636    }
28637 
28638    /* Lock both the pvt and the owner if owner is present.  This will
28639     * not fail. */
28640    owner_chan_ref = sip_pvt_lock_full(p);
28641 
28642    copy_socket_data(&p->socket, &req->socket);
28643 
28644    ast_sockaddr_copy(&p->recv, addr);
28645 
28646    /* if we have an owner, then this request has been authenticated */
28647    if (p->owner) {
28648       req->authenticated = 1;
28649    }
28650 
28651    if (p->do_history) /* This is a request or response, note what it was for */
28652       append_history(p, "Rx", "%s / %s / %s", ast_str_buffer(req->data), sip_get_header(req, "CSeq"), REQ_OFFSET_TO_STR(req, rlpart2));
28653 
28654    if (handle_incoming(p, req, addr, &recount, &nounlock) == -1) {
28655       /* Request failed */
28656       ast_debug(1, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
28657    }
28658 
28659    if (recount) {
28660       ast_update_use_count();
28661    }
28662 
28663    if (p->owner && !nounlock) {
28664       ast_channel_unlock(p->owner);
28665    }
28666    if (owner_chan_ref) {
28667       ast_channel_unref(owner_chan_ref);
28668    }
28669    sip_pvt_unlock(p);
28670    ast_mutex_unlock(&netlock);
28671 
28672    if (p->logger_callid) {
28673       ast_callid_threadassoc_remove();
28674    }
28675    ao2_t_ref(p, -1, "throw away dialog ptr from find_call at end of routine"); /* p is gone after the return */
28676 
28677    return 1;
28678 }
28679 
28680 /*! \brief Returns the port to use for this socket
28681  *
28682  * \param type The type of transport used
28683  * \param port Port we are checking to see if it's the standard port.
28684  * \note port is expected in host byte order
28685  */
28686 static int sip_standard_port(enum sip_transport type, int port)
28687 {
28688    if (type & SIP_TRANSPORT_TLS)
28689       return port == STANDARD_TLS_PORT;
28690    else
28691       return port == STANDARD_SIP_PORT;
28692 }
28693 
28694 static int threadinfo_locate_cb(void *obj, void *arg, int flags)
28695 {
28696    struct sip_threadinfo *th = obj;
28697    struct ast_sockaddr *s = arg;
28698 
28699    if (!ast_sockaddr_cmp(s, &th->tcptls_session->remote_address)) {
28700       return CMP_MATCH | CMP_STOP;
28701    }
28702 
28703    return 0;
28704 }
28705 
28706 /*!
28707  * \brief Find thread for TCP/TLS session (based on IP/Port
28708  *
28709  * \note This function returns an astobj2 reference
28710  */
28711 static struct ast_tcptls_session_instance *sip_tcp_locate(struct ast_sockaddr *s)
28712 {
28713    struct sip_threadinfo *th;
28714    struct ast_tcptls_session_instance *tcptls_instance = NULL;
28715 
28716    if ((th = ao2_callback(threadt, 0, threadinfo_locate_cb, s))) {
28717       tcptls_instance = (ao2_ref(th->tcptls_session, +1), th->tcptls_session);
28718       ao2_t_ref(th, -1, "decrement ref from callback");
28719    }
28720 
28721    return tcptls_instance;
28722 }
28723 
28724 /*!
28725  * \brief Helper for dns resolution to filter by address family.
28726  *
28727  * \note return 0 if addr is [::] else it returns addr's family.
28728  */
28729 int get_address_family_filter(unsigned int transport)
28730 {
28731    const struct ast_sockaddr *addr = NULL;
28732 
28733    if ((transport == SIP_TRANSPORT_UDP) || !transport) {
28734       addr = &bindaddr;
28735    } else if (transport == SIP_TRANSPORT_TCP || transport == SIP_TRANSPORT_WS) {
28736       addr = &sip_tcp_desc.local_address;
28737    } else if (transport == SIP_TRANSPORT_TLS || transport == SIP_TRANSPORT_WSS) {
28738       addr = &sip_tls_desc.local_address;
28739    }
28740 
28741    if (ast_sockaddr_is_ipv6(addr) && ast_sockaddr_is_any(addr)) {
28742       return 0;
28743    }
28744 
28745    return addr->ss.ss_family;
28746 }
28747 
28748 /*! \todo Get socket for dialog, prepare if needed, and return file handle  */
28749 static int sip_prepare_socket(struct sip_pvt *p)
28750 {
28751    struct sip_socket *s = &p->socket;
28752    static const char name[] = "SIP socket";
28753    struct sip_threadinfo *th = NULL;
28754    struct ast_tcptls_session_instance *tcptls_session;
28755    struct ast_tcptls_session_args *ca;
28756    struct ast_sockaddr sa_tmp;
28757    pthread_t launched;
28758 
28759    /* check to see if a socket is already active */
28760    if ((s->fd != -1) && (s->type == SIP_TRANSPORT_UDP)) {
28761       return s->fd;
28762    }
28763    if ((s->type & (SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS)) &&
28764          (s->tcptls_session) &&
28765          (s->tcptls_session->fd != -1)) {
28766       return s->tcptls_session->fd;
28767    }
28768    if ((s->type & (SIP_TRANSPORT_WS | SIP_TRANSPORT_WSS))) {
28769       return s->ws_session ? ast_websocket_fd(s->ws_session) : -1;
28770    }
28771 
28772    /*! \todo Check this... This might be wrong, depending on the proxy configuration
28773       If proxy is in "force" mode its correct.
28774     */
28775    if (p->outboundproxy && p->outboundproxy->transport) {
28776       s->type = p->outboundproxy->transport;
28777    }
28778 
28779    if (s->type == SIP_TRANSPORT_UDP) {
28780       s->fd = sipsock;
28781       return s->fd;
28782    }
28783 
28784    /* At this point we are dealing with a TCP/TLS connection
28785     * 1. We need to check to see if a connection thread exists
28786     *    for this address, if so use that.
28787     * 2. If a thread does not exist for this address, but the tcptls_session
28788     *    exists on the socket, the connection was closed.
28789     * 3. If no tcptls_session thread exists for the address, and no tcptls_session
28790     *    already exists on the socket, create a new one and launch a new thread.
28791     */
28792 
28793    /* 1.  check for existing threads */
28794    ast_sockaddr_copy(&sa_tmp, sip_real_dst(p));
28795    if ((tcptls_session = sip_tcp_locate(&sa_tmp))) {
28796       s->fd = tcptls_session->fd;
28797       if (s->tcptls_session) {
28798          ao2_ref(s->tcptls_session, -1);
28799          s->tcptls_session = NULL;
28800       }
28801       s->tcptls_session = tcptls_session;
28802       return s->fd;
28803    /* 2.  Thread not found, if tcptls_session already exists, it once had a thread and is now terminated */
28804    } else if (s->tcptls_session) {
28805       return s->fd; /* XXX whether reconnection is ever necessary here needs to be investigated further */
28806    }
28807 
28808    /* 3.  Create a new TCP/TLS client connection */
28809    /* create new session arguments for the client connection */
28810    if (!(ca = ao2_alloc(sizeof(*ca), sip_tcptls_client_args_destructor)) ||
28811       !(ca->name = ast_strdup(name))) {
28812       goto create_tcptls_session_fail;
28813    }
28814    ca->accept_fd = -1;
28815    ast_sockaddr_copy(&ca->remote_address,sip_real_dst(p));
28816    /* if type is TLS, we need to create a tls cfg for this session arg */
28817    if (s->type == SIP_TRANSPORT_TLS) {
28818       if (!(ca->tls_cfg = ast_calloc(1, sizeof(*ca->tls_cfg)))) {
28819          goto create_tcptls_session_fail;
28820       }
28821       memcpy(ca->tls_cfg, &default_tls_cfg, sizeof(*ca->tls_cfg));
28822 
28823       if (!(ca->tls_cfg->certfile = ast_strdup(default_tls_cfg.certfile)) ||
28824          !(ca->tls_cfg->pvtfile = ast_strdup(default_tls_cfg.pvtfile)) ||
28825          !(ca->tls_cfg->cipher = ast_strdup(default_tls_cfg.cipher)) ||
28826          !(ca->tls_cfg->cafile = ast_strdup(default_tls_cfg.cafile)) ||
28827          !(ca->tls_cfg->capath = ast_strdup(default_tls_cfg.capath))) {
28828 
28829          goto create_tcptls_session_fail;
28830       }
28831 
28832       /* this host is used as the common name in ssl/tls */
28833       if (!ast_strlen_zero(p->tohost)) {
28834          ast_copy_string(ca->hostname, p->tohost, sizeof(ca->hostname));
28835       }
28836    }
28837 
28838    /* Create a client connection for address, this does not start the connection, just sets it up. */
28839    if (!(s->tcptls_session = ast_tcptls_client_create(ca))) {
28840       goto create_tcptls_session_fail;
28841    }
28842 
28843    s->fd = s->tcptls_session->fd;
28844 
28845    /* client connections need to have the sip_threadinfo object created before
28846     * the thread is detached.  This ensures the alert_pipe is up before it will
28847     * be used.  Note that this function links the new threadinfo object into the
28848     * threadt container. */
28849    if (!(th = sip_threadinfo_create(s->tcptls_session, s->type))) {
28850       goto create_tcptls_session_fail;
28851    }
28852 
28853    /* Give the new thread a reference to the tcptls_session */
28854    ao2_ref(s->tcptls_session, +1);
28855 
28856    if (ast_pthread_create_detached_background(&launched, NULL, sip_tcp_worker_fn, s->tcptls_session)) {
28857       ast_debug(1, "Unable to launch '%s'.", ca->name);
28858       ao2_ref(s->tcptls_session, -1); /* take away the thread ref we just gave it */
28859       goto create_tcptls_session_fail;
28860    }
28861 
28862    return s->fd;
28863 
28864 create_tcptls_session_fail:
28865    if (ca) {
28866       ao2_t_ref(ca, -1, "failed to create client, getting rid of client tcptls_session arguments");
28867    }
28868    if (s->tcptls_session) {
28869       ast_tcptls_close_session_file(s->tcptls_session);
28870       s->fd = -1;
28871       ao2_ref(s->tcptls_session, -1);
28872       s->tcptls_session = NULL;
28873    }
28874    if (th) {
28875       ao2_t_unlink(threadt, th, "Removing tcptls thread info object, thread failed to open");
28876    }
28877 
28878    return -1;
28879 }
28880 
28881 /*!
28882  * \brief Get cached MWI info
28883  * \return TRUE if found MWI in cache
28884  */
28885 static int get_cached_mwi(struct sip_peer *peer, int *new, int *old)
28886 {
28887    struct sip_mailbox *mailbox;
28888    int in_cache;
28889 
28890    in_cache = 0;
28891    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
28892       struct ast_event *event;
28893       event = ast_event_get_cached(AST_EVENT_MWI,
28894          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
28895          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
28896          AST_EVENT_IE_END);
28897       if (!event)
28898          continue;
28899       *new += ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
28900       *old += ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
28901       ast_event_destroy(event);
28902       in_cache = 1;
28903    }
28904 
28905    return in_cache;
28906 }
28907 
28908 /*! \brief Send message waiting indication to alert peer that they've got voicemail
28909  *  \note Both peer and associated sip_pvt must be unlocked prior to calling this function
28910  *  \returns -1 on failure, 0 on success
28911  */
28912 static int sip_send_mwi_to_peer(struct sip_peer *peer, int cache_only)
28913 {
28914    /* Called with peer lock, but releases it */
28915    struct sip_pvt *p;
28916    int newmsgs = 0, oldmsgs = 0;
28917    const char *vmexten = NULL;
28918 
28919    ao2_lock(peer);
28920 
28921    if (peer->vmexten) {
28922       vmexten = ast_strdupa(peer->vmexten);
28923    }
28924 
28925    if (ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY) && !peer->mwipvt) {
28926       update_peer_lastmsgssent(peer, -1, 1);
28927       ao2_unlock(peer);
28928       return -1;
28929    }
28930 
28931    /* Do we have an IP address? If not, skip this peer */
28932    if (ast_sockaddr_isnull(&peer->addr) && ast_sockaddr_isnull(&peer->defaddr)) {
28933       update_peer_lastmsgssent(peer, -1, 1);
28934       ao2_unlock(peer);
28935       return -1;
28936    }
28937 
28938    /* Attempt to use cached mwi to get message counts. */
28939    if (!get_cached_mwi(peer, &newmsgs, &oldmsgs) && !cache_only) {
28940       /* Fall back to manually checking the mailbox if not cache_only and get_cached_mwi failed */
28941       struct ast_str *mailbox_str = ast_str_alloca(512);
28942       peer_mailboxes_to_str(&mailbox_str, peer);
28943       /* if there is no mailbox do nothing */
28944       if (!ast_str_strlen(mailbox_str)) {
28945          ao2_unlock(peer);
28946          return -1;
28947       }
28948       ao2_unlock(peer);
28949       /* If there is no mailbox do nothing */
28950       if (!ast_str_strlen(mailbox_str)) {
28951          update_peer_lastmsgssent(peer, -1, 0);
28952          return 0;
28953       }
28954       ast_app_inboxcount(ast_str_buffer(mailbox_str), &newmsgs, &oldmsgs);
28955       ao2_lock(peer);
28956    }
28957 
28958    if (peer->mwipvt) {
28959       /* Base message on subscription */
28960       p = dialog_ref(peer->mwipvt, "sip_send_mwi_to_peer: Setting dialog ptr p from peer->mwipvt");
28961       ao2_unlock(peer);
28962    } else {
28963       ao2_unlock(peer);
28964       /* Build temporary dialog for this message */
28965       if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL, NULL))) {
28966          update_peer_lastmsgssent(peer, -1, 0);
28967          return -1;
28968       }
28969 
28970       /* If we don't set the socket type to 0, then create_addr_from_peer will fail immediately if the peer
28971        * uses any transport other than UDP. We set the type to 0 here and then let create_addr_from_peer copy
28972        * the peer's socket information to the sip_pvt we just allocated
28973        */
28974       set_socket_transport(&p->socket, 0);
28975       if (create_addr_from_peer(p, peer)) {
28976          /* Maybe they're not registered, etc. */
28977          dialog_unlink_all(p);
28978          dialog_unref(p, "unref dialog p just created via sip_alloc");
28979          update_peer_lastmsgssent(peer, -1, 0);
28980          return -1;
28981       }
28982       /* Recalculate our side, and recalculate Call ID */
28983       ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
28984       build_via(p);
28985 
28986       ao2_lock(peer);
28987       if (!ast_strlen_zero(peer->mwi_from)) {
28988          ast_string_field_set(p, mwi_from, peer->mwi_from);
28989       } else if (!ast_strlen_zero(default_mwi_from)) {
28990          ast_string_field_set(p, mwi_from, default_mwi_from);
28991       }
28992       ao2_unlock(peer);
28993 
28994       /* Change the dialog callid. */
28995       change_callid_pvt(p, NULL);
28996 
28997       /* Destroy this session after 32 secs */
28998       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
28999    }
29000 
29001    /* We have multiple threads (mwi events and monitor retransmits) working with this PVT and as we modify the sip history if that's turned on,
29002       we really need to have a lock on it */
29003    sip_pvt_lock(p);
29004 
29005    /* Send MWI */
29006    ast_set_flag(&p->flags[0], SIP_OUTGOING);
29007    /* the following will decrement the refcount on p as it finishes */
29008    transmit_notify_with_mwi(p, newmsgs, oldmsgs, vmexten);
29009    sip_pvt_unlock(p);
29010    dialog_unref(p, "unref dialog ptr p just before it goes out of scope at the end of sip_send_mwi_to_peer.");
29011 
29012    update_peer_lastmsgssent(peer, ((newmsgs > 0x7fff ? 0x7fff0000 : (newmsgs << 16)) | (oldmsgs > 0xffff ? 0xffff : oldmsgs)), 0);
29013 
29014    return 0;
29015 }
29016 
29017 /*!
29018  * \brief helper function for the monitoring thread -- seems to be called with the assumption that the dialog is locked
29019  *
29020  * \return CMP_MATCH for items to be unlinked from dialogs_rtpcheck.
29021  */
29022 static int check_rtp_timeout(struct sip_pvt *dialog, time_t t)
29023 {
29024    int timeout;
29025    int hold_timeout;
29026    int keepalive;
29027 
29028    if (!dialog->rtp) {
29029       /*
29030        * We have no RTP.  Since we don't do much with video RTP for
29031        * now, stop checking this dialog.
29032        */
29033       return CMP_MATCH;
29034    }
29035 
29036    /* If we have no active owner, no need to check timers */
29037    if (!dialog->owner) {
29038       return CMP_MATCH;
29039    }
29040 
29041    /* If the call is redirected outside Asterisk, no need to check timers */
29042    if (!ast_sockaddr_isnull(&dialog->redirip)) {
29043       return CMP_MATCH;
29044    }
29045 
29046    /* If the call is involved in a T38 fax session do not check RTP timeout */
29047    if (dialog->t38.state == T38_ENABLED) {
29048       return CMP_MATCH;
29049    }
29050    /* If the call is not in UP state return for later check. */
29051    if (ast_channel_state(dialog->owner) != AST_STATE_UP) {
29052       return 0;
29053    }
29054 
29055    /* Store these values locally to avoid multiple function calls */
29056    timeout = ast_rtp_instance_get_timeout(dialog->rtp);
29057    hold_timeout = ast_rtp_instance_get_hold_timeout(dialog->rtp);
29058    keepalive = ast_rtp_instance_get_keepalive(dialog->rtp);
29059 
29060    /* If we have no timers set, return now */
29061    if (!keepalive && !timeout && !hold_timeout) {
29062       return CMP_MATCH;
29063    }
29064 
29065    /* Check AUDIO RTP keepalives */
29066    if (dialog->lastrtptx && keepalive && (t > dialog->lastrtptx + keepalive)) {
29067       /* Need to send an empty RTP packet */
29068       dialog->lastrtptx = time(NULL);
29069       ast_rtp_instance_sendcng(dialog->rtp, 0);
29070    }
29071 
29072    /*! \todo Check video RTP keepalives
29073 
29074       Do we need to move the lastrtptx to the RTP structure to have one for audio and one
29075       for video? It really does belong to the RTP structure.
29076    */
29077 
29078    /* Check AUDIO RTP timers */
29079    if (dialog->lastrtprx && (timeout || hold_timeout) && (t > dialog->lastrtprx + timeout)) {
29080       if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD) || (hold_timeout && (t > dialog->lastrtprx + hold_timeout))) {
29081          /* Needs a hangup */
29082          if (timeout) {
29083             if (!dialog->owner || ast_channel_trylock(dialog->owner)) {
29084                /*
29085                 * Don't block, just try again later.
29086                 * If there was no owner, the call is dead already.
29087                 */
29088                return 0;
29089             }
29090             ast_log(LOG_NOTICE, "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
29091                ast_channel_name(dialog->owner), (long) (t - dialog->lastrtprx));
29092             manager_event(EVENT_FLAG_CALL, "SessionTimeout", "Source: RTPTimeout\r\n"
29093                   "Channel: %s\r\nUniqueid: %s\r\n", ast_channel_name(dialog->owner), ast_channel_uniqueid(dialog->owner));
29094             /* Issue a softhangup */
29095             ast_softhangup_nolock(dialog->owner, AST_SOFTHANGUP_DEV);
29096             ast_channel_unlock(dialog->owner);
29097             /* forget the timeouts for this call, since a hangup
29098                has already been requested and we don't want to
29099                repeatedly request hangups
29100             */
29101             ast_rtp_instance_set_timeout(dialog->rtp, 0);
29102             ast_rtp_instance_set_hold_timeout(dialog->rtp, 0);
29103             if (dialog->vrtp) {
29104                ast_rtp_instance_set_timeout(dialog->vrtp, 0);
29105                ast_rtp_instance_set_hold_timeout(dialog->vrtp, 0);
29106             }
29107             /* finally unlink the dialog from dialogs_rtpcheck. */
29108             return CMP_MATCH;
29109          }
29110       }
29111    }
29112    return 0;
29113 }
29114 
29115 /*! \brief The SIP monitoring thread
29116 \note This thread monitors all the SIP sessions and peers that needs notification of mwi
29117    (and thus do not have a separate thread) indefinitely
29118 */
29119 static void *do_monitor(void *data)
29120 {
29121    int res;
29122    time_t t;
29123    int reloading;
29124 
29125    /* Add an I/O event to our SIP UDP socket */
29126    if (sipsock > -1) {
29127       sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
29128    }
29129 
29130    /* From here on out, we die whenever asked */
29131    for(;;) {
29132       /* Check for a reload request */
29133       ast_mutex_lock(&sip_reload_lock);
29134       reloading = sip_reloading;
29135       sip_reloading = FALSE;
29136       ast_mutex_unlock(&sip_reload_lock);
29137       if (reloading) {
29138          ast_verb(1, "Reloading SIP\n");
29139          sip_do_reload(sip_reloadreason);
29140 
29141          /* Change the I/O fd of our UDP socket */
29142          if (sipsock > -1) {
29143             if (sipsock_read_id) {
29144                sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
29145             } else {
29146                sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
29147             }
29148          } else if (sipsock_read_id) {
29149             ast_io_remove(io, sipsock_read_id);
29150             sipsock_read_id = NULL;
29151          }
29152       }
29153 
29154       /* Check for dialogs needing to be killed */
29155       t = time(NULL);
29156 
29157       /*
29158        * Check dialogs with rtp and rtptimeout.
29159        * All dialogs which have rtp are in dialogs_rtpcheck.
29160        */
29161       ao2_t_callback(dialogs_rtpcheck, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE,
29162          dialog_checkrtp_cb, &t,
29163          "callback to check rtptimeout and hangup calls if necessary");
29164       /*
29165        * Check dialogs marked to be destroyed.
29166        * All dialogs with needdestroy set are in dialogs_needdestroy.
29167        */
29168       ao2_t_callback(dialogs_needdestroy, OBJ_NODATA | OBJ_MULTIPLE, dialog_needdestroy,
29169          NULL, "callback to check dialogs which need to be destroyed");
29170 
29171       /* XXX TODO The scheduler usage in this module does not have sufficient
29172        * synchronization being done between running the scheduler and places
29173        * scheduling tasks.  As it is written, any scheduled item may not run
29174        * any sooner than about  1 second, regardless of whether a sooner time
29175        * was asked for. */
29176 
29177       pthread_testcancel();
29178       /* Wait for sched or io */
29179       res = ast_sched_wait(sched);
29180       if ((res < 0) || (res > 1000)) {
29181          res = 1000;
29182       }
29183       res = ast_io_wait(io, res);
29184       if (res > 20) {
29185          ast_debug(1, "chan_sip: ast_io_wait ran %d all at once\n", res);
29186       }
29187       ast_mutex_lock(&monlock);
29188       res = ast_sched_runq(sched);
29189       if (res >= 20) {
29190          ast_debug(1, "chan_sip: ast_sched_runq ran %d all at once\n", res);
29191       }
29192       ast_mutex_unlock(&monlock);
29193    }
29194 
29195    /* Never reached */
29196    return NULL;
29197 }
29198 
29199 /*! \brief Start the channel monitor thread */
29200 static int restart_monitor(void)
29201 {
29202    /* If we're supposed to be stopped -- stay stopped */
29203    if (monitor_thread == AST_PTHREADT_STOP)
29204       return 0;
29205    ast_mutex_lock(&monlock);
29206    if (monitor_thread == pthread_self()) {
29207       ast_mutex_unlock(&monlock);
29208       ast_log(LOG_WARNING, "Cannot kill myself\n");
29209       return -1;
29210    }
29211    if (monitor_thread != AST_PTHREADT_NULL) {
29212       /* Wake up the thread */
29213       pthread_kill(monitor_thread, SIGURG);
29214    } else {
29215       /* Start a new monitor */
29216       if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
29217          ast_mutex_unlock(&monlock);
29218          ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
29219          return -1;
29220       }
29221    }
29222    ast_mutex_unlock(&monlock);
29223    return 0;
29224 }
29225 
29226 static void acl_change_event_cb(const struct ast_event *event, void *userdata)
29227 {
29228    ast_log(LOG_NOTICE, "Reloading chan_sip in response to ACL change event.\n");
29229 
29230    ast_mutex_lock(&sip_reload_lock);
29231 
29232    if (sip_reloading) {
29233       ast_verbose("Previous SIP reload not yet done\n");
29234    } else {
29235       sip_reloading = TRUE;
29236       sip_reloadreason = CHANNEL_ACL_RELOAD;
29237    }
29238 
29239    ast_mutex_unlock(&sip_reload_lock);
29240 
29241    restart_monitor();
29242 }
29243 
29244 /*! \brief Session-Timers: Restart session timer */
29245 static void restart_session_timer(struct sip_pvt *p)
29246 {
29247    if (p->stimer->st_active == TRUE) {
29248       ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
29249       AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
29250             dialog_unref(p, "Removing session timer ref"));
29251       start_session_timer(p);
29252    }
29253 }
29254 
29255 
29256 /*! \brief Session-Timers: Stop session timer */
29257 static void stop_session_timer(struct sip_pvt *p)
29258 {
29259    if (p->stimer->st_active == TRUE) {
29260       p->stimer->st_active = FALSE;
29261       ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
29262       AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
29263             dialog_unref(p, "removing session timer ref"));
29264    }
29265 }
29266 
29267 
29268 /*! \brief Session-Timers: Start session timer */
29269 static void start_session_timer(struct sip_pvt *p)
29270 {
29271    unsigned int timeout_ms;
29272 
29273    if (p->stimer->st_schedid > -1) {
29274       /* in the event a timer is already going, stop it */
29275       ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
29276       AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
29277          dialog_unref(p, "unref stimer->st_schedid from dialog"));
29278    }
29279 
29280    /*
29281     * RFC 4028 Section 10
29282     * If the side not performing refreshes does not receive a
29283     * session refresh request before the session expiration, it SHOULD send
29284     * a BYE to terminate the session, slightly before the session
29285     * expiration.  The minimum of 32 seconds and one third of the session
29286     * interval is RECOMMENDED.
29287     */
29288 
29289    timeout_ms = (1000 * p->stimer->st_interval);
29290    if (p->stimer->st_ref == SESSION_TIMER_REFRESHER_US) {
29291       timeout_ms /= 2;
29292    } else {
29293       timeout_ms -= MIN(timeout_ms / 3, 32000);
29294    }
29295 
29296    p->stimer->st_schedid = ast_sched_add(sched, timeout_ms, proc_session_timer,
29297          dialog_ref(p, "adding session timer ref"));
29298 
29299    if (p->stimer->st_schedid < 0) {
29300       dialog_unref(p, "removing session timer ref");
29301       ast_log(LOG_ERROR, "ast_sched_add failed - %s\n", p->callid);
29302    } else {
29303       p->stimer->st_active = TRUE;
29304       ast_debug(2, "Session timer started: %d - %s %ums\n", p->stimer->st_schedid, p->callid, timeout_ms);
29305    }
29306 }
29307 
29308 
29309 /*! \brief Session-Timers: Process session refresh timeout event */
29310 static int proc_session_timer(const void *vp)
29311 {
29312    struct sip_pvt *p = (struct sip_pvt *) vp;
29313    int res = 0;
29314 
29315    if (!p->stimer) {
29316       ast_log(LOG_WARNING, "Null stimer in proc_session_timer - %s\n", p->callid);
29317       goto return_unref;
29318    }
29319 
29320    ast_debug(2, "Session timer expired: %d - %s\n", p->stimer->st_schedid, p->callid);
29321 
29322    if (!p->owner) {
29323       goto return_unref;
29324    }
29325 
29326    if ((p->stimer->st_active != TRUE) || (ast_channel_state(p->owner) != AST_STATE_UP)) {
29327       goto return_unref;
29328    }
29329 
29330    if (p->stimer->st_ref == SESSION_TIMER_REFRESHER_US) {
29331       res = 1;
29332       if (T38_ENABLED == p->t38.state) {
29333          transmit_reinvite_with_sdp(p, TRUE, TRUE);
29334       } else {
29335          transmit_reinvite_with_sdp(p, FALSE, TRUE);
29336       }
29337    } else {
29338       if (p->stimer->quit_flag) {
29339          goto return_unref;
29340       }
29341       ast_log(LOG_WARNING, "Session-Timer expired - %s\n", p->callid);
29342       sip_pvt_lock(p);
29343       while (p->owner && ast_channel_trylock(p->owner)) {
29344          sip_pvt_unlock(p);
29345          usleep(1);
29346          if (p->stimer && p->stimer->quit_flag) {
29347             goto return_unref;
29348          }
29349          sip_pvt_lock(p);
29350       }
29351 
29352       manager_event(EVENT_FLAG_CALL, "SessionTimeout", "Source: SIPSessionTimer\r\n"
29353             "Channel: %s\r\nUniqueid: %s\r\n", ast_channel_name(p->owner), ast_channel_uniqueid(p->owner));
29354       ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
29355       ast_channel_unlock(p->owner);
29356       sip_pvt_unlock(p);
29357    }
29358 
29359 return_unref:
29360    if (!res) {
29361       /* An error occurred.  Stop session timer processing */
29362       if (p->stimer) {
29363          ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
29364          /* Don't pass go, don't collect $200.. we are the scheduled
29365           * callback. We can rip ourself out here. */
29366          p->stimer->st_schedid = -1;
29367          /* Calling stop_session_timer is nice for consistent debug
29368           * logs. */
29369          stop_session_timer(p);
29370       }
29371 
29372       /* If we are not asking to be rescheduled, then we need to release our
29373        * reference to the dialog. */
29374       dialog_unref(p, "removing session timer ref");
29375    }
29376 
29377    return res;
29378 }
29379 
29380 
29381 /*! \brief Session-Timers: Function for parsing Min-SE header */
29382 int parse_minse (const char *p_hdrval, int *const p_interval)
29383 {
29384    if (ast_strlen_zero(p_hdrval)) {
29385       ast_log(LOG_WARNING, "Null Min-SE header\n");
29386       return -1;
29387    }
29388 
29389    *p_interval = 0;
29390    p_hdrval = ast_skip_blanks(p_hdrval);
29391    if (!sscanf(p_hdrval, "%30d", p_interval)) {
29392       ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
29393       return -1;
29394    }
29395 
29396    ast_debug(2, "Received Min-SE: %d\n", *p_interval);
29397    return 0;
29398 }
29399 
29400 
29401 /*! \brief Session-Timers: Function for parsing Session-Expires header */
29402 int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher_param *const p_ref)
29403 {
29404    char *p_token;
29405    int  ref_idx;
29406    char *p_se_hdr;
29407 
29408    if (ast_strlen_zero(p_hdrval)) {
29409       ast_log(LOG_WARNING, "Null Session-Expires header\n");
29410       return -1;
29411    }
29412 
29413    *p_ref = SESSION_TIMER_REFRESHER_PARAM_UNKNOWN;
29414    *p_interval = 0;
29415 
29416    p_se_hdr = ast_strdupa(p_hdrval);
29417    p_se_hdr = ast_skip_blanks(p_se_hdr);
29418 
29419    while ((p_token = strsep(&p_se_hdr, ";"))) {
29420       p_token = ast_skip_blanks(p_token);
29421       if (!sscanf(p_token, "%30d", p_interval)) {
29422          ast_log(LOG_WARNING, "Parsing of Session-Expires failed\n");
29423          return -1;
29424       }
29425 
29426       ast_debug(2, "Session-Expires: %d\n", *p_interval);
29427 
29428       if (!p_se_hdr)
29429          continue;
29430 
29431       p_se_hdr = ast_skip_blanks(p_se_hdr);
29432       ref_idx = strlen("refresher=");
29433       if (!strncasecmp(p_se_hdr, "refresher=", ref_idx)) {
29434          p_se_hdr += ref_idx;
29435          p_se_hdr = ast_skip_blanks(p_se_hdr);
29436 
29437          if (!strncasecmp(p_se_hdr, "uac", strlen("uac"))) {
29438             *p_ref = SESSION_TIMER_REFRESHER_PARAM_UAC;
29439             ast_debug(2, "Refresher: UAC\n");
29440          } else if (!strncasecmp(p_se_hdr, "uas", strlen("uas"))) {
29441             *p_ref = SESSION_TIMER_REFRESHER_PARAM_UAS;
29442             ast_debug(2, "Refresher: UAS\n");
29443          } else {
29444             ast_log(LOG_WARNING, "Invalid refresher value %s\n", p_se_hdr);
29445             return -1;
29446          }
29447          break;
29448       }
29449    }
29450    return 0;
29451 }
29452 
29453 
29454 /*! \brief Handle 422 response to INVITE with session-timer requested
29455 
29456    Session-Timers:   An INVITE originated by Asterisk that asks for session-timers support
29457    from the UAS can result into a 422 response. This is how a UAS or an intermediary proxy
29458    server tells Asterisk that the session refresh interval offered by Asterisk is too low
29459    for them.  The proc_422_rsp() function handles a 422 response.  It extracts the Min-SE
29460    header that comes back in 422 and sends a new INVITE accordingly. */
29461 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp)
29462 {
29463    int rtn;
29464    const char *p_hdrval;
29465    int minse;
29466 
29467    p_hdrval = sip_get_header(rsp, "Min-SE");
29468    if (ast_strlen_zero(p_hdrval)) {
29469       ast_log(LOG_WARNING, "422 response without a Min-SE header %s\n", p_hdrval);
29470       return;
29471    }
29472    rtn = parse_minse(p_hdrval, &minse);
29473    if (rtn != 0) {
29474       ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
29475       return;
29476    }
29477    p->stimer->st_cached_min_se = minse;
29478    if (p->stimer->st_interval < minse) {
29479       p->stimer->st_interval = minse;
29480    }
29481    transmit_invite(p, SIP_INVITE, 1, 2, NULL);
29482 }
29483 
29484 
29485 /*! \brief Get Max or Min SE (session timer expiry)
29486  * \param p pointer to the SIP dialog
29487  * \param max if true, get max se, otherwise min se
29488 */
29489 int st_get_se(struct sip_pvt *p, int max)
29490 {
29491    if (max == TRUE) {
29492       if (p->stimer->st_cached_max_se) {
29493          return  p->stimer->st_cached_max_se;
29494       }
29495       if (p->relatedpeer) {
29496          p->stimer->st_cached_max_se = p->relatedpeer->stimer.st_max_se;
29497          return (p->stimer->st_cached_max_se);
29498       }
29499       p->stimer->st_cached_max_se = global_max_se;
29500       return (p->stimer->st_cached_max_se);
29501    } 
29502    /* Find Min SE timer */
29503    if (p->stimer->st_cached_min_se) {
29504       return p->stimer->st_cached_min_se;
29505    } 
29506    if (p->relatedpeer) {
29507       p->stimer->st_cached_min_se = p->relatedpeer->stimer.st_min_se;
29508       return (p->stimer->st_cached_min_se);
29509    }
29510    p->stimer->st_cached_min_se = global_min_se;
29511    return (p->stimer->st_cached_min_se);
29512 }
29513 
29514 
29515 /*! \brief Get the entity (UAC or UAS) that's acting as the session-timer refresher
29516  * \note This is only called when processing an INVITE, so in that case Asterisk is
29517  *       always currently the UAS. If this is ever used to process responses, the
29518  *       function will have to be changed.
29519  * \param p pointer to the SIP dialog
29520 */
29521 enum st_refresher st_get_refresher(struct sip_pvt *p)
29522 {
29523    if (p->stimer->st_cached_ref != SESSION_TIMER_REFRESHER_AUTO) {
29524       return p->stimer->st_cached_ref;
29525    }
29526 
29527    if (p->relatedpeer) {
29528       p->stimer->st_cached_ref = (p->relatedpeer->stimer.st_ref == SESSION_TIMER_REFRESHER_PARAM_UAC) ? SESSION_TIMER_REFRESHER_THEM : SESSION_TIMER_REFRESHER_US;
29529       return p->stimer->st_cached_ref;
29530    }
29531    
29532    p->stimer->st_cached_ref = (global_st_refresher == SESSION_TIMER_REFRESHER_PARAM_UAC) ? SESSION_TIMER_REFRESHER_THEM : SESSION_TIMER_REFRESHER_US;
29533    return p->stimer->st_cached_ref;
29534 }
29535 
29536 
29537 /*!
29538  * \brief Get the session-timer mode 
29539  * \param p pointer to the SIP dialog 
29540  * \param no_cached, set this to true in order to force a peername lookup on
29541  *        the session timer mode.
29542 */
29543 enum st_mode st_get_mode(struct sip_pvt *p, int no_cached)
29544 {
29545    if (!p->stimer) {
29546       sip_st_alloc(p);
29547       if (!p->stimer) {
29548          return SESSION_TIMER_MODE_INVALID;
29549       }
29550    }
29551 
29552    if (!no_cached && p->stimer->st_cached_mode != SESSION_TIMER_MODE_INVALID)
29553       return p->stimer->st_cached_mode;
29554 
29555    if (p->relatedpeer) {
29556       p->stimer->st_cached_mode = p->relatedpeer->stimer.st_mode_oper;
29557       return p->stimer->st_cached_mode;
29558    }
29559 
29560    p->stimer->st_cached_mode = global_st_mode;
29561    return global_st_mode;
29562 }
29563 
29564 /*! \brief Send keep alive packet to peer */
29565 static int sip_send_keepalive(const void *data)
29566 {
29567    struct sip_peer *peer = (struct sip_peer*) data;
29568    int res = 0;
29569    const char keepalive[] = "\r\n";
29570 
29571    peer->keepalivesend = -1;
29572 
29573    if (!peer->keepalive || ast_sockaddr_isnull(&peer->addr)) {
29574       sip_unref_peer(peer, "release keepalive peer ref");
29575       return 0;
29576    }
29577 
29578    /* Send the packet out using the proper method for this peer */
29579    if ((peer->socket.fd != -1) && (peer->socket.type == SIP_TRANSPORT_UDP)) {
29580       res = ast_sendto(peer->socket.fd, keepalive, sizeof(keepalive), 0, &peer->addr);
29581    } else if ((peer->socket.type & (SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS)) &&
29582          (peer->socket.tcptls_session) &&
29583          (peer->socket.tcptls_session->fd != -1)) {
29584       res = sip_tcptls_write(peer->socket.tcptls_session, keepalive, sizeof(keepalive));
29585    } else if (peer->socket.type == SIP_TRANSPORT_UDP) {
29586       res = ast_sendto(sipsock, keepalive, sizeof(keepalive), 0, &peer->addr);
29587    }
29588 
29589    if (res == -1) {
29590       switch (errno) {
29591       case EBADF:             /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
29592       case EHOSTUNREACH:      /* Host can't be reached */
29593       case ENETDOWN:          /* Interface down */
29594       case ENETUNREACH:       /* Network failure */
29595       case ECONNREFUSED:      /* ICMP port unreachable */
29596          res = XMIT_ERROR;       /* Don't bother with trying to transmit again */
29597       }
29598    }
29599 
29600    if (res != sizeof(keepalive)) {
29601       ast_log(LOG_WARNING, "sip_send_keepalive to %s returned %d: %s\n", ast_sockaddr_stringify(&peer->addr), res, strerror(errno));
29602    }
29603 
29604    AST_SCHED_REPLACE_UNREF(peer->keepalivesend, sched,
29605             peer->keepalive * 1000, sip_send_keepalive, peer,
29606             sip_unref_peer(_data, "removing keepalive peer ref"),
29607             sip_unref_peer(peer, "removing keepalive peer ref"),
29608             sip_ref_peer(peer, "adding keepalive peer ref"));
29609 
29610    sip_unref_peer(peer, "release keepalive peer ref");
29611 
29612    return 0;
29613 }
29614 
29615 /*! \brief React to lack of answer to Qualify poke */
29616 static int sip_poke_noanswer(const void *data)
29617 {
29618    struct sip_peer *peer = (struct sip_peer *)data;
29619 
29620    peer->pokeexpire = -1;
29621 
29622    if (peer->lastms > -1) {
29623       ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE!  Last qualify: %d\n", peer->name, peer->lastms);
29624       if (sip_cfg.peer_rtupdate) {
29625          ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", "-1", SENTINEL);
29626       }
29627       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
29628       if (sip_cfg.regextenonqualify) {
29629          register_peer_exten(peer, FALSE);
29630       }
29631    }
29632 
29633    if (peer->call) {
29634       dialog_unlink_all(peer->call);
29635       peer->call = dialog_unref(peer->call, "unref dialog peer->call");
29636       /* peer->call = sip_destroy(peer->call);*/
29637    }
29638 
29639    /* Don't send a devstate change if nothing changed. */
29640    if (peer->lastms > -1) {
29641       peer->lastms = -1;
29642       ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", peer->name);
29643    }
29644 
29645    /* Try again quickly */
29646    AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
29647          DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer,
29648          sip_unref_peer(_data, "removing poke peer ref"),
29649          sip_unref_peer(peer, "removing poke peer ref"),
29650          sip_ref_peer(peer, "adding poke peer ref"));
29651 
29652    /* Release the ref held by the running scheduler entry */
29653    sip_unref_peer(peer, "release peer poke noanswer ref");
29654 
29655    return 0;
29656 }
29657 
29658 /*! \brief Check availability of peer, also keep NAT open
29659 \note This is done with 60 seconds between each ping,
29660    unless forced by cli or manager. If peer is unreachable,
29661    we check every 10th second by default.
29662 \note Do *not* hold a pvt lock while calling this function.
29663    This function calls sip_alloc, which can cause a deadlock
29664    if another sip_pvt is held.
29665 */
29666 static int sip_poke_peer(struct sip_peer *peer, int force)
29667 {
29668    struct sip_pvt *p;
29669    int xmitres = 0;
29670    
29671    if ((!peer->maxms && !force) || ast_sockaddr_isnull(&peer->addr)) {
29672       /* IF we have no IP, or this isn't to be monitored, return
29673         immediately after clearing things out */
29674       AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
29675             sip_unref_peer(peer, "removing poke peer ref"));
29676       
29677       peer->lastms = 0;
29678       if (peer->call) {
29679          peer->call = dialog_unref(peer->call, "unref dialog peer->call");
29680       }
29681       return 0;
29682    }
29683    if (peer->call) {
29684       if (sipdebug) {
29685          ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
29686       }
29687       dialog_unlink_all(peer->call);
29688       peer->call = dialog_unref(peer->call, "unref dialog peer->call");
29689       /* peer->call = sip_destroy(peer->call); */
29690    }
29691    if (!(p = sip_alloc(NULL, NULL, 0, SIP_OPTIONS, NULL, NULL))) {
29692       return -1;
29693    }
29694    peer->call = dialog_ref(p, "copy sip alloc from p to peer->call");
29695 
29696    p->sa = peer->addr;
29697    p->recv = peer->addr;
29698    copy_socket_data(&p->socket, &peer->socket);
29699    ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
29700    ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
29701    ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
29702 
29703    /* Send OPTIONs to peer's fullcontact */
29704    if (!ast_strlen_zero(peer->fullcontact)) {
29705       ast_string_field_set(p, fullcontact, peer->fullcontact);
29706    }
29707 
29708    if (!ast_strlen_zero(peer->fromuser)) {
29709       ast_string_field_set(p, fromuser, peer->fromuser);
29710    }
29711 
29712    if (!ast_strlen_zero(peer->tohost)) {
29713       ast_string_field_set(p, tohost, peer->tohost);
29714    } else {
29715       ast_string_field_set(p, tohost, ast_sockaddr_stringify_host_remote(&peer->addr));
29716    }
29717 
29718    /* Recalculate our side, and recalculate Call ID */
29719    ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
29720    build_via(p);
29721 
29722    /* Change the dialog callid. */
29723    change_callid_pvt(p, NULL);
29724 
29725    AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
29726          sip_unref_peer(peer, "removing poke peer ref"));
29727    
29728    if (p->relatedpeer)
29729       p->relatedpeer = sip_unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
29730    p->relatedpeer = sip_ref_peer(peer, "setting the relatedpeer field in the dialog");
29731    ast_set_flag(&p->flags[0], SIP_OUTGOING);
29732 #ifdef VOCAL_DATA_HACK
29733    ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
29734    xmitres = transmit_invite(p, SIP_INVITE, 0, 2, NULL); /* sinks the p refcount */
29735 #else
29736    xmitres = transmit_invite(p, SIP_OPTIONS, 0, 2, NULL); /* sinks the p refcount */
29737 #endif
29738    peer->ps = ast_tvnow();
29739    if (xmitres == XMIT_ERROR) {
29740       /* Immediately unreachable, network problems */
29741       sip_poke_noanswer(sip_ref_peer(peer, "add ref for peerexpire (fake, for sip_poke_noanswer to remove)"));
29742    } else if (!force) {
29743       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, peer->maxms * 2, sip_poke_noanswer, peer,
29744             sip_unref_peer(_data, "removing poke peer ref"),
29745             sip_unref_peer(peer, "removing poke peer ref"),
29746             sip_ref_peer(peer, "adding poke peer ref"));
29747    }
29748    dialog_unref(p, "unref dialog at end of sip_poke_peer, obtained from sip_alloc, just before it goes out of scope");
29749    return 0;
29750 }
29751 
29752 /*! \brief Part of PBX channel interface
29753 \note
29754 \par  Return values:---
29755 
29756    If we have qualify on and the device is not reachable, regardless of registration
29757    state we return AST_DEVICE_UNAVAILABLE
29758 
29759    For peers with call limit:
29760       - not registered        AST_DEVICE_UNAVAILABLE
29761       - registered, no call         AST_DEVICE_NOT_INUSE
29762       - registered, active calls    AST_DEVICE_INUSE
29763       - registered, call limit reached AST_DEVICE_BUSY
29764       - registered, onhold       AST_DEVICE_ONHOLD
29765       - registered, ringing         AST_DEVICE_RINGING
29766 
29767    For peers without call limit:
29768       - not registered        AST_DEVICE_UNAVAILABLE
29769       - registered            AST_DEVICE_NOT_INUSE
29770       - fixed IP (!dynamic)         AST_DEVICE_NOT_INUSE
29771    
29772    Peers that does not have a known call and can't be reached by OPTIONS
29773       - unreachable           AST_DEVICE_UNAVAILABLE
29774 
29775    If we return AST_DEVICE_UNKNOWN, the device state engine will try to find
29776    out a state by walking the channel list.
29777 
29778    The queue system (\ref app_queue.c) treats a member as "active"
29779    if devicestate is != AST_DEVICE_UNAVAILBALE && != AST_DEVICE_INVALID
29780 
29781    When placing a call to the queue member, queue system sets a member to busy if
29782    != AST_DEVICE_NOT_INUSE and != AST_DEVICE_UNKNOWN
29783 
29784 */
29785 static int sip_devicestate(const char *data)
29786 {
29787    char *host;
29788    char *tmp;
29789    struct sip_peer *p;
29790 
29791    int res = AST_DEVICE_INVALID;
29792 
29793    /* make sure data is not null. Maybe unnecessary, but better be safe */
29794    host = ast_strdupa(data ? data : "");
29795    if ((tmp = strchr(host, '@')))
29796       host = tmp + 1;
29797 
29798    ast_debug(3, "Checking device state for peer %s\n", host);
29799 
29800    /* If sip_find_peer asks for a realtime peer, then this breaks rtautoclear.  This
29801     * is because when a peer tries to autoexpire, the last thing it does is to
29802     * queue up an event telling the system that the devicestate has changed
29803     * (presumably to unavailable).  If we ask for a realtime peer here, this would
29804     * load it BACK into memory, thus defeating the point of trying to clear dead
29805     * hosts out of memory.
29806     */
29807    if ((p = sip_find_peer(host, NULL, FALSE, FINDALLDEVICES, TRUE, 0))) {
29808       if (!(ast_sockaddr_isnull(&p->addr) && ast_sockaddr_isnull(&p->defaddr))) {
29809          /* we have an address for the peer */
29810 
29811          /* Check status in this order
29812             - Hold
29813             - Ringing
29814             - Busy (enforced only by call limit)
29815             - Inuse (we have a call)
29816             - Unreachable (qualify)
29817             If we don't find any of these state, report AST_DEVICE_NOT_INUSE
29818             for registered devices */
29819 
29820          if (p->onhold)
29821             /* First check for hold or ring states */
29822             res = AST_DEVICE_ONHOLD;
29823          else if (p->ringing) {
29824             if (p->ringing == p->inuse)
29825                res = AST_DEVICE_RINGING;
29826             else
29827                res = AST_DEVICE_RINGINUSE;
29828          } else if (p->call_limit && (p->inuse == p->call_limit))
29829             /* check call limit */
29830             res = AST_DEVICE_BUSY;
29831          else if (p->call_limit && p->busy_level && p->inuse >= p->busy_level)
29832             /* We're forcing busy before we've reached the call limit */
29833             res = AST_DEVICE_BUSY;
29834          else if (p->call_limit && p->inuse)
29835             /* Not busy, but we do have a call */
29836             res = AST_DEVICE_INUSE;
29837          else if (p->maxms && ((p->lastms > p->maxms) || (p->lastms < 0)))
29838             /* We don't have a call. Are we reachable at all? Requires qualify= */
29839             res = AST_DEVICE_UNAVAILABLE;
29840          else  /* Default reply if we're registered and have no other data */
29841             res = AST_DEVICE_NOT_INUSE;
29842       } else {
29843          /* there is no address, it's unavailable */
29844          res = AST_DEVICE_UNAVAILABLE;
29845       }
29846       sip_unref_peer(p, "sip_unref_peer, from sip_devicestate, release ref from sip_find_peer");
29847    }
29848 
29849    return res;
29850 }
29851 
29852 /*! \brief PBX interface function -build SIP pvt structure
29853  * SIP calls initiated by the PBX arrive here.
29854  *
29855  * \verbatim
29856  * SIP Dial string syntax:
29857  *    SIP/devicename
29858  * or SIP/username@domain (SIP uri)
29859  * or SIP/username[:password[:md5secret[:authname[:transport]]]]@host[:port]
29860  * or SIP/devicename/extension
29861  * or SIP/devicename/extension/IPorHost
29862  * or SIP/username@domain//IPorHost
29863  * and there is an optional [!dnid] argument you can append to alter the
29864  * To: header.
29865  * \endverbatim
29866  */
29867 static struct ast_channel *sip_request_call(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, const char *dest, int *cause)
29868 {
29869    struct sip_pvt *p;
29870    struct ast_channel *tmpc = NULL;
29871    char *ext = NULL, *host;
29872    char tmp[256];
29873    char tmp2[256];
29874    char *dnid;
29875    char *secret = NULL;
29876    char *md5secret = NULL;
29877    char *authname = NULL;
29878    char *trans = NULL;
29879    char dialstring[256];
29880    char *remote_address;
29881    enum sip_transport transport = 0;
29882    struct ast_callid *callid;
29883    AST_DECLARE_APP_ARGS(args,
29884       AST_APP_ARG(peerorhost);
29885       AST_APP_ARG(exten);
29886       AST_APP_ARG(remote_address);
29887    );
29888 
29889    /* mask request with some set of allowed formats.
29890     * XXX this needs to be fixed.
29891     * The original code uses AST_FORMAT_AUDIO_MASK, but it is
29892     * unclear what to use here. We have global_capabilities, which is
29893     * configured from sip.conf, and sip_tech.capabilities, which is
29894     * hardwired to all audio formats.
29895     */
29896    if (!(ast_format_cap_has_type(cap, AST_FORMAT_TYPE_AUDIO))) {
29897       ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format %s while capability is %s\n",
29898       ast_getformatname_multiple(tmp, sizeof(tmp), cap),
29899       ast_getformatname_multiple(tmp2, sizeof(tmp2), sip_cfg.caps));
29900       *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;   /* Can't find codec to connect to host */
29901       return NULL;
29902    }
29903    ast_debug(1, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), cap));
29904 
29905    if (ast_strlen_zero(dest)) {
29906       ast_log(LOG_ERROR, "Unable to create channel with empty destination.\n");
29907       *cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
29908       return NULL;
29909    }
29910 
29911    callid = ast_read_threadstorage_callid();
29912    if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE, NULL, callid))) {
29913       ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", dest);
29914       *cause = AST_CAUSE_SWITCH_CONGESTION;
29915       if (callid) {
29916          ast_callid_unref(callid);
29917       }
29918       return NULL;
29919    }
29920 
29921    p->outgoing_call = TRUE;
29922 
29923    snprintf(dialstring, sizeof(dialstring), "%s/%s", type, dest);
29924    ast_string_field_set(p, dialstring, dialstring);
29925 
29926    if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
29927       dialog_unlink_all(p);
29928       dialog_unref(p, "unref dialog p from mem fail");
29929       /* sip_destroy(p); */
29930       ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
29931       *cause = AST_CAUSE_SWITCH_CONGESTION;
29932       if (callid) {
29933          ast_callid_unref(callid);
29934       }
29935       return NULL;
29936    }
29937 
29938    /* Save the destination, the SIP dial string */
29939    ast_copy_string(tmp, dest, sizeof(tmp));
29940 
29941    /* Find DNID and take it away */
29942    dnid = strchr(tmp, '!');
29943    if (dnid != NULL) {
29944       *dnid++ = '\0';
29945       ast_string_field_set(p, todnid, dnid);
29946    }
29947 
29948    /* Divvy up the items separated by slashes */
29949    AST_NONSTANDARD_APP_ARGS(args, tmp, '/');
29950 
29951    /* Find at sign - @ */
29952    host = strchr(args.peerorhost, '@');
29953    if (host) {
29954       *host++ = '\0';
29955       ext = args.peerorhost;
29956       secret = strchr(ext, ':');
29957    }
29958    if (secret) {
29959       *secret++ = '\0';
29960       md5secret = strchr(secret, ':');
29961    }
29962    if (md5secret) {
29963       *md5secret++ = '\0';
29964       authname = strchr(md5secret, ':');
29965    }
29966    if (authname) {
29967       *authname++ = '\0';
29968       trans = strchr(authname, ':');
29969    }
29970    if (trans) {
29971       *trans++ = '\0';
29972       if (!strcasecmp(trans, "tcp"))
29973          transport = SIP_TRANSPORT_TCP;
29974       else if (!strcasecmp(trans, "tls"))
29975          transport = SIP_TRANSPORT_TLS;
29976       else {
29977          if (strcasecmp(trans, "udp"))
29978             ast_log(LOG_WARNING, "'%s' is not a valid transport option to Dial() for SIP calls, using udp by default.\n", trans);
29979          transport = SIP_TRANSPORT_UDP;
29980       }
29981    } else { /* use default */
29982       transport = SIP_TRANSPORT_UDP;
29983    }
29984 
29985    if (!host) {
29986       ext = args.exten;
29987       host = args.peerorhost;
29988       remote_address = args.remote_address;
29989    } else {
29990       remote_address = args.remote_address;
29991       if (!ast_strlen_zero(args.exten)) {
29992          ast_log(LOG_NOTICE, "Conflicting extension values given. Using '%s' and not '%s'\n", ext, args.exten);
29993       }
29994    }
29995 
29996    if (!ast_strlen_zero(remote_address)) {
29997       p->options->outboundproxy = proxy_from_config(remote_address, 0, NULL);
29998       if (!p->options->outboundproxy) {
29999          ast_log(LOG_WARNING, "Unable to parse outboundproxy %s. We will not use this remote IP address\n", remote_address);
30000       }
30001    }
30002 
30003    set_socket_transport(&p->socket, transport);
30004 
30005    /* We now have
30006       host = peer name, DNS host name or DNS domain (for SRV)
30007       ext = extension (user part of URI)
30008       dnid = destination of the call (applies to the To: header)
30009    */
30010    if (create_addr(p, host, NULL, 1)) {
30011       *cause = AST_CAUSE_UNREGISTERED;
30012       ast_debug(3, "Cant create SIP call - target device not registered\n");
30013       dialog_unlink_all(p);
30014       dialog_unref(p, "unref dialog p UNREGISTERED");
30015       /* sip_destroy(p); */
30016       if (callid) {
30017          ast_callid_unref(callid);
30018       }
30019       return NULL;
30020    }
30021    if (ast_strlen_zero(p->peername) && ext)
30022       ast_string_field_set(p, peername, ext);
30023    /* Recalculate our side, and recalculate Call ID */
30024    ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
30025    /* When chan_sip is first loaded or reloaded, we need to check for NAT and set the appropiate flags
30026       now that we have the auto_* settings. */
30027    check_for_nat(&p->sa, p);
30028    /* If there is a peer related to this outgoing call and it hasn't re-registered after
30029       a reload, we need to set the peer's NAT flags accordingly. */
30030    if (p->relatedpeer) {
30031 
30032       if (!ast_strlen_zero(p->relatedpeer->fullcontact) && !p->natdetected &&
30033          (ast_test_flag(&p->flags[2], SIP_PAGE3_NAT_AUTO_RPORT) && !ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT))) {
30034          /* We need to make an attempt to determine if a peer is behind NAT
30035             if the peer has the auto_force_rport flag set. */
30036          struct ast_sockaddr tmpaddr;
30037 
30038          __set_address_from_contact(p->relatedpeer->fullcontact, &tmpaddr, 0);
30039 
30040          check_for_nat(&tmpaddr, p);
30041       }
30042 
30043       set_peer_nat(p, p->relatedpeer);
30044    }
30045 
30046    do_setnat(p);
30047 
30048    build_via(p);
30049 
30050    /* Change the dialog callid. */
30051    change_callid_pvt(p, NULL);
30052 
30053    /* We have an extension to call, don't use the full contact here */
30054    /* This to enable dialing registered peers with extension dialling,
30055       like SIP/peername/extension   
30056       SIP/peername will still use the full contact
30057     */
30058    if (ext) {
30059       ast_string_field_set(p, username, ext);
30060       ast_string_field_set(p, fullcontact, NULL);
30061    }
30062    if (secret && !ast_strlen_zero(secret))
30063       ast_string_field_set(p, peersecret, secret);
30064 
30065    if (md5secret && !ast_strlen_zero(md5secret))
30066       ast_string_field_set(p, peermd5secret, md5secret);
30067 
30068    if (authname && !ast_strlen_zero(authname))
30069       ast_string_field_set(p, authname, authname);
30070 #if 0
30071    printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
30072 #endif
30073    ast_format_cap_append(p->prefcaps, cap);
30074    ast_format_cap_joint_copy(cap, p->caps, p->jointcaps);
30075 
30076    sip_pvt_lock(p);
30077 
30078    tmpc = sip_new(p, AST_STATE_DOWN, host, requestor ? ast_channel_linkedid(requestor) : NULL, callid);  /* Place the call */
30079    if (callid) {
30080       callid = ast_callid_unref(callid);
30081    }
30082 
30083    if (sip_cfg.callevents)
30084       manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
30085          "Channel: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
30086          p->owner ? ast_channel_name(p->owner) : "", "SIP", p->callid, p->fullcontact, p->peername);
30087    sip_pvt_unlock(p);
30088    if (!tmpc) {
30089       dialog_unlink_all(p);
30090       /* sip_destroy(p); */
30091    } else {
30092       ast_channel_unlock(tmpc);
30093    }
30094    dialog_unref(p, "toss pvt ptr at end of sip_request_call");
30095    ast_update_use_count();
30096    restart_monitor();
30097    return tmpc;
30098 }
30099 
30100 /*! \brief Parse insecure= setting in sip.conf and set flags according to setting */
30101 static void set_insecure_flags (struct ast_flags *flags, const char *value, int lineno)
30102 {
30103    if (ast_strlen_zero(value))
30104       return;
30105 
30106    if (!ast_false(value)) {
30107       char buf[64];
30108       char *word, *next;
30109 
30110       ast_copy_string(buf, value, sizeof(buf));
30111       next = buf;
30112       while ((word = strsep(&next, ","))) {
30113          if (!strcasecmp(word, "port"))
30114             ast_set_flag(&flags[0], SIP_INSECURE_PORT);
30115          else if (!strcasecmp(word, "invite"))
30116             ast_set_flag(&flags[0], SIP_INSECURE_INVITE);
30117          else
30118             ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", value, lineno);
30119       }
30120    }
30121 }
30122 
30123 /*!
30124   \brief Handle T.38 configuration options common to users and peers
30125   \returns non-zero if any config options were handled, zero otherwise
30126 */
30127 static int handle_t38_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v,
30128                unsigned int *maxdatagram)
30129 {
30130    int res = 1;
30131 
30132    if (!strcasecmp(v->name, "t38pt_udptl")) {
30133       char *buf = ast_strdupa(v->value);
30134       char *word, *next = buf;
30135 
30136       ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT);
30137 
30138       while ((word = strsep(&next, ","))) {
30139          if (ast_true(word) || !strcasecmp(word, "fec")) {
30140             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
30141             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_FEC);
30142          } else if (!strcasecmp(word, "redundancy")) {
30143             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
30144             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY);
30145          } else if (!strcasecmp(word, "none")) {
30146             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
30147             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL);
30148          } else if (!strncasecmp(word, "maxdatagram=", 12)) {
30149             if (sscanf(&word[12], "%30u", maxdatagram) != 1) {
30150                ast_log(LOG_WARNING, "Invalid maxdatagram '%s' at line %d of %s\n", v->value, v->lineno, config);
30151                *maxdatagram = global_t38_maxdatagram;
30152             }
30153          }
30154       }
30155    } else if (!strcasecmp(v->name, "t38pt_usertpsource")) {
30156       ast_set_flag(&mask[1], SIP_PAGE2_UDPTL_DESTINATION);
30157       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_UDPTL_DESTINATION);
30158    } else {
30159       res = 0;
30160    }
30161 
30162    return res;
30163 }
30164 
30165 /*!
30166   \brief Handle flag-type options common to configuration of devices - peers
30167   \param flags array of three struct ast_flags
30168   \param mask array of three struct ast_flags
30169   \param v linked list of config variables to process
30170   \returns non-zero if any config options were handled, zero otherwise
30171 */
30172 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
30173 {
30174    int res = 1;
30175 
30176    if (!strcasecmp(v->name, "trustrpid")) {
30177       ast_set_flag(&mask[0], SIP_TRUSTRPID);
30178       ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
30179    } else if (!strcasecmp(v->name, "sendrpid")) {
30180       ast_set_flag(&mask[0], SIP_SENDRPID);
30181       if (!strcasecmp(v->value, "pai")) {
30182          ast_set_flag(&flags[0], SIP_SENDRPID_PAI);
30183       } else if (!strcasecmp(v->value, "rpid")) {
30184          ast_set_flag(&flags[0], SIP_SENDRPID_RPID);
30185       } else if (ast_true(v->value)) {
30186          ast_set_flag(&flags[0], SIP_SENDRPID_RPID);
30187       }
30188    } else if (!strcasecmp(v->name, "rpid_update")) {
30189       ast_set_flag(&mask[1], SIP_PAGE2_RPID_UPDATE);
30190       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RPID_UPDATE);
30191    } else if (!strcasecmp(v->name, "rpid_immediate")) {
30192       ast_set_flag(&mask[1], SIP_PAGE2_RPID_IMMEDIATE);
30193       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RPID_IMMEDIATE);
30194    } else if (!strcasecmp(v->name, "trust_id_outbound")) {
30195       ast_set_flag(&mask[1], SIP_PAGE2_TRUST_ID_OUTBOUND);
30196       ast_clear_flag(&flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND);
30197       if (!strcasecmp(v->value, "legacy")) {
30198          ast_set_flag(&flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND_LEGACY);
30199       } else if (ast_true(v->value)) {
30200          ast_set_flag(&flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND_YES);
30201       } else if (ast_false(v->value)) {
30202          ast_set_flag(&flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND_NO);
30203       } else {
30204          ast_log(LOG_WARNING, "Unknown trust_id_outbound mode '%s' on line %d, using legacy\n", v->value, v->lineno);
30205          ast_set_flag(&flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND_LEGACY);
30206       }
30207    } else if (!strcasecmp(v->name, "g726nonstandard")) {
30208       ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
30209       ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
30210    } else if (!strcasecmp(v->name, "useclientcode")) {
30211       ast_set_flag(&mask[0], SIP_USECLIENTCODE);
30212       ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
30213    } else if (!strcasecmp(v->name, "dtmfmode")) {
30214       ast_set_flag(&mask[0], SIP_DTMF);
30215       ast_clear_flag(&flags[0], SIP_DTMF);
30216       if (!strcasecmp(v->value, "inband"))
30217          ast_set_flag(&flags[0], SIP_DTMF_INBAND);
30218       else if (!strcasecmp(v->value, "rfc2833"))
30219          ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
30220       else if (!strcasecmp(v->value, "info"))
30221          ast_set_flag(&flags[0], SIP_DTMF_INFO);
30222       else if (!strcasecmp(v->value, "shortinfo"))
30223          ast_set_flag(&flags[0], SIP_DTMF_SHORTINFO);
30224       else if (!strcasecmp(v->value, "auto"))
30225          ast_set_flag(&flags[0], SIP_DTMF_AUTO);
30226       else {
30227          ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
30228          ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
30229       }
30230    } else if (!strcasecmp(v->name, "nat")) {
30231       sip_parse_nat_option(v->value, mask, flags);
30232    } else if (!strcasecmp(v->name, "directmedia") || !strcasecmp(v->name, "canreinvite")) {
30233       ast_set_flag(&mask[0], SIP_REINVITE);
30234       ast_clear_flag(&flags[0], SIP_REINVITE);
30235       if (ast_true(v->value)) {
30236          ast_set_flag(&flags[0], SIP_DIRECT_MEDIA | SIP_DIRECT_MEDIA_NAT);
30237       } else if (!ast_false(v->value)) {
30238          char buf[64];
30239          char *word, *next = buf;
30240 
30241          ast_copy_string(buf, v->value, sizeof(buf));
30242          while ((word = strsep(&next, ","))) {
30243             if (!strcasecmp(word, "update")) {
30244                ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_DIRECT_MEDIA);
30245             } else if (!strcasecmp(word, "nonat")) {
30246                ast_set_flag(&flags[0], SIP_DIRECT_MEDIA);
30247                ast_clear_flag(&flags[0], SIP_DIRECT_MEDIA_NAT);
30248             } else if (!strcasecmp(word, "outgoing")) {
30249                ast_set_flag(&flags[0], SIP_DIRECT_MEDIA);
30250                ast_set_flag(&mask[2], SIP_PAGE3_DIRECT_MEDIA_OUTGOING);
30251                ast_set_flag(&flags[2], SIP_PAGE3_DIRECT_MEDIA_OUTGOING);
30252             } else {
30253                ast_log(LOG_WARNING, "Unknown directmedia mode '%s' on line %d\n", v->value, v->lineno);
30254             }
30255          }
30256       }
30257    } else if (!strcasecmp(v->name, "insecure")) {
30258       ast_set_flag(&mask[0], SIP_INSECURE);
30259       ast_clear_flag(&flags[0], SIP_INSECURE);
30260       set_insecure_flags(&flags[0], v->value, v->lineno);   
30261    } else if (!strcasecmp(v->name, "progressinband")) {
30262       ast_set_flag(&mask[0], SIP_PROG_INBAND);
30263       ast_clear_flag(&flags[0], SIP_PROG_INBAND);
30264       if (ast_true(v->value))
30265          ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
30266       else if (strcasecmp(v->value, "never"))
30267          ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
30268    } else if (!strcasecmp(v->name, "promiscredir")) {
30269       ast_set_flag(&mask[0], SIP_PROMISCREDIR);
30270       ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
30271    } else if (!strcasecmp(v->name, "videosupport")) {
30272       if (!strcasecmp(v->value, "always")) {
30273          ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
30274          ast_set_flag(&flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
30275       } else {
30276          ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
30277          ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
30278       }
30279    } else if (!strcasecmp(v->name, "textsupport")) {
30280       ast_set_flag(&mask[1], SIP_PAGE2_TEXTSUPPORT);
30281       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_TEXTSUPPORT);
30282       res = 1;
30283    } else if (!strcasecmp(v->name, "allowoverlap")) {
30284       ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
30285       ast_clear_flag(&flags[1], SIP_PAGE2_ALLOWOVERLAP);
30286       if (ast_true(v->value)) {
30287          ast_set_flag(&flags[1], SIP_PAGE2_ALLOWOVERLAP_YES);
30288       } else if (!strcasecmp(v->value, "dtmf")){
30289          ast_set_flag(&flags[1], SIP_PAGE2_ALLOWOVERLAP_DTMF);
30290       }
30291    } else if (!strcasecmp(v->name, "allowsubscribe")) {
30292       ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
30293       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
30294    } else if (!strcasecmp(v->name, "ignoresdpversion")) {
30295       ast_set_flag(&mask[1], SIP_PAGE2_IGNORESDPVERSION);
30296       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_IGNORESDPVERSION);
30297    } else if (!strcasecmp(v->name, "faxdetect")) {
30298       ast_set_flag(&mask[1], SIP_PAGE2_FAX_DETECT);
30299       if (ast_true(v->value)) {
30300          ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
30301       } else if (ast_false(v->value)) {
30302          ast_clear_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
30303       } else {
30304          char *buf = ast_strdupa(v->value);
30305          char *word, *next = buf;
30306 
30307          while ((word = strsep(&next, ","))) {
30308             if (!strcasecmp(word, "cng")) {
30309                ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_CNG);
30310             } else if (!strcasecmp(word, "t38")) {
30311                ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_T38);
30312             } else {
30313                ast_log(LOG_WARNING, "Unknown faxdetect mode '%s' on line %d.\n", word, v->lineno);
30314             }
30315          }
30316       }
30317    } else if (!strcasecmp(v->name, "rfc2833compensate")) {
30318       ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
30319       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
30320    } else if (!strcasecmp(v->name, "buggymwi")) {
30321       ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
30322       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
30323    } else
30324       res = 0;
30325 
30326    return res;
30327 }
30328 
30329 /*! \brief Add SIP domain to list of domains we are responsible for */
30330 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
30331 {
30332    struct domain *d;
30333 
30334    if (ast_strlen_zero(domain)) {
30335       ast_log(LOG_WARNING, "Zero length domain.\n");
30336       return 1;
30337    }
30338 
30339    if (!(d = ast_calloc(1, sizeof(*d))))
30340       return 0;
30341 
30342    ast_copy_string(d->domain, domain, sizeof(d->domain));
30343 
30344    if (!ast_strlen_zero(context))
30345       ast_copy_string(d->context, context, sizeof(d->context));
30346 
30347    d->mode = mode;
30348 
30349    AST_LIST_LOCK(&domain_list);
30350    AST_LIST_INSERT_TAIL(&domain_list, d, list);
30351    AST_LIST_UNLOCK(&domain_list);
30352 
30353    if (sipdebug)
30354       ast_debug(1, "Added local SIP domain '%s'\n", domain);
30355 
30356    return 1;
30357 }
30358 
30359 /*! \brief  check_sip_domain: Check if domain part of uri is local to our server */
30360 static int check_sip_domain(const char *domain, char *context, size_t len)
30361 {
30362    struct domain *d;
30363    int result = 0;
30364 
30365    AST_LIST_LOCK(&domain_list);
30366    AST_LIST_TRAVERSE(&domain_list, d, list) {
30367       if (strcasecmp(d->domain, domain)) {
30368          continue;
30369       }
30370 
30371       if (len && !ast_strlen_zero(d->context))
30372          ast_copy_string(context, d->context, len);
30373 
30374       result = 1;
30375       break;
30376    }
30377    AST_LIST_UNLOCK(&domain_list);
30378 
30379    return result;
30380 }
30381 
30382 /*! \brief Clear our domain list (at reload) */
30383 static void clear_sip_domains(void)
30384 {
30385    struct domain *d;
30386 
30387    AST_LIST_LOCK(&domain_list);
30388    while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
30389       ast_free(d);
30390    AST_LIST_UNLOCK(&domain_list);
30391 }
30392 
30393 /*!
30394  * \internal
30395  * \brief Realm authentication container destructor.
30396  *
30397  * \param obj Container object to destroy.
30398  *
30399  * \return Nothing
30400  */
30401 static void destroy_realm_authentication(void *obj)
30402 {
30403    struct sip_auth_container *credentials = obj;
30404    struct sip_auth *auth;
30405 
30406    while ((auth = AST_LIST_REMOVE_HEAD(&credentials->list, node))) {
30407       ast_free(auth);
30408    }
30409 }
30410 
30411 /*!
30412  * \internal
30413  * \brief Add realm authentication to credentials.
30414  *
30415  * \param credentials Realm authentication container to create/add authentication credentials.
30416  * \param configuration Credential configuration value.
30417  * \param lineno Line number in config file.
30418  *
30419  * \return Nothing
30420  */
30421 static void add_realm_authentication(struct sip_auth_container **credentials, const char *configuration, int lineno)
30422 {
30423    char *authcopy;
30424    char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
30425    struct sip_auth *auth;
30426 
30427    if (ast_strlen_zero(configuration)) {
30428       /* Nothing to add */
30429       return;
30430    }
30431 
30432    ast_debug(1, "Auth config ::  %s\n", configuration);
30433 
30434    authcopy = ast_strdupa(configuration);
30435    username = authcopy;
30436 
30437    /* split user[:secret] and relm */
30438    realm = strrchr(username, '@');
30439    if (realm)
30440       *realm++ = '\0';
30441    if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
30442       ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
30443       return;
30444    }
30445 
30446    /* parse username at ':' for secret, or '#" for md5secret */
30447    if ((secret = strchr(username, ':'))) {
30448       *secret++ = '\0';
30449    } else if ((md5secret = strchr(username, '#'))) {
30450       *md5secret++ = '\0';
30451    }
30452 
30453    /* Create the continer if needed. */
30454    if (!*credentials) {
30455       *credentials = ao2_t_alloc(sizeof(**credentials), destroy_realm_authentication,
30456          "Create realm auth container.");
30457       if (!*credentials) {
30458          /* Failed to create the credentials container. */
30459          return;
30460       }
30461    }
30462 
30463    /* Create the authentication credential entry. */
30464    auth = ast_calloc(1, sizeof(*auth));
30465    if (!auth) {
30466       return;
30467    }
30468    ast_copy_string(auth->realm, realm, sizeof(auth->realm));
30469    ast_copy_string(auth->username, username, sizeof(auth->username));
30470    if (secret)
30471       ast_copy_string(auth->secret, secret, sizeof(auth->secret));
30472    if (md5secret)
30473       ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
30474 
30475    /* Add credential to container list. */
30476    AST_LIST_INSERT_TAIL(&(*credentials)->list, auth, node);
30477 
30478    ast_verb(3, "Added authentication for realm %s\n", realm);
30479 }
30480 
30481 /*!
30482  * \internal
30483  * \brief Find authentication for a specific realm.
30484  *
30485  * \param credentials Realm authentication container to search.
30486  * \param realm Authentication realm to find.
30487  *
30488  * \return Found authentication credential or NULL.
30489  */
30490 static struct sip_auth *find_realm_authentication(struct sip_auth_container *credentials, const char *realm)
30491 {
30492    struct sip_auth *auth;
30493 
30494    if (credentials) {
30495       AST_LIST_TRAVERSE(&credentials->list, auth, node) {
30496          if (!strcasecmp(auth->realm, realm)) {
30497             break;
30498          }
30499       }
30500    } else {
30501       auth = NULL;
30502    }
30503 
30504    return auth;
30505 }
30506 
30507 /*! \brief
30508  * implement the setvar config line
30509  */
30510 static struct ast_variable *add_var(const char *buf, struct ast_variable *list)
30511 {
30512    struct ast_variable *tmpvar = NULL;
30513    char *varname = ast_strdupa(buf), *varval = NULL;
30514    
30515    if ((varval = strchr(varname, '='))) {
30516       *varval++ = '\0';
30517       if ((tmpvar = ast_variable_new(varname, varval, ""))) {
30518          tmpvar->next = list;
30519          list = tmpvar;
30520       }
30521    }
30522    return list;
30523 }
30524 
30525 /*! \brief Set peer defaults before configuring specific configurations */
30526 static void set_peer_defaults(struct sip_peer *peer)
30527 {
30528    if (peer->expire == 0) {
30529       /* Don't reset expire or port time during reload
30530          if we have an active registration
30531       */
30532       peer->expire = -1;
30533       peer->pokeexpire = -1;
30534       peer->keepalivesend = -1;
30535       set_socket_transport(&peer->socket, SIP_TRANSPORT_UDP);
30536    }
30537    peer->type = SIP_TYPE_PEER;
30538    ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
30539    ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
30540    ast_copy_flags(&peer->flags[2], &global_flags[2], SIP_PAGE3_FLAGS_TO_COPY);
30541    ast_string_field_set(peer, context, sip_cfg.default_context);
30542    ast_string_field_set(peer, record_on_feature, sip_cfg.default_record_on_feature);
30543    ast_string_field_set(peer, record_off_feature, sip_cfg.default_record_off_feature);
30544    ast_string_field_set(peer, messagecontext, sip_cfg.messagecontext);
30545    ast_string_field_set(peer, subscribecontext, sip_cfg.default_subscribecontext);
30546    ast_string_field_set(peer, language, default_language);
30547    ast_string_field_set(peer, mohinterpret, default_mohinterpret);
30548    ast_string_field_set(peer, mohsuggest, default_mohsuggest);
30549    ast_string_field_set(peer, engine, default_engine);
30550    ast_sockaddr_setnull(&peer->addr);
30551    ast_sockaddr_setnull(&peer->defaddr);
30552    ast_format_cap_copy(peer->caps, sip_cfg.caps);
30553    peer->maxcallbitrate = default_maxcallbitrate;
30554    peer->rtptimeout = global_rtptimeout;
30555    peer->rtpholdtimeout = global_rtpholdtimeout;
30556    peer->rtpkeepalive = global_rtpkeepalive;
30557    peer->allowtransfer = sip_cfg.allowtransfer;
30558    peer->autoframing = global_autoframing;
30559    peer->t38_maxdatagram = global_t38_maxdatagram;
30560    peer->qualifyfreq = global_qualifyfreq;
30561    if (global_callcounter)
30562       peer->call_limit=INT_MAX;
30563    ast_string_field_set(peer, vmexten, default_vmexten);
30564    ast_string_field_set(peer, secret, "");
30565    ast_string_field_set(peer, description, "");
30566    ast_string_field_set(peer, remotesecret, "");
30567    ast_string_field_set(peer, md5secret, "");
30568    ast_string_field_set(peer, cid_num, "");
30569    ast_string_field_set(peer, cid_name, "");
30570    ast_string_field_set(peer, cid_tag, "");
30571    ast_string_field_set(peer, fromdomain, "");
30572    ast_string_field_set(peer, fromuser, "");
30573    ast_string_field_set(peer, regexten, "");
30574    peer->callgroup = 0;
30575    peer->pickupgroup = 0;
30576    peer->maxms = default_qualify;
30577    peer->keepalive = default_keepalive;
30578    peer->prefs = default_prefs;
30579    ast_string_field_set(peer, zone, default_zone);
30580    peer->stimer.st_mode_oper = global_st_mode;  /* Session-Timers */
30581    peer->stimer.st_ref = global_st_refresher;
30582    peer->stimer.st_min_se = global_min_se;
30583    peer->stimer.st_max_se = global_max_se;
30584    peer->timer_t1 = global_t1;
30585    peer->timer_b = global_timer_b;
30586    clear_peer_mailboxes(peer);
30587    peer->disallowed_methods = sip_cfg.disallowed_methods;
30588    peer->transports = default_transports;
30589    peer->default_outbound_transport = default_primary_transport;
30590    if (peer->outboundproxy) {
30591       ao2_ref(peer->outboundproxy, -1);
30592       peer->outboundproxy = NULL;
30593    }
30594 }
30595 
30596 /*! \brief Create temporary peer (used in autocreatepeer mode) */
30597 static struct sip_peer *temp_peer(const char *name)
30598 {
30599    struct sip_peer *peer;
30600 
30601    if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
30602       return NULL;
30603 
30604    if (ast_string_field_init(peer, 512)) {
30605       ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
30606       return NULL;
30607    }
30608    
30609    if (!(peer->cc_params = ast_cc_config_params_init())) {
30610       ao2_t_ref(peer, -1, "failed to allocate cc_params for peer");
30611       return NULL;
30612    }
30613 
30614    if (!(peer->caps = ast_format_cap_alloc_nolock())) {
30615       ao2_t_ref(peer, -1, "failed to allocate format capabilities, drop peer");
30616       return NULL;
30617    }
30618 
30619    ast_atomic_fetchadd_int(&apeerobjs, 1);
30620    set_peer_defaults(peer);
30621 
30622    ast_copy_string(peer->name, name, sizeof(peer->name));
30623 
30624    peer->selfdestruct = TRUE;
30625    peer->host_dynamic = TRUE;
30626    peer->prefs = default_prefs;
30627    reg_source_db(peer);
30628 
30629    return peer;
30630 }
30631 
30632 /*! \todo document this function */
30633 static void add_peer_mailboxes(struct sip_peer *peer, const char *value)
30634 {
30635    char *next, *mbox, *context;
30636 
30637    next = ast_strdupa(value);
30638 
30639    while ((mbox = context = strsep(&next, ","))) {
30640       struct sip_mailbox *mailbox;
30641       int duplicate = 0;
30642       /* remove leading/trailing whitespace from mailbox string */
30643       mbox = ast_strip(mbox);
30644       strsep(&context, "@");
30645 
30646       if (ast_strlen_zero(mbox)) {
30647          continue;
30648       }
30649 
30650       /* Check whether the mailbox is already in the list */
30651       AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
30652          if (!strcmp(mailbox->mailbox, mbox) && !strcmp(S_OR(mailbox->context, ""), S_OR(context, ""))) {
30653             duplicate = 1;
30654             break;
30655          }
30656       }
30657       if (duplicate) {
30658          continue;
30659       }
30660 
30661       if (!(mailbox = ast_calloc(1, sizeof(*mailbox) + strlen(mbox) + strlen(S_OR(context, ""))))) {
30662          continue;
30663       }
30664 
30665       if (!ast_strlen_zero(context)) {
30666          mailbox->context = mailbox->mailbox + strlen(mbox) + 1;
30667          strcpy(mailbox->context, context); /* SAFE */
30668       }
30669       strcpy(mailbox->mailbox, mbox); /* SAFE */
30670 
30671       AST_LIST_INSERT_TAIL(&peer->mailboxes, mailbox, entry);
30672    }
30673 }
30674 
30675 /*! \brief Build peer from configuration (file or realtime static/dynamic) */
30676 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only)
30677 {
30678    struct sip_peer *peer = NULL;
30679    struct ast_acl_list *oldacl = NULL;
30680    struct ast_acl_list *olddirectmediaacl = NULL;
30681    int found = 0;
30682    int firstpass = 1;
30683    uint16_t port = 0;
30684    int format = 0;      /* Ama flags */
30685    int timerb_set = 0, timert1_set = 0;
30686    time_t regseconds = 0;
30687    struct ast_flags peerflags[3] = {{(0)}};
30688    struct ast_flags mask[3] = {{(0)}};
30689    struct sip_peer tmp_peer;
30690    const char *srvlookup = NULL;
30691    static int deprecation_warning = 1;
30692    int alt_fullcontact = alt ? 1 : 0, headercount = 0;
30693    struct ast_str *fullcontact = ast_str_alloca(512);
30694    int acl_change_subscription_needed = 0;
30695 
30696    if (!realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
30697       /* Note we do NOT use sip_find_peer here, to avoid realtime recursion */
30698       /* We also use a case-sensitive comparison (unlike sip_find_peer) so
30699          that case changes made to the peer name will be properly handled
30700          during reload
30701       */
30702       ast_copy_string(tmp_peer.name, name, sizeof(tmp_peer.name));
30703       peer = ao2_t_find(peers, &tmp_peer, OBJ_POINTER | OBJ_UNLINK, "find and unlink peer from peers table");
30704    }
30705 
30706    if (peer) {
30707       /* Already in the list, remove it and it will be added back (or FREE'd)  */
30708       found++;
30709       /* we've unlinked the peer from the peers container but not unlinked from the peers_by_ip container yet
30710         this leads to a wrong refcounter and the peer object is never destroyed */
30711       if (!ast_sockaddr_isnull(&peer->addr)) {
30712          ao2_t_unlink(peers_by_ip, peer, "ao2_unlink peer from peers_by_ip table");
30713       }
30714       if (!(peer->the_mark))
30715          firstpass = 0;
30716    } else {
30717       if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct"))) {
30718          return NULL;
30719       }
30720       if (!(peer->caps = ast_format_cap_alloc_nolock())) {
30721          ao2_t_ref(peer, -1, "failed to allocate format capabilities, drop peer");
30722          return NULL;
30723       }
30724       if (ast_string_field_init(peer, 512)) {
30725          ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
30726          return NULL;
30727       }
30728 
30729       if (!(peer->cc_params = ast_cc_config_params_init())) {
30730          ao2_t_ref(peer, -1, "failed to allocate cc_params for peer");
30731          return NULL;
30732       }
30733 
30734       if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
30735          ast_atomic_fetchadd_int(&rpeerobjs, 1);
30736          ast_debug(3, "-REALTIME- peer built. Name: %s. Peer objects: %d\n", name, rpeerobjs);
30737       } else
30738          ast_atomic_fetchadd_int(&speerobjs, 1);
30739    }
30740 
30741    /* Note that our peer HAS had its reference count increased */
30742    if (firstpass) {
30743       oldacl = peer->acl;
30744       peer->acl = NULL;
30745       olddirectmediaacl = peer->directmediaacl;
30746       peer->directmediaacl = NULL;
30747       set_peer_defaults(peer);   /* Set peer defaults */
30748       peer->type = 0;
30749    }
30750 
30751    /* in case the case of the peer name has changed, update the name */
30752    ast_copy_string(peer->name, name, sizeof(peer->name));
30753 
30754    /* If we have channel variables, remove them (reload) */
30755    if (peer->chanvars) {
30756       ast_variables_destroy(peer->chanvars);
30757       peer->chanvars = NULL;
30758       /* XXX should unregister ? */
30759    }
30760 
30761    if (found)
30762       peer->portinuri = 0;
30763 
30764    /* If we have realm authentication information, remove them (reload) */
30765    ao2_lock(peer);
30766    if (peer->auth) {
30767       ao2_t_ref(peer->auth, -1, "Removing old peer authentication");
30768       peer->auth = NULL;
30769    }
30770    ao2_unlock(peer);
30771 
30772    /* clear the transport information.  We will detect if a default value is required after parsing the config */
30773    peer->default_outbound_transport = 0;
30774    peer->transports = 0;
30775 
30776    if (!devstate_only) {
30777       struct sip_mailbox *mailbox;
30778       AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
30779          mailbox->delme = 1;
30780       }
30781    }
30782 
30783    /* clear named callgroup and named pickup group container */
30784    peer->named_callgroups = ast_unref_namedgroups(peer->named_callgroups);
30785    peer->named_pickupgroups = ast_unref_namedgroups(peer->named_pickupgroups);
30786 
30787    for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
30788       if (!devstate_only) {
30789          if (handle_common_options(&peerflags[0], &mask[0], v)) {
30790             continue;
30791          }
30792          if (handle_t38_options(&peerflags[0], &mask[0], v, &peer->t38_maxdatagram)) {
30793             continue;
30794          }
30795          if (!strcasecmp(v->name, "transport")) {
30796             char *val = ast_strdupa(v->value);
30797             char *trans;
30798 
30799             peer->transports = peer->default_outbound_transport = 0;
30800             while ((trans = strsep(&val, ","))) {
30801                trans = ast_skip_blanks(trans);
30802 
30803                if (!strncasecmp(trans, "udp", 3)) {
30804                   peer->transports |= SIP_TRANSPORT_UDP;
30805                } else if (!strncasecmp(trans, "wss", 3)) {
30806                   peer->transports |= SIP_TRANSPORT_WSS;
30807                } else if (!strncasecmp(trans, "ws", 2)) {
30808                   peer->transports |= SIP_TRANSPORT_WS;
30809                } else if (sip_cfg.tcp_enabled && !strncasecmp(trans, "tcp", 3)) {
30810                   peer->transports |= SIP_TRANSPORT_TCP;
30811                } else if (default_tls_cfg.enabled && !strncasecmp(trans, "tls", 3)) {
30812                   peer->transports |= SIP_TRANSPORT_TLS;
30813                } else if (!strncasecmp(trans, "tcp", 3) || !strncasecmp(trans, "tls", 3)) {
30814                   ast_log(LOG_WARNING, "'%.3s' is not a valid transport type when %.3senable=no. If no other is specified, the defaults from general will be used.\n", trans, trans);
30815                } else {
30816                   ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, the defaults from general will be used.\n", trans);
30817                }
30818 
30819                if (!peer->default_outbound_transport) { /*!< The first transport listed should be default outbound */
30820                   peer->default_outbound_transport = peer->transports;
30821                }
30822             }
30823          } else if (realtime && !strcasecmp(v->name, "regseconds")) {
30824             ast_get_time_t(v->value, &regseconds, 0, NULL);
30825          } else if (realtime && !strcasecmp(v->name, "name")) {
30826             ast_copy_string(peer->name, v->value, sizeof(peer->name));
30827          } else if (realtime && !strcasecmp(v->name, "useragent")) {
30828             ast_string_field_set(peer, useragent, v->value);
30829          } else if (!strcasecmp(v->name, "type")) {
30830             if (!strcasecmp(v->value, "peer")) {
30831                peer->type |= SIP_TYPE_PEER;
30832             } else if (!strcasecmp(v->value, "user")) {
30833                peer->type |= SIP_TYPE_USER;
30834             } else if (!strcasecmp(v->value, "friend")) {
30835                peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
30836             }
30837          } else if (!strcasecmp(v->name, "remotesecret")) {
30838             ast_string_field_set(peer, remotesecret, v->value);
30839          } else if (!strcasecmp(v->name, "secret")) {
30840             ast_string_field_set(peer, secret, v->value);
30841          } else if (!strcasecmp(v->name, "description")) {
30842             ast_string_field_set(peer, description, v->value);
30843          } else if (!strcasecmp(v->name, "md5secret")) {
30844             ast_string_field_set(peer, md5secret, v->value);
30845          } else if (!strcasecmp(v->name, "auth")) {
30846             add_realm_authentication(&peer->auth, v->value, v->lineno);
30847          } else if (!strcasecmp(v->name, "callerid")) {
30848             char cid_name[80] = { '\0' }, cid_num[80] = { '\0' };
30849 
30850             ast_callerid_split(v->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
30851             ast_string_field_set(peer, cid_name, cid_name);
30852             ast_string_field_set(peer, cid_num, cid_num);
30853          } else if (!strcasecmp(v->name, "mwi_from")) {
30854             ast_string_field_set(peer, mwi_from, v->value);
30855          } else if (!strcasecmp(v->name, "fullname")) {
30856             ast_string_field_set(peer, cid_name, v->value);
30857          } else if (!strcasecmp(v->name, "trunkname")) {
30858             /* This is actually for a trunk, so we don't want to override callerid */
30859             ast_string_field_set(peer, cid_name, "");
30860          } else if (!strcasecmp(v->name, "cid_number")) {
30861             ast_string_field_set(peer, cid_num, v->value);
30862          } else if (!strcasecmp(v->name, "cid_tag")) {
30863             ast_string_field_set(peer, cid_tag, v->value);
30864          } else if (!strcasecmp(v->name, "context")) {
30865             ast_string_field_set(peer, context, v->value);
30866             ast_set_flag(&peer->flags[1], SIP_PAGE2_HAVEPEERCONTEXT);
30867          } else if (!strcasecmp(v->name, "recordonfeature")) {
30868             ast_string_field_set(peer, record_on_feature, v->value);
30869          } else if (!strcasecmp(v->name, "recordofffeature")) {
30870             ast_string_field_set(peer, record_off_feature, v->value);
30871          } else if (!strcasecmp(v->name, "outofcall_message_context")) {
30872             ast_string_field_set(peer, messagecontext, v->value);
30873          } else if (!strcasecmp(v->name, "subscribecontext")) {
30874             ast_string_field_set(peer, subscribecontext, v->value);
30875          } else if (!strcasecmp(v->name, "fromdomain")) {
30876             char *fromdomainport;
30877             ast_string_field_set(peer, fromdomain, v->value);
30878             if ((fromdomainport = strchr(peer->fromdomain, ':'))) {
30879                *fromdomainport++ = '\0';
30880                if (!(peer->fromdomainport = port_str2int(fromdomainport, 0))) {
30881                   ast_log(LOG_NOTICE, "'%s' is not a valid port number for fromdomain.\n",fromdomainport);
30882                }
30883             } else {
30884                peer->fromdomainport = STANDARD_SIP_PORT;
30885             }
30886          } else if (!strcasecmp(v->name, "usereqphone")) {
30887             ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
30888          } else if (!strcasecmp(v->name, "fromuser")) {
30889             ast_string_field_set(peer, fromuser, v->value);
30890          } else if (!strcasecmp(v->name, "outboundproxy")) {
30891             struct sip_proxy *proxy;
30892             if (ast_strlen_zero(v->value)) {
30893                ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf\n", v->lineno);
30894                continue;
30895             }
30896             proxy = proxy_from_config(v->value, v->lineno, peer->outboundproxy);
30897             if (!proxy) {
30898                ast_log(LOG_WARNING, "failure parsing the outbound proxy on line %d of sip.conf.\n", v->lineno);
30899                continue;
30900             }
30901             peer->outboundproxy = proxy;
30902          } else if (!strcasecmp(v->name, "host")) {
30903             if (!strcasecmp(v->value, "dynamic")) {
30904                /* They'll register with us */
30905                if ((!found && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) || !peer->host_dynamic) {
30906                   /* Initialize stuff if this is a new peer, or if it used to
30907                    * not be dynamic before the reload. */
30908                   ast_sockaddr_setnull(&peer->addr);
30909                }
30910                peer->host_dynamic = TRUE;
30911             } else {
30912                /* Non-dynamic.  Make sure we become that way if we're not */
30913                AST_SCHED_DEL_UNREF(sched, peer->expire,
30914                      sip_unref_peer(peer, "removing register expire ref"));
30915                peer->host_dynamic = FALSE;
30916                srvlookup = v->value;
30917             }
30918          } else if (!strcasecmp(v->name, "defaultip")) {
30919             if (!ast_strlen_zero(v->value) && ast_get_ip(&peer->defaddr, v->value)) {
30920                sip_unref_peer(peer, "sip_unref_peer: from build_peer defaultip");
30921                return NULL;
30922             }
30923          } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny") || !strcasecmp(v->name, "acl")) {
30924             int ha_error = 0;
30925             if (!ast_strlen_zero(v->value)) {
30926                ast_append_acl(v->name, v->value, &peer->acl, &ha_error, &acl_change_subscription_needed);
30927             }
30928             if (ha_error) {
30929                ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
30930             }
30931          } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny") || !strcasecmp(v->name, "contactacl")) {
30932             int ha_error = 0;
30933             if (!ast_strlen_zero(v->value)) {
30934                ast_append_acl(v->name + 7, v->value, &peer->contactacl, &ha_error, &acl_change_subscription_needed);
30935             }
30936             if (ha_error) {
30937                ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
30938             }
30939          } else if (!strcasecmp(v->name, "directmediapermit") || !strcasecmp(v->name, "directmediadeny") || !strcasecmp(v->name, "directmediaacl")) {
30940             int ha_error = 0;
30941             ast_append_acl(v->name + 11, v->value, &peer->directmediaacl, &ha_error, &acl_change_subscription_needed);
30942             if (ha_error) {
30943                ast_log(LOG_ERROR, "Bad directmedia ACL entry in configuration line %d : %s\n", v->lineno, v->value);
30944             }
30945          } else if (!strcasecmp(v->name, "port")) {
30946             peer->portinuri = 1;
30947             if (!(port = port_str2int(v->value, 0))) {
30948                if (realtime) {
30949                   /* If stored as integer, could be 0 for some DBs (notably MySQL) */
30950                   peer->portinuri = 0;
30951                } else {
30952                   ast_log(LOG_WARNING, "Invalid peer port configuration at line %d : %s\n", v->lineno, v->value);
30953                }
30954             }
30955          } else if (!strcasecmp(v->name, "callingpres")) {
30956             peer->callingpres = ast_parse_caller_presentation(v->value);
30957             if (peer->callingpres == -1) {
30958                peer->callingpres = atoi(v->value);
30959             }
30960          } else if (!strcasecmp(v->name, "username") || !strcmp(v->name, "defaultuser")) {   /* "username" is deprecated */
30961             ast_string_field_set(peer, username, v->value);
30962             if (!strcasecmp(v->name, "username")) {
30963                if (deprecation_warning) {
30964                   ast_log(LOG_NOTICE, "The 'username' field for sip peers has been deprecated in favor of the term 'defaultuser'\n");
30965                   deprecation_warning = 0;
30966                }
30967                peer->deprecated_username = 1;
30968             }
30969          } else if (!strcasecmp(v->name, "tonezone")) {
30970             struct ast_tone_zone *new_zone;
30971             if (!(new_zone = ast_get_indication_zone(v->value))) {
30972                ast_log(LOG_ERROR, "Unknown country code '%s' for tonezone in device [%s] at line %d. Check indications.conf for available country codes.\n", v->value, peer->name, v->lineno);
30973             } else {
30974                ast_tone_zone_unref(new_zone);
30975                ast_string_field_set(peer, zone, v->value);
30976             }
30977          } else if (!strcasecmp(v->name, "language")) {
30978             ast_string_field_set(peer, language, v->value);
30979          } else if (!strcasecmp(v->name, "regexten")) {
30980             ast_string_field_set(peer, regexten, v->value);
30981          } else if (!strcasecmp(v->name, "callbackextension")) {
30982             ast_string_field_set(peer, callback, v->value);
30983          } else if (!strcasecmp(v->name, "amaflags")) {
30984             format = ast_cdr_amaflags2int(v->value);
30985             if (format < 0) {
30986                ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
30987             } else {
30988                peer->amaflags = format;
30989             }
30990          } else if (!strcasecmp(v->name, "maxforwards")) {
30991             if (sscanf(v->value, "%30d", &peer->maxforwards) != 1
30992                || peer->maxforwards < 1 || 255 < peer->maxforwards) {
30993                ast_log(LOG_WARNING, "'%s' is not a valid maxforwards value at line %d.  Using default.\n", v->value, v->lineno);
30994                peer->maxforwards = sip_cfg.default_max_forwards;
30995             }
30996          } else if (!strcasecmp(v->name, "accountcode")) {
30997             ast_string_field_set(peer, accountcode, v->value);
30998          } else if (!strcasecmp(v->name, "mohinterpret")) {
30999             ast_string_field_set(peer, mohinterpret, v->value);
31000          } else if (!strcasecmp(v->name, "mohsuggest")) {
31001             ast_string_field_set(peer, mohsuggest, v->value);
31002          } else if (!strcasecmp(v->name, "parkinglot")) {
31003             ast_string_field_set(peer, parkinglot, v->value);
31004          } else if (!strcasecmp(v->name, "rtp_engine")) {
31005             ast_string_field_set(peer, engine, v->value);
31006          } else if (!strcasecmp(v->name, "mailbox")) {
31007             add_peer_mailboxes(peer, v->value);
31008          } else if (!strcasecmp(v->name, "hasvoicemail")) {
31009             /* People expect that if 'hasvoicemail' is set, that the mailbox will
31010              * be also set, even if not explicitly specified. */
31011             if (ast_true(v->value) && AST_LIST_EMPTY(&peer->mailboxes)) {
31012                add_peer_mailboxes(peer, name);
31013             }
31014          } else if (!strcasecmp(v->name, "subscribemwi")) {
31015             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
31016          } else if (!strcasecmp(v->name, "vmexten")) {
31017             ast_string_field_set(peer, vmexten, v->value);
31018          } else if (!strcasecmp(v->name, "callgroup")) {
31019             peer->callgroup = ast_get_group(v->value);
31020          } else if (!strcasecmp(v->name, "allowtransfer")) {
31021             peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
31022          } else if (!strcasecmp(v->name, "pickupgroup")) {
31023             peer->pickupgroup = ast_get_group(v->value);
31024          } else if (!strcasecmp(v->name, "namedcallgroup")) {
31025             peer->named_callgroups = ast_get_namedgroups(v->value);
31026          } else if (!strcasecmp(v->name, "namedpickupgroup")) {
31027             peer->named_pickupgroups = ast_get_namedgroups(v->value);
31028          } else if (!strcasecmp(v->name, "allow")) {
31029             int error = ast_parse_allow_disallow(&peer->prefs, peer->caps, v->value, TRUE);
31030             if (error) {
31031                ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
31032             }
31033          } else if (!strcasecmp(v->name, "disallow")) {
31034             int error =  ast_parse_allow_disallow(&peer->prefs, peer->caps, v->value, FALSE);
31035             if (error) {
31036                ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
31037             }
31038          } else if (!strcasecmp(v->name, "preferred_codec_only")) {
31039             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_PREFERRED_CODEC);
31040          } else if (!strcasecmp(v->name, "autoframing")) {
31041             peer->autoframing = ast_true(v->value);
31042          } else if (!strcasecmp(v->name, "rtptimeout")) {
31043             if ((sscanf(v->value, "%30d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
31044                ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
31045                peer->rtptimeout = global_rtptimeout;
31046             }
31047          } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
31048             if ((sscanf(v->value, "%30d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
31049                ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
31050                peer->rtpholdtimeout = global_rtpholdtimeout;
31051             }
31052          } else if (!strcasecmp(v->name, "rtpkeepalive")) {
31053             if ((sscanf(v->value, "%30d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
31054                ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d.  Using default.\n", v->value, v->lineno);
31055                peer->rtpkeepalive = global_rtpkeepalive;
31056             }
31057          } else if (!strcasecmp(v->name, "timert1")) {
31058             if ((sscanf(v->value, "%30d", &peer->timer_t1) != 1) || (peer->timer_t1 < 200) || (peer->timer_t1 < global_t1min)) {
31059                ast_log(LOG_WARNING, "'%s' is not a valid T1 time at line %d.  Using default.\n", v->value, v->lineno);
31060                peer->timer_t1 = global_t1min;
31061             }
31062             timert1_set = 1;
31063          } else if (!strcasecmp(v->name, "timerb")) {
31064             if ((sscanf(v->value, "%30d", &peer->timer_b) != 1) || (peer->timer_b < 200)) {
31065                ast_log(LOG_WARNING, "'%s' is not a valid Timer B time at line %d.  Using default.\n", v->value, v->lineno);
31066                peer->timer_b = global_timer_b;
31067             }
31068             timerb_set = 1;
31069          } else if (!strcasecmp(v->name, "setvar")) {
31070             peer->chanvars = add_var(v->value, peer->chanvars);
31071          } else if (!strcasecmp(v->name, "header")) {
31072             char tmp[4096];
31073             snprintf(tmp, sizeof(tmp), "__SIPADDHEADERpre%2d=%s", ++headercount, v->value);
31074             peer->chanvars = add_var(tmp, peer->chanvars);
31075          } else if (!strcasecmp(v->name, "qualifyfreq")) {
31076             int i;
31077             if (sscanf(v->value, "%30d", &i) == 1) {
31078                peer->qualifyfreq = i * 1000;
31079             } else {
31080                ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
31081                peer->qualifyfreq = global_qualifyfreq;
31082             }
31083          } else if (!strcasecmp(v->name, "maxcallbitrate")) {
31084             peer->maxcallbitrate = atoi(v->value);
31085             if (peer->maxcallbitrate < 0) {
31086                peer->maxcallbitrate = default_maxcallbitrate;
31087             }
31088          } else if (!strcasecmp(v->name, "session-timers")) {
31089             int i = (int) str2stmode(v->value);
31090             if (i < 0) {
31091                ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
31092                peer->stimer.st_mode_oper = global_st_mode;
31093             } else {
31094                peer->stimer.st_mode_oper = i;
31095             }
31096          } else if (!strcasecmp(v->name, "session-expires")) {
31097             if (sscanf(v->value, "%30d", &peer->stimer.st_max_se) != 1) {
31098                ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
31099                peer->stimer.st_max_se = global_max_se;
31100             }
31101          } else if (!strcasecmp(v->name, "session-minse")) {
31102             if (sscanf(v->value, "%30d", &peer->stimer.st_min_se) != 1) {
31103                ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
31104                peer->stimer.st_min_se = global_min_se;
31105             }
31106             if (peer->stimer.st_min_se < DEFAULT_MIN_SE) {
31107                ast_log(LOG_WARNING, "session-minse '%s' at line %d of %s is not allowed to be < %d secs\n", v->value, v->lineno, config, DEFAULT_MIN_SE);
31108                peer->stimer.st_min_se = global_min_se;
31109             }
31110          } else if (!strcasecmp(v->name, "session-refresher")) {
31111             int i = (int) str2strefresherparam(v->value);
31112             if (i < 0) {
31113                ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
31114                peer->stimer.st_ref = global_st_refresher;
31115             } else {
31116                peer->stimer.st_ref = i;
31117             }
31118          } else if (!strcasecmp(v->name, "disallowed_methods")) {
31119             char *disallow = ast_strdupa(v->value);
31120             mark_parsed_methods(&peer->disallowed_methods, disallow);
31121          } else if (!strcasecmp(v->name, "unsolicited_mailbox")) {
31122             ast_string_field_set(peer, unsolicited_mailbox, v->value);
31123          } else if (!strcasecmp(v->name, "use_q850_reason")) {
31124             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_Q850_REASON);
31125          } else if (!strcasecmp(v->name, "encryption")) {
31126             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_USE_SRTP);
31127          } else if (!strcasecmp(v->name, "encryption_taglen")) {
31128             ast_set2_flag(&peer->flags[2], !strcasecmp(v->value, "32"), SIP_PAGE3_SRTP_TAG_32);
31129          } else if (!strcasecmp(v->name, "snom_aoc_enabled")) {
31130             ast_set2_flag(&peer->flags[2], ast_true(v->value), SIP_PAGE3_SNOM_AOC);
31131          } else if (!strcasecmp(v->name, "avpf")) {
31132             ast_set2_flag(&peer->flags[2], ast_true(v->value), SIP_PAGE3_USE_AVPF);
31133          } else if (!strcasecmp(v->name, "icesupport")) {
31134             ast_set2_flag(&peer->flags[2], ast_true(v->value), SIP_PAGE3_ICE_SUPPORT);
31135          } else if (!strcasecmp(v->name, "force_avp")) {
31136             ast_set2_flag(&peer->flags[2], ast_true(v->value), SIP_PAGE3_FORCE_AVP);
31137          } else {
31138             ast_rtp_dtls_cfg_parse(&peer->dtls_cfg, v->name, v->value);
31139          }
31140       }
31141 
31142       /* Apply the encryption tag length to the DTLS configuration, in case DTLS is in use */
31143       peer->dtls_cfg.suite = (ast_test_flag(&peer->flags[2], SIP_PAGE3_SRTP_TAG_32) ? AST_AES_CM_128_HMAC_SHA1_32 : AST_AES_CM_128_HMAC_SHA1_80);
31144 
31145       /* These apply to devstate lookups */
31146       if (realtime && !strcasecmp(v->name, "lastms")) {
31147          sscanf(v->value, "%30d", &peer->lastms);
31148       } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
31149          ast_sockaddr_parse(&peer->addr, v->value, PARSE_PORT_FORBID);
31150       } else if (realtime && !strcasecmp(v->name, "fullcontact")) {
31151          if (alt_fullcontact && !alt) {
31152             /* Reset, because the alternate also has a fullcontact and we
31153              * do NOT want the field value to be doubled. It might be
31154              * tempting to skip this, but the first table might not have
31155              * fullcontact and since we're here, we know that the alternate
31156              * absolutely does. */
31157             alt_fullcontact = 0;
31158             ast_str_reset(fullcontact);
31159          }
31160          /* Reconstruct field, because realtime separates our value at the ';' */
31161          if (ast_str_strlen(fullcontact) > 0) {
31162             ast_str_append(&fullcontact, 0, ";%s", v->value);
31163          } else {
31164             ast_str_set(&fullcontact, 0, "%s", v->value);
31165          }
31166       } else if (!strcasecmp(v->name, "qualify")) {
31167          if (!strcasecmp(v->value, "no")) {
31168             peer->maxms = 0;
31169          } else if (!strcasecmp(v->value, "yes")) {
31170             peer->maxms = default_qualify ? default_qualify : DEFAULT_MAXMS;
31171          } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
31172             ast_log(LOG_WARNING, "Qualification of peer '%s' should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", peer->name, v->lineno);
31173             peer->maxms = 0;
31174          }
31175          if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->maxms > 0) {
31176             /* This would otherwise cause a network storm, where the
31177              * qualify response refreshes the peer from the database,
31178              * which in turn causes another qualify to be sent, ad
31179              * infinitum. */
31180             ast_log(LOG_WARNING, "Qualify is incompatible with dynamic uncached realtime.  Please either turn rtcachefriends on or turn qualify off on peer '%s'\n", peer->name);
31181             peer->maxms = 0;
31182          }
31183       } else if (!strcasecmp(v->name, "keepalive")) {
31184          if (!strcasecmp(v->value, "no")) {
31185             peer->keepalive = 0;
31186          } else if (!strcasecmp(v->value, "yes")) {
31187             peer->keepalive = DEFAULT_KEEPALIVE_INTERVAL;
31188          } else if (sscanf(v->value, "%30d", &peer->keepalive) != 1) {
31189             ast_log(LOG_WARNING, "Keep alive of peer '%s' should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", peer->name, v->lineno);
31190             peer->keepalive = 0;
31191          }
31192       } else if (!strcasecmp(v->name, "callcounter")) {
31193          peer->call_limit = ast_true(v->value) ? INT_MAX : 0;
31194       } else if (!strcasecmp(v->name, "call-limit")) {
31195          peer->call_limit = atoi(v->value);
31196          if (peer->call_limit < 0) {
31197             peer->call_limit = 0;
31198          }
31199       } else if (!strcasecmp(v->name, "busylevel")) {
31200          peer->busy_level = atoi(v->value);
31201          if (peer->busy_level < 0) {
31202             peer->busy_level = 0;
31203          }
31204       } else if (ast_cc_is_config_param(v->name)) {
31205          ast_cc_set_param(peer->cc_params, v->name, v->value);
31206       }
31207    }
31208 
31209    if (!devstate_only) {
31210       struct sip_mailbox *mailbox;
31211       AST_LIST_TRAVERSE_SAFE_BEGIN(&peer->mailboxes, mailbox, entry) {
31212          if (mailbox->delme) {
31213             AST_LIST_REMOVE_CURRENT(entry);
31214             destroy_mailbox(mailbox);
31215          }
31216       }
31217       AST_LIST_TRAVERSE_SAFE_END;
31218    }
31219 
31220    if (!can_parse_xml && (ast_get_cc_agent_policy(peer->cc_params) == AST_CC_AGENT_NATIVE)) {
31221       ast_log(LOG_WARNING, "Peer %s has a cc_agent_policy of 'native' but required libxml2 dependency is not installed. Changing policy to 'never'\n", peer->name);
31222       ast_set_cc_agent_policy(peer->cc_params, AST_CC_AGENT_NEVER);
31223    }
31224 
31225    /* Note that Timer B is dependent upon T1 and MUST NOT be lower
31226     * than T1 * 64, according to RFC 3261, Section 17.1.1.2 */
31227    if (peer->timer_b < peer->timer_t1 * 64) {
31228       if (timerb_set && timert1_set) {
31229          ast_log(LOG_WARNING, "Timer B has been set lower than recommended for peer %s (%d < 64 * Timer-T1=%d)\n", peer->name, peer->timer_b, peer->timer_t1);
31230       } else if (timerb_set) {
31231          if ((peer->timer_t1 = peer->timer_b / 64) < global_t1min) {
31232             ast_log(LOG_WARNING, "Timer B has been set lower than recommended (%d < 64 * timert1=%d). (RFC 3261, 17.1.1.2)\n", peer->timer_b, peer->timer_t1);
31233             peer->timer_t1 = global_t1min;
31234             peer->timer_b = peer->timer_t1 * 64;
31235          }
31236          peer->timer_t1 = peer->timer_b / 64;
31237       } else {
31238          peer->timer_b = peer->timer_t1 * 64;
31239       }
31240    }
31241 
31242    if (!peer->default_outbound_transport) {
31243       /* Set default set of transports */
31244       peer->transports = default_transports;
31245       /* Set default primary transport */
31246       peer->default_outbound_transport = default_primary_transport;
31247    }
31248 
31249    /* The default transport type set during build_peer should only replace the socket.type when...
31250     * 1. Registration is not present and the socket.type and default transport types are different.
31251     * 2. The socket.type is not an acceptable transport type after rebuilding peer.
31252     * 3. The socket.type is not set yet. */
31253    if (((peer->socket.type != peer->default_outbound_transport) && (peer->expire == -1)) ||
31254       !(peer->socket.type & peer->transports) || !(peer->socket.type)) {
31255       set_socket_transport(&peer->socket, peer->default_outbound_transport);
31256    }
31257 
31258    ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
31259    ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
31260    ast_copy_flags(&peer->flags[2], &peerflags[2], mask[2].flags);
31261 
31262    if (ast_str_strlen(fullcontact)) {
31263       ast_string_field_set(peer, fullcontact, ast_str_buffer(fullcontact));
31264       peer->rt_fromcontact = TRUE;
31265       /* We have a hostname in the fullcontact, but if we don't have an
31266        * address listed on the entry (or if it's 'dynamic'), then we need to
31267        * parse the entry to obtain the IP address, so a dynamic host can be
31268        * contacted immediately after reload (as opposed to waiting for it to
31269        * register once again). But if we have an address for this peer and NAT was
31270        * specified, use that address instead. */
31271       /* XXX May need to revisit the final argument; does the realtime DB store whether
31272        * the original contact was over TLS or not? XXX */
31273       if ((!ast_test_flag(&peer->flags[2],  SIP_PAGE3_NAT_AUTO_RPORT) && !ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT))
31274           || ast_sockaddr_isnull(&peer->addr)) {
31275          __set_address_from_contact(ast_str_buffer(fullcontact), &peer->addr, 0);
31276       }
31277    }
31278 
31279    if (srvlookup && peer->dnsmgr == NULL) {
31280       char transport[MAXHOSTNAMELEN];
31281       char _srvlookup[MAXHOSTNAMELEN];
31282       char *params;
31283 
31284       ast_copy_string(_srvlookup, srvlookup, sizeof(_srvlookup));
31285       if ((params = strchr(_srvlookup, ';'))) {
31286          *params++ = '\0';
31287       }
31288 
31289       snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(peer->socket.type), get_srv_protocol(peer->socket.type));
31290 
31291       peer->addr.ss.ss_family = get_address_family_filter(peer->socket.type); /* Filter address family */
31292       if (ast_dnsmgr_lookup_cb(_srvlookup, &peer->addr, &peer->dnsmgr, sip_cfg.srvlookup && !peer->portinuri ? transport : NULL,
31293                on_dns_update_peer, sip_ref_peer(peer, "Store peer on dnsmgr"))) {
31294          ast_log(LOG_ERROR, "srvlookup failed for host: %s, on peer %s, removing peer\n", _srvlookup, peer->name);
31295          sip_unref_peer(peer, "dnsmgr lookup failed, getting rid of peer dnsmgr ref");
31296          sip_unref_peer(peer, "getting rid of a peer pointer");
31297          return NULL;
31298       }
31299       if (!peer->dnsmgr) {
31300          /* dnsmgr refresh disabeld, release reference */
31301          sip_unref_peer(peer, "dnsmgr disabled, unref peer");
31302       }
31303 
31304       ast_string_field_set(peer, tohost, srvlookup);
31305 
31306       if (global_dynamic_exclude_static && !ast_sockaddr_isnull(&peer->addr)) {
31307          int ha_error = 0;
31308 
31309          ast_append_acl("deny", ast_sockaddr_stringify_addr(&peer->addr), &sip_cfg.contact_acl, &ha_error, NULL);
31310          if (ha_error) {
31311             ast_log(LOG_ERROR, "Bad or unresolved host/IP entry in configuration for peer %s, cannot add to contact ACL\n", peer->name);
31312          }
31313       }
31314    } else if (peer->dnsmgr && !peer->host_dynamic) {
31315       /* force a refresh here on reload if dnsmgr already exists and host is set. */
31316       ast_dnsmgr_refresh(peer->dnsmgr);
31317    }
31318 
31319    if (port && !realtime && peer->host_dynamic) {
31320       ast_sockaddr_set_port(&peer->defaddr, port);
31321    } else if (port) {
31322       ast_sockaddr_set_port(&peer->addr, port);
31323    }
31324 
31325    if (ast_sockaddr_port(&peer->addr) == 0) {
31326       ast_sockaddr_set_port(&peer->addr,
31327                   (peer->socket.type & SIP_TRANSPORT_TLS) ?
31328                   STANDARD_TLS_PORT : STANDARD_SIP_PORT);
31329    }
31330    if (ast_sockaddr_port(&peer->defaddr) == 0) {
31331       ast_sockaddr_set_port(&peer->defaddr,
31332                   (peer->socket.type & SIP_TRANSPORT_TLS) ?
31333                   STANDARD_TLS_PORT : STANDARD_SIP_PORT);
31334    }
31335    if (!peer->socket.port) {
31336       peer->socket.port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
31337    }
31338 
31339    if (realtime) {
31340       int enablepoke = 1;
31341 
31342       if (!sip_cfg.ignore_regexpire && peer->host_dynamic) {
31343          time_t nowtime = time(NULL);
31344 
31345          if ((nowtime - regseconds) > 0) {
31346             destroy_association(peer);
31347             memset(&peer->addr, 0, sizeof(peer->addr));
31348             peer->lastms = -1;
31349             enablepoke = 0;
31350             ast_debug(1, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
31351          }
31352       }
31353 
31354       /* Startup regular pokes */
31355       if (!devstate_only && enablepoke) {
31356          sip_ref_peer(peer, "schedule qualify");
31357          sip_poke_peer(peer, 0);
31358       }
31359    }
31360 
31361    if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
31362       sip_cfg.allowsubscribe = TRUE;   /* No global ban any more */
31363    }
31364    /* If read-only RT backend, then refresh from local DB cache */
31365    if (peer->host_dynamic && (!peer->is_realtime || !sip_cfg.peer_rtupdate)) {
31366       reg_source_db(peer);
31367    }
31368 
31369    /* If they didn't request that MWI is sent *only* on subscribe, go ahead and
31370     * subscribe to it now. */
31371    if (!devstate_only && !ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
31372       !AST_LIST_EMPTY(&peer->mailboxes)) {
31373       add_peer_mwi_subs(peer);
31374       /* Send MWI from the event cache only.  This is so we can send initial
31375        * MWI if app_voicemail got loaded before chan_sip.  If it is the other
31376        * way, then we will get events when app_voicemail gets loaded. */
31377       sip_send_mwi_to_peer(peer, 1);
31378    }
31379 
31380    peer->the_mark = 0;
31381 
31382    oldacl = ast_free_acl_list(oldacl);
31383    olddirectmediaacl = ast_free_acl_list(olddirectmediaacl);
31384    if (!ast_strlen_zero(peer->callback)) { /* build string from peer info */
31385       char *reg_string;
31386       if (ast_asprintf(&reg_string, "%s?%s:%s@%s/%s", peer->name, peer->username, !ast_strlen_zero(peer->remotesecret) ? peer->remotesecret : peer->secret, peer->tohost, peer->callback) >= 0) {
31387          sip_register(reg_string, 0); /* XXX TODO: count in registry_count */
31388          ast_free(reg_string);
31389       }
31390    }
31391 
31392    /* If an ACL change subscription is needed and doesn't exist, we need one. */
31393    if (acl_change_subscription_needed) {
31394       acl_change_event_subscribe();
31395    }
31396 
31397    return peer;
31398 }
31399 
31400 static int peer_markall_func(void *device, void *arg, int flags)
31401 {
31402    struct sip_peer *peer = device;
31403    if (!peer->selfdestruct) {
31404       peer->the_mark = 1;
31405    }
31406    return 0;
31407 }
31408 
31409 static int peer_markall_autopeers_func(void *device, void *arg, int flags)
31410 {
31411    struct sip_peer *peer = device;
31412    if (peer->selfdestruct) {
31413       peer->the_mark = 1;
31414    }
31415    return 0;
31416 }
31417 
31418 /*!
31419  * \internal
31420  * \brief If no default formats are set in config, these are used 
31421  */
31422 static void sip_set_default_format_capabilities(struct ast_format_cap *cap)
31423 {
31424    struct ast_format tmp_fmt;
31425 
31426    ast_format_cap_remove_all(cap);
31427    ast_format_cap_add(cap, ast_format_set(&tmp_fmt, AST_FORMAT_ULAW, 0));
31428    ast_format_cap_add(cap, ast_format_set(&tmp_fmt, AST_FORMAT_TESTLAW, 0));
31429    ast_format_cap_add(cap, ast_format_set(&tmp_fmt, AST_FORMAT_ALAW, 0));
31430    ast_format_cap_add(cap, ast_format_set(&tmp_fmt, AST_FORMAT_GSM, 0));
31431    ast_format_cap_add(cap, ast_format_set(&tmp_fmt, AST_FORMAT_H263, 0));
31432 }
31433 
31434 static void display_nat_warning(const char *cat, int reason, struct ast_flags *flags) {
31435    int global_nat, specific_nat;
31436 
31437    if (reason == CHANNEL_MODULE_LOAD && (specific_nat = ast_test_flag(&flags[0], SIP_NAT_FORCE_RPORT)) != (global_nat = ast_test_flag(&global_flags[0], SIP_NAT_FORCE_RPORT))) {
31438       ast_log(LOG_WARNING, "!!! PLEASE NOTE: Setting 'nat' for a peer/user that differs from the  global setting can make\n");
31439       ast_log(LOG_WARNING, "!!! the name of that peer/user discoverable by an attacker. Replies for non-existent peers/users\n");
31440       ast_log(LOG_WARNING, "!!! will be sent to a different port than replies for an existing peer/user. If at all possible,\n");
31441       ast_log(LOG_WARNING, "!!! use the global 'nat' setting and do not set 'nat' per peer/user.\n");
31442       ast_log(LOG_WARNING, "!!! (config category='%s' global force_rport='%s' peer/user force_rport='%s')\n", cat, AST_CLI_YESNO(global_nat), AST_CLI_YESNO(specific_nat));
31443    }
31444 }
31445 
31446 static void cleanup_all_regs(void)
31447 {
31448       /* First, destroy all outstanding registry calls */
31449       /* This is needed, since otherwise active registry entries will not be destroyed */
31450       ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {  /* regl is locked */
31451             ASTOBJ_WRLOCK(iterator); /* now regl is locked, and the object is also locked */
31452             if (iterator->call) {
31453                ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
31454                /* This will also remove references to the registry */
31455                dialog_unlink_all(iterator->call);
31456                iterator->call = dialog_unref(iterator->call, "remove iterator->call from registry traversal");
31457             }
31458             if (iterator->expire > -1) {
31459                AST_SCHED_DEL_UNREF(sched, iterator->expire, registry_unref(iterator, "reg ptr unref from reload config"));
31460             }
31461             if (iterator->timeout > -1) {
31462                AST_SCHED_DEL_UNREF(sched, iterator->timeout, registry_unref(iterator, "reg ptr unref from reload config"));
31463             }
31464             if (iterator->dnsmgr) {
31465                ast_dnsmgr_release(iterator->dnsmgr);
31466                iterator->dnsmgr = NULL;
31467                registry_unref(iterator, "reg ptr unref from dnsmgr");
31468             }
31469             ASTOBJ_UNLOCK(iterator);
31470       } while(0));
31471 }
31472 
31473 /*! \brief Re-read SIP.conf config file
31474 \note This function reloads all config data, except for
31475    active peers (with registrations). They will only
31476    change configuration data at restart, not at reload.
31477    SIP debug and recordhistory state will not change
31478  */
31479 static int reload_config(enum channelreloadreason reason)
31480 {
31481    struct ast_config *cfg, *ucfg;
31482    struct ast_variable *v;
31483    struct sip_peer *peer;
31484    char *cat, *stringp, *context, *oldregcontext;
31485    char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
31486    struct ast_flags mask[3] = {{0}};
31487    struct ast_flags setflags[3] = {{0}};
31488    struct ast_flags config_flags = { (reason == CHANNEL_MODULE_LOAD || reason == CHANNEL_ACL_RELOAD) ? 0 : ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) ? 0 : CONFIG_FLAG_FILEUNCHANGED };
31489    int auto_sip_domains = FALSE;
31490    struct ast_sockaddr old_bindaddr = bindaddr;
31491    int registry_count = 0, peer_count = 0, timerb_set = 0, timert1_set = 0;
31492    int subscribe_network_change = 1;
31493    time_t run_start, run_end;
31494    int bindport = 0;
31495    int acl_change_subscription_needed = 0;
31496    int min_subexpiry_set = 0, max_subexpiry_set = 0;
31497 
31498    run_start = time(0);
31499    ast_unload_realtime("sipregs");
31500    ast_unload_realtime("sippeers");
31501    cfg = ast_config_load(config, config_flags);
31502 
31503    /* We *must* have a config file otherwise stop immediately */
31504    if (!cfg) {
31505       ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
31506       return -1;
31507    } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
31508       ucfg = ast_config_load("users.conf", config_flags);
31509       if (ucfg == CONFIG_STATUS_FILEUNCHANGED) {
31510          return 1;
31511       } else if (ucfg == CONFIG_STATUS_FILEINVALID) {
31512          ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
31513          return 1;
31514       }
31515       /* Must reread both files, because one changed */
31516       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
31517       if ((cfg = ast_config_load(config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
31518          ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
31519          ast_config_destroy(ucfg);
31520          return 1;
31521       }
31522       if (!cfg) {
31523          /* should have been able to reload here */
31524          ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
31525          return -1;
31526       }
31527    } else if (cfg == CONFIG_STATUS_FILEINVALID) {
31528       ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
31529       return 1;
31530    } else {
31531       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
31532       if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEINVALID) {
31533          ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
31534          ast_config_destroy(cfg);
31535          return 1;
31536       }
31537    }
31538 
31539    sip_cfg.contact_acl = ast_free_acl_list(sip_cfg.contact_acl);
31540 
31541    default_tls_cfg.enabled = FALSE;    /* Default: Disable TLS */
31542 
31543    if (reason != CHANNEL_MODULE_LOAD) {
31544       ast_debug(4, "--------------- SIP reload started\n");
31545 
31546       clear_sip_domains();
31547       ast_mutex_lock(&authl_lock);
31548       if (authl) {
31549          ao2_t_ref(authl, -1, "Removing old global authentication");
31550          authl = NULL;
31551       }
31552       ast_mutex_unlock(&authl_lock);
31553 
31554       cleanup_all_regs();
31555 
31556       /* Then, actually destroy users and registry */
31557       ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
31558       ast_debug(4, "--------------- Done destroying registry list\n");
31559       ao2_t_callback(peers, OBJ_NODATA, peer_markall_func, NULL, "callback to mark all peers");
31560    }
31561 
31562    /* Reset certificate handling for TLS sessions */
31563    if (reason != CHANNEL_MODULE_LOAD) {
31564       ast_free(default_tls_cfg.certfile);
31565       ast_free(default_tls_cfg.pvtfile);
31566       ast_free(default_tls_cfg.cipher);
31567       ast_free(default_tls_cfg.cafile);
31568       ast_free(default_tls_cfg.capath);
31569    }
31570    default_tls_cfg.certfile = ast_strdup(AST_CERTFILE); /*XXX Not sure if this is useful */
31571    default_tls_cfg.pvtfile = ast_strdup("");
31572    default_tls_cfg.cipher = ast_strdup("");
31573    default_tls_cfg.cafile = ast_strdup("");
31574    default_tls_cfg.capath = ast_strdup("");
31575 
31576    /* Initialize copy of current sip_cfg.regcontext for later use in removing stale contexts */
31577    ast_copy_string(oldcontexts, sip_cfg.regcontext, sizeof(oldcontexts));
31578    oldregcontext = oldcontexts;
31579 
31580    /* Clear all flags before setting default values */
31581    /* Preserve debugging settings for console */
31582    sipdebug &= sip_debug_console;
31583    ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
31584    ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
31585    ast_clear_flag(&global_flags[2], AST_FLAGS_ALL);
31586 
31587    /* Reset IP addresses  */
31588    ast_sockaddr_parse(&bindaddr, "0.0.0.0:0", 0);
31589    memset(&internip, 0, sizeof(internip));
31590 
31591    /* Free memory for local network address mask */
31592    ast_free_ha(localaddr);
31593    memset(&localaddr, 0, sizeof(localaddr));
31594    memset(&externaddr, 0, sizeof(externaddr));
31595    memset(&media_address, 0, sizeof(media_address));
31596    memset(&default_prefs, 0 , sizeof(default_prefs));
31597    memset(&sip_cfg.outboundproxy, 0, sizeof(struct sip_proxy));
31598    sip_cfg.outboundproxy.force = FALSE;      /*!< Don't force proxy usage, use route: headers */
31599    default_transports = SIP_TRANSPORT_UDP;
31600    default_primary_transport = SIP_TRANSPORT_UDP;
31601    ourport_tcp = STANDARD_SIP_PORT;
31602    ourport_tls = STANDARD_TLS_PORT;
31603    externtcpport = STANDARD_SIP_PORT;
31604    externtlsport = STANDARD_TLS_PORT;
31605    sip_cfg.srvlookup = DEFAULT_SRVLOOKUP;
31606    global_tos_sip = DEFAULT_TOS_SIP;
31607    global_tos_audio = DEFAULT_TOS_AUDIO;
31608    global_tos_video = DEFAULT_TOS_VIDEO;
31609    global_tos_text = DEFAULT_TOS_TEXT;
31610    global_cos_sip = DEFAULT_COS_SIP;
31611    global_cos_audio = DEFAULT_COS_AUDIO;
31612    global_cos_video = DEFAULT_COS_VIDEO;
31613    global_cos_text = DEFAULT_COS_TEXT;
31614 
31615    externhost[0] = '\0';         /* External host name (for behind NAT DynDNS support) */
31616    externexpire = 0;       /* Expiration for DNS re-issuing */
31617    externrefresh = 10;
31618 
31619    /* Reset channel settings to default before re-configuring */
31620    sip_cfg.allow_external_domains = DEFAULT_ALLOW_EXT_DOM;           /* Allow external invites */
31621    sip_cfg.regcontext[0] = '\0';
31622    sip_set_default_format_capabilities(sip_cfg.caps);
31623    sip_cfg.regextenonqualify = DEFAULT_REGEXTENONQUALIFY;
31624    sip_cfg.legacy_useroption_parsing = DEFAULT_LEGACY_USEROPTION_PARSING;
31625    sip_cfg.send_diversion = DEFAULT_SEND_DIVERSION;
31626    sip_cfg.notifyringing = DEFAULT_NOTIFYRINGING;
31627    sip_cfg.notifycid = DEFAULT_NOTIFYCID;
31628    sip_cfg.notifyhold = FALSE;      /*!< Keep track of hold status for a peer */
31629    sip_cfg.directrtpsetup = FALSE;     /* Experimental feature, disabled by default */
31630    sip_cfg.alwaysauthreject = DEFAULT_ALWAYSAUTHREJECT;
31631    sip_cfg.auth_options_requests = DEFAULT_AUTH_OPTIONS;
31632    sip_cfg.auth_message_requests = DEFAULT_AUTH_MESSAGE;
31633    sip_cfg.messagecontext[0] = '\0';
31634    sip_cfg.accept_outofcall_message = DEFAULT_ACCEPT_OUTOFCALL_MESSAGE;
31635    sip_cfg.allowsubscribe = FALSE;
31636    sip_cfg.disallowed_methods = SIP_UNKNOWN;
31637    sip_cfg.contact_acl = NULL;      /* Reset the contact ACL */
31638    snprintf(global_useragent, sizeof(global_useragent), "%s %s", DEFAULT_USERAGENT, ast_get_version());
31639    snprintf(global_sdpsession, sizeof(global_sdpsession), "%s %s", DEFAULT_SDPSESSION, ast_get_version());
31640    snprintf(global_sdpowner, sizeof(global_sdpowner), "%s", DEFAULT_SDPOWNER);
31641    global_prematuremediafilter = TRUE;
31642    ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
31643    ast_copy_string(sip_cfg.realm, S_OR(ast_config_AST_SYSTEM_NAME, DEFAULT_REALM), sizeof(sip_cfg.realm));
31644    sip_cfg.domainsasrealm = DEFAULT_DOMAINSASREALM;
31645    ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
31646    ast_copy_string(default_mwi_from, DEFAULT_MWI_FROM, sizeof(default_mwi_from));
31647    sip_cfg.compactheaders = DEFAULT_COMPACTHEADERS;
31648    global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
31649    global_regattempts_max = 0;
31650    global_reg_retry_403 = 0;
31651    sip_cfg.pedanticsipchecking = DEFAULT_PEDANTIC;
31652    sip_cfg.autocreatepeer = DEFAULT_AUTOCREATEPEER;
31653    global_autoframing = 0;
31654    sip_cfg.allowguest = DEFAULT_ALLOWGUEST;
31655    global_callcounter = DEFAULT_CALLCOUNTER;
31656    global_match_auth_username = FALSE;    /*!< Match auth username if available instead of From: Default off. */
31657    global_rtptimeout = 0;
31658    global_rtpholdtimeout = 0;
31659    global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
31660    sip_cfg.allowtransfer = TRANSFER_OPENFORALL; /* Merrily accept all transfers by default */
31661    sip_cfg.rtautoclear = 120;
31662    ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE);   /* Default for all devices: TRUE */
31663    ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP_YES); /* Default for all devices: Yes */
31664    sip_cfg.peer_rtupdate = TRUE;
31665    global_dynamic_exclude_static = 0;  /* Exclude static peers */
31666    sip_cfg.tcp_enabled = FALSE;
31667 
31668    /* Session-Timers */
31669    global_st_mode = SESSION_TIMER_MODE_ACCEPT;
31670    global_st_refresher = SESSION_TIMER_REFRESHER_PARAM_UAS;
31671    global_min_se  = DEFAULT_MIN_SE;
31672    global_max_se  = DEFAULT_MAX_SE;
31673 
31674    /* Peer poking settings */
31675    global_qualify_gap = DEFAULT_QUALIFY_GAP;
31676    global_qualify_peers = DEFAULT_QUALIFY_PEERS;
31677 
31678    /* Initialize some reasonable defaults at SIP reload (used both for channel and as default for devices */
31679    ast_copy_string(sip_cfg.default_context, DEFAULT_CONTEXT, sizeof(sip_cfg.default_context));
31680    ast_copy_string(sip_cfg.default_record_on_feature, DEFAULT_RECORD_FEATURE, sizeof(sip_cfg.default_record_on_feature));
31681    ast_copy_string(sip_cfg.default_record_off_feature, DEFAULT_RECORD_FEATURE, sizeof(sip_cfg.default_record_off_feature));
31682    sip_cfg.default_subscribecontext[0] = '\0';
31683    sip_cfg.default_max_forwards = DEFAULT_MAX_FORWARDS;
31684    default_language[0] = '\0';
31685    default_fromdomain[0] = '\0';
31686    default_fromdomainport = 0;
31687    default_qualify = DEFAULT_QUALIFY;
31688    default_keepalive = DEFAULT_KEEPALIVE;
31689    default_zone[0] = '\0';
31690    default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
31691    ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
31692    ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
31693    ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
31694    ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833);    /*!< Default DTMF setting: RFC2833 */
31695    ast_set_flag(&global_flags[0], SIP_DIRECT_MEDIA);    /*!< Allow re-invites */
31696    ast_set_flag(&global_flags[2], SIP_PAGE3_NAT_AUTO_RPORT); /*!< Default to nat=auto_force_rport */
31697    ast_copy_string(default_engine, DEFAULT_ENGINE, sizeof(default_engine));
31698    ast_copy_string(default_parkinglot, DEFAULT_PARKINGLOT, sizeof(default_parkinglot));
31699 
31700    /* Debugging settings, always default to off */
31701    dumphistory = FALSE;
31702    recordhistory = FALSE;
31703    sipdebug &= ~sip_debug_config;
31704 
31705    /* Misc settings for the channel */
31706    global_relaxdtmf = FALSE;
31707    sip_cfg.callevents = DEFAULT_CALLEVENTS;
31708    global_authfailureevents = FALSE;
31709    global_t1 = DEFAULT_TIMER_T1;
31710    global_timer_b = 64 * DEFAULT_TIMER_T1;
31711    global_t1min = DEFAULT_T1MIN;
31712    global_qualifyfreq = DEFAULT_QUALIFYFREQ;
31713    global_t38_maxdatagram = -1;
31714    global_shrinkcallerid = 1;
31715    global_refer_addheaders = TRUE;
31716    authlimit = DEFAULT_AUTHLIMIT;
31717    authtimeout = DEFAULT_AUTHTIMEOUT;
31718    global_store_sip_cause = DEFAULT_STORE_SIP_CAUSE;
31719    min_expiry = DEFAULT_MIN_EXPIRY;
31720    max_expiry = DEFAULT_MAX_EXPIRY;
31721    default_expiry = DEFAULT_DEFAULT_EXPIRY;
31722 
31723    sip_cfg.matchexternaddrlocally = DEFAULT_MATCHEXTERNADDRLOCALLY;
31724 
31725    /* Copy the default jb config over global_jbconf */
31726    memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
31727 
31728    ast_clear_flag(&global_flags[1], SIP_PAGE2_FAX_DETECT);
31729    ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
31730    ast_clear_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT);
31731    ast_clear_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION);
31732 
31733    /* Read the [general] config section of sip.conf (or from realtime config) */
31734    for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
31735       if (handle_common_options(&setflags[0], &mask[0], v)) {
31736          continue;
31737       }
31738       if (handle_t38_options(&setflags[0], &mask[0], v, &global_t38_maxdatagram)) {
31739          continue;
31740       }
31741       /* handle jb conf */
31742       if (!ast_jb_read_conf(&global_jbconf, v->name, v->value)) {
31743          continue;
31744       }
31745 
31746       /* handle tls conf, don't allow setting of tlsverifyclient as it isn't supported by chan_sip */
31747       if (!strcasecmp(v->name, "tlsverifyclient")) {
31748          ast_log(LOG_WARNING, "Ignoring unsupported option 'tlsverifyclient'\n");
31749          continue;
31750       } else if (!ast_tls_read_conf(&default_tls_cfg, &sip_tls_desc, v->name, v->value)) {
31751          continue;
31752       }
31753 
31754       if (!strcasecmp(v->name, "context")) {
31755          ast_copy_string(sip_cfg.default_context, v->value, sizeof(sip_cfg.default_context));
31756       } else if (!strcasecmp(v->name, "recordonfeature")) {
31757          ast_copy_string(sip_cfg.default_record_on_feature, v->value, sizeof(sip_cfg.default_record_on_feature));
31758       } else if (!strcasecmp(v->name, "recordofffeature")) {
31759          ast_copy_string(sip_cfg.default_record_off_feature, v->value, sizeof(sip_cfg.default_record_off_feature));
31760       } else if (!strcasecmp(v->name, "subscribecontext")) {
31761          ast_copy_string(sip_cfg.default_subscribecontext, v->value, sizeof(sip_cfg.default_subscribecontext));
31762       } else if (!strcasecmp(v->name, "callcounter")) {
31763          global_callcounter = ast_true(v->value) ? 1 : 0;
31764       } else if (!strcasecmp(v->name, "allowguest")) {
31765          sip_cfg.allowguest = ast_true(v->value) ? 1 : 0;
31766       } else if (!strcasecmp(v->name, "realm")) {
31767          ast_copy_string(sip_cfg.realm, v->value, sizeof(sip_cfg.realm));
31768       } else if (!strcasecmp(v->name, "domainsasrealm")) {
31769          sip_cfg.domainsasrealm = ast_true(v->value);
31770       } else if (!strcasecmp(v->name, "useragent")) {
31771          ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
31772          ast_debug(1, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
31773       } else if (!strcasecmp(v->name, "sdpsession")) {
31774          ast_copy_string(global_sdpsession, v->value, sizeof(global_sdpsession));
31775       } else if (!strcasecmp(v->name, "sdpowner")) {
31776          /* Field cannot contain spaces */
31777          if (!strstr(v->value, " ")) {
31778             ast_copy_string(global_sdpowner, v->value, sizeof(global_sdpowner));
31779          } else {
31780             ast_log(LOG_WARNING, "'%s' must not contain spaces at line %d.  Using default.\n", v->value, v->lineno);
31781          }
31782       } else if (!strcasecmp(v->name, "allowtransfer")) {
31783          sip_cfg.allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
31784       } else if (!strcasecmp(v->name, "rtcachefriends")) {
31785          ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);
31786       } else if (!strcasecmp(v->name, "rtsavesysname")) {
31787          sip_cfg.rtsave_sysname = ast_true(v->value);
31788       } else if (!strcasecmp(v->name, "rtupdate")) {
31789          sip_cfg.peer_rtupdate = ast_true(v->value);
31790       } else if (!strcasecmp(v->name, "ignoreregexpire")) {
31791          sip_cfg.ignore_regexpire = ast_true(v->value);
31792       } else if (!strcasecmp(v->name, "timert1")) {
31793          /* Defaults to 500ms, but RFC 3261 states that it is recommended
31794           * for the value to be set higher, though a lower value is only
31795           * allowed on private networks unconnected to the Internet. */
31796          global_t1 = atoi(v->value);
31797       } else if (!strcasecmp(v->name, "timerb")) {
31798          int tmp = atoi(v->value);
31799          if (tmp < 500) {
31800             global_timer_b = global_t1 * 64;
31801             ast_log(LOG_WARNING, "Invalid value for timerb ('%s').  Setting to default ('%d').\n", v->value, global_timer_b);
31802          }
31803          timerb_set = 1;
31804       } else if (!strcasecmp(v->name, "t1min")) {
31805          global_t1min = atoi(v->value);
31806       } else if (!strcasecmp(v->name, "transport")) {
31807          char *val = ast_strdupa(v->value);
31808          char *trans;
31809 
31810          default_transports = default_primary_transport = 0;
31811          while ((trans = strsep(&val, ","))) {
31812             trans = ast_skip_blanks(trans);
31813 
31814             if (!strncasecmp(trans, "udp", 3)) {
31815                default_transports |= SIP_TRANSPORT_UDP;
31816             } else if (!strncasecmp(trans, "tcp", 3)) {
31817                default_transports |= SIP_TRANSPORT_TCP;
31818             } else if (!strncasecmp(trans, "tls", 3)) {
31819                default_transports |= SIP_TRANSPORT_TLS;
31820             } else if (!strncasecmp(trans, "wss", 3)) {
31821                default_transports |= SIP_TRANSPORT_WSS;
31822             } else if (!strncasecmp(trans, "ws", 2)) {
31823                default_transports |= SIP_TRANSPORT_WS;
31824             } else {
31825                ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
31826             }
31827             if (default_primary_transport == 0) {
31828                default_primary_transport = default_transports;
31829             }
31830          }
31831       } else if (!strcasecmp(v->name, "tcpenable")) {
31832          if (!ast_false(v->value)) {
31833             ast_debug(2, "Enabling TCP socket for listening\n");
31834             sip_cfg.tcp_enabled = TRUE;
31835          }
31836       } else if (!strcasecmp(v->name, "tcpbindaddr")) {
31837          if (ast_parse_arg(v->value, PARSE_ADDR,
31838                  &sip_tcp_desc.local_address)) {
31839             ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
31840                v->name, v->value, v->lineno, config);
31841          }
31842          ast_debug(2, "Setting TCP socket address to %s\n",
31843               ast_sockaddr_stringify(&sip_tcp_desc.local_address));
31844       } else if (!strcasecmp(v->name, "dynamic_exclude_static") || !strcasecmp(v->name, "dynamic_excludes_static")) {
31845          global_dynamic_exclude_static = ast_true(v->value);
31846       } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny") || !strcasecmp(v->name, "contactacl")) {
31847          int ha_error = 0;
31848          ast_append_acl(v->name + 7, v->value, &sip_cfg.contact_acl, &ha_error, &acl_change_subscription_needed);
31849          if (ha_error) {
31850             ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
31851          }
31852       } else if (!strcasecmp(v->name, "rtautoclear")) {
31853          int i = atoi(v->value);
31854          if (i > 0) {
31855             sip_cfg.rtautoclear = i;
31856          } else {
31857             i = 0;
31858          }
31859          ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
31860       } else if (!strcasecmp(v->name, "usereqphone")) {
31861          ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);
31862       } else if (!strcasecmp(v->name, "prematuremedia")) {
31863          global_prematuremediafilter = ast_true(v->value);
31864       } else if (!strcasecmp(v->name, "relaxdtmf")) {
31865          global_relaxdtmf = ast_true(v->value);
31866       } else if (!strcasecmp(v->name, "vmexten")) {
31867          ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
31868       } else if (!strcasecmp(v->name, "rtptimeout")) {
31869          if ((sscanf(v->value, "%30d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
31870             ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
31871             global_rtptimeout = 0;
31872          }
31873       } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
31874          if ((sscanf(v->value, "%30d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
31875             ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
31876             global_rtpholdtimeout = 0;
31877          }
31878       } else if (!strcasecmp(v->name, "rtpkeepalive")) {
31879          if ((sscanf(v->value, "%30d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
31880             ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d.  Using default.\n", v->value, v->lineno);
31881             global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
31882          }
31883       } else if (!strcasecmp(v->name, "compactheaders")) {
31884          sip_cfg.compactheaders = ast_true(v->value);
31885       } else if (!strcasecmp(v->name, "notifymimetype")) {
31886          ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
31887       } else if (!strcasecmp(v->name, "directrtpsetup")) {
31888          sip_cfg.directrtpsetup = ast_true(v->value);
31889       } else if (!strcasecmp(v->name, "notifyringing")) {
31890          sip_cfg.notifyringing = ast_true(v->value);
31891       } else if (!strcasecmp(v->name, "notifyhold")) {
31892          sip_cfg.notifyhold = ast_true(v->value);
31893       } else if (!strcasecmp(v->name, "notifycid")) {
31894          if (!strcasecmp(v->value, "ignore-context")) {
31895             sip_cfg.notifycid = IGNORE_CONTEXT;
31896          } else {
31897             sip_cfg.notifycid = ast_true(v->value) ? ENABLED : DISABLED;
31898          }
31899       } else if (!strcasecmp(v->name, "alwaysauthreject")) {
31900          sip_cfg.alwaysauthreject = ast_true(v->value);
31901       } else if (!strcasecmp(v->name, "auth_options_requests")) {
31902          if (ast_true(v->value)) {
31903             sip_cfg.auth_options_requests = 1;
31904          }
31905       } else if (!strcasecmp(v->name, "auth_message_requests")) {
31906          sip_cfg.auth_message_requests = ast_true(v->value) ? 1 : 0;
31907       } else if (!strcasecmp(v->name, "accept_outofcall_message")) {
31908          sip_cfg.accept_outofcall_message = ast_true(v->value) ? 1 : 0;
31909       } else if (!strcasecmp(v->name, "outofcall_message_context")) {
31910          ast_copy_string(sip_cfg.messagecontext, v->value, sizeof(sip_cfg.messagecontext));
31911       } else if (!strcasecmp(v->name, "mohinterpret")) {
31912          ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
31913       } else if (!strcasecmp(v->name, "mohsuggest")) {
31914          ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
31915       } else if (!strcasecmp(v->name, "tonezone")) {
31916          struct ast_tone_zone *new_zone;
31917          if (!(new_zone = ast_get_indication_zone(v->value))) {
31918             ast_log(LOG_ERROR, "Unknown country code '%s' for tonezone in [general] at line %d. Check indications.conf for available country codes.\n", v->value, v->lineno);
31919          } else {
31920             ast_tone_zone_unref(new_zone);
31921             ast_copy_string(default_zone, v->value, sizeof(default_zone));
31922          }
31923       } else if (!strcasecmp(v->name, "language")) {
31924          ast_copy_string(default_language, v->value, sizeof(default_language));
31925       } else if (!strcasecmp(v->name, "regcontext")) {
31926          ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
31927          stringp = newcontexts;
31928          /* Let's remove any contexts that are no longer defined in regcontext */
31929          cleanup_stale_contexts(stringp, oldregcontext);
31930          /* Create contexts if they don't exist already */
31931          while ((context = strsep(&stringp, "&"))) {
31932             ast_copy_string(used_context, context, sizeof(used_context));
31933             ast_context_find_or_create(NULL, NULL, context, "SIP");
31934          }
31935          ast_copy_string(sip_cfg.regcontext, v->value, sizeof(sip_cfg.regcontext));
31936       } else if (!strcasecmp(v->name, "regextenonqualify")) {
31937          sip_cfg.regextenonqualify = ast_true(v->value);
31938       } else if (!strcasecmp(v->name, "legacy_useroption_parsing")) {
31939          sip_cfg.legacy_useroption_parsing = ast_true(v->value);
31940       } else if (!strcasecmp(v->name, "send_diversion")) {
31941          sip_cfg.send_diversion = ast_true(v->value);
31942       } else if (!strcasecmp(v->name, "callerid")) {
31943          ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
31944       } else if (!strcasecmp(v->name, "mwi_from")) {
31945          ast_copy_string(default_mwi_from, v->value, sizeof(default_mwi_from));
31946       } else if (!strcasecmp(v->name, "fromdomain")) {
31947          char *fromdomainport;
31948          ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
31949          if ((fromdomainport = strchr(default_fromdomain, ':'))) {
31950             *fromdomainport++ = '\0';
31951             if (!(default_fromdomainport = port_str2int(fromdomainport, 0))) {
31952                ast_log(LOG_NOTICE, "'%s' is not a valid port number for fromdomain.\n",fromdomainport);
31953             }
31954          } else {
31955             default_fromdomainport = STANDARD_SIP_PORT;
31956          }
31957       } else if (!strcasecmp(v->name, "outboundproxy")) {
31958          struct sip_proxy *proxy;
31959          if (ast_strlen_zero(v->value)) {
31960             ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf\n", v->lineno);
31961             continue;
31962          }
31963          proxy = proxy_from_config(v->value, v->lineno, &sip_cfg.outboundproxy);
31964          if (!proxy) {
31965             ast_log(LOG_WARNING, "failure parsing the outbound proxy on line %d of sip.conf.\n", v->lineno);
31966             continue;
31967          }
31968       } else if (!strcasecmp(v->name, "autocreatepeer")) {
31969          if (!strcasecmp(v->value, "persist")) {
31970             sip_cfg.autocreatepeer = AUTOPEERS_PERSIST;
31971          } else {
31972             sip_cfg.autocreatepeer = ast_true(v->value) ? AUTOPEERS_VOLATILE : AUTOPEERS_DISABLED;
31973          }
31974       } else if (!strcasecmp(v->name, "match_auth_username")) {
31975          global_match_auth_username = ast_true(v->value);
31976       } else if (!strcasecmp(v->name, "srvlookup")) {
31977          sip_cfg.srvlookup = ast_true(v->value);
31978       } else if (!strcasecmp(v->name, "pedantic")) {
31979          sip_cfg.pedanticsipchecking = ast_true(v->value);
31980       } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
31981          max_expiry = atoi(v->value);
31982          if (max_expiry < 1) {
31983             max_expiry = DEFAULT_MAX_EXPIRY;
31984          }
31985       } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
31986          min_expiry = atoi(v->value);
31987          if (min_expiry < 1) {
31988             min_expiry = DEFAULT_MIN_EXPIRY;
31989          }
31990       } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
31991          default_expiry = atoi(v->value);
31992          if (default_expiry < 1) {
31993             default_expiry = DEFAULT_DEFAULT_EXPIRY;
31994          }
31995       } else if (!strcasecmp(v->name, "submaxexpirey") || !strcasecmp(v->name, "submaxexpiry")) {
31996          max_subexpiry = atoi(v->value);
31997          if (max_subexpiry < 1) {
31998             max_subexpiry = DEFAULT_MAX_EXPIRY;
31999          }
32000          max_subexpiry_set = 1;
32001       } else if (!strcasecmp(v->name, "subminexpirey") || !strcasecmp(v->name, "subminexpiry")) {
32002          min_subexpiry = atoi(v->value);
32003          if (min_subexpiry < 1) {
32004             min_subexpiry = DEFAULT_MIN_EXPIRY;
32005          }
32006          min_subexpiry_set = 1;
32007       } else if (!strcasecmp(v->name, "mwiexpiry") || !strcasecmp(v->name, "mwiexpirey")) {
32008          mwi_expiry = atoi(v->value);
32009          if (mwi_expiry < 1) {
32010             mwi_expiry = DEFAULT_MWI_EXPIRY;
32011          }
32012       } else if (!strcasecmp(v->name, "tcpauthtimeout")) {
32013          if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
32014                  &authtimeout, DEFAULT_AUTHTIMEOUT, 1, INT_MAX)) {
32015             ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
32016                v->name, v->value, v->lineno, config);
32017          }
32018       } else if (!strcasecmp(v->name, "tcpauthlimit")) {
32019          if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
32020                  &authlimit, DEFAULT_AUTHLIMIT, 1, INT_MAX)) {
32021             ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
32022                v->name, v->value, v->lineno, config);
32023          }
32024       } else if (!strcasecmp(v->name, "sipdebug")) {
32025          if (ast_true(v->value))
32026             sipdebug |= sip_debug_config;
32027       } else if (!strcasecmp(v->name, "dumphistory")) {
32028          dumphistory = ast_true(v->value);
32029       } else if (!strcasecmp(v->name, "recordhistory")) {
32030          recordhistory = ast_true(v->value);
32031       } else if (!strcasecmp(v->name, "registertimeout")) {
32032          global_reg_timeout = atoi(v->value);
32033          if (global_reg_timeout < 1) {
32034             global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
32035          }
32036       } else if (!strcasecmp(v->name, "registerattempts")) {
32037          global_regattempts_max = atoi(v->value);
32038       } else if (!strcasecmp(v->name, "register_retry_403")) {
32039          global_reg_retry_403 = ast_true(v->value);
32040       } else if (!strcasecmp(v->name, "bindaddr") || !strcasecmp(v->name, "udpbindaddr")) {
32041          if (ast_parse_arg(v->value, PARSE_ADDR, &bindaddr)) {
32042             ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
32043          }
32044       } else if (!strcasecmp(v->name, "localnet")) {
32045          struct ast_ha *na;
32046          int ha_error = 0;
32047 
32048          if (!(na = ast_append_ha("d", v->value, localaddr, &ha_error))) {
32049             ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
32050          } else {
32051             localaddr = na;
32052          }
32053          if (ha_error) {
32054             ast_log(LOG_ERROR, "Bad localnet configuration value line %d : %s\n", v->lineno, v->value);
32055          }
32056       } else if (!strcasecmp(v->name, "media_address")) {
32057          if (ast_parse_arg(v->value, PARSE_ADDR, &media_address))
32058             ast_log(LOG_WARNING, "Invalid address for media_address keyword: %s\n", v->value);
32059       } else if (!strcasecmp(v->name, "externaddr") || !strcasecmp(v->name, "externip")) {
32060          if (ast_parse_arg(v->value, PARSE_ADDR, &externaddr)) {
32061             ast_log(LOG_WARNING,
32062                "Invalid address for externaddr keyword: %s\n",
32063                v->value);
32064          }
32065          externexpire = 0;
32066       } else if (!strcasecmp(v->name, "externhost")) {
32067          ast_copy_string(externhost, v->value, sizeof(externhost));
32068          if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
32069             ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
32070          }
32071          externexpire = time(NULL);
32072       } else if (!strcasecmp(v->name, "externrefresh")) {
32073          if (sscanf(v->value, "%30d", &externrefresh) != 1) {
32074             ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
32075             externrefresh = 10;
32076          }
32077       } else if (!strcasecmp(v->name, "externtcpport")) {
32078          if (!(externtcpport = port_str2int(v->value, 0))) {
32079             ast_log(LOG_WARNING, "Invalid externtcpport value, must be a positive integer between 1 and 65535 at line %d\n", v->lineno);
32080             externtcpport = 0;
32081          }
32082       } else if (!strcasecmp(v->name, "externtlsport")) {
32083          if (!(externtlsport = port_str2int(v->value, STANDARD_TLS_PORT))) {
32084             ast_log(LOG_WARNING, "Invalid externtlsport value, must be a positive integer between 1 and 65535 at line %d\n", v->lineno);
32085          }
32086       } else if (!strcasecmp(v->name, "allow")) {
32087          int error =  ast_parse_allow_disallow(&default_prefs, sip_cfg.caps, v->value, TRUE);
32088          if (error) {
32089             ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
32090          }
32091       } else if (!strcasecmp(v->name, "disallow")) {
32092          int error =  ast_parse_allow_disallow(&default_prefs, sip_cfg.caps, v->value, FALSE);
32093          if (error) {
32094             ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
32095          }
32096       } else if (!strcasecmp(v->name, "preferred_codec_only")) {
32097          ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_PREFERRED_CODEC);
32098       } else if (!strcasecmp(v->name, "autoframing")) {
32099          global_autoframing = ast_true(v->value);
32100       } else if (!strcasecmp(v->name, "allowexternaldomains")) {
32101          sip_cfg.allow_external_domains = ast_true(v->value);
32102       } else if (!strcasecmp(v->name, "autodomain")) {
32103          auto_sip_domains = ast_true(v->value);
32104       } else if (!strcasecmp(v->name, "domain")) {
32105          char *domain = ast_strdupa(v->value);
32106          char *cntx = strchr(domain, ',');
32107 
32108          if (cntx) {
32109             *cntx++ = '\0';
32110          }
32111 
32112          if (ast_strlen_zero(cntx)) {
32113             ast_debug(1, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
32114          }
32115          if (ast_strlen_zero(domain)) {
32116             ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
32117          } else {
32118             add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, cntx ? ast_strip(cntx) : "");
32119          }
32120       } else if (!strcasecmp(v->name, "register")) {
32121          if (sip_register(v->value, v->lineno) == 0) {
32122             registry_count++;
32123          }
32124       } else if (!strcasecmp(v->name, "mwi")) {
32125          sip_subscribe_mwi(v->value, v->lineno);
32126       } else if (!strcasecmp(v->name, "tos_sip")) {
32127          if (ast_str2tos(v->value, &global_tos_sip)) {
32128             ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, refer to QoS documentation\n", v->lineno);
32129          }
32130       } else if (!strcasecmp(v->name, "tos_audio")) {
32131          if (ast_str2tos(v->value, &global_tos_audio)) {
32132             ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, refer to QoS documentation\n", v->lineno);
32133          }
32134       } else if (!strcasecmp(v->name, "tos_video")) {
32135          if (ast_str2tos(v->value, &global_tos_video)) {
32136             ast_log(LOG_WARNING, "Invalid tos_video value at line %d, refer to QoS documentation\n", v->lineno);
32137          }
32138       } else if (!strcasecmp(v->name, "tos_text")) {
32139          if (ast_str2tos(v->value, &global_tos_text)) {
32140             ast_log(LOG_WARNING, "Invalid tos_text value at line %d, refer to QoS documentation\n", v->lineno);
32141          }
32142       } else if (!strcasecmp(v->name, "cos_sip")) {
32143          if (ast_str2cos(v->value, &global_cos_sip)) {
32144             ast_log(LOG_WARNING, "Invalid cos_sip value at line %d, refer to QoS documentation\n", v->lineno);
32145          }
32146       } else if (!strcasecmp(v->name, "cos_audio")) {
32147          if (ast_str2cos(v->value, &global_cos_audio)) {
32148             ast_log(LOG_WARNING, "Invalid cos_audio value at line %d, refer to QoS documentation\n", v->lineno);
32149          }
32150       } else if (!strcasecmp(v->name, "cos_video")) {
32151          if (ast_str2cos(v->value, &global_cos_video)) {
32152             ast_log(LOG_WARNING, "Invalid cos_video value at line %d, refer to QoS documentation\n", v->lineno);
32153          }
32154       } else if (!strcasecmp(v->name, "cos_text")) {
32155          if (ast_str2cos(v->value, &global_cos_text)) {
32156             ast_log(LOG_WARNING, "Invalid cos_text value at line %d, refer to QoS documentation\n", v->lineno);
32157          }
32158       } else if (!strcasecmp(v->name, "bindport")) {
32159          if (sscanf(v->value, "%5d", &bindport) != 1) {
32160             ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
32161          }
32162       } else if (!strcasecmp(v->name, "qualify")) {
32163          if (!strcasecmp(v->value, "no")) {
32164             default_qualify = 0;
32165          } else if (!strcasecmp(v->value, "yes")) {
32166             default_qualify = DEFAULT_MAXMS;
32167          } else if (sscanf(v->value, "%30d", &default_qualify) != 1) {
32168             ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
32169             default_qualify = 0;
32170          }
32171       } else if (!strcasecmp(v->name, "keepalive")) {
32172          if (!strcasecmp(v->value, "no")) {
32173             default_keepalive = 0;
32174          } else if (!strcasecmp(v->value, "yes")) {
32175             default_keepalive = DEFAULT_KEEPALIVE_INTERVAL;
32176          } else if (sscanf(v->value, "%30d", &default_keepalive) != 1) {
32177             ast_log(LOG_WARNING, "Keep alive default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
32178             default_keepalive = 0;
32179          }
32180       } else if (!strcasecmp(v->name, "qualifyfreq")) {
32181          int i;
32182          if (sscanf(v->value, "%30d", &i) == 1) {
32183             global_qualifyfreq = i * 1000;
32184          } else {
32185             ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
32186             global_qualifyfreq = DEFAULT_QUALIFYFREQ;
32187          }
32188       } else if (!strcasecmp(v->name, "callevents")) {
32189          sip_cfg.callevents = ast_true(v->value);
32190       } else if (!strcasecmp(v->name, "authfailureevents")) {
32191          global_authfailureevents = ast_true(v->value);
32192       } else if (!strcasecmp(v->name, "maxcallbitrate")) {
32193          default_maxcallbitrate = atoi(v->value);
32194          if (default_maxcallbitrate < 0) {
32195             default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
32196          }
32197       } else if (!strcasecmp(v->name, "matchexternaddrlocally") || !strcasecmp(v->name, "matchexterniplocally")) {
32198          sip_cfg.matchexternaddrlocally = ast_true(v->value);
32199       } else if (!strcasecmp(v->name, "session-timers")) {
32200          int i = (int) str2stmode(v->value);
32201          if (i < 0) {
32202             ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
32203             global_st_mode = SESSION_TIMER_MODE_ACCEPT;
32204          } else {
32205             global_st_mode = i;
32206          }
32207       } else if (!strcasecmp(v->name, "session-expires")) {
32208          if (sscanf(v->value, "%30d", &global_max_se) != 1) {
32209             ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
32210             global_max_se = DEFAULT_MAX_SE;
32211          }
32212       } else if (!strcasecmp(v->name, "session-minse")) {
32213          if (sscanf(v->value, "%30d", &global_min_se) != 1) {
32214             ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
32215             global_min_se = DEFAULT_MIN_SE;
32216          }
32217          if (global_min_se < DEFAULT_MIN_SE) {
32218             ast_log(LOG_WARNING, "session-minse '%s' at line %d of %s is not allowed to be < %d secs\n", v->value, v->lineno, config, DEFAULT_MIN_SE);
32219             global_min_se = DEFAULT_MIN_SE;
32220          }
32221       } else if (!strcasecmp(v->name, "session-refresher")) {
32222          int i = (int) str2strefresherparam(v->value);
32223          if (i < 0) {
32224             ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
32225             global_st_refresher = SESSION_TIMER_REFRESHER_PARAM_UAS;
32226          } else {
32227             global_st_refresher = i;
32228          }
32229       } else if (!strcasecmp(v->name, "storesipcause")) {
32230          global_store_sip_cause = ast_true(v->value);
32231          if (global_store_sip_cause) {
32232             ast_log(LOG_WARNING, "Usage of SIP_CAUSE is deprecated.  Please use HANGUPCAUSE instead.\n");
32233          }
32234       } else if (!strcasecmp(v->name, "qualifygap")) {
32235          if (sscanf(v->value, "%30d", &global_qualify_gap) != 1) {
32236             ast_log(LOG_WARNING, "Invalid qualifygap '%s' at line %d of %s\n", v->value, v->lineno, config);
32237             global_qualify_gap = DEFAULT_QUALIFY_GAP;
32238          }
32239       } else if (!strcasecmp(v->name, "qualifypeers")) {
32240          if (sscanf(v->value, "%30d", &global_qualify_peers) != 1) {
32241             ast_log(LOG_WARNING, "Invalid pokepeers '%s' at line %d of %s\n", v->value, v->lineno, config);
32242             global_qualify_peers = DEFAULT_QUALIFY_PEERS;
32243          }
32244       } else if (!strcasecmp(v->name, "disallowed_methods")) {
32245          char *disallow = ast_strdupa(v->value);
32246          mark_parsed_methods(&sip_cfg.disallowed_methods, disallow);
32247       } else if (!strcasecmp(v->name, "shrinkcallerid")) {
32248          if (ast_true(v->value)) {
32249             global_shrinkcallerid = 1;
32250          } else if (ast_false(v->value)) {
32251             global_shrinkcallerid = 0;
32252          } else {
32253             ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
32254          }
32255       } else if (!strcasecmp(v->name, "use_q850_reason")) {
32256          ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_Q850_REASON);
32257       } else if (!strcasecmp(v->name, "maxforwards")) {
32258          if (sscanf(v->value, "%30d", &sip_cfg.default_max_forwards) != 1
32259             || sip_cfg.default_max_forwards < 1 || 255 < sip_cfg.default_max_forwards) {
32260             ast_log(LOG_WARNING, "'%s' is not a valid maxforwards value at line %d.  Using default.\n", v->value, v->lineno);
32261             sip_cfg.default_max_forwards = DEFAULT_MAX_FORWARDS;
32262          }
32263       } else if (!strcasecmp(v->name, "subscribe_network_change_event")) {
32264          if (ast_true(v->value)) {
32265             subscribe_network_change = 1;
32266          } else if (ast_false(v->value)) {
32267             subscribe_network_change = 0;
32268          } else {
32269             ast_log(LOG_WARNING, "subscribe_network_change_event value %s is not valid at line %d.\n", v->value, v->lineno);
32270          }
32271       } else if (!strcasecmp(v->name, "snom_aoc_enabled")) {
32272          ast_set2_flag(&global_flags[2], ast_true(v->value), SIP_PAGE3_SNOM_AOC);
32273       } else if (!strcasecmp(v->name, "icesupport")) {
32274          ast_set2_flag(&global_flags[2], ast_true(v->value), SIP_PAGE3_ICE_SUPPORT);
32275       } else if (!strcasecmp(v->name, "parkinglot")) {
32276          ast_copy_string(default_parkinglot, v->value, sizeof(default_parkinglot));
32277       } else if (!strcasecmp(v->name, "refer_addheaders")) {
32278          global_refer_addheaders = ast_true(v->value);
32279       } else if (!strcasecmp(v->name, "websocket_write_timeout")) {
32280          if (sscanf(v->value, "%30d", &sip_cfg.websocket_write_timeout) != 1
32281             || sip_cfg.websocket_write_timeout < 0) {
32282             ast_log(LOG_WARNING, "'%s' is not a valid websocket_write_timeout value at line %d. Using default '%d'.\n", v->value, v->lineno, AST_DEFAULT_WEBSOCKET_WRITE_TIMEOUT);
32283             sip_cfg.websocket_write_timeout = AST_DEFAULT_WEBSOCKET_WRITE_TIMEOUT;
32284          }
32285       }
32286    }
32287 
32288    /* Override global defaults if setting found in general section */
32289    ast_copy_flags(&global_flags[0], &setflags[0], mask[0].flags);
32290    ast_copy_flags(&global_flags[1], &setflags[1], mask[1].flags);
32291    ast_copy_flags(&global_flags[2], &setflags[2], mask[2].flags);
32292 
32293    /* For backwards compatibility the corresponding registration timer value is used if subscription timer value isn't set by configuration */
32294    if (!min_subexpiry_set) {
32295       min_subexpiry = min_expiry;
32296    }
32297    if (!max_subexpiry_set) {
32298       max_subexpiry = max_expiry;
32299    }
32300 
32301    if (reason != CHANNEL_MODULE_LOAD && sip_cfg.autocreatepeer != AUTOPEERS_PERSIST) {
32302       ao2_t_callback(peers, OBJ_NODATA, peer_markall_autopeers_func, NULL, "callback to mark autopeers for destruction");
32303    }
32304 
32305    if (subscribe_network_change) {
32306       network_change_event_subscribe();
32307    } else {
32308       network_change_event_unsubscribe();
32309    }
32310 
32311    if (global_t1 < global_t1min) {
32312       ast_log(LOG_WARNING, "'t1min' (%d) cannot be greater than 't1timer' (%d).  Resetting 't1timer' to the value of 't1min'\n", global_t1min, global_t1);
32313       global_t1 = global_t1min;
32314    }
32315 
32316    if (global_timer_b < global_t1 * 64) {
32317       if (timerb_set && timert1_set) {
32318          ast_log(LOG_WARNING, "Timer B has been set lower than recommended (%d < 64 * timert1=%d). (RFC 3261, 17.1.1.2)\n", global_timer_b, global_t1);
32319       } else if (timerb_set) {
32320          if ((global_t1 = global_timer_b / 64) < global_t1min) {
32321             ast_log(LOG_WARNING, "Timer B has been set lower than recommended (%d < 64 * timert1=%d). (RFC 3261, 17.1.1.2)\n", global_timer_b, global_t1);
32322             global_t1 = global_t1min;
32323             global_timer_b = global_t1 * 64;
32324          }
32325       } else {
32326          global_timer_b = global_t1 * 64;
32327       }
32328    }
32329    if (!sip_cfg.allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
32330       ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
32331       sip_cfg.allow_external_domains = 1;
32332    }
32333    /* If not or badly configured, set default transports */
32334    if (!sip_cfg.tcp_enabled && (default_transports & SIP_TRANSPORT_TCP)) {
32335       ast_log(LOG_WARNING, "Cannot use 'tcp' transport with tcpenable=no. Removing from available transports.\n");
32336       default_primary_transport &= ~SIP_TRANSPORT_TCP;
32337       default_transports &= ~SIP_TRANSPORT_TCP;
32338    }
32339    if (!default_tls_cfg.enabled && (default_transports & SIP_TRANSPORT_TLS)) {
32340       ast_log(LOG_WARNING, "Cannot use 'tls' transport with tlsenable=no. Removing from available transports.\n");
32341       default_primary_transport &= ~SIP_TRANSPORT_TLS;
32342       default_transports &= ~SIP_TRANSPORT_TLS;
32343    }
32344    if (!default_transports) {
32345       ast_log(LOG_WARNING, "No valid transports available, falling back to 'udp'.\n");
32346       default_transports = default_primary_transport = SIP_TRANSPORT_UDP;
32347    } else if (!default_primary_transport) {
32348       ast_log(LOG_WARNING, "No valid default transport. Selecting 'udp' as default.\n");
32349       default_primary_transport = SIP_TRANSPORT_UDP;
32350    }
32351 
32352    /* Build list of authentication to various SIP realms, i.e. service providers */
32353    for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
32354       /* Format for authentication is auth = username:password@realm */
32355       if (!strcasecmp(v->name, "auth")) {
32356          add_realm_authentication(&authl, v->value, v->lineno);
32357       }
32358    }
32359 
32360    if (bindport) {
32361       if (ast_sockaddr_port(&bindaddr)) {
32362          ast_log(LOG_WARNING, "bindport is also specified in bindaddr. "
32363             "Using %d.\n", bindport);
32364       }
32365       ast_sockaddr_set_port(&bindaddr, bindport);
32366    }
32367 
32368    if (!ast_sockaddr_port(&bindaddr)) {
32369       ast_sockaddr_set_port(&bindaddr, STANDARD_SIP_PORT);
32370    }
32371 
32372    /* Set UDP address and open socket */
32373    ast_sockaddr_copy(&internip, &bindaddr);
32374    if (ast_find_ourip(&internip, &bindaddr, 0)) {
32375       ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
32376       ast_config_destroy(cfg);
32377       return 0;
32378    }
32379 
32380    ast_mutex_lock(&netlock);
32381    if ((sipsock > -1) && (ast_sockaddr_cmp(&old_bindaddr, &bindaddr))) {
32382       close(sipsock);
32383       sipsock = -1;
32384    }
32385    if (sipsock < 0) {
32386       sipsock = socket(ast_sockaddr_is_ipv6(&bindaddr) ?
32387              AF_INET6 : AF_INET, SOCK_DGRAM, 0);
32388       if (sipsock < 0) {
32389          ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
32390          ast_config_destroy(cfg);
32391          ast_mutex_unlock(&netlock);
32392          return -1;
32393       } else {
32394          /* Allow SIP clients on the same host to access us: */
32395          const int reuseFlag = 1;
32396 
32397          setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
32398                (const char*)&reuseFlag,
32399                sizeof reuseFlag);
32400 
32401          ast_enable_packet_fragmentation(sipsock);
32402 
32403          if (ast_bind(sipsock, &bindaddr) < 0) {
32404             ast_log(LOG_WARNING, "Failed to bind to %s: %s\n",
32405                ast_sockaddr_stringify(&bindaddr), strerror(errno));
32406             close(sipsock);
32407             sipsock = -1;
32408          } else {
32409             ast_verb(2, "SIP Listening on %s\n", ast_sockaddr_stringify(&bindaddr));
32410             ast_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
32411          }
32412       }
32413    } else {
32414       ast_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
32415    }
32416    ast_mutex_unlock(&netlock);
32417 
32418    /* Start TCP server */
32419    if (sip_cfg.tcp_enabled) {
32420       if (ast_sockaddr_isnull(&sip_tcp_desc.local_address)) {
32421          ast_sockaddr_copy(&sip_tcp_desc.local_address, &bindaddr);
32422       }
32423       if (!ast_sockaddr_port(&sip_tcp_desc.local_address)) {
32424          ast_sockaddr_set_port(&sip_tcp_desc.local_address, STANDARD_SIP_PORT);
32425       }
32426    } else {
32427       ast_sockaddr_setnull(&sip_tcp_desc.local_address);
32428    }
32429    ast_tcptls_server_start(&sip_tcp_desc);
32430    if (sip_cfg.tcp_enabled && sip_tcp_desc.accept_fd == -1) {
32431       /* TCP server start failed. Tell the admin */
32432       ast_log(LOG_ERROR, "SIP TCP Server start failed. Not listening on TCP socket.\n");
32433    } else {
32434       ast_debug(2, "SIP TCP server started\n");
32435    }
32436 
32437    /* Start TLS server if needed */
32438    memcpy(sip_tls_desc.tls_cfg, &default_tls_cfg, sizeof(default_tls_cfg));
32439 
32440    if (ast_ssl_setup(sip_tls_desc.tls_cfg)) {
32441       if (ast_sockaddr_isnull(&sip_tls_desc.local_address)) {
32442          ast_sockaddr_copy(&sip_tls_desc.local_address, &bindaddr);
32443          ast_sockaddr_set_port(&sip_tls_desc.local_address,
32444                      STANDARD_TLS_PORT);
32445       }
32446       if (!ast_sockaddr_port(&sip_tls_desc.local_address)) {
32447          ast_sockaddr_set_port(&sip_tls_desc.local_address,
32448                      STANDARD_TLS_PORT);
32449       }
32450       ast_tcptls_server_start(&sip_tls_desc);
32451       if (default_tls_cfg.enabled && sip_tls_desc.accept_fd == -1) {
32452          ast_log(LOG_ERROR, "TLS Server start failed. Not listening on TLS socket.\n");
32453          sip_tls_desc.tls_cfg = NULL;
32454       }
32455    } else if (sip_tls_desc.tls_cfg->enabled) {
32456       sip_tls_desc.tls_cfg = NULL;
32457       ast_log(LOG_WARNING, "SIP TLS server did not load because of errors.\n");
32458    }
32459 
32460    if (ucfg) {
32461       struct ast_variable *gen;
32462       int genhassip, genregistersip;
32463       const char *hassip, *registersip;
32464       
32465       genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
32466       genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
32467       gen = ast_variable_browse(ucfg, "general");
32468       cat = ast_category_browse(ucfg, NULL);
32469       while (cat) {
32470          if (strcasecmp(cat, "general")) {
32471             hassip = ast_variable_retrieve(ucfg, cat, "hassip");
32472             registersip = ast_variable_retrieve(ucfg, cat, "registersip");
32473             if (ast_true(hassip) || (!hassip && genhassip)) {
32474                peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0, 0);
32475                if (peer) {
32476                   /* user.conf entries are always of type friend */
32477                   peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
32478                   ao2_t_link(peers, peer, "link peer into peer table");
32479                   if ((peer->type & SIP_TYPE_PEER) && !ast_sockaddr_isnull(&peer->addr)) {
32480                      ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
32481                   }
32482                   
32483                   sip_unref_peer(peer, "sip_unref_peer: from reload_config");
32484                   peer_count++;
32485                }
32486             }
32487             if (ast_true(registersip) || (!registersip && genregistersip)) {
32488                char tmp[256];
32489                const char *host = ast_variable_retrieve(ucfg, cat, "host");
32490                const char *username = ast_variable_retrieve(ucfg, cat, "username");
32491                const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
32492                const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
32493                const char *authuser = ast_variable_retrieve(ucfg, cat, "authuser");
32494                if (!host) {
32495                   host = ast_variable_retrieve(ucfg, "general", "host");
32496                }
32497                if (!username) {
32498                   username = ast_variable_retrieve(ucfg, "general", "username");
32499                }
32500                if (!secret) {
32501                   secret = ast_variable_retrieve(ucfg, "general", "secret");
32502                }
32503                if (!contact) {
32504                   contact = "s";
32505                }
32506                if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
32507                   if (!ast_strlen_zero(secret)) {
32508                      if (!ast_strlen_zero(authuser)) {
32509                         snprintf(tmp, sizeof(tmp), "%s?%s:%s:%s@%s/%s", cat, username, secret, authuser, host, contact);
32510                      } else {
32511                         snprintf(tmp, sizeof(tmp), "%s?%s:%s@%s/%s", cat, username, secret, host, contact);
32512                      }
32513                   } else if (!ast_strlen_zero(authuser)) {
32514                      snprintf(tmp, sizeof(tmp), "%s?%s::%s@%s/%s", cat, username, authuser, host, contact);
32515                   } else {
32516                      snprintf(tmp, sizeof(tmp), "%s?%s@%s/%s", cat, username, host, contact);
32517                   }
32518                   if (sip_register(tmp, 0) == 0) {
32519                      registry_count++;
32520                   }
32521                }
32522             }
32523          }
32524          cat = ast_category_browse(ucfg, cat);
32525       }
32526       ast_config_destroy(ucfg);
32527    }
32528 
32529    /* Load peers, users and friends */
32530    cat = NULL;
32531    while ( (cat = ast_category_browse(cfg, cat)) ) {
32532       const char *utype;
32533       if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
32534          continue;
32535       utype = ast_variable_retrieve(cfg, cat, "type");
32536       if (!utype) {
32537          ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
32538          continue;
32539       } else {
32540          if (!strcasecmp(utype, "user")) {
32541             ;
32542          } else if (!strcasecmp(utype, "friend")) {
32543             ;
32544          } else if (!strcasecmp(utype, "peer")) {
32545             ;
32546          } else {
32547             ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
32548             continue;
32549          }
32550          peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0, 0);
32551          if (peer) {
32552             display_nat_warning(cat, reason, &peer->flags[0]);
32553             ao2_t_link(peers, peer, "link peer into peers table");
32554             if ((peer->type & SIP_TYPE_PEER) && !ast_sockaddr_isnull(&peer->addr)) {
32555                ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
32556             }
32557             sip_unref_peer(peer, "unref the result of the build_peer call. Now, the links from the tables are the only ones left.");
32558             peer_count++;
32559          }
32560       }
32561    }
32562 
32563    /* Add default domains - host name, IP address and IP:port
32564     * Only do this if user added any sip domain with "localdomains"
32565     * In order to *not* break backwards compatibility
32566     *    Some phones address us at IP only, some with additional port number
32567     */
32568    if (auto_sip_domains) {
32569       char temp[MAXHOSTNAMELEN];
32570 
32571       /* First our default IP address */
32572       if (!ast_sockaddr_isnull(&bindaddr) && !ast_sockaddr_is_any(&bindaddr)) {
32573          add_sip_domain(ast_sockaddr_stringify_addr(&bindaddr),
32574                    SIP_DOMAIN_AUTO, NULL);
32575       } else if (!ast_sockaddr_isnull(&internip) && !ast_sockaddr_is_any(&internip)) {
32576       /* Our internal IP address, if configured */
32577          add_sip_domain(ast_sockaddr_stringify_addr(&internip),
32578                    SIP_DOMAIN_AUTO, NULL);
32579       } else {
32580          ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
32581       }
32582 
32583       /* If TCP is running on a different IP than UDP, then add it too */
32584       if (!ast_sockaddr_isnull(&sip_tcp_desc.local_address) &&
32585           !ast_sockaddr_cmp(&bindaddr, &sip_tcp_desc.local_address)) {
32586          add_sip_domain(ast_sockaddr_stringify_addr(&sip_tcp_desc.local_address),
32587                    SIP_DOMAIN_AUTO, NULL);
32588       }
32589 
32590       /* If TLS is running on a different IP than UDP and TCP, then add that too */
32591       if (!ast_sockaddr_isnull(&sip_tls_desc.local_address) &&
32592           !ast_sockaddr_cmp(&bindaddr, &sip_tls_desc.local_address) &&
32593           !ast_sockaddr_cmp(&sip_tcp_desc.local_address,
32594                   &sip_tls_desc.local_address)) {
32595          add_sip_domain(ast_sockaddr_stringify_addr(&sip_tcp_desc.local_address),
32596                    SIP_DOMAIN_AUTO, NULL);
32597       }
32598 
32599       /* Our extern IP address, if configured */
32600       if (!ast_sockaddr_isnull(&externaddr)) {
32601          add_sip_domain(ast_sockaddr_stringify_addr(&externaddr),
32602                    SIP_DOMAIN_AUTO, NULL);
32603       }
32604 
32605       /* Extern host name (NAT traversal support) */
32606       if (!ast_strlen_zero(externhost)) {
32607          add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
32608       }
32609       
32610       /* Our host name */
32611       if (!gethostname(temp, sizeof(temp))) {
32612          add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
32613       }
32614    }
32615 
32616    /* Release configuration from memory */
32617    ast_config_destroy(cfg);
32618 
32619    register_realtime_peers_with_callbackextens();
32620 
32621    /* Load the list of manual NOTIFY types to support */
32622    if (notify_types) {
32623       ast_config_destroy(notify_types);
32624    }
32625    if ((notify_types = ast_config_load(notify_config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
32626       ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed.\n", notify_config);
32627       notify_types = NULL;
32628    }
32629 
32630    /* Done, tell the manager */
32631    manager_event(EVENT_FLAG_SYSTEM, "ChannelReload", "ChannelType: SIP\r\nReloadReason: %s\r\nRegistry_Count: %d\r\nPeer_Count: %d\r\n", channelreloadreason2txt(reason), registry_count, peer_count);
32632    run_end = time(0);
32633    ast_debug(4, "SIP reload_config done...Runtime= %d sec\n", (int)(run_end-run_start));
32634 
32635    /* If an ACL change subscription is needed and doesn't exist, we need one. */
32636    if (acl_change_subscription_needed) {
32637       acl_change_event_subscribe();
32638    }
32639 
32640    return 0;
32641 }
32642 
32643 static int apply_directmedia_acl(struct sip_pvt *p, struct ast_acl_list *directmediaacl, const char *op)
32644 {
32645    struct ast_sockaddr us = { { 0, }, }, them = { { 0, }, };
32646    int res = AST_SENSE_ALLOW;
32647 
32648    ast_rtp_instance_get_remote_address(p->rtp, &them);
32649    ast_rtp_instance_get_local_address(p->rtp, &us);
32650 
32651    if ((res = ast_apply_acl(directmediaacl, &them, "SIP Direct Media ACL: ")) == AST_SENSE_DENY) {
32652       const char *us_addr = ast_strdupa(ast_sockaddr_stringify(&us));
32653       const char *them_addr = ast_strdupa(ast_sockaddr_stringify(&them));
32654 
32655       ast_debug(3, "Reinvite %s to %s denied by directmedia ACL on %s\n",
32656          op, them_addr, us_addr);
32657    }
32658 
32659    return res;
32660 }
32661 
32662 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan)
32663 {
32664    struct sip_pvt *p;
32665    struct ast_udptl *udptl = NULL;
32666    
32667    p = ast_channel_tech_pvt(chan);
32668    if (!p) {
32669       return NULL;
32670    }
32671 
32672    sip_pvt_lock(p);
32673    if (p->udptl && ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
32674       udptl = p->udptl;
32675    }
32676    sip_pvt_unlock(p);
32677    return udptl;
32678 }
32679 
32680 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl)
32681 {
32682    struct sip_pvt *p;
32683 
32684    /* Lock the channel and the private safely. */
32685    ast_channel_lock(chan);
32686    p = ast_channel_tech_pvt(chan);
32687    if (!p) {
32688       ast_channel_unlock(chan);
32689       return -1;
32690    }
32691    sip_pvt_lock(p);
32692    if (p->owner != chan) {
32693       /* I suppose it could be argued that if this happens it is a bug. */
32694       ast_debug(1, "The private is not owned by channel %s anymore.\n", ast_channel_name(chan));
32695       sip_pvt_unlock(p);
32696       ast_channel_unlock(chan);
32697       return 0;
32698    }
32699 
32700    if (udptl) {
32701       ast_udptl_get_peer(udptl, &p->udptlredirip);
32702    } else {
32703       memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
32704    }
32705    if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
32706       if (!p->pendinginvite) {
32707          ast_debug(3, "Sending reinvite on SIP '%s' - It's UDPTL soon redirected to IP %s\n",
32708                p->callid, ast_sockaddr_stringify(udptl ? &p->udptlredirip : &p->ourip));
32709          transmit_reinvite_with_sdp(p, TRUE, FALSE);
32710       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
32711          ast_debug(3, "Deferring reinvite on SIP '%s' - It's UDPTL will be redirected to IP %s\n",
32712                p->callid, ast_sockaddr_stringify(udptl ? &p->udptlredirip : &p->ourip));
32713          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
32714       }
32715    }
32716    /* Reset lastrtprx timer */
32717    p->lastrtprx = p->lastrtptx = time(NULL);
32718    sip_pvt_unlock(p);
32719    ast_channel_unlock(chan);
32720    return 0;
32721 }
32722 
32723 static int sip_allow_anyrtp_remote(struct ast_channel *chan1, struct ast_channel *chan2, char *rtptype)
32724 {
32725    struct sip_pvt *p1 = NULL, *p2 = NULL;
32726    struct ast_acl_list *p2_directmediaacl = NULL; /* opposed directmediaha for comparing against first channel host address */
32727    struct ast_acl_list *p1_directmediaacl = NULL; /* opposed directmediaha for comparing against second channel host address */
32728    int res = 1;
32729 
32730    if (!(p1 = ast_channel_tech_pvt(chan1))) {
32731       return 0;
32732    }
32733 
32734    if (!(p2 = ast_channel_tech_pvt(chan2))) {
32735       return 0;
32736    }
32737 
32738    sip_pvt_lock(p2);
32739    if (p2->relatedpeer && p2->relatedpeer->directmediaacl) {
32740       p2_directmediaacl = ast_duplicate_acl_list(p2->relatedpeer->directmediaacl);
32741    }
32742    sip_pvt_unlock(p2);
32743 
32744    sip_pvt_lock(p1);
32745    if (p1->relatedpeer && p1->relatedpeer->directmediaacl) {
32746       p1_directmediaacl = ast_duplicate_acl_list(p1->relatedpeer->directmediaacl);
32747    }
32748 
32749    if (p2_directmediaacl && ast_test_flag(&p1->flags[0], SIP_DIRECT_MEDIA)) {
32750       if (!apply_directmedia_acl(p1, p2_directmediaacl, rtptype)) {
32751          res = 0;
32752       }
32753    }
32754    sip_pvt_unlock(p1);
32755 
32756    if (res == 0) {
32757       goto allow_anyrtp_remote_end;
32758    }
32759 
32760    sip_pvt_lock(p2);
32761    if (p1_directmediaacl && ast_test_flag(&p2->flags[0], SIP_DIRECT_MEDIA)) {
32762       if (!apply_directmedia_acl(p2, p1_directmediaacl, rtptype)) {
32763          res = 0;
32764       }
32765    }
32766    sip_pvt_unlock(p2);
32767 
32768 allow_anyrtp_remote_end:
32769 
32770    if (p2_directmediaacl) {
32771       p2_directmediaacl = ast_free_acl_list(p2_directmediaacl);
32772    }
32773 
32774    if (p1_directmediaacl) {
32775       p1_directmediaacl = ast_free_acl_list(p1_directmediaacl);
32776    }
32777 
32778    return res;
32779 }
32780 
32781 static int sip_allow_rtp_remote(struct ast_channel *chan1, struct ast_channel *chan2)
32782 {
32783    return sip_allow_anyrtp_remote(chan1, chan2, "audio");
32784 }
32785 
32786 static int sip_allow_vrtp_remote(struct ast_channel *chan1, struct ast_channel *chan2)
32787 {
32788    return sip_allow_anyrtp_remote(chan1, chan2, "video");
32789 }
32790 
32791 static enum ast_rtp_glue_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
32792 {
32793    struct sip_pvt *p = NULL;
32794    enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_LOCAL;
32795 
32796    if (!(p = ast_channel_tech_pvt(chan))) {
32797       return AST_RTP_GLUE_RESULT_FORBID;
32798    }
32799 
32800    sip_pvt_lock(p);
32801    if (!(p->rtp)) {
32802       sip_pvt_unlock(p);
32803       return AST_RTP_GLUE_RESULT_FORBID;
32804    }
32805 
32806    ao2_ref(p->rtp, +1);
32807    *instance = p->rtp;
32808 
32809    if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
32810       res = AST_RTP_GLUE_RESULT_REMOTE;
32811    } else if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT)) {
32812       res = AST_RTP_GLUE_RESULT_REMOTE;
32813    } else if (ast_test_flag(&global_jbconf, AST_JB_FORCED)) {
32814       res = AST_RTP_GLUE_RESULT_FORBID;
32815    }
32816 
32817    if (p->srtp) {
32818       res = AST_RTP_GLUE_RESULT_FORBID;
32819    }
32820 
32821    sip_pvt_unlock(p);
32822 
32823    return res;
32824 }
32825 
32826 static enum ast_rtp_glue_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
32827 {
32828    struct sip_pvt *p = NULL;
32829    enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_FORBID;
32830 
32831    if (!(p = ast_channel_tech_pvt(chan))) {
32832       return AST_RTP_GLUE_RESULT_FORBID;
32833    }
32834 
32835    sip_pvt_lock(p);
32836    if (!(p->vrtp)) {
32837       sip_pvt_unlock(p);
32838       return AST_RTP_GLUE_RESULT_FORBID;
32839    }
32840 
32841    ao2_ref(p->vrtp, +1);
32842    *instance = p->vrtp;
32843 
32844    if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
32845       res = AST_RTP_GLUE_RESULT_REMOTE;
32846    }
32847 
32848    sip_pvt_unlock(p);
32849 
32850    return res;
32851 }
32852 
32853 static enum ast_rtp_glue_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
32854 {
32855    struct sip_pvt *p = NULL;
32856    enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_FORBID;
32857 
32858    if (!(p = ast_channel_tech_pvt(chan))) {
32859       return AST_RTP_GLUE_RESULT_FORBID;
32860    }
32861 
32862    sip_pvt_lock(p);
32863    if (!(p->trtp)) {
32864       sip_pvt_unlock(p);
32865       return AST_RTP_GLUE_RESULT_FORBID;
32866    }
32867 
32868    ao2_ref(p->trtp, +1);
32869    *instance = p->trtp;
32870 
32871    if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
32872       res = AST_RTP_GLUE_RESULT_REMOTE;
32873    }
32874 
32875    sip_pvt_unlock(p);
32876 
32877    return res;
32878 }
32879 
32880 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)
32881 {
32882    struct sip_pvt *p;
32883    int changed = 0;
32884 
32885    /* Lock the channel and the private safely. */
32886    ast_channel_lock(chan);
32887    p = ast_channel_tech_pvt(chan);
32888    if (!p) {
32889       ast_channel_unlock(chan);
32890       return -1;
32891    }
32892    sip_pvt_lock(p);
32893    if (p->owner != chan) {
32894       /* I suppose it could be argued that if this happens it is a bug. */
32895       ast_debug(1, "The private is not owned by channel %s anymore.\n", ast_channel_name(chan));
32896       sip_pvt_unlock(p);
32897       ast_channel_unlock(chan);
32898       return 0;
32899    }
32900 
32901    /* Disable early RTP bridge  */
32902    if ((instance || vinstance || tinstance) &&
32903       !ast_bridged_channel(chan) &&
32904       !sip_cfg.directrtpsetup) {
32905       sip_pvt_unlock(p);
32906       ast_channel_unlock(chan);
32907       return 0;
32908    }
32909 
32910    if (p->alreadygone) {
32911       /* If we're destroyed, don't bother */
32912       sip_pvt_unlock(p);
32913       ast_channel_unlock(chan);
32914       return 0;
32915    }
32916 
32917    /* if this peer cannot handle reinvites of the media stream to devices
32918       that are known to be behind a NAT, then stop the process now
32919    */
32920    if (nat_active && !ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT)) {
32921       sip_pvt_unlock(p);
32922       ast_channel_unlock(chan);
32923       return 0;
32924    }
32925 
32926    if (instance) {
32927       changed |= ast_rtp_instance_get_and_cmp_remote_address(instance, &p->redirip);
32928 
32929       if (p->rtp) {
32930          /* Prevent audio RTCP reads */
32931          ast_channel_set_fd(chan, 1, -1);
32932          /* Silence RTCP while audio RTP is inactive */
32933          ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 0);
32934       }
32935    } else if (!ast_sockaddr_isnull(&p->redirip)) {
32936       memset(&p->redirip, 0, sizeof(p->redirip));
32937       changed = 1;
32938 
32939       if (p->rtp) {
32940          /* Enable RTCP since it will be inactive if we're coming back
32941           * from a reinvite */
32942          ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 1);
32943          /* Enable audio RTCP reads */
32944          ast_channel_set_fd(chan, 1, ast_rtp_instance_fd(p->rtp, 1));
32945       }
32946    }
32947 
32948    if (vinstance) {
32949       changed |= ast_rtp_instance_get_and_cmp_remote_address(vinstance, &p->vredirip);
32950 
32951       if (p->vrtp) {
32952          /* Prevent video RTCP reads */
32953          ast_channel_set_fd(chan, 3, -1);
32954          /* Silence RTCP while video RTP is inactive */
32955          ast_rtp_instance_set_prop(p->vrtp, AST_RTP_PROPERTY_RTCP, 0);
32956       }
32957    } else if (!ast_sockaddr_isnull(&p->vredirip)) {
32958       memset(&p->vredirip, 0, sizeof(p->vredirip));
32959       changed = 1;
32960 
32961       if (p->vrtp) {
32962          /* Enable RTCP since it will be inactive if we're coming back
32963           * from a reinvite */
32964          ast_rtp_instance_set_prop(p->vrtp, AST_RTP_PROPERTY_RTCP, 1);
32965          /* Enable video RTCP reads */
32966          ast_channel_set_fd(chan, 3, ast_rtp_instance_fd(p->vrtp, 1));
32967       }
32968    }
32969 
32970    if (tinstance) {
32971       changed |= ast_rtp_instance_get_and_cmp_remote_address(tinstance, &p->tredirip);
32972    } else if (!ast_sockaddr_isnull(&p->tredirip)) {
32973       memset(&p->tredirip, 0, sizeof(p->tredirip));
32974       changed = 1;
32975    }
32976    if (cap && !ast_format_cap_is_empty(cap) && !ast_format_cap_identical(p->redircaps, cap)) {
32977       ast_format_cap_copy(p->redircaps, cap);
32978       changed = 1;
32979    }
32980 
32981    if (ast_test_flag(&p->flags[2], SIP_PAGE3_DIRECT_MEDIA_OUTGOING) && !p->outgoing_call) {
32982       /* We only wish to withhold sending the initial direct media reinvite on the incoming dialog.
32983        * Further direct media reinvites beyond the initial should be sent. In order to allow further
32984        * direct media reinvites to be sent, we clear this flag.
32985        */
32986       ast_clear_flag(&p->flags[2], SIP_PAGE3_DIRECT_MEDIA_OUTGOING);
32987       sip_pvt_unlock(p);
32988       ast_channel_unlock(chan);
32989       return 0;
32990    }
32991 
32992    if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER) && !ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
32993       if (ast_channel_state(chan) != AST_STATE_UP) {     /* We are in early state */
32994          if (p->do_history)
32995             append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
32996          ast_debug(1, "Early remote bridge setting SIP '%s' - Sending media to %s\n", p->callid, ast_sockaddr_stringify(instance ? &p->redirip : &p->ourip));
32997       } else if (!p->pendinginvite) {   /* We are up, and have no outstanding invite */
32998          ast_debug(3, "Sending reinvite on SIP '%s' - It's audio soon redirected to IP %s\n", p->callid, ast_sockaddr_stringify(instance ? &p->redirip : &p->ourip));
32999          transmit_reinvite_with_sdp(p, FALSE, FALSE);
33000       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
33001          ast_debug(3, "Deferring reinvite on SIP '%s' - It's audio will be redirected to IP %s\n", p->callid, ast_sockaddr_stringify(instance ? &p->redirip : &p->ourip));
33002          /* We have a pending Invite. Send re-invite when we're done with the invite */
33003          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
33004       }
33005    }
33006    /* Reset lastrtprx timer */
33007    p->lastrtprx = p->lastrtptx = time(NULL);
33008    sip_pvt_unlock(p);
33009    ast_channel_unlock(chan);
33010    return 0;
33011 }
33012 
33013 static void sip_get_codec(struct ast_channel *chan, struct ast_format_cap *result)
33014 {
33015    struct sip_pvt *p = ast_channel_tech_pvt(chan);
33016    ast_format_cap_append(result, ast_format_cap_is_empty(p->peercaps) ? p->caps : p->peercaps);
33017 }
33018 
33019 static struct ast_rtp_glue sip_rtp_glue = {
33020    .type = "SIP",
33021    .get_rtp_info = sip_get_rtp_peer,
33022    .allow_rtp_remote = sip_allow_rtp_remote,
33023    .get_vrtp_info = sip_get_vrtp_peer,
33024    .allow_vrtp_remote = sip_allow_vrtp_remote,
33025    .get_trtp_info = sip_get_trtp_peer,
33026    .update_peer = sip_set_rtp_peer,
33027    .get_codec = sip_get_codec,
33028 };
33029 
33030 static char *app_dtmfmode = "SIPDtmfMode";
33031 static char *app_sipaddheader = "SIPAddHeader";
33032 static char *app_sipremoveheader = "SIPRemoveHeader";
33033 #ifdef TEST_FRAMEWORK
33034 static char *app_sipsendcustominfo = "SIPSendCustomINFO";
33035 #endif
33036 
33037 /*! \brief Set the DTMFmode for an outbound SIP call (application) */
33038 static int sip_dtmfmode(struct ast_channel *chan, const char *data)
33039 {
33040    struct sip_pvt *p;
33041    const char *mode = data;
33042 
33043    if (!data) {
33044       ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
33045       return 0;
33046    }
33047    ast_channel_lock(chan);
33048    if (!IS_SIP_TECH(ast_channel_tech(chan))) {
33049       ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
33050       ast_channel_unlock(chan);
33051       return 0;
33052    }
33053    p = ast_channel_tech_pvt(chan);
33054    if (!p) {
33055       ast_channel_unlock(chan);
33056       return 0;
33057    }
33058    sip_pvt_lock(p);
33059    if (!strcasecmp(mode, "info")) {
33060       ast_clear_flag(&p->flags[0], SIP_DTMF);
33061       ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
33062       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
33063    } else if (!strcasecmp(mode, "shortinfo")) {
33064       ast_clear_flag(&p->flags[0], SIP_DTMF);
33065       ast_set_flag(&p->flags[0], SIP_DTMF_SHORTINFO);
33066       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
33067    } else if (!strcasecmp(mode, "rfc2833")) {
33068       ast_clear_flag(&p->flags[0], SIP_DTMF);
33069       ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
33070       p->jointnoncodeccapability |= AST_RTP_DTMF;
33071    } else if (!strcasecmp(mode, "inband")) {
33072       ast_clear_flag(&p->flags[0], SIP_DTMF);
33073       ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
33074       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
33075    } else {
33076       ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n", mode);
33077    }
33078    if (p->rtp)
33079       ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
33080    if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
33081        (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
33082       enable_dsp_detect(p);
33083    } else {
33084       disable_dsp_detect(p);
33085    }
33086    sip_pvt_unlock(p);
33087    ast_channel_unlock(chan);
33088    return 0;
33089 }
33090 
33091 /*! \brief Add a SIP header to an outbound INVITE */
33092 static int sip_addheader(struct ast_channel *chan, const char *data)
33093 {
33094    int no = 0;
33095    int ok = FALSE;
33096    char varbuf[30];
33097    const char *inbuf = data;
33098    char *subbuf;
33099    
33100    if (ast_strlen_zero(inbuf)) {
33101       ast_log(LOG_WARNING, "This application requires the argument: Header\n");
33102       return 0;
33103    }
33104    ast_channel_lock(chan);
33105 
33106    /* Check for headers */
33107    while (!ok && no <= 50) {
33108       no++;
33109       snprintf(varbuf, sizeof(varbuf), "__SIPADDHEADER%.2d", no);
33110 
33111       /* Compare without the leading underscores */
33112       if ((pbx_builtin_getvar_helper(chan, (const char *) varbuf + 2) == (const char *) NULL)) {
33113          ok = TRUE;
33114       }
33115    }
33116    if (ok) {
33117       size_t len = strlen(inbuf);
33118       subbuf = ast_alloca(len + 1);
33119       ast_get_encoded_str(inbuf, subbuf, len + 1);
33120       pbx_builtin_setvar_helper(chan, varbuf, subbuf);
33121       if (sipdebug) {
33122          ast_debug(1, "SIP Header added \"%s\" as %s\n", inbuf, varbuf);
33123       }
33124    } else {
33125       ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
33126    }
33127    ast_channel_unlock(chan);
33128    return 0;
33129 }
33130 
33131 /*! \brief Remove SIP headers added previously with SipAddHeader application */
33132 static int sip_removeheader(struct ast_channel *chan, const char *data)
33133 {
33134    struct ast_var_t *newvariable;
33135    struct varshead *headp;
33136    int removeall = 0;
33137    char *inbuf = (char *) data;
33138 
33139    if (ast_strlen_zero(inbuf)) {
33140       removeall = 1;
33141    }
33142    ast_channel_lock(chan);
33143 
33144    headp=ast_channel_varshead(chan);
33145    AST_LIST_TRAVERSE_SAFE_BEGIN (headp, newvariable, entries) {
33146       if (strncasecmp(ast_var_name(newvariable), "SIPADDHEADER", strlen("SIPADDHEADER")) == 0) {
33147          if (removeall || (!strncasecmp(ast_var_value(newvariable),inbuf,strlen(inbuf)))) {
33148             if (sipdebug) {
33149                ast_debug(1,"removing SIP Header \"%s\" as %s\n",
33150                   ast_var_value(newvariable),
33151                   ast_var_name(newvariable));
33152             }
33153             AST_LIST_REMOVE_CURRENT(entries);
33154             ast_var_delete(newvariable);
33155          }
33156       }
33157    }
33158    AST_LIST_TRAVERSE_SAFE_END;
33159 
33160    ast_channel_unlock(chan);
33161    return 0;
33162 }
33163 
33164 #ifdef TEST_FRAMEWORK
33165 /*! \brief Send a custom INFO message via AST_CONTROL_CUSTOM indication */
33166 static int sip_sendcustominfo(struct ast_channel *chan, const char *data)
33167 {
33168    char *info_data, *useragent;
33169 
33170    if (ast_strlen_zero(data)) {
33171       ast_log(LOG_WARNING, "You must provide data to be sent\n");
33172       return 0;
33173    }
33174 
33175    useragent = ast_strdupa(data);
33176    info_data = strsep(&useragent, ",");
33177 
33178    if (ast_sipinfo_send(chan, NULL, "text/plain", info_data, useragent)) {
33179       ast_log(LOG_WARNING, "Failed to create payload for custom SIP INFO\n");
33180       return 0;
33181    }
33182    return 0;
33183 }
33184 #endif
33185 
33186 /*! \brief Transfer call before connect with a 302 redirect
33187 \note Called by the transfer() dialplan application through the sip_transfer()
33188    pbx interface function if the call is in ringing state
33189 \todo Fix this function so that we wait for reply to the REFER and
33190    react to errors, denials or other issues the other end might have.
33191  */
33192 static int sip_sipredirect(struct sip_pvt *p, const char *dest)
33193 {
33194    char *cdest;
33195    char *extension, *domain;
33196 
33197    cdest = ast_strdupa(dest);
33198 
33199    extension = strsep(&cdest, "@");
33200    domain = cdest;
33201    if (ast_strlen_zero(extension)) {
33202       ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
33203       return 0;
33204    }
33205 
33206    /* we'll issue the redirect message here */
33207    if (!domain) {
33208       char *local_to_header;
33209       char to_header[256];
33210 
33211       ast_copy_string(to_header, sip_get_header(&p->initreq, "To"), sizeof(to_header));
33212       if (ast_strlen_zero(to_header)) {
33213          ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
33214          return 0;
33215       }
33216       if (((local_to_header = strcasestr(to_header, "sip:")) || (local_to_header = strcasestr(to_header, "sips:")))
33217          && (local_to_header = strchr(local_to_header, '@'))) {
33218          char ldomain[256];
33219 
33220          memset(ldomain, 0, sizeof(ldomain));
33221          local_to_header++;
33222          /* This is okey because lhost and lport are as big as tmp */
33223          sscanf(local_to_header, "%256[^<>; ]", ldomain);
33224          if (ast_strlen_zero(ldomain)) {
33225             ast_log(LOG_ERROR, "Can't find the host address\n");
33226             return 0;
33227          }
33228          domain = ast_strdupa(ldomain);
33229       }
33230    }
33231 
33232    ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s>", extension, domain);
33233    transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);
33234 
33235    sip_scheddestroy(p, SIP_TRANS_TIMEOUT);   /* Make sure we stop send this reply. */
33236    sip_alreadygone(p);
33237 
33238    if (p->owner) {
33239       enum ast_control_transfer message = AST_TRANSFER_SUCCESS;
33240       ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
33241    }
33242    /* hangup here */
33243    return 0;
33244 }
33245 
33246 static int sip_is_xml_parsable(void)
33247 {
33248 #ifdef HAVE_LIBXML2
33249    return TRUE;
33250 #else
33251    return FALSE;
33252 #endif
33253 }
33254 
33255 /*! \brief Send a poke to all known peers */
33256 static void sip_poke_all_peers(void)
33257 {
33258    int ms = 0, num = 0;
33259    struct ao2_iterator i;
33260    struct sip_peer *peer;
33261 
33262    if (!speerobjs) { /* No peers, just give up */
33263       return;
33264    }
33265 
33266    i = ao2_iterator_init(peers, 0);
33267    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
33268       ao2_lock(peer);
33269       /* Don't schedule poking on a peer without qualify */
33270       if (peer->maxms) {
33271          if (num == global_qualify_peers) {
33272             ms += global_qualify_gap;
33273             num = 0;
33274          } else {
33275             num++;
33276          }
33277          AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ms, sip_poke_peer_s, peer,
33278                sip_unref_peer(_data, "removing poke peer ref"),
33279                sip_unref_peer(peer, "removing poke peer ref"),
33280                sip_ref_peer(peer, "adding poke peer ref"));
33281       }
33282       ao2_unlock(peer);
33283       sip_unref_peer(peer, "toss iterator peer ptr");
33284    }
33285    ao2_iterator_destroy(&i);
33286 }
33287 
33288 /*! \brief Send a keepalive to all known peers */
33289 static void sip_keepalive_all_peers(void)
33290 {
33291    struct ao2_iterator i;
33292    struct sip_peer *peer;
33293 
33294    if (!speerobjs) {       /* No peers, just give up */
33295       return;
33296    }
33297 
33298    i = ao2_iterator_init(peers, 0);
33299    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
33300       ao2_lock(peer);
33301       AST_SCHED_REPLACE_UNREF(peer->keepalivesend, sched, 0, sip_send_keepalive, peer,
33302                sip_unref_peer(_data, "removing poke peer ref"),
33303                sip_unref_peer(peer, "removing poke peer ref"),
33304                sip_ref_peer(peer, "adding poke peer ref"));
33305       ao2_unlock(peer);
33306       sip_unref_peer(peer, "toss iterator peer ptr");
33307    }
33308    ao2_iterator_destroy(&i);
33309 }
33310 
33311 /*! \brief Send all known registrations */
33312 static void sip_send_all_registers(void)
33313 {
33314    int ms;
33315    int regspacing;
33316    if (!regobjs) {
33317       return;
33318    }
33319    regspacing = default_expiry * 1000/regobjs;
33320    if (regspacing > 100) {
33321       regspacing = 100;
33322    }
33323    ms = regspacing;
33324    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
33325       ASTOBJ_WRLOCK(iterator);
33326       ms += regspacing;
33327       AST_SCHED_REPLACE_UNREF(iterator->expire, sched, ms, sip_reregister, iterator,
33328                         registry_unref(_data, "REPLACE sched del decs the refcount"),
33329                         registry_unref(iterator, "REPLACE sched add failure decs the refcount"),
33330                         registry_addref(iterator, "REPLACE sched add incs the refcount"));
33331       ASTOBJ_UNLOCK(iterator);
33332    } while (0)
33333    );
33334 }
33335 
33336 /*! \brief Send all MWI subscriptions */
33337 static void sip_send_all_mwi_subscriptions(void)
33338 {
33339    ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
33340       struct sip_subscription_mwi *saved;
33341       ASTOBJ_WRLOCK(iterator);
33342       AST_SCHED_DEL(sched, iterator->resub);
33343       saved = ASTOBJ_REF(iterator);
33344       if ((iterator->resub = ast_sched_add(sched, 1, sip_subscribe_mwi_do, saved)) < 0) {
33345          ASTOBJ_UNREF(saved, sip_subscribe_mwi_destroy);
33346       }
33347       ASTOBJ_UNLOCK(iterator);
33348    } while (0));
33349 }
33350 
33351 /* SRTP */
33352 static int setup_srtp(struct sip_srtp **srtp)
33353 {
33354    if (!ast_rtp_engine_srtp_is_registered()) {
33355       ast_log(LOG_ERROR, "No SRTP module loaded, can't setup SRTP session.\n");
33356       return -1;
33357    }
33358 
33359    if (!(*srtp = sip_srtp_alloc())) { /* Allocate SRTP data structure */
33360       return -1;
33361    }
33362 
33363    return 0;
33364 }
33365 
33366 static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct sip_srtp **srtp, const char *a)
33367 {
33368    struct ast_rtp_engine_dtls *dtls;
33369 
33370    /* If no RTP instance exists for this media stream don't bother processing the crypto line */
33371    if (!rtp) {
33372       ast_debug(3, "Received offer with crypto line for media stream that is not enabled\n");
33373       return FALSE;
33374    }
33375 
33376    if (strncasecmp(a, "crypto:", 7)) {
33377       return FALSE;
33378    }
33379    if (!*srtp) {
33380       if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
33381          ast_log(LOG_WARNING, "Ignoring unexpected crypto attribute in SDP answer\n");
33382          return FALSE;
33383       }
33384 
33385       if (setup_srtp(srtp) < 0) {
33386          return FALSE;
33387       }
33388    }
33389 
33390    if (!(*srtp)->crypto && !((*srtp)->crypto = sdp_crypto_setup())) {
33391       return FALSE;
33392    }
33393 
33394    if (sdp_crypto_process((*srtp)->crypto, a, rtp, *srtp) < 0) {
33395       return FALSE;
33396    }
33397 
33398    ast_set_flag(*srtp, SRTP_CRYPTO_OFFER_OK);
33399 
33400    if ((dtls = ast_rtp_instance_get_dtls(rtp))) {
33401       dtls->stop(rtp);
33402       p->dtls_cfg.enabled = 0;
33403    }
33404 
33405    return TRUE;
33406 }
33407 
33408 /*! \brief Reload module */
33409 static int sip_do_reload(enum channelreloadreason reason)
33410 {
33411    time_t start_poke, end_poke;
33412 
33413    reload_config(reason);
33414    ast_sched_dump(sched);
33415 
33416    start_poke = time(0);
33417    /* Prune peers who still are supposed to be deleted */
33418    unlink_marked_peers_from_tables();
33419 
33420    ast_debug(4, "--------------- Done destroying pruned peers\n");
33421 
33422    /* Send qualify (OPTIONS) to all peers */
33423    sip_poke_all_peers();
33424 
33425    /* Send keepalive to all peers */
33426    sip_keepalive_all_peers();
33427 
33428    /* Register with all services */
33429    sip_send_all_registers();
33430 
33431    sip_send_all_mwi_subscriptions();
33432 
33433    end_poke = time(0);
33434 
33435    ast_debug(4, "do_reload finished. peer poke/prune reg contact time = %d sec.\n", (int)(end_poke-start_poke));
33436 
33437    ast_debug(4, "--------------- SIP reload done\n");
33438 
33439    return 0;
33440 }
33441 
33442 /*! \brief Force reload of module from cli */
33443 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
33444 {
33445    static struct sip_peer *tmp_peer, *new_peer;
33446 
33447    switch (cmd) {
33448    case CLI_INIT:
33449       e->command = "sip reload";
33450       e->usage =
33451          "Usage: sip reload\n"
33452          "       Reloads SIP configuration from sip.conf\n";
33453       return NULL;
33454    case CLI_GENERATE:
33455       return NULL;
33456    }
33457 
33458    ast_mutex_lock(&sip_reload_lock);
33459    if (sip_reloading) {
33460       ast_verbose("Previous SIP reload not yet done\n");
33461    } else {
33462       sip_reloading = TRUE;
33463       sip_reloadreason = (a && a->fd) ? CHANNEL_CLI_RELOAD : CHANNEL_MODULE_RELOAD;
33464    }
33465    ast_mutex_unlock(&sip_reload_lock);
33466    restart_monitor();
33467 
33468    tmp_peer = bogus_peer;
33469    /* Create new bogus peer possibly with new global settings. */
33470    if ((new_peer = temp_peer("(bogus_peer)"))) {
33471       ast_string_field_set(new_peer, md5secret, BOGUS_PEER_MD5SECRET);
33472       ast_clear_flag(&new_peer->flags[0], SIP_INSECURE);
33473       bogus_peer = new_peer;
33474       ao2_t_ref(tmp_peer, -1, "unref the old bogus_peer during reload");
33475    } else {
33476       ast_log(LOG_ERROR, "Could not update the fake authentication peer.\n");
33477       /* You probably have bigger (memory?) issues to worry about though.. */
33478    }
33479 
33480    return CLI_SUCCESS;
33481 }
33482 
33483 /*! \brief  Part of Asterisk module interface */
33484 static int reload(void)
33485 {
33486    if (sip_reload(0, 0, NULL)) {
33487       return 0;
33488    }
33489    return 1;
33490 }
33491 
33492 /*! \brief  Return the first entry from ast_sockaddr_resolve filtered by address family
33493  *
33494  * \warn Using this function probably means you have a faulty design.
33495  */
33496 static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
33497                   const char* name, int flag, int family)
33498 {
33499    struct ast_sockaddr *addrs;
33500    int addrs_cnt;
33501 
33502    addrs_cnt = ast_sockaddr_resolve(&addrs, name, flag, family);
33503    if (addrs_cnt <= 0) {
33504       return 1;
33505    }
33506    if (addrs_cnt > 1) {
33507       ast_debug(1, "Multiple addresses, using the first one only\n");
33508    }
33509 
33510    ast_sockaddr_copy(addr, &addrs[0]);
33511 
33512    ast_free(addrs);
33513    return 0;
33514 }
33515 
33516 /*! \brief  Return the first entry from ast_sockaddr_resolve filtered by family of binddaddr
33517  *
33518  * \warn Using this function probably means you have a faulty design.
33519  */
33520 static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
33521                   const char* name, int flag)
33522 {
33523    return ast_sockaddr_resolve_first_af(addr, name, flag, get_address_family_filter(SIP_TRANSPORT_UDP));
33524 }
33525 
33526 /*! \brief  Return the first entry from ast_sockaddr_resolve filtered by family of binddaddr
33527  *
33528  * \warn Using this function probably means you have a faulty design.
33529  */
33530 static int ast_sockaddr_resolve_first_transport(struct ast_sockaddr *addr,
33531                   const char* name, int flag, unsigned int transport)
33532 {
33533         return ast_sockaddr_resolve_first_af(addr, name, flag, get_address_family_filter(transport));
33534 }
33535 
33536 /*! \brief
33537  * \note The only member of the peer used here is the name field
33538  */
33539 static int peer_hash_cb(const void *obj, const int flags)
33540 {
33541    const struct sip_peer *peer = obj;
33542 
33543    return ast_str_case_hash(peer->name);
33544 }
33545 
33546 /*!
33547  * \note The only member of the peer used here is the name field
33548  */
33549 static int peer_cmp_cb(void *obj, void *arg, int flags)
33550 {
33551    struct sip_peer *peer = obj, *peer2 = arg;
33552 
33553    return !strcasecmp(peer->name, peer2->name) ? CMP_MATCH | CMP_STOP : 0;
33554 }
33555 
33556 /*!
33557  * Hash function based on the the peer's ip address.  For IPv6, we use the end
33558  * of the address.
33559  * \todo Find a better hashing function
33560  */
33561 static int peer_iphash_cb(const void *obj, const int flags)
33562 {
33563    const struct sip_peer *peer = obj;
33564    int ret = 0;
33565 
33566    if (ast_sockaddr_isnull(&peer->addr)) {
33567       ast_log(LOG_ERROR, "Empty address\n");
33568    }
33569 
33570    ret = ast_sockaddr_hash(&peer->addr);
33571 
33572    if (ret < 0) {
33573       ret = -ret;
33574    }
33575 
33576    return ret;
33577 }
33578 
33579 /*!
33580  * Match Peers by IP and Port number.
33581  *
33582  * This function has two modes.
33583  *  - If the peer arg does not have INSECURE_PORT set, then we will only return
33584  *    a match for a peer that matches both the IP and port.
33585  *  - If the peer arg does have the INSECURE_PORT flag set, then we will only
33586  *    return a match for a peer that matches the IP and has insecure=port
33587  *    in its configuration.
33588  *
33589  * This callback will be used twice when doing peer matching.  There is a first
33590  * pass for full IP+port matching, and a second pass in case there is a match
33591  * that meets the insecure=port criteria.
33592  *
33593  * \note Connections coming in over TCP or TLS should never be matched by port.
33594  *
33595  * \note the peer's addr struct provides to fields combined to make a key: the sin_addr.s_addr and sin_port fields.
33596  */
33597 static int peer_ipcmp_cb_full(void *obj, void *arg, void *data, int flags)
33598 {
33599    struct sip_peer *peer = obj, *peer2 = arg;
33600    char *callback = data;
33601 
33602    if (!ast_strlen_zero(callback) && strcasecmp(peer->callback, callback)) {
33603       /* We require a callback extension match, but don't have one */
33604       return 0;
33605    }
33606 
33607    /* At this point, we match the callback extension if we need to. Carry on. */
33608 
33609    if (ast_sockaddr_cmp_addr(&peer->addr, &peer2->addr)) {
33610       /* IP doesn't match */
33611       return 0;
33612    }
33613 
33614    /* We matched the IP, check to see if we need to match by port as well. */
33615    if ((peer->transports & peer2->transports) & (SIP_TRANSPORT_TLS | SIP_TRANSPORT_TCP)) {
33616       /* peer matching on port is not possible with TCP/TLS */
33617       return CMP_MATCH | CMP_STOP;
33618    } else if (ast_test_flag(&peer2->flags[0], SIP_INSECURE_PORT)) {
33619       /* We are allowing match without port for peers configured that
33620        * way in this pass through the peers. */
33621       return ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT) ?
33622             (CMP_MATCH | CMP_STOP) : 0;
33623    }
33624 
33625    /* Now only return a match if the port matches, as well. */
33626    return ast_sockaddr_port(&peer->addr) == ast_sockaddr_port(&peer2->addr) ?
33627          (CMP_MATCH | CMP_STOP) : 0;
33628 }
33629 
33630 static int peer_ipcmp_cb(void *obj, void *arg, int flags)
33631 {
33632    return peer_ipcmp_cb_full(obj, arg, NULL, flags);
33633 }
33634 
33635 static int threadt_hash_cb(const void *obj, const int flags)
33636 {
33637    const struct sip_threadinfo *th = obj;
33638 
33639    return ast_sockaddr_hash(&th->tcptls_session->remote_address);
33640 }
33641 
33642 static int threadt_cmp_cb(void *obj, void *arg, int flags)
33643 {
33644    struct sip_threadinfo *th = obj, *th2 = arg;
33645 
33646    return (th->tcptls_session == th2->tcptls_session) ? CMP_MATCH | CMP_STOP : 0;
33647 }
33648 
33649 /*!
33650  * \note The only member of the dialog used here callid string
33651  */
33652 static int dialog_hash_cb(const void *obj, const int flags)
33653 {
33654    const struct sip_pvt *pvt = obj;
33655 
33656    return ast_str_case_hash(pvt->callid);
33657 }
33658 
33659 /*!
33660  * \note Same as dialog_cmp_cb, except without the CMP_STOP on match
33661  */
33662 static int dialog_find_multiple(void *obj, void *arg, int flags)
33663 {
33664    struct sip_pvt *pvt = obj, *pvt2 = arg;
33665 
33666    return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH : 0;
33667 }
33668 
33669 /*!
33670  * \note The only member of the dialog used here callid string
33671  */
33672 static int dialog_cmp_cb(void *obj, void *arg, int flags)
33673 {
33674    struct sip_pvt *pvt = obj, *pvt2 = arg;
33675 
33676    return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH | CMP_STOP : 0;
33677 }
33678 
33679 /*! \brief SIP Cli commands definition */
33680 static struct ast_cli_entry cli_sip[] = {
33681    AST_CLI_DEFINE(sip_show_channels, "List active SIP channels or subscriptions"),
33682    AST_CLI_DEFINE(sip_show_channelstats, "List statistics for active SIP channels"),
33683    AST_CLI_DEFINE(sip_show_domains, "List our local SIP domains"),
33684    AST_CLI_DEFINE(sip_show_inuse, "List all inuse/limits"),
33685    AST_CLI_DEFINE(sip_show_objects, "List all SIP object allocations"),
33686    AST_CLI_DEFINE(sip_show_peers, "List defined SIP peers"),
33687    AST_CLI_DEFINE(sip_show_registry, "List SIP registration status"),
33688    AST_CLI_DEFINE(sip_unregister, "Unregister (force expiration) a SIP peer from the registry"),
33689    AST_CLI_DEFINE(sip_show_settings, "Show SIP global settings"),
33690    AST_CLI_DEFINE(sip_show_mwi, "Show MWI subscriptions"),
33691    AST_CLI_DEFINE(sip_cli_notify, "Send a notify packet to a SIP peer"),
33692    AST_CLI_DEFINE(sip_show_channel, "Show detailed SIP channel info"),
33693    AST_CLI_DEFINE(sip_show_history, "Show SIP dialog history"),
33694    AST_CLI_DEFINE(sip_show_peer, "Show details on specific SIP peer"),
33695    AST_CLI_DEFINE(sip_show_users, "List defined SIP users"),
33696    AST_CLI_DEFINE(sip_show_user, "Show details on specific SIP user"),
33697    AST_CLI_DEFINE(sip_qualify_peer, "Send an OPTIONS packet to a peer"),
33698    AST_CLI_DEFINE(sip_show_sched, "Present a report on the status of the scheduler queue"),
33699    AST_CLI_DEFINE(sip_prune_realtime, "Prune cached Realtime users/peers"),
33700    AST_CLI_DEFINE(sip_do_debug, "Enable/Disable SIP debugging"),
33701    AST_CLI_DEFINE(sip_set_history, "Enable/Disable SIP history"),
33702    AST_CLI_DEFINE(sip_reload, "Reload SIP configuration"),
33703    AST_CLI_DEFINE(sip_show_tcp, "List TCP Connections")
33704 };
33705 
33706 /*! \brief SIP test registration */
33707 static void sip_register_tests(void)
33708 {
33709    sip_config_parser_register_tests();
33710    sip_request_parser_register_tests();
33711    sip_dialplan_function_register_tests();
33712 }
33713 
33714 /*! \brief SIP test registration */
33715 static void sip_unregister_tests(void)
33716 {
33717    sip_config_parser_unregister_tests();
33718    sip_request_parser_unregister_tests();
33719    sip_dialplan_function_unregister_tests();
33720 }
33721 
33722 #ifdef TEST_FRAMEWORK
33723 AST_TEST_DEFINE(test_sip_mwi_subscribe_parse)
33724 {
33725    int found = 0;
33726    enum ast_test_result_state res = AST_TEST_PASS;
33727    const char *mwi1 = "1234@mysipprovider.com/1234";
33728    const char *mwi2 = "1234:password@mysipprovider.com/1234";
33729    const char *mwi3 = "1234:password@mysipprovider.com:5061/1234";
33730    const char *mwi4 = "1234:password:authuser@mysipprovider.com/1234";
33731    const char *mwi5 = "1234:password:authuser@mysipprovider.com:5061/1234";
33732    const char *mwi6 = "1234:password";
33733 
33734    switch (cmd) {
33735    case TEST_INIT:
33736       info->name = "sip_mwi_subscribe_parse_test";
33737       info->category = "/channels/chan_sip/";
33738       info->summary = "SIP MWI subscribe line parse unit test";
33739       info->description =
33740          "Tests the parsing of mwi subscription lines (e.g., mwi => from sip.conf)";
33741       return AST_TEST_NOT_RUN;
33742    case TEST_EXECUTE:
33743       break;
33744    }
33745 
33746    if (sip_subscribe_mwi(mwi1, 1)) {
33747       res = AST_TEST_FAIL;
33748    } else {
33749       found = 0;
33750       res = AST_TEST_FAIL;
33751       ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
33752          ASTOBJ_WRLOCK(iterator);
33753          if (
33754             !strcmp(iterator->hostname, "mysipprovider.com") &&
33755             !strcmp(iterator->username, "1234") &&
33756             !strcmp(iterator->secret, "") &&
33757             !strcmp(iterator->authuser, "") &&
33758             !strcmp(iterator->mailbox, "1234") &&
33759             iterator->portno == 0) {
33760             found = 1;
33761             res = AST_TEST_PASS;
33762          }
33763          ASTOBJ_UNLOCK(iterator);
33764       } while(0));
33765       if (!found) {
33766          ast_test_status_update(test, "sip_subscribe_mwi test 1 failed\n");
33767       }
33768    }
33769 
33770    if (sip_subscribe_mwi(mwi2, 1)) {
33771       res = AST_TEST_FAIL;
33772    } else {
33773       found = 0;
33774       res = AST_TEST_FAIL;
33775       ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
33776          ASTOBJ_WRLOCK(iterator);
33777          if (
33778             !strcmp(iterator->hostname, "mysipprovider.com") &&
33779             !strcmp(iterator->username, "1234") &&
33780             !strcmp(iterator->secret, "password") &&
33781             !strcmp(iterator->authuser, "") &&
33782             !strcmp(iterator->mailbox, "1234") &&
33783             iterator->portno == 0) {
33784             found = 1;
33785             res = AST_TEST_PASS;
33786          }
33787          ASTOBJ_UNLOCK(iterator);
33788       } while(0));
33789       if (!found) {
33790          ast_test_status_update(test, "sip_subscribe_mwi test 2 failed\n");
33791       }
33792    }
33793 
33794    if (sip_subscribe_mwi(mwi3, 1)) {
33795       res = AST_TEST_FAIL;
33796    } else {
33797       found = 0;
33798       res = AST_TEST_FAIL;
33799       ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
33800          ASTOBJ_WRLOCK(iterator);
33801          if (
33802             !strcmp(iterator->hostname, "mysipprovider.com") &&
33803             !strcmp(iterator->username, "1234") &&
33804             !strcmp(iterator->secret, "password") &&
33805             !strcmp(iterator->authuser, "") &&
33806             !strcmp(iterator->mailbox, "1234") &&
33807             iterator->portno == 5061) {
33808             found = 1;
33809             res = AST_TEST_PASS;
33810          }
33811          ASTOBJ_UNLOCK(iterator);
33812       } while(0));
33813       if (!found) {
33814          ast_test_status_update(test, "sip_subscribe_mwi test 3 failed\n");
33815       }
33816    }
33817 
33818    if (sip_subscribe_mwi(mwi4, 1)) {
33819       res = AST_TEST_FAIL;
33820    } else {
33821       found = 0;
33822       res = AST_TEST_FAIL;
33823       ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
33824          ASTOBJ_WRLOCK(iterator);
33825          if (
33826             !strcmp(iterator->hostname, "mysipprovider.com") &&
33827             !strcmp(iterator->username, "1234") &&
33828             !strcmp(iterator->secret, "password") &&
33829             !strcmp(iterator->authuser, "authuser") &&
33830             !strcmp(iterator->mailbox, "1234") &&
33831             iterator->portno == 0) {
33832             found = 1;
33833             res = AST_TEST_PASS;
33834          }
33835          ASTOBJ_UNLOCK(iterator);
33836       } while(0));
33837       if (!found) {
33838          ast_test_status_update(test, "sip_subscribe_mwi test 4 failed\n");
33839       }
33840    }
33841 
33842    if (sip_subscribe_mwi(mwi5, 1)) {
33843       res = AST_TEST_FAIL;
33844    } else {
33845       found = 0;
33846       res = AST_TEST_FAIL;
33847       ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
33848          ASTOBJ_WRLOCK(iterator);
33849          if (
33850             !strcmp(iterator->hostname, "mysipprovider.com") &&
33851             !strcmp(iterator->username, "1234") &&
33852             !strcmp(iterator->secret, "password") &&
33853             !strcmp(iterator->authuser, "authuser") &&
33854             !strcmp(iterator->mailbox, "1234") &&
33855             iterator->portno == 5061) {
33856             found = 1;
33857             res = AST_TEST_PASS;
33858          }
33859          ASTOBJ_UNLOCK(iterator);
33860       } while(0));
33861       if (!found) {
33862          ast_test_status_update(test, "sip_subscribe_mwi test 5 failed\n");
33863       }
33864    }
33865    
33866    if (sip_subscribe_mwi(mwi6, 1)) {
33867       res = AST_TEST_PASS;
33868    } else {
33869       res = AST_TEST_FAIL;
33870    }
33871    return res;
33872 }
33873 
33874 AST_TEST_DEFINE(test_sip_peers_get)
33875 {
33876    struct sip_peer *peer;
33877    struct ast_data *node;
33878    struct ast_data_query query = {
33879       .path = "/asterisk/channel/sip/peers",
33880       .search = "peers/peer/name=test_peer_data_provider"
33881    };
33882 
33883    switch (cmd) {
33884       case TEST_INIT:
33885          info->name = "sip_peers_get_data_test";
33886          info->category = "/main/data/sip/peers/";
33887          info->summary = "SIP peers data providers unit test";
33888          info->description =
33889             "Tests whether the SIP peers data provider implementation works as expected.";
33890          return AST_TEST_NOT_RUN;
33891       case TEST_EXECUTE:
33892          break;
33893    }
33894 
33895    /* Create the peer that we will retrieve. */
33896    peer = build_peer("test_peer_data_provider", NULL, NULL, 0, 0);
33897    if (!peer) {
33898       return AST_TEST_FAIL;
33899    }
33900    peer->type = SIP_TYPE_USER;
33901    peer->call_limit = 10;
33902    ao2_link(peers, peer);
33903 
33904    /* retrieve the chan_sip/peers tree and check the created peer. */
33905    node = ast_data_get(&query);
33906    if (!node) {
33907       ao2_unlink(peers, peer);
33908       ao2_ref(peer, -1);
33909       return AST_TEST_FAIL;
33910    }
33911 
33912    /* compare item. */
33913    if (strcmp(ast_data_retrieve_string(node, "peer/name"), "test_peer_data_provider")) {
33914       ao2_unlink(peers, peer);
33915       ao2_ref(peer, -1);
33916       ast_data_free(node);
33917       return AST_TEST_FAIL;
33918    }
33919 
33920    if (strcmp(ast_data_retrieve_string(node, "peer/type"), "user")) {
33921       ao2_unlink(peers, peer);
33922       ao2_ref(peer, -1);
33923       ast_data_free(node);
33924       return AST_TEST_FAIL;
33925    }
33926 
33927    if (ast_data_retrieve_int(node, "peer/call_limit") != 10) {
33928       ao2_unlink(peers, peer);
33929       ao2_ref(peer, -1);
33930       ast_data_free(node);
33931       return AST_TEST_FAIL;
33932    }
33933 
33934    /* release resources */
33935    ast_data_free(node);
33936 
33937    ao2_unlink(peers, peer);
33938    ao2_ref(peer, -1);
33939 
33940    return AST_TEST_PASS;
33941 }
33942 
33943 /*!
33944  * \brief Imitation TCP reception loop
33945  *
33946  * This imitates the logic used by SIP's TCP code. Its purpose
33947  * is to either
33948  * 1) Combine fragments into a single message
33949  * 2) Break up combined messages into single messages
33950  *
33951  * \param fragments The message fragments. This simulates the data received on a TCP socket.
33952  * \param num_fragments This indicates the number of fragments to receive
33953  * \param overflow This is a place to stash extra data if more than one message is received
33954  *        in a single fragment
33955  * \param[out] messages The parsed messages are placed in this array
33956  * \param[out] num_messages The number of messages that were parsed
33957  * \param test Used for printing messages
33958  * \retval 0 Success
33959  * \retval -1 Failure
33960  */
33961 static int mock_tcp_loop(char *fragments[], size_t num_fragments,
33962       struct ast_str **overflow, char **messages, int *num_messages, struct ast_test* test)
33963 {
33964    struct ast_str *req_data;
33965    int i = 0;
33966    int res = 0;
33967 
33968    req_data = ast_str_create(128);
33969    ast_str_reset(*overflow);
33970 
33971    while (i < num_fragments || ast_str_strlen(*overflow) > 0) {
33972       enum message_integrity message_integrity = MESSAGE_FRAGMENT;
33973       ast_str_reset(req_data);
33974       while (message_integrity == MESSAGE_FRAGMENT) {
33975          if (ast_str_strlen(*overflow) > 0) {
33976             ast_str_append(&req_data, 0, "%s", ast_str_buffer(*overflow));
33977             ast_str_reset(*overflow);
33978          } else {
33979             ast_str_append(&req_data, 0, "%s", fragments[i++]);
33980          }
33981          message_integrity = check_message_integrity(&req_data, overflow);
33982       }
33983       if (strcmp(ast_str_buffer(req_data), messages[*num_messages])) {
33984          ast_test_status_update(test, "Mismatch in SIP messages.\n");
33985          ast_test_status_update(test, "Expected message:\n%s", messages[*num_messages]);
33986          ast_test_status_update(test, "Parsed message:\n%s", ast_str_buffer(req_data));
33987          res = -1;
33988          goto end;
33989       } else {
33990          ast_test_status_update(test, "Successfully read message:\n%s", ast_str_buffer(req_data));
33991       }
33992       (*num_messages)++;
33993    }
33994 
33995 end:
33996    ast_free(req_data);
33997    return res;
33998 };
33999 
34000 AST_TEST_DEFINE(test_tcp_message_fragmentation)
34001 {
34002    /* Normal single message in one fragment */
34003    char *normal[] = {
34004       "INVITE sip:bob@example.org SIP/2.0\r\n"
34005       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34006       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34007       "To: <sip:bob@example.org:5060>\r\n"
34008       "Call-ID: 12345\r\n"
34009       "CSeq: 1 INVITE\r\n"
34010       "Contact: sip:127.0.0.1:5061\r\n"
34011       "Max-Forwards: 70\r\n"
34012       "Content-Type: application/sdp\r\n"
34013       "Content-Length: 130\r\n"
34014       "\r\n"
34015       "v=0\r\n"
34016       "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
34017       "s=-\r\n"
34018       "c=IN IP4 127.0.0.1\r\n"
34019       "t=0 0\r\n"
34020       "m=audio 10000 RTP/AVP 0\r\n"
34021       "a=rtpmap:0 PCMU/8000\r\n"
34022    };
34023 
34024    /* Single message in two fragments.
34025     * Fragments combine to make "normal"
34026     */
34027    char *fragmented[] = {
34028       "INVITE sip:bob@example.org SIP/2.0\r\n"
34029       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34030       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34031       "To: <sip:bob@example.org:5060>\r\n"
34032       "Call-ID: 12345\r\n"
34033       "CSeq: 1 INVITE\r\n"
34034       "Contact: sip:127.0.0.1:5061\r\n"
34035       "Max-Forwards: ",
34036 
34037       "70\r\n"
34038       "Content-Type: application/sdp\r\n"
34039       "Content-Length: 130\r\n"
34040       "\r\n"
34041       "v=0\r\n"
34042       "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
34043       "s=-\r\n"
34044       "c=IN IP4 127.0.0.1\r\n"
34045       "t=0 0\r\n"
34046       "m=audio 10000 RTP/AVP 0\r\n"
34047       "a=rtpmap:0 PCMU/8000\r\n"
34048    };
34049    /* Single message in two fragments, divided precisely at the body
34050     * Fragments combine to make "normal"
34051     */
34052    char *fragmented_body[] = {
34053       "INVITE sip:bob@example.org SIP/2.0\r\n"
34054       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34055       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34056       "To: <sip:bob@example.org:5060>\r\n"
34057       "Call-ID: 12345\r\n"
34058       "CSeq: 1 INVITE\r\n"
34059       "Contact: sip:127.0.0.1:5061\r\n"
34060       "Max-Forwards: 70\r\n"
34061       "Content-Type: application/sdp\r\n"
34062       "Content-Length: 130\r\n"
34063       "\r\n",
34064 
34065       "v=0\r\n"
34066       "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
34067       "s=-\r\n"
34068       "c=IN IP4 127.0.0.1\r\n"
34069       "t=0 0\r\n"
34070       "m=audio 10000 RTP/AVP 0\r\n"
34071       "a=rtpmap:0 PCMU/8000\r\n"
34072    };
34073 
34074    /* Single message in three fragments
34075     * Fragments combine to make "normal"
34076     */
34077    char *multi_fragment[] = {
34078       "INVITE sip:bob@example.org SIP/2.0\r\n"
34079       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34080       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34081       "To: <sip:bob@example.org:5060>\r\n"
34082       "Call-ID: 12345\r\n"
34083       "CSeq: 1 INVITE\r\n",
34084 
34085       "Contact: sip:127.0.0.1:5061\r\n"
34086       "Max-Forwards: 70\r\n"
34087       "Content-Type: application/sdp\r\n"
34088       "Content-Length: 130\r\n"
34089       "\r\n"
34090       "v=0\r\n"
34091       "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
34092       "s=-\r\n"
34093       "c=IN IP4",
34094 
34095       " 127.0.0.1\r\n"
34096       "t=0 0\r\n"
34097       "m=audio 10000 RTP/AVP 0\r\n"
34098       "a=rtpmap:0 PCMU/8000\r\n"
34099    };
34100 
34101    /* Two messages in a single fragment
34102     * Fragments split into "multi_message_divided"
34103     */
34104    char *multi_message[] = {
34105       "SIP/2.0 100 Trying\r\n"
34106       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34107       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34108       "To: <sip:bob@example.org:5060>\r\n"
34109       "Call-ID: 12345\r\n"
34110       "CSeq: 1 INVITE\r\n"
34111       "Contact: <sip:bob@example.org:5060>\r\n"
34112       "Content-Length: 0\r\n"
34113       "\r\n"
34114       "SIP/2.0 180 Ringing\r\n"
34115       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34116       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34117       "To: <sip:bob@example.org:5060>\r\n"
34118       "Call-ID: 12345\r\n"
34119       "CSeq: 1 INVITE\r\n"
34120       "Contact: <sip:bob@example.org:5060>\r\n"
34121       "Content-Length: 0\r\n"
34122       "\r\n"
34123    };
34124    char *multi_message_divided[] = {
34125       "SIP/2.0 100 Trying\r\n"
34126       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34127       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34128       "To: <sip:bob@example.org:5060>\r\n"
34129       "Call-ID: 12345\r\n"
34130       "CSeq: 1 INVITE\r\n"
34131       "Contact: <sip:bob@example.org:5060>\r\n"
34132       "Content-Length: 0\r\n"
34133       "\r\n",
34134 
34135       "SIP/2.0 180 Ringing\r\n"
34136       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34137       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34138       "To: <sip:bob@example.org:5060>\r\n"
34139       "Call-ID: 12345\r\n"
34140       "CSeq: 1 INVITE\r\n"
34141       "Contact: <sip:bob@example.org:5060>\r\n"
34142       "Content-Length: 0\r\n"
34143       "\r\n"
34144    };
34145    /* Two messages with bodies combined into one fragment
34146     * Fragments split into "multi_message_body_divided"
34147     */
34148    char *multi_message_body[] = {
34149       "INVITE sip:bob@example.org SIP/2.0\r\n"
34150       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34151       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34152       "To: <sip:bob@example.org:5060>\r\n"
34153       "Call-ID: 12345\r\n"
34154       "CSeq: 1 INVITE\r\n"
34155       "Contact: sip:127.0.0.1:5061\r\n"
34156       "Max-Forwards: 70\r\n"
34157       "Content-Type: application/sdp\r\n"
34158       "Content-Length: 130\r\n"
34159       "\r\n"
34160       "v=0\r\n"
34161       "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
34162       "s=-\r\n"
34163       "c=IN IP4 127.0.0.1\r\n"
34164       "t=0 0\r\n"
34165       "m=audio 10000 RTP/AVP 0\r\n"
34166       "a=rtpmap:0 PCMU/8000\r\n"
34167       "INVITE sip:bob@example.org SIP/2.0\r\n"
34168       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34169       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34170       "To: <sip:bob@example.org:5060>\r\n"
34171       "Call-ID: 12345\r\n"
34172       "CSeq: 2 INVITE\r\n"
34173       "Contact: sip:127.0.0.1:5061\r\n"
34174       "Max-Forwards: 70\r\n"
34175       "Content-Type: application/sdp\r\n"
34176       "Content-Length: 130\r\n"
34177       "\r\n"
34178       "v=0\r\n"
34179       "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
34180       "s=-\r\n"
34181       "c=IN IP4 127.0.0.1\r\n"
34182       "t=0 0\r\n"
34183       "m=audio 10000 RTP/AVP 0\r\n"
34184       "a=rtpmap:0 PCMU/8000\r\n"
34185    };
34186    char *multi_message_body_divided[] = {
34187       "INVITE sip:bob@example.org SIP/2.0\r\n"
34188       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34189       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34190       "To: <sip:bob@example.org:5060>\r\n"
34191       "Call-ID: 12345\r\n"
34192       "CSeq: 1 INVITE\r\n"
34193       "Contact: sip:127.0.0.1:5061\r\n"
34194       "Max-Forwards: 70\r\n"
34195       "Content-Type: application/sdp\r\n"
34196       "Content-Length: 130\r\n"
34197       "\r\n"
34198       "v=0\r\n"
34199       "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
34200       "s=-\r\n"
34201       "c=IN IP4 127.0.0.1\r\n"
34202       "t=0 0\r\n"
34203       "m=audio 10000 RTP/AVP 0\r\n"
34204       "a=rtpmap:0 PCMU/8000\r\n",
34205 
34206       "INVITE sip:bob@example.org SIP/2.0\r\n"
34207       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34208       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34209       "To: <sip:bob@example.org:5060>\r\n"
34210       "Call-ID: 12345\r\n"
34211       "CSeq: 2 INVITE\r\n"
34212       "Contact: sip:127.0.0.1:5061\r\n"
34213       "Max-Forwards: 70\r\n"
34214       "Content-Type: application/sdp\r\n"
34215       "Content-Length: 130\r\n"
34216       "\r\n"
34217       "v=0\r\n"
34218       "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
34219       "s=-\r\n"
34220       "c=IN IP4 127.0.0.1\r\n"
34221       "t=0 0\r\n"
34222       "m=audio 10000 RTP/AVP 0\r\n"
34223       "a=rtpmap:0 PCMU/8000\r\n"
34224    };
34225 
34226    /* Two messages that appear in two fragments. Fragment
34227     * boundaries do not align with message boundaries.
34228     * Fragments combine to make "multi_message_divided"
34229     */
34230    char *multi_message_in_fragments[] = {
34231       "SIP/2.0 100 Trying\r\n"
34232       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34233       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34234       "To: <sip:bob@example.org:5060>\r\n"
34235       "Call-ID: 12345\r\n"
34236       "CSeq: 1 INVI",
34237 
34238       "TE\r\n"
34239       "Contact: <sip:bob@example.org:5060>\r\n"
34240       "Content-Length: 0\r\n"
34241       "\r\n"
34242       "SIP/2.0 180 Ringing\r\n"
34243       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34244       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34245       "To: <sip:bob@example.org:5060>\r\n"
34246       "Call-ID: 12345\r\n"
34247       "CSeq: 1 INVITE\r\n"
34248       "Contact: <sip:bob@example.org:5060>\r\n"
34249       "Content-Length: 0\r\n"
34250       "\r\n"
34251    };
34252 
34253    /* Message with compact content-length header
34254     * Same as "normal" but with compact content-length header
34255     */
34256    char *compact[] = {
34257       "INVITE sip:bob@example.org SIP/2.0\r\n"
34258       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34259       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34260       "To: <sip:bob@example.org:5060>\r\n"
34261       "Call-ID: 12345\r\n"
34262       "CSeq: 1 INVITE\r\n"
34263       "Contact: sip:127.0.0.1:5061\r\n"
34264       "Max-Forwards: 70\r\n"
34265       "Content-Type: application/sdp\r\n"
34266       "l:130\r\n" /* intentionally no space */
34267       "\r\n"
34268       "v=0\r\n"
34269       "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
34270       "s=-\r\n"
34271       "c=IN IP4 127.0.0.1\r\n"
34272       "t=0 0\r\n"
34273       "m=audio 10000 RTP/AVP 0\r\n"
34274       "a=rtpmap:0 PCMU/8000\r\n"
34275    };
34276 
34277    /* Message with faux content-length headers
34278     * Same as "normal" but with extra fake content-length headers
34279     */
34280    char *faux[] = {
34281       "INVITE sip:bob@example.org SIP/2.0\r\n"
34282       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34283       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34284       "To: <sip:bob@example.org:5060>\r\n"
34285       "Call-ID: 12345\r\n"
34286       "CSeq: 1 INVITE\r\n"
34287       "Contact: sip:127.0.0.1:5061\r\n"
34288       "Max-Forwards: 70\r\n"
34289       "Content-Type: application/sdp\r\n"
34290       "DisContent-Length: 0\r\n"
34291       "MalContent-Length: 60\r\n"
34292       "Content-Length:130\r\n" /* intentionally no space */
34293       "\r\n"
34294       "v=0\r\n"
34295       "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
34296       "s=-\r\n"
34297       "c=IN IP4 127.0.0.1\r\n"
34298       "t=0 0\r\n"
34299       "m=audio 10000 RTP/AVP 0\r\n"
34300       "a=rtpmap:0 PCMU/8000\r\n"
34301    };
34302 
34303    /* Message with folded Content-Length header
34304     * Message is "normal" with Content-Length spread across three lines
34305     *
34306     * This is the test that requires pedantic=yes in order to pass
34307     */
34308    char *folded[] = {
34309       "INVITE sip:bob@example.org SIP/2.0\r\n"
34310       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34311       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34312       "To: <sip:bob@example.org:5060>\r\n"
34313       "Call-ID: 12345\r\n"
34314       "CSeq: 1 INVITE\r\n"
34315       "Contact: sip:127.0.0.1:5061\r\n"
34316       "Max-Forwards: 70\r\n"
34317       "Content-Type: application/sdp\r\n"
34318       "Content-Length: \t\r\n"
34319       "\t \r\n"
34320       " 130\t \r\n"
34321       "\r\n"
34322       "v=0\r\n"
34323       "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
34324       "s=-\r\n"
34325       "c=IN IP4 127.0.0.1\r\n"
34326       "t=0 0\r\n"
34327       "m=audio 10000 RTP/AVP 0\r\n"
34328       "a=rtpmap:0 PCMU/8000\r\n"
34329    };
34330 
34331    /* Message with compact Content-length header in message and
34332     * full Content-Length header in the body. Ensure that the header
34333     * in the message is read and that the one in the body is ignored
34334     */
34335    char *cl_in_body[] = {
34336       "INVITE sip:bob@example.org SIP/2.0\r\n"
34337       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34338       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34339       "To: <sip:bob@example.org:5060>\r\n"
34340       "Call-ID: 12345\r\n"
34341       "CSeq: 1 INVITE\r\n"
34342       "Contact: sip:127.0.0.1:5061\r\n"
34343       "Max-Forwards: 70\r\n"
34344       "Content-Type: application/sdp\r\n"
34345       "l: 149\r\n"
34346       "\r\n"
34347       "v=0\r\n"
34348       "Content-Length: 0\r\n"
34349       "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
34350       "s=-\r\n"
34351       "c=IN IP4 127.0.0.1\r\n"
34352       "t=0 0\r\n"
34353       "m=audio 10000 RTP/AVP 0\r\n"
34354       "a=rtpmap:0 PCMU/8000\r\n"
34355    };
34356 
34357    struct ast_str *overflow;
34358    struct {
34359       char **fragments;
34360       char **expected;
34361       int num_expected;
34362       const char *description;
34363    } tests[] = {
34364       { normal, normal, 1, "normal" },
34365       { fragmented, normal, 1, "fragmented" },
34366       { fragmented_body, normal, 1, "fragmented_body" },
34367       { multi_fragment, normal, 1, "multi_fragment" },
34368       { multi_message, multi_message_divided, 2, "multi_message" },
34369       { multi_message_body, multi_message_body_divided, 2, "multi_message_body" },
34370       { multi_message_in_fragments, multi_message_divided, 2, "multi_message_in_fragments" },
34371       { compact, compact, 1, "compact" },
34372       { faux, faux, 1, "faux" },
34373       { folded, folded, 1, "folded" },
34374       { cl_in_body, cl_in_body, 1, "cl_in_body" },
34375    };
34376    int i;
34377    enum ast_test_result_state res = AST_TEST_PASS;
34378 
34379    switch (cmd) {
34380       case TEST_INIT:
34381          info->name = "sip_tcp_message_fragmentation";
34382          info->category = "/main/sip/transport/";
34383          info->summary = "SIP TCP message fragmentation test";
34384          info->description =
34385             "Tests reception of different TCP messages that have been fragmented or"
34386             "run together. This test mimicks the code that TCP reception uses.";
34387          return AST_TEST_NOT_RUN;
34388       case TEST_EXECUTE:
34389          break;
34390    }
34391    if (!sip_cfg.pedanticsipchecking) {
34392       ast_log(LOG_WARNING, "Not running test. Pedantic SIP checking is not enabled, so it is guaranteed to fail\n");
34393       return AST_TEST_NOT_RUN;
34394    }
34395 
34396    overflow = ast_str_create(128);
34397    if (!overflow) {
34398       return AST_TEST_FAIL;
34399    }
34400    for (i = 0; i < ARRAY_LEN(tests); ++i) {
34401       int num_messages = 0;
34402       if (mock_tcp_loop(tests[i].fragments, ARRAY_LEN(tests[i].fragments),
34403                &overflow, tests[i].expected, &num_messages, test)) {
34404          ast_test_status_update(test, "Failed to parse message '%s'\n", tests[i].description);
34405          res = AST_TEST_FAIL;
34406          break;
34407       }
34408       if (num_messages != tests[i].num_expected) {
34409          ast_test_status_update(test, "Did not receive the expected number of messages. "
34410                "Expected %d but received %d\n", tests[i].num_expected, num_messages);
34411          res = AST_TEST_FAIL;
34412          break;
34413       }
34414    }
34415    ast_free(overflow);
34416    return res;
34417 }
34418 
34419 AST_TEST_DEFINE(get_in_brackets_const_test)
34420 {
34421    const char *input;
34422    const char *start = NULL;
34423    int len = 0;
34424    int res;
34425 
34426 #define CHECK_RESULTS(in, expected_res, expected_start, expected_len)   do {  \
34427       input = (in);                 \
34428       res = get_in_brackets_const(input, &start, &len);  \
34429       if ((expected_res) != res) {           \
34430          ast_test_status_update(test, "Unexpected result: %d != %d\n", expected_res, res); \
34431          return AST_TEST_FAIL;            \
34432       }                    \
34433       if ((expected_start) != start) {       \
34434          const char *e = expected_start ? expected_start : "(null)"; \
34435          const char *a = start ? start : "(null)"; \
34436          ast_test_status_update(test, "Unexpected start: %s != %s\n", e, a); \
34437          return AST_TEST_FAIL;            \
34438       }                    \
34439       if ((expected_len) != len) {           \
34440          ast_test_status_update(test, "Unexpected len: %d != %d\n", expected_len, len); \
34441          return AST_TEST_FAIL;            \
34442       }                    \
34443    } while(0)
34444 
34445    switch (cmd) {
34446    case TEST_INIT:
34447       info->name = __func__;
34448       info->category = "/channels/chan_sip/";
34449       info->summary = "get_in_brackets_const test";
34450       info->description =
34451          "Tests the get_in_brackets_const function";
34452       return AST_TEST_NOT_RUN;
34453    case TEST_EXECUTE:
34454       break;
34455    }
34456 
34457    CHECK_RESULTS("", 1, NULL, -1);
34458    CHECK_RESULTS("normal <test>", 0, input + 8, 4);
34459    CHECK_RESULTS("\"normal\" <test>", 0, input + 10, 4);
34460    CHECK_RESULTS("not normal <test", -1, NULL, -1);
34461    CHECK_RESULTS("\"yes < really\" <test>", 0, input + 16, 4);
34462    CHECK_RESULTS("\"even > this\" <test>", 0, input + 15, 4);
34463    CHECK_RESULTS("<sip:id1@10.10.10.10;lr>", 0, input + 1, 22);
34464    CHECK_RESULTS("<sip:id1@10.10.10.10;lr>, <sip:id1@10.10.10.20;lr>", 0, input + 1, 22);
34465    CHECK_RESULTS("<sip:id1,id2@10.10.10.10;lr>", 0, input + 1, 26);
34466    CHECK_RESULTS("<sip:id1@10., <sip:id2@10.10.10.10;lr>", 0, input + 1, 36);
34467    CHECK_RESULTS("\"quoted text\" <sip:dlg1@10.10.10.10;lr>", 0, input + 15, 23);
34468 
34469    return AST_TEST_PASS;
34470 }
34471 
34472 #endif
34473 
34474 #define DATA_EXPORT_SIP_PEER(MEMBER)            \
34475    MEMBER(sip_peer, name, AST_DATA_STRING)         \
34476    MEMBER(sip_peer, secret, AST_DATA_PASSWORD)     \
34477    MEMBER(sip_peer, md5secret, AST_DATA_PASSWORD)     \
34478    MEMBER(sip_peer, remotesecret, AST_DATA_PASSWORD)  \
34479    MEMBER(sip_peer, context, AST_DATA_STRING)      \
34480    MEMBER(sip_peer, subscribecontext, AST_DATA_STRING)   \
34481    MEMBER(sip_peer, username, AST_DATA_STRING)     \
34482    MEMBER(sip_peer, accountcode, AST_DATA_STRING)     \
34483    MEMBER(sip_peer, tohost, AST_DATA_STRING)    \
34484    MEMBER(sip_peer, regexten, AST_DATA_STRING)     \
34485    MEMBER(sip_peer, fromuser, AST_DATA_STRING)     \
34486    MEMBER(sip_peer, fromdomain, AST_DATA_STRING)      \
34487    MEMBER(sip_peer, fullcontact, AST_DATA_STRING)     \
34488    MEMBER(sip_peer, cid_num, AST_DATA_STRING)      \
34489    MEMBER(sip_peer, cid_name, AST_DATA_STRING)     \
34490    MEMBER(sip_peer, vmexten, AST_DATA_STRING)      \
34491    MEMBER(sip_peer, language, AST_DATA_STRING)     \
34492    MEMBER(sip_peer, mohinterpret, AST_DATA_STRING)    \
34493    MEMBER(sip_peer, mohsuggest, AST_DATA_STRING)      \
34494    MEMBER(sip_peer, parkinglot, AST_DATA_STRING)      \
34495    MEMBER(sip_peer, useragent, AST_DATA_STRING)    \
34496    MEMBER(sip_peer, mwi_from, AST_DATA_STRING)     \
34497    MEMBER(sip_peer, engine, AST_DATA_STRING)    \
34498    MEMBER(sip_peer, unsolicited_mailbox, AST_DATA_STRING)   \
34499    MEMBER(sip_peer, is_realtime, AST_DATA_BOOLEAN)    \
34500    MEMBER(sip_peer, host_dynamic, AST_DATA_BOOLEAN)   \
34501    MEMBER(sip_peer, autoframing, AST_DATA_BOOLEAN)    \
34502    MEMBER(sip_peer, inuse, AST_DATA_INTEGER)    \
34503    MEMBER(sip_peer, ringing, AST_DATA_INTEGER)     \
34504    MEMBER(sip_peer, onhold, AST_DATA_INTEGER)      \
34505    MEMBER(sip_peer, call_limit, AST_DATA_INTEGER)     \
34506    MEMBER(sip_peer, t38_maxdatagram, AST_DATA_INTEGER)   \
34507    MEMBER(sip_peer, maxcallbitrate, AST_DATA_INTEGER) \
34508    MEMBER(sip_peer, rtptimeout, AST_DATA_SECONDS)     \
34509    MEMBER(sip_peer, rtpholdtimeout, AST_DATA_SECONDS) \
34510    MEMBER(sip_peer, rtpkeepalive, AST_DATA_SECONDS)   \
34511    MEMBER(sip_peer, lastms, AST_DATA_MILLISECONDS)    \
34512    MEMBER(sip_peer, maxms, AST_DATA_MILLISECONDS)     \
34513    MEMBER(sip_peer, qualifyfreq, AST_DATA_MILLISECONDS)  \
34514    MEMBER(sip_peer, timer_t1, AST_DATA_MILLISECONDS)  \
34515    MEMBER(sip_peer, timer_b, AST_DATA_MILLISECONDS)   \
34516    MEMBER(sip_peer, description, AST_DATA_STRING)
34517 
34518 AST_DATA_STRUCTURE(sip_peer, DATA_EXPORT_SIP_PEER);
34519 
34520 static int peers_data_provider_get(const struct ast_data_search *search,
34521    struct ast_data *data_root)
34522 {
34523    struct sip_peer *peer;
34524    struct ao2_iterator i;
34525    struct ast_data *data_peer, *data_peer_mailboxes = NULL, *data_peer_mailbox, *enum_node;
34526    struct ast_data *data_sip_options;
34527    int total_mailboxes, x;
34528    struct sip_mailbox *mailbox;
34529 
34530    i = ao2_iterator_init(peers, 0);
34531    while ((peer = ao2_iterator_next(&i))) {
34532       ao2_lock(peer);
34533 
34534       data_peer = ast_data_add_node(data_root, "peer");
34535       if (!data_peer) {
34536          ao2_unlock(peer);
34537          ao2_ref(peer, -1);
34538          continue;
34539       }
34540 
34541       ast_data_add_structure(sip_peer, data_peer, peer);
34542 
34543       /* transfer mode */
34544       enum_node = ast_data_add_node(data_peer, "allowtransfer");
34545       if (!enum_node) {
34546          ao2_unlock(peer);
34547          ao2_ref(peer, -1);
34548          continue;
34549       }
34550       ast_data_add_str(enum_node, "text", transfermode2str(peer->allowtransfer));
34551       ast_data_add_int(enum_node, "value", peer->allowtransfer);
34552 
34553       /* transports */
34554       ast_data_add_str(data_peer, "transports", get_transport_list(peer->transports));
34555 
34556       /* peer type */
34557       if ((peer->type & SIP_TYPE_USER) && (peer->type & SIP_TYPE_PEER)) {
34558          ast_data_add_str(data_peer, "type", "friend");
34559       } else if (peer->type & SIP_TYPE_PEER) {
34560          ast_data_add_str(data_peer, "type", "peer");
34561       } else if (peer->type & SIP_TYPE_USER) {
34562          ast_data_add_str(data_peer, "type", "user");
34563       }
34564 
34565       /* mailboxes */
34566       total_mailboxes = 0;
34567       AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
34568          if (!total_mailboxes) {
34569             data_peer_mailboxes = ast_data_add_node(data_peer, "mailboxes");
34570             if (!data_peer_mailboxes) {
34571                break;
34572             }
34573             total_mailboxes++;
34574          }
34575 
34576          data_peer_mailbox = ast_data_add_node(data_peer_mailboxes, "mailbox");
34577          if (!data_peer_mailbox) {
34578             continue;
34579          }
34580          ast_data_add_str(data_peer_mailbox, "mailbox", mailbox->mailbox);
34581          ast_data_add_str(data_peer_mailbox, "context", mailbox->context);
34582       }
34583 
34584       /* amaflags */
34585       enum_node = ast_data_add_node(data_peer, "amaflags");
34586       if (!enum_node) {
34587          ao2_unlock(peer);
34588          ao2_ref(peer, -1);
34589          continue;
34590       }
34591       ast_data_add_int(enum_node, "value", peer->amaflags);
34592       ast_data_add_str(enum_node, "text", ast_cdr_flags2str(peer->amaflags));
34593 
34594       /* sip options */
34595       data_sip_options = ast_data_add_node(data_peer, "sipoptions");
34596       if (!data_sip_options) {
34597          ao2_unlock(peer);
34598          ao2_ref(peer, -1);
34599          continue;
34600       }
34601       for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
34602          ast_data_add_bool(data_sip_options, sip_options[x].text, peer->sipoptions & sip_options[x].id);
34603       }
34604 
34605       /* callingpres */
34606       enum_node = ast_data_add_node(data_peer, "callingpres");
34607       if (!enum_node) {
34608          ao2_unlock(peer);
34609          ao2_ref(peer, -1);
34610          continue;
34611       }
34612       ast_data_add_int(enum_node, "value", peer->callingpres);
34613       ast_data_add_str(enum_node, "text", ast_describe_caller_presentation(peer->callingpres));
34614 
34615       /* codecs */
34616       ast_data_add_codecs(data_peer, "codecs", peer->caps);
34617 
34618       if (!ast_data_search_match(search, data_peer)) {
34619          ast_data_remove_node(data_root, data_peer);
34620       }
34621 
34622       ao2_unlock(peer);
34623       ao2_ref(peer, -1);
34624    }
34625    ao2_iterator_destroy(&i);
34626 
34627    return 0;
34628 }
34629 
34630 static const struct ast_data_handler peers_data_provider = {
34631    .version = AST_DATA_HANDLER_VERSION,
34632    .get = peers_data_provider_get
34633 };
34634 
34635 static const struct ast_data_entry sip_data_providers[] = {
34636    AST_DATA_ENTRY("asterisk/channel/sip/peers", &peers_data_provider),
34637 };
34638 
34639 static const struct ast_sip_api_tech chan_sip_api_provider = {
34640    .version = AST_SIP_API_VERSION,
34641    .name = "chan_sip",
34642    .sipinfo_send = sipinfo_send,
34643 };
34644 
34645 /*! \brief PBX load module - initialization */
34646 static int load_module(void)
34647 {
34648    ast_verbose("SIP channel loading...\n");
34649 
34650    if (!(sip_tech.capabilities = ast_format_cap_alloc())) {
34651       return AST_MODULE_LOAD_FAILURE;
34652    }
34653 
34654    if (ast_sip_api_provider_register(&chan_sip_api_provider)) {
34655       return AST_MODULE_LOAD_FAILURE;
34656    }
34657 
34658    /* the fact that ao2_containers can't resize automatically is a major worry! */
34659    /* if the number of objects gets above MAX_XXX_BUCKETS, things will slow down */
34660    peers = ao2_t_container_alloc(HASH_PEER_SIZE, peer_hash_cb, peer_cmp_cb, "allocate peers");
34661    peers_by_ip = ao2_t_container_alloc(HASH_PEER_SIZE, peer_iphash_cb, peer_ipcmp_cb, "allocate peers_by_ip");
34662    dialogs = ao2_t_container_alloc(HASH_DIALOG_SIZE, dialog_hash_cb, dialog_cmp_cb, "allocate dialogs");
34663    dialogs_needdestroy = ao2_t_container_alloc(1, NULL, NULL, "allocate dialogs_needdestroy");
34664    dialogs_rtpcheck = ao2_t_container_alloc(HASH_DIALOG_SIZE, dialog_hash_cb, dialog_cmp_cb, "allocate dialogs for rtpchecks");
34665    threadt = ao2_t_container_alloc(HASH_DIALOG_SIZE, threadt_hash_cb, threadt_cmp_cb, "allocate threadt table");
34666    if (!peers || !peers_by_ip || !dialogs || !dialogs_needdestroy || !dialogs_rtpcheck
34667       || !threadt) {
34668       ast_log(LOG_ERROR, "Unable to create primary SIP container(s)\n");
34669       return AST_MODULE_LOAD_FAILURE;
34670    }
34671 
34672    if (!(sip_cfg.caps = ast_format_cap_alloc())) {
34673       return AST_MODULE_LOAD_FAILURE;
34674    }
34675    ast_format_cap_add_all_by_type(sip_tech.capabilities, AST_FORMAT_TYPE_AUDIO);
34676 
34677    ASTOBJ_CONTAINER_INIT(&regl); /* Registry object list -- not searched for anything */
34678    ASTOBJ_CONTAINER_INIT(&submwil); /* MWI subscription object list */
34679 
34680    if (!(sched = ast_sched_context_create())) {
34681       ast_log(LOG_ERROR, "Unable to create scheduler context\n");
34682       return AST_MODULE_LOAD_FAILURE;
34683    }
34684 
34685    if (!(io = io_context_create())) {
34686       ast_log(LOG_ERROR, "Unable to create I/O context\n");
34687       return AST_MODULE_LOAD_FAILURE;
34688    }
34689 
34690    sip_reloadreason = CHANNEL_MODULE_LOAD;
34691 
34692    can_parse_xml = sip_is_xml_parsable();
34693    if (reload_config(sip_reloadreason)) { /* Load the configuration from sip.conf */
34694       ast_sip_api_provider_unregister();
34695       return AST_MODULE_LOAD_DECLINE;
34696    }
34697 
34698    /* Initialize bogus peer. Can be done first after reload_config() */
34699    if (!(bogus_peer = temp_peer("(bogus_peer)"))) {
34700       ast_log(LOG_ERROR, "Unable to create bogus_peer for authentication\n");
34701       io_context_destroy(io);
34702       ast_sched_context_destroy(sched);
34703       return AST_MODULE_LOAD_FAILURE;
34704    }
34705    /* Make sure the auth will always fail. */
34706    ast_string_field_set(bogus_peer, md5secret, BOGUS_PEER_MD5SECRET);
34707    ast_clear_flag(&bogus_peer->flags[0], SIP_INSECURE);
34708 
34709    /* Prepare the version that does not require DTMF BEGIN frames.
34710     * We need to use tricks such as memcpy and casts because the variable
34711     * has const fields.
34712     */
34713    memcpy(&sip_tech_info, &sip_tech, sizeof(sip_tech));
34714    memset((void *) &sip_tech_info.send_digit_begin, 0, sizeof(sip_tech_info.send_digit_begin));
34715 
34716    if (ast_msg_tech_register(&sip_msg_tech)) {
34717       /* LOAD_FAILURE stops Asterisk, so cleanup is a moot point. */
34718       return AST_MODULE_LOAD_FAILURE;
34719    }
34720 
34721    /* Make sure we can register our sip channel type */
34722    if (ast_channel_register(&sip_tech)) {
34723       ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
34724       ao2_t_ref(bogus_peer, -1, "unref the bogus_peer");
34725       io_context_destroy(io);
34726       ast_sched_context_destroy(sched);
34727       return AST_MODULE_LOAD_FAILURE;
34728    }
34729 
34730 #ifdef TEST_FRAMEWORK
34731    AST_TEST_REGISTER(test_sip_peers_get);
34732    AST_TEST_REGISTER(test_sip_mwi_subscribe_parse);
34733    AST_TEST_REGISTER(test_tcp_message_fragmentation);
34734    AST_TEST_REGISTER(get_in_brackets_const_test);
34735 #endif
34736 
34737    /* Register AstData providers */
34738    ast_data_register_multiple(sip_data_providers, ARRAY_LEN(sip_data_providers));
34739 
34740    /* Register all CLI functions for SIP */
34741    ast_cli_register_multiple(cli_sip, ARRAY_LEN(cli_sip));
34742 
34743    /* Tell the UDPTL subdriver that we're here */
34744    ast_udptl_proto_register(&sip_udptl);
34745 
34746    /* Tell the RTP engine about our RTP glue */
34747    ast_rtp_glue_register(&sip_rtp_glue);
34748 
34749    /* Register dialplan applications */
34750    ast_register_application_xml(app_dtmfmode, sip_dtmfmode);
34751    ast_register_application_xml(app_sipaddheader, sip_addheader);
34752    ast_register_application_xml(app_sipremoveheader, sip_removeheader);
34753 #ifdef TEST_FRAMEWORK
34754    ast_register_application_xml(app_sipsendcustominfo, sip_sendcustominfo);
34755 #endif
34756 
34757    /* Register dialplan functions */
34758    ast_custom_function_register(&sip_header_function);
34759    ast_custom_function_register(&sippeer_function);
34760    ast_custom_function_register(&sipchaninfo_function);
34761    ast_custom_function_register(&checksipdomain_function);
34762 
34763    /* Register manager commands */
34764    ast_manager_register_xml("SIPpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peers);
34765    ast_manager_register_xml("SIPshowpeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peer);
34766    ast_manager_register_xml("SIPqualifypeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_qualify_peer);
34767    ast_manager_register_xml("SIPshowregistry", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_show_registry);
34768    ast_manager_register_xml("SIPnotify", EVENT_FLAG_SYSTEM, manager_sipnotify);
34769    ast_manager_register_xml("SIPpeerstatus", EVENT_FLAG_SYSTEM, manager_sip_peer_status);
34770    sip_poke_all_peers();
34771    sip_keepalive_all_peers();
34772    sip_send_all_registers();
34773    sip_send_all_mwi_subscriptions();
34774    initialize_escs();
34775 
34776    if (sip_epa_register(&cc_epa_static_data)) {
34777       ast_sip_api_provider_unregister();
34778       return AST_MODULE_LOAD_DECLINE;
34779    }
34780 
34781    if (sip_reqresp_parser_init() == -1) {
34782       ast_log(LOG_ERROR, "Unable to initialize the SIP request and response parser\n");
34783       ast_sip_api_provider_unregister();
34784       return AST_MODULE_LOAD_DECLINE;
34785    }
34786 
34787    if (can_parse_xml) {
34788       /* SIP CC agents require the ability to parse XML PIDF bodies
34789        * in incoming PUBLISH requests
34790        */
34791       if (ast_cc_agent_register(&sip_cc_agent_callbacks)) {
34792          ast_sip_api_provider_unregister();
34793          return AST_MODULE_LOAD_DECLINE;
34794       }
34795    }
34796    if (ast_cc_monitor_register(&sip_cc_monitor_callbacks)) {
34797       ast_sip_api_provider_unregister();
34798       return AST_MODULE_LOAD_DECLINE;
34799    }
34800    if (!(sip_monitor_instances = ao2_container_alloc(37, sip_monitor_instance_hash_fn, sip_monitor_instance_cmp_fn))) {
34801       ast_sip_api_provider_unregister();
34802       return AST_MODULE_LOAD_DECLINE;
34803    }
34804 
34805    /* And start the monitor for the first time */
34806    restart_monitor();
34807 
34808    ast_realtime_require_field(ast_check_realtime("sipregs") ? "sipregs" : "sippeers",
34809       "name", RQ_CHAR, 10,
34810       "ipaddr", RQ_CHAR, INET6_ADDRSTRLEN - 1,
34811       "port", RQ_UINTEGER2, 5,
34812       "regseconds", RQ_INTEGER4, 11,
34813       "defaultuser", RQ_CHAR, 10,
34814       "fullcontact", RQ_CHAR, 35,
34815       "regserver", RQ_CHAR, 20,
34816       "useragent", RQ_CHAR, 20,
34817       "lastms", RQ_INTEGER4, 11,
34818       SENTINEL);
34819 
34820 
34821    sip_register_tests();
34822    network_change_event_subscribe();
34823 
34824    ast_websocket_add_protocol("sip", sip_websocket_callback);
34825 
34826    return AST_MODULE_LOAD_SUCCESS;
34827 }
34828 
34829 /*! \brief PBX unload module API */
34830 static int unload_module(void)
34831 {
34832    struct sip_pvt *p;
34833    struct sip_threadinfo *th;
34834    struct ast_context *con;
34835    struct ao2_iterator i;
34836    int wait_count;
34837 
34838    ast_sip_api_provider_unregister();
34839 
34840    ast_websocket_remove_protocol("sip", sip_websocket_callback);
34841 
34842    network_change_event_unsubscribe();
34843    acl_change_event_unsubscribe();
34844 
34845    ast_sched_dump(sched);
34846    
34847    /* First, take us out of the channel type list */
34848    ast_channel_unregister(&sip_tech);
34849 
34850    ast_msg_tech_unregister(&sip_msg_tech);
34851 
34852    /* Unregister dial plan functions */
34853    ast_custom_function_unregister(&sipchaninfo_function);
34854    ast_custom_function_unregister(&sippeer_function);
34855    ast_custom_function_unregister(&sip_header_function);
34856    ast_custom_function_unregister(&checksipdomain_function);
34857 
34858    /* Unregister dial plan applications */
34859    ast_unregister_application(app_dtmfmode);
34860    ast_unregister_application(app_sipaddheader);
34861    ast_unregister_application(app_sipremoveheader);
34862 #ifdef TEST_FRAMEWORK
34863    ast_unregister_application(app_sipsendcustominfo);
34864 
34865    AST_TEST_UNREGISTER(test_sip_peers_get);
34866    AST_TEST_UNREGISTER(test_sip_mwi_subscribe_parse);
34867    AST_TEST_UNREGISTER(test_tcp_message_fragmentation);
34868    AST_TEST_UNREGISTER(get_in_brackets_const_test);
34869 #endif
34870    /* Unregister all the AstData providers */
34871    ast_data_unregister(NULL);
34872 
34873    /* Unregister CLI commands */
34874    ast_cli_unregister_multiple(cli_sip, ARRAY_LEN(cli_sip));
34875 
34876    /* Disconnect from UDPTL */
34877    ast_udptl_proto_unregister(&sip_udptl);
34878 
34879    /* Disconnect from RTP engine */
34880    ast_rtp_glue_unregister(&sip_rtp_glue);
34881 
34882    /* Unregister AMI actions */
34883    ast_manager_unregister("SIPpeers");
34884    ast_manager_unregister("SIPshowpeer");
34885    ast_manager_unregister("SIPqualifypeer");
34886    ast_manager_unregister("SIPshowregistry");
34887    ast_manager_unregister("SIPnotify");
34888    ast_manager_unregister("SIPpeerstatus");
34889    
34890    /* Kill TCP/TLS server threads */
34891    if (sip_tcp_desc.master) {
34892       ast_tcptls_server_stop(&sip_tcp_desc);
34893    }
34894    if (sip_tls_desc.master) {
34895       ast_tcptls_server_stop(&sip_tls_desc);
34896    }
34897    ast_ssl_teardown(sip_tls_desc.tls_cfg);
34898 
34899    /* Kill all existing TCP/TLS threads */
34900    i = ao2_iterator_init(threadt, 0);
34901    while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
34902       pthread_t thread = th->threadid;
34903       th->stop = 1;
34904       pthread_kill(thread, SIGURG);
34905       ao2_t_ref(th, -1, "decrement ref from iterator");
34906    }
34907    ao2_iterator_destroy(&i);
34908 
34909    /* Hangup all dialogs if they have an owner */
34910    i = ao2_iterator_init(dialogs, 0);
34911    while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
34912       if (p->owner)
34913          ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
34914       ao2_t_ref(p, -1, "toss dialog ptr from iterator_next");
34915    }
34916    ao2_iterator_destroy(&i);
34917 
34918    unlink_all_peers_from_tables();
34919 
34920    ast_mutex_lock(&monlock);
34921    if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
34922       pthread_t th = monitor_thread;
34923       monitor_thread = AST_PTHREADT_STOP;
34924       pthread_cancel(th);
34925       pthread_kill(th, SIGURG);
34926       ast_mutex_unlock(&monlock);
34927       pthread_join(th, NULL);
34928    } else {
34929       monitor_thread = AST_PTHREADT_STOP;
34930       ast_mutex_unlock(&monlock);
34931    }
34932 
34933    /* Destroy all the dialogs and free their memory */
34934    i = ao2_iterator_init(dialogs, 0);
34935    while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
34936       dialog_unlink_all(p);
34937       ao2_t_ref(p, -1, "throw away iterator result");
34938    }
34939    ao2_iterator_destroy(&i);
34940 
34941    /* Free memory for local network address mask */
34942    ast_free_ha(localaddr);
34943 
34944    ast_mutex_lock(&authl_lock);
34945    if (authl) {
34946       ao2_t_ref(authl, -1, "Removing global authentication");
34947       authl = NULL;
34948    }
34949    ast_mutex_unlock(&authl_lock);
34950 
34951    sip_epa_unregister_all();
34952    destroy_escs();
34953 
34954    ast_free(default_tls_cfg.certfile);
34955    ast_free(default_tls_cfg.pvtfile);
34956    ast_free(default_tls_cfg.cipher);
34957    ast_free(default_tls_cfg.cafile);
34958    ast_free(default_tls_cfg.capath);
34959 
34960    cleanup_all_regs();
34961    ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
34962    ASTOBJ_CONTAINER_DESTROY(&regl);
34963 
34964    ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
34965       ASTOBJ_WRLOCK(iterator);
34966       if (iterator->dnsmgr) {
34967          ast_dnsmgr_release(iterator->dnsmgr);
34968          iterator->dnsmgr = NULL;
34969          ASTOBJ_UNREF(iterator, sip_subscribe_mwi_destroy);
34970       }
34971       ASTOBJ_UNLOCK(iterator);
34972    } while(0));
34973    ASTOBJ_CONTAINER_DESTROYALL(&submwil, sip_subscribe_mwi_destroy);
34974    ASTOBJ_CONTAINER_DESTROY(&submwil);
34975 
34976    /*
34977     * Wait awhile for the TCP/TLS thread container to become empty.
34978     *
34979     * XXX This is a hack, but the worker threads cannot be created
34980     * joinable.  They can die on their own and remove themselves
34981     * from the container thus resulting in a huge memory leak.
34982     */
34983    wait_count = 1000;
34984    while (ao2_container_count(threadt) && --wait_count) {
34985       sched_yield();
34986    }
34987    if (!wait_count) {
34988       ast_debug(2, "TCP/TLS thread container did not become empty :(\n");
34989    }
34990 
34991    ao2_t_ref(bogus_peer, -1, "unref the bogus_peer");
34992 
34993    ao2_t_ref(peers, -1, "unref the peers table");
34994    ao2_t_ref(peers_by_ip, -1, "unref the peers_by_ip table");
34995    ao2_t_ref(dialogs, -1, "unref the dialogs table");
34996    ao2_t_ref(dialogs_needdestroy, -1, "unref dialogs_needdestroy");
34997    ao2_t_ref(dialogs_rtpcheck, -1, "unref dialogs_rtpcheck");
34998    ao2_t_ref(threadt, -1, "unref the thread table");
34999    ao2_t_ref(sip_monitor_instances, -1, "unref the sip_monitor_instances table");
35000 
35001    clear_sip_domains();
35002    sip_cfg.contact_acl = ast_free_acl_list(sip_cfg.contact_acl);
35003    if (sipsock_read_id) {
35004       ast_io_remove(io, sipsock_read_id);
35005       sipsock_read_id = NULL;
35006    }
35007    close(sipsock);
35008    io_context_destroy(io);
35009    ast_sched_context_destroy(sched);
35010    con = ast_context_find(used_context);
35011    if (con) {
35012       ast_context_destroy(con, "SIP");
35013    }
35014    ast_unload_realtime("sipregs");
35015    ast_unload_realtime("sippeers");
35016    ast_cc_monitor_unregister(&sip_cc_monitor_callbacks);
35017    ast_cc_agent_unregister(&sip_cc_agent_callbacks);
35018 
35019    sip_reqresp_parser_exit();
35020    sip_unregister_tests();
35021 
35022    if (notify_types) {
35023       ast_config_destroy(notify_types);
35024       notify_types = NULL;
35025    }
35026 
35027    ast_format_cap_destroy(sip_tech.capabilities);
35028    sip_cfg.caps = ast_format_cap_destroy(sip_cfg.caps);
35029 
35030    return 0;
35031 }
35032 
35033 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Session Initiation Protocol (SIP)",
35034       .load = load_module,
35035       .unload = unload_module,
35036       .reload = reload,
35037       .load_pri = AST_MODPRI_CHANNEL_DRIVER,
35038       .nonoptreq = "res_crypto,chan_local,res_http_websocket",
35039           );