Sat Apr 26 2014 22:01:32

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: 412873 $")
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 /*
00223    Uncomment the define below,  if you are having refcount related memory leaks.
00224    With this uncommented, this module will generate a file, /tmp/refs, which contains
00225    a history of the ao2_ref() calls. To be useful, all calls to ao2_* functions should
00226    be modified to ao2_t_* calls, and include a tag describing what is happening with
00227    enough detail, to make pairing up a reference count increment with its corresponding decrement.
00228    The refcounter program in utils/ can be invaluable in highlighting objects that are not
00229    balanced, along with the complete history for that object.
00230    In normal operation, the macros defined will throw away the tags, so they do not
00231    affect the speed of the program at all. They can be considered to be documentation.
00232 
00233    Note: This must also be enabled in channels/sip/security_events.c
00234 */
00235 /* #define  REF_DEBUG 1 */
00236 
00237 #include "asterisk/lock.h"
00238 #include "asterisk/config.h"
00239 #include "asterisk/module.h"
00240 #include "asterisk/pbx.h"
00241 #include "asterisk/sched.h"
00242 #include "asterisk/io.h"
00243 #include "asterisk/rtp_engine.h"
00244 #include "asterisk/udptl.h"
00245 #include "asterisk/acl.h"
00246 #include "asterisk/manager.h"
00247 #include "asterisk/callerid.h"
00248 #include "asterisk/cli.h"
00249 #include "asterisk/musiconhold.h"
00250 #include "asterisk/dsp.h"
00251 #include "asterisk/features.h"
00252 #include "asterisk/srv.h"
00253 #include "asterisk/astdb.h"
00254 #include "asterisk/causes.h"
00255 #include "asterisk/utils.h"
00256 #include "asterisk/file.h"
00257 #include "asterisk/astobj2.h"
00258 #include "asterisk/dnsmgr.h"
00259 #include "asterisk/devicestate.h"
00260 #include "asterisk/monitor.h"
00261 #include "asterisk/netsock2.h"
00262 #include "asterisk/localtime.h"
00263 #include "asterisk/abstract_jb.h"
00264 #include "asterisk/threadstorage.h"
00265 #include "asterisk/translate.h"
00266 #include "asterisk/ast_version.h"
00267 #include "asterisk/event.h"
00268 #include "asterisk/cel.h"
00269 #include "asterisk/data.h"
00270 #include "asterisk/aoc.h"
00271 #include "asterisk/message.h"
00272 #include "sip/include/sip.h"
00273 #include "sip/include/globals.h"
00274 #include "sip/include/config_parser.h"
00275 #include "sip/include/reqresp_parser.h"
00276 #include "sip/include/sip_utils.h"
00277 #include "sip/include/srtp.h"
00278 #include "sip/include/sdp_crypto.h"
00279 #include "asterisk/ccss.h"
00280 #include "asterisk/xml.h"
00281 #include "sip/include/dialog.h"
00282 #include "sip/include/dialplan_functions.h"
00283 #include "sip/include/security_events.h"
00284 #include "asterisk/sip_api.h"
00285 
00286 /*** DOCUMENTATION
00287    <application name="SIPDtmfMode" language="en_US">
00288       <synopsis>
00289          Change the dtmfmode for a SIP call.
00290       </synopsis>
00291       <syntax>
00292          <parameter name="mode" required="true">
00293             <enumlist>
00294                <enum name="inband" />
00295                <enum name="info" />
00296                <enum name="rfc2833" />
00297             </enumlist>
00298          </parameter>
00299       </syntax>
00300       <description>
00301          <para>Changes the dtmfmode for a SIP call.</para>
00302       </description>
00303    </application>
00304    <application name="SIPAddHeader" language="en_US">
00305       <synopsis>
00306          Add a SIP header to the outbound call.
00307       </synopsis>
00308       <syntax argsep=":">
00309          <parameter name="Header" required="true" />
00310          <parameter name="Content" required="true" />
00311       </syntax>
00312       <description>
00313          <para>Adds a header to a SIP call placed with DIAL.</para>
00314          <para>Remember to use the X-header if you are adding non-standard SIP
00315          headers, like <literal>X-Asterisk-Accountcode:</literal>. Use this with care.
00316          Adding the wrong headers may jeopardize the SIP dialog.</para>
00317          <para>Always returns <literal>0</literal>.</para>
00318       </description>
00319    </application>
00320    <application name="SIPRemoveHeader" language="en_US">
00321       <synopsis>
00322          Remove SIP headers previously added with SIPAddHeader
00323       </synopsis>
00324       <syntax>
00325          <parameter name="Header" required="false" />
00326       </syntax>
00327       <description>
00328          <para>SIPRemoveHeader() allows you to remove headers which were previously
00329          added with SIPAddHeader(). If no parameter is supplied, all previously added
00330          headers will be removed. If a parameter is supplied, only the matching headers
00331          will be removed.</para>
00332          <para>For example you have added these 2 headers:</para>
00333          <para>SIPAddHeader(P-Asserted-Identity: sip:foo@bar);</para>
00334          <para>SIPAddHeader(P-Preferred-Identity: sip:bar@foo);</para>
00335          <para></para>
00336          <para>// remove all headers</para>
00337          <para>SIPRemoveHeader();</para>
00338          <para>// remove all P- headers</para>
00339          <para>SIPRemoveHeader(P-);</para>
00340          <para>// remove only the PAI header (note the : at the end)</para>
00341          <para>SIPRemoveHeader(P-Asserted-Identity:);</para>
00342          <para></para>
00343          <para>Always returns <literal>0</literal>.</para>
00344       </description>
00345    </application>
00346    <application name="SIPSendCustomINFO" language="en_US">
00347       <synopsis>
00348          Send a custom INFO frame on specified channels.
00349       </synopsis>
00350       <syntax>
00351          <parameter name="Data" required="true" />
00352          <parameter name="UserAgent" required="false" />
00353       </syntax>
00354       <description>
00355          <para>SIPSendCustomINFO() allows you to send a custom INFO message on all
00356          active SIP channels or on channels with the specified User Agent. This
00357          application is only available if TEST_FRAMEWORK is defined.</para>
00358       </description>
00359    </application>
00360    <function name="SIP_HEADER" language="en_US">
00361       <synopsis>
00362          Gets the specified SIP header from an incoming INVITE message.
00363       </synopsis>
00364       <syntax>
00365          <parameter name="name" required="true" />
00366          <parameter name="number">
00367             <para>If not specified, defaults to <literal>1</literal>.</para>
00368          </parameter>
00369       </syntax>
00370       <description>
00371          <para>Since there are several headers (such as Via) which can occur multiple
00372          times, SIP_HEADER takes an optional second argument to specify which header with
00373          that name to retrieve. Headers start at offset <literal>1</literal>.</para>
00374          <para>Please observe that contents of the SDP (an attachment to the 
00375          SIP request) can't be accessed with this function.</para>
00376       </description>
00377    </function>
00378    <function name="SIPPEER" language="en_US">
00379       <synopsis>
00380          Gets SIP peer information.
00381       </synopsis>
00382       <syntax>
00383          <parameter name="peername" required="true" />
00384          <parameter name="item">
00385             <enumlist>
00386                <enum name="ip">
00387                   <para>(default) The IP address.</para>
00388                </enum>
00389                <enum name="port">
00390                   <para>The port number.</para>
00391                </enum>
00392                <enum name="mailbox">
00393                   <para>The configured mailbox.</para>
00394                </enum>
00395                <enum name="context">
00396                   <para>The configured context.</para>
00397                </enum>
00398                <enum name="expire">
00399                   <para>The epoch time of the next expire.</para>
00400                </enum>
00401                <enum name="dynamic">
00402                   <para>Is it dynamic? (yes/no).</para>
00403                </enum>
00404                <enum name="callerid_name">
00405                   <para>The configured Caller ID name.</para>
00406                </enum>
00407                <enum name="callerid_num">
00408                   <para>The configured Caller ID number.</para>
00409                </enum>
00410                <enum name="callgroup">
00411                   <para>The configured Callgroup.</para>
00412                </enum>
00413                <enum name="pickupgroup">
00414                   <para>The configured Pickupgroup.</para>
00415                </enum>
00416                <enum name="namedcallgroup">
00417                   <para>The configured Named Callgroup.</para>
00418                </enum>
00419                <enum name="namedpickupgroup">
00420                   <para>The configured Named Pickupgroup.</para>
00421                </enum>
00422                <enum name="codecs">
00423                   <para>The configured codecs.</para>
00424                </enum>
00425                <enum name="status">
00426                   <para>Status (if qualify=yes).</para>
00427                </enum>
00428                <enum name="regexten">
00429                   <para>Extension activated at registration.</para>
00430                </enum>
00431                <enum name="limit">
00432                   <para>Call limit (call-limit).</para>
00433                </enum>
00434                <enum name="busylevel">
00435                   <para>Configured call level for signalling busy.</para>
00436                </enum>
00437                <enum name="curcalls">
00438                   <para>Current amount of calls. Only available if call-limit is set.</para>
00439                </enum>
00440                <enum name="language">
00441                   <para>Default language for peer.</para>
00442                </enum>
00443                <enum name="accountcode">
00444                   <para>Account code for this peer.</para>
00445                </enum>
00446                <enum name="useragent">
00447                   <para>Current user agent header used by peer.</para>
00448                </enum>
00449                <enum name="maxforwards">
00450                   <para>The value used for SIP loop prevention in outbound requests</para>
00451                </enum>
00452                <enum name="chanvar[name]">
00453                   <para>A channel variable configured with setvar for this peer.</para>
00454                </enum>
00455                <enum name="codec[x]">
00456                   <para>Preferred codec index number <replaceable>x</replaceable> (beginning with zero).</para>
00457                </enum>
00458             </enumlist>
00459          </parameter>
00460       </syntax>
00461       <description></description>
00462    </function>
00463    <function name="SIPCHANINFO" language="en_US">
00464       <synopsis>
00465          Gets the specified SIP parameter from the current channel.
00466       </synopsis>
00467       <syntax>
00468          <parameter name="item" required="true">
00469             <enumlist>
00470                <enum name="peerip">
00471                   <para>The IP address of the peer.</para>
00472                </enum>
00473                <enum name="recvip">
00474                   <para>The source IP address of the peer.</para>
00475                </enum>
00476                <enum name="from">
00477                   <para>The SIP URI from the <literal>From:</literal> header.</para>
00478                </enum>
00479                <enum name="uri">
00480                   <para>The SIP URI from the <literal>Contact:</literal> header.</para>
00481                </enum>
00482                <enum name="useragent">
00483                   <para>The Useragent header used by the peer.</para>
00484                </enum>
00485                <enum name="peername">
00486                   <para>The name of the peer.</para>
00487                </enum>
00488                <enum name="t38passthrough">
00489                   <para><literal>1</literal> if T38 is offered or enabled in this channel,
00490                   otherwise <literal>0</literal>.</para>
00491                </enum>
00492             </enumlist>
00493          </parameter>
00494       </syntax>
00495       <description></description>
00496    </function>
00497    <function name="CHECKSIPDOMAIN" language="en_US">
00498       <synopsis>
00499          Checks if domain is a local domain.
00500       </synopsis>
00501       <syntax>
00502          <parameter name="domain" required="true" />
00503       </syntax>
00504       <description>
00505          <para>This function checks if the <replaceable>domain</replaceable> in the argument is configured
00506          as a local SIP domain that this Asterisk server is configured to handle.
00507          Returns the domain name if it is locally handled, otherwise an empty string.
00508          Check the <literal>domain=</literal> configuration in <filename>sip.conf</filename>.</para>
00509       </description>
00510    </function>
00511    <manager name="SIPpeers" language="en_US">
00512       <synopsis>
00513          List SIP peers (text format).
00514       </synopsis>
00515       <syntax>
00516          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00517       </syntax>
00518       <description>
00519          <para>Lists SIP peers in text format with details on current status.
00520          <literal>Peerlist</literal> will follow as separate events, followed by a final event called
00521          <literal>PeerlistComplete</literal>.</para>
00522       </description>
00523    </manager>
00524    <manager name="SIPshowpeer" language="en_US">
00525       <synopsis>
00526          show SIP peer (text format).
00527       </synopsis>
00528       <syntax>
00529          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00530          <parameter name="Peer" required="true">
00531             <para>The peer name you want to check.</para>
00532          </parameter>
00533       </syntax>
00534       <description>
00535          <para>Show one SIP peer with details on current status.</para>
00536       </description>
00537    </manager>
00538    <manager name="SIPqualifypeer" language="en_US">
00539       <synopsis>
00540          Qualify SIP peers.
00541       </synopsis>
00542       <syntax>
00543          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00544          <parameter name="Peer" required="true">
00545             <para>The peer name you want to qualify.</para>
00546          </parameter>
00547       </syntax>
00548       <description>
00549          <para>Qualify a SIP peer.</para>
00550       </description>
00551    </manager>
00552    <manager name="SIPshowregistry" language="en_US">
00553       <synopsis>
00554          Show SIP registrations (text format).
00555       </synopsis>
00556       <syntax>
00557          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00558       </syntax>
00559       <description>
00560          <para>Lists all registration requests and status. Registrations will follow as separate
00561          events followed by a final event called <literal>RegistrationsComplete</literal>.</para>
00562       </description>
00563    </manager>
00564    <manager name="SIPnotify" language="en_US">
00565       <synopsis>
00566          Send a SIP notify.
00567       </synopsis>
00568       <syntax>
00569          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00570          <parameter name="Channel" required="true">
00571             <para>Peer to receive the notify.</para>
00572          </parameter>
00573          <parameter name="Variable" required="true">
00574             <para>At least one variable pair must be specified.
00575             <replaceable>name</replaceable>=<replaceable>value</replaceable></para>
00576          </parameter>
00577       </syntax>
00578       <description>
00579          <para>Sends a SIP Notify event.</para>
00580          <para>All parameters for this event must be specified in the body of this request
00581          via multiple <literal>Variable: name=value</literal> sequences.</para>
00582       </description>
00583    </manager>
00584    <manager name="SIPpeerstatus" language="en_US">
00585       <synopsis>
00586          Show the status of one or all of the sip peers.
00587       </synopsis>
00588       <syntax>
00589          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00590          <parameter name="Peer" required="false">
00591             <para>The peer name you want to check.</para>
00592          </parameter>
00593       </syntax>
00594       <description>
00595          <para>Retrieves the status of one or all of the sip peers.  If no peer name is specified, status
00596          for all of the sip peers will be retrieved.</para>
00597       </description>
00598    </manager>
00599    <info name="SIPMessageFromInfo" language="en_US" tech="SIP">
00600       <para>The <literal>from</literal> parameter can be a configured peer name
00601       or in the form of "display-name" &lt;URI&gt;.</para>
00602    </info>
00603    <info name="SIPMessageToInfo" language="en_US" tech="SIP">
00604       <para>Specifying a prefix of <literal>sip:</literal> will send the
00605       message as a SIP MESSAGE request.</para>
00606    </info>
00607  ***/
00608 
00609 static int min_expiry = DEFAULT_MIN_EXPIRY;        /*!< Minimum accepted registration time */
00610 static int max_expiry = DEFAULT_MAX_EXPIRY;        /*!< Maximum accepted registration time */
00611 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
00612 static int min_subexpiry = DEFAULT_MIN_EXPIRY;     /*!< Minimum accepted subscription time */
00613 static int max_subexpiry = DEFAULT_MAX_EXPIRY;     /*!< Maximum accepted subscription time */
00614 static int mwi_expiry = DEFAULT_MWI_EXPIRY;
00615 
00616 static int unauth_sessions = 0;
00617 static int authlimit = DEFAULT_AUTHLIMIT;
00618 static int authtimeout = DEFAULT_AUTHTIMEOUT;
00619 
00620 /*! \brief Global jitterbuffer configuration - by default, jb is disabled
00621  *  \note Values shown here match the defaults shown in sip.conf.sample */
00622 static struct ast_jb_conf default_jbconf =
00623 {
00624    .flags = 0,
00625    .max_size = 200,
00626    .resync_threshold = 1000,
00627    .impl = "fixed",
00628    .target_extra = 40,
00629 };
00630 static struct ast_jb_conf global_jbconf;                /*!< Global jitterbuffer configuration */
00631 
00632 static const char config[] = "sip.conf";                /*!< Main configuration file */
00633 static const char notify_config[] = "sip_notify.conf";  /*!< Configuration file for sending Notify with CLI commands to reconfigure or reboot phones */
00634 
00635 /*! \brief Readable descriptions of device states.
00636  *  \note Should be aligned to above table as index */
00637 static const struct invstate2stringtable {
00638    const enum invitestates state;
00639    const char *desc;
00640 } invitestate2string[] = {
00641    {INV_NONE,              "None"  },
00642    {INV_CALLING,           "Calling (Trying)"},
00643    {INV_PROCEEDING,        "Proceeding "},
00644    {INV_EARLY_MEDIA,       "Early media"},
00645    {INV_COMPLETED,         "Completed (done)"},
00646    {INV_CONFIRMED,         "Confirmed (up)"},
00647    {INV_TERMINATED,        "Done"},
00648    {INV_CANCELLED,         "Cancelled"}
00649 };
00650 
00651 /*! \brief Subscription types that we support. We support
00652  * - dialoginfo updates (really device status, not dialog info as was the original intent of the standard)
00653  * - SIMPLE presence used for device status
00654  * - Voicemail notification subscriptions
00655  */
00656 static const struct cfsubscription_types {
00657    enum subscriptiontype type;
00658    const char * const event;
00659    const char * const mediatype;
00660    const char * const text;
00661 } subscription_types[] = {
00662    { NONE,        "-",        "unknown",               "unknown" },
00663    /* RFC 4235: SIP Dialog event package */
00664    { DIALOG_INFO_XML, "dialog",   "application/dialog-info+xml", "dialog-info+xml" },
00665    { CPIM_PIDF_XML,   "presence", "application/cpim-pidf+xml",   "cpim-pidf+xml" },  /* RFC 3863 */
00666    { PIDF_XML,        "presence", "application/pidf+xml",        "pidf+xml" },       /* RFC 3863 */
00667    { XPIDF_XML,       "presence", "application/xpidf+xml",       "xpidf+xml" },       /* Pre-RFC 3863 with MS additions */
00668    { MWI_NOTIFICATION,  "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
00669 };
00670 
00671 /*! \brief The core structure to setup dialogs. We parse incoming messages by using
00672  *  structure and then route the messages according to the type.
00673  *
00674  *  \note Note that sip_methods[i].id == i must hold or the code breaks
00675  */
00676 static const struct  cfsip_methods {
00677    enum sipmethod id;
00678    int need_rtp;     /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
00679    char * const text;
00680    enum can_create_dialog can_create;
00681 } sip_methods[] = {
00682    { SIP_UNKNOWN,   RTP,    "-UNKNOWN-",CAN_CREATE_DIALOG },
00683    { SIP_RESPONSE,  NO_RTP, "SIP/2.0",  CAN_NOT_CREATE_DIALOG },
00684    { SIP_REGISTER,  NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
00685    { SIP_OPTIONS,   NO_RTP, "OPTIONS",  CAN_CREATE_DIALOG },
00686    { SIP_NOTIFY,    NO_RTP, "NOTIFY",   CAN_CREATE_DIALOG },
00687    { SIP_INVITE,    RTP,    "INVITE",   CAN_CREATE_DIALOG },
00688    { SIP_ACK,       NO_RTP, "ACK",      CAN_NOT_CREATE_DIALOG },
00689    { SIP_PRACK,     NO_RTP, "PRACK",    CAN_NOT_CREATE_DIALOG },
00690    { SIP_BYE,       NO_RTP, "BYE",      CAN_NOT_CREATE_DIALOG },
00691    { SIP_REFER,     NO_RTP, "REFER",    CAN_CREATE_DIALOG },
00692    { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE",CAN_CREATE_DIALOG },
00693    { SIP_MESSAGE,   NO_RTP, "MESSAGE",  CAN_CREATE_DIALOG },
00694    { SIP_UPDATE,    NO_RTP, "UPDATE",   CAN_NOT_CREATE_DIALOG },
00695    { SIP_INFO,      NO_RTP, "INFO",     CAN_NOT_CREATE_DIALOG },
00696    { SIP_CANCEL,    NO_RTP, "CANCEL",   CAN_NOT_CREATE_DIALOG },
00697    { SIP_PUBLISH,   NO_RTP, "PUBLISH",  CAN_CREATE_DIALOG },
00698    { SIP_PING,      NO_RTP, "PING",     CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
00699 };
00700 
00701 /*! \brief Diversion header reasons
00702  *
00703  * The core defines a bunch of constants used to define
00704  * redirecting reasons. This provides a translation table
00705  * between those and the strings which may be present in
00706  * a SIP Diversion header
00707  */
00708 static const struct sip_reasons {
00709    enum AST_REDIRECTING_REASON code;
00710    char * const text;
00711 } sip_reason_table[] = {
00712    { AST_REDIRECTING_REASON_UNKNOWN, "unknown" },
00713    { AST_REDIRECTING_REASON_USER_BUSY, "user-busy" },
00714    { AST_REDIRECTING_REASON_NO_ANSWER, "no-answer" },
00715    { AST_REDIRECTING_REASON_UNAVAILABLE, "unavailable" },
00716    { AST_REDIRECTING_REASON_UNCONDITIONAL, "unconditional" },
00717    { AST_REDIRECTING_REASON_TIME_OF_DAY, "time-of-day" },
00718    { AST_REDIRECTING_REASON_DO_NOT_DISTURB, "do-not-disturb" },
00719    { AST_REDIRECTING_REASON_DEFLECTION, "deflection" },
00720    { AST_REDIRECTING_REASON_FOLLOW_ME, "follow-me" },
00721    { AST_REDIRECTING_REASON_OUT_OF_ORDER, "out-of-service" },
00722    { AST_REDIRECTING_REASON_AWAY, "away" },
00723    { AST_REDIRECTING_REASON_CALL_FWD_DTE, "unknown"},
00724    { AST_REDIRECTING_REASON_SEND_TO_VM, "send_to_vm"},
00725 };
00726 
00727 
00728 /*! \name DefaultSettings
00729    Default setttings are used as a channel setting and as a default when
00730    configuring devices
00731 */
00732 /*@{*/
00733 static char default_language[MAX_LANGUAGE];      /*!< Default language setting for new channels */
00734 static char default_callerid[AST_MAX_EXTENSION]; /*!< Default caller ID for sip messages */
00735 static char default_mwi_from[80];                /*!< Default caller ID for MWI updates */
00736 static char default_fromdomain[AST_MAX_EXTENSION]; /*!< Default domain on outound messages */
00737 static int default_fromdomainport;                 /*!< Default domain port on outbound messages */
00738 static char default_notifymime[AST_MAX_EXTENSION]; /*!< Default MIME media type for MWI notify messages */
00739 static char default_vmexten[AST_MAX_EXTENSION];    /*!< Default From Username on MWI updates */
00740 static int default_qualify;                        /*!< Default Qualify= setting */
00741 static int default_keepalive;                      /*!< Default keepalive= setting */
00742 static char default_mohinterpret[MAX_MUSICCLASS];  /*!< Global setting for moh class to use when put on hold */
00743 static char default_mohsuggest[MAX_MUSICCLASS];    /*!< Global setting for moh class to suggest when putting
00744                                                     *   a bridged channel on hold */
00745 static char default_parkinglot[AST_MAX_CONTEXT];   /*!< Parkinglot */
00746 static char default_engine[256];                   /*!< Default RTP engine */
00747 static int default_maxcallbitrate;                 /*!< Maximum bitrate for call */
00748 static struct ast_codec_pref default_prefs;        /*!< Default codec prefs */
00749 static char default_zone[MAX_TONEZONE_COUNTRY];        /*!< Default tone zone for channels created from the SIP driver */
00750 static unsigned int default_transports;            /*!< Default Transports (enum sip_transport) that are acceptable */
00751 static unsigned int default_primary_transport;     /*!< Default primary Transport (enum sip_transport) for outbound connections to devices */
00752 /*@}*/
00753 
00754 static struct sip_settings sip_cfg;    /*!< SIP configuration data.
00755                \note in the future we could have multiple of these (per domain, per device group etc) */
00756 
00757 /*!< use this macro when ast_uri_decode is dependent on pedantic checking to be on. */
00758 #define SIP_PEDANTIC_DECODE(str) \
00759    if (sip_cfg.pedanticsipchecking && !ast_strlen_zero(str)) { \
00760       ast_uri_decode(str, ast_uri_sip_user); \
00761    }  \
00762 
00763 static unsigned int chan_idx;       /*!< used in naming sip channel */
00764 static int global_match_auth_username;    /*!< Match auth username if available instead of From: Default off. */
00765 
00766 static int global_relaxdtmf;        /*!< Relax DTMF */
00767 static int global_prematuremediafilter;   /*!< Enable/disable premature frames in a call (causing 183 early media) */
00768 static int global_rtptimeout;       /*!< Time out call if no RTP */
00769 static int global_rtpholdtimeout;   /*!< Time out call if no RTP during hold */
00770 static int global_rtpkeepalive;     /*!< Send RTP keepalives */
00771 static int global_reg_timeout;      /*!< Global time between attempts for outbound registrations */
00772 static int global_regattempts_max;  /*!< Registration attempts before giving up */
00773 static int global_reg_retry_403;    /*!< Treat 403 responses to registrations as 401 responses */
00774 static int global_shrinkcallerid;   /*!< enable or disable shrinking of caller id  */
00775 static int global_callcounter;      /*!< Enable call counters for all devices. This is currently enabled by setting the peer
00776                                      *   call-limit to INT_MAX. When we remove the call-limit from the code, we can make it
00777                                      *   with just a boolean flag in the device structure */
00778 static unsigned int global_tos_sip;      /*!< IP type of service for SIP packets */
00779 static unsigned int global_tos_audio;    /*!< IP type of service for audio RTP packets */
00780 static unsigned int global_tos_video;    /*!< IP type of service for video RTP packets */
00781 static unsigned int global_tos_text;     /*!< IP type of service for text RTP packets */
00782 static unsigned int global_cos_sip;      /*!< 802.1p class of service for SIP packets */
00783 static unsigned int global_cos_audio;    /*!< 802.1p class of service for audio RTP packets */
00784 static unsigned int global_cos_video;    /*!< 802.1p class of service for video RTP packets */
00785 static unsigned int global_cos_text;     /*!< 802.1p class of service for text RTP packets */
00786 static unsigned int recordhistory;       /*!< Record SIP history. Off by default */
00787 static unsigned int dumphistory;         /*!< Dump history to verbose before destroying SIP dialog */
00788 static char global_useragent[AST_MAX_EXTENSION];    /*!< Useragent for the SIP channel */
00789 static char global_sdpsession[AST_MAX_EXTENSION];   /*!< SDP session name for the SIP channel */
00790 static char global_sdpowner[AST_MAX_EXTENSION];     /*!< SDP owner name for the SIP channel */
00791 static int global_authfailureevents;     /*!< Whether we send authentication failure manager events or not. Default no. */
00792 static int global_t1;           /*!< T1 time */
00793 static int global_t1min;        /*!< T1 roundtrip time minimum */
00794 static int global_timer_b;      /*!< Timer B - RFC 3261 Section 17.1.1.2 */
00795 static unsigned int global_autoframing; /*!< Turn autoframing on or off. */
00796 static int global_qualifyfreq;          /*!< Qualify frequency */
00797 static int global_qualify_gap;          /*!< Time between our group of peer pokes */
00798 static int global_qualify_peers;        /*!< Number of peers to poke at a given time */
00799 
00800 static enum st_mode global_st_mode;           /*!< Mode of operation for Session-Timers           */
00801 static enum st_refresher_param global_st_refresher; /*!< Session-Timer refresher                        */
00802 static int global_min_se;                     /*!< Lowest threshold for session refresh interval  */
00803 static int global_max_se;                     /*!< Highest threshold for session refresh interval */
00804 
00805 static int global_store_sip_cause;    /*!< Whether the MASTER_CHANNEL(HASH(SIP_CAUSE,[chan_name])) var should be set */
00806 
00807 static int global_dynamic_exclude_static = 0; /*!< Exclude static peers from contact registrations */
00808 static unsigned char global_refer_addheaders; /*!< Add extra headers to outgoing REFER */
00809 /*@}*/
00810 
00811 /*!
00812  * We use libxml2 in order to parse XML that may appear in the body of a SIP message. Currently,
00813  * the only usage is for parsing PIDF bodies of incoming PUBLISH requests in the call-completion
00814  * event package. This variable is set at module load time and may be checked at runtime to determine
00815  * if XML parsing support was found.
00816  */
00817 static int can_parse_xml;
00818 
00819 /*! \name Object counters @{
00820  *  \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
00821  *  should be used to modify these values. */
00822 static int speerobjs = 0;     /*!< Static peers */
00823 static int rpeerobjs = 0;     /*!< Realtime peers */
00824 static int apeerobjs = 0;     /*!< Autocreated peer objects */
00825 static int regobjs = 0;       /*!< Registry objects */
00826 /* }@ */
00827 
00828 static struct ast_flags global_flags[3] = {{0}};  /*!< global SIP_ flags */
00829 static int global_t38_maxdatagram;                /*!< global T.38 FaxMaxDatagram override */
00830 
00831 static struct ast_event_sub *network_change_event_subscription; /*!< subscription id for network change events */
00832 static struct ast_event_sub *acl_change_event_subscription; /*!< subscription id for named ACL system change events */
00833 static int network_change_event_sched_id = -1;
00834 
00835 static char used_context[AST_MAX_CONTEXT];        /*!< name of automatically created context for unloading */
00836 
00837 AST_MUTEX_DEFINE_STATIC(netlock);
00838 
00839 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
00840    when it's doing something critical. */
00841 AST_MUTEX_DEFINE_STATIC(monlock);
00842 
00843 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
00844 
00845 /*! \brief This is the thread for the monitor which checks for input on the channels
00846    which are not currently in use.  */
00847 static pthread_t monitor_thread = AST_PTHREADT_NULL;
00848 
00849 static int sip_reloading = FALSE;                       /*!< Flag for avoiding multiple reloads at the same time */
00850 static enum channelreloadreason sip_reloadreason;       /*!< Reason for last reload/load of configuration */
00851 
00852 struct ast_sched_context *sched;     /*!< The scheduling context */
00853 static struct io_context *io;           /*!< The IO context */
00854 static int *sipsock_read_id;            /*!< ID of IO entry for sipsock FD */
00855 struct sip_pkt;
00856 static AST_LIST_HEAD_STATIC(domain_list, domain);    /*!< The SIP domain list */
00857 
00858 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
00859 
00860 static enum sip_debug_e sipdebug;
00861 
00862 /*! \brief extra debugging for 'text' related events.
00863  *  At the moment this is set together with sip_debug_console.
00864  *  \note It should either go away or be implemented properly.
00865  */
00866 static int sipdebug_text;
00867 
00868 static const struct _map_x_s referstatusstrings[] = {
00869    { REFER_IDLE,      "<none>" },
00870    { REFER_SENT,      "Request sent" },
00871    { REFER_RECEIVED,  "Request received" },
00872    { REFER_CONFIRMED, "Confirmed" },
00873    { REFER_ACCEPTED,  "Accepted" },
00874    { REFER_RINGING,   "Target ringing" },
00875    { REFER_200OK,     "Done" },
00876    { REFER_FAILED,    "Failed" },
00877    { REFER_NOAUTH,    "Failed - auth failure" },
00878    { -1,               NULL} /* terminator */
00879 };
00880 
00881 /* --- Hash tables of various objects --------*/
00882 #ifdef LOW_MEMORY
00883 static const int HASH_PEER_SIZE = 17;
00884 static const int HASH_DIALOG_SIZE = 17;
00885 #else
00886 static const int HASH_PEER_SIZE = 563; /*!< Size of peer hash table, prime number preferred! */
00887 static const int HASH_DIALOG_SIZE = 563;
00888 #endif
00889 
00890 static const struct {
00891    enum ast_cc_service_type service;
00892    const char *service_string;
00893 } sip_cc_service_map [] = {
00894    [AST_CC_NONE] = { AST_CC_NONE, "" },
00895    [AST_CC_CCBS] = { AST_CC_CCBS, "BS" },
00896    [AST_CC_CCNR] = { AST_CC_CCNR, "NR" },
00897    [AST_CC_CCNL] = { AST_CC_CCNL, "NL" },
00898 };
00899 
00900 static enum ast_cc_service_type service_string_to_service_type(const char * const service_string)
00901 {
00902    enum ast_cc_service_type service;
00903    for (service = AST_CC_CCBS; service <= AST_CC_CCNL; ++service) {
00904       if (!strcasecmp(service_string, sip_cc_service_map[service].service_string)) {
00905          return service;
00906       }
00907    }
00908    return AST_CC_NONE;
00909 }
00910 
00911 static const struct {
00912    enum sip_cc_notify_state state;
00913    const char *state_string;
00914 } sip_cc_notify_state_map [] = {
00915    [CC_QUEUED] = {CC_QUEUED, "cc-state: queued"},
00916    [CC_READY] = {CC_READY, "cc-state: ready"},
00917 };
00918 
00919 AST_LIST_HEAD_STATIC(epa_static_data_list, epa_backend);
00920 
00921 static int sip_epa_register(const struct epa_static_data *static_data)
00922 {
00923    struct epa_backend *backend = ast_calloc(1, sizeof(*backend));
00924 
00925    if (!backend) {
00926       return -1;
00927    }
00928 
00929    backend->static_data = static_data;
00930 
00931    AST_LIST_LOCK(&epa_static_data_list);
00932    AST_LIST_INSERT_TAIL(&epa_static_data_list, backend, next);
00933    AST_LIST_UNLOCK(&epa_static_data_list);
00934    return 0;
00935 }
00936 
00937 static void sip_epa_unregister_all(void)
00938 {
00939    struct epa_backend *backend;
00940 
00941    AST_LIST_LOCK(&epa_static_data_list);
00942    while ((backend = AST_LIST_REMOVE_HEAD(&epa_static_data_list, next))) {
00943       ast_free(backend);
00944    }
00945    AST_LIST_UNLOCK(&epa_static_data_list);
00946 }
00947 
00948 static void cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry);
00949 
00950 static void cc_epa_destructor(void *data)
00951 {
00952    struct sip_epa_entry *epa_entry = data;
00953    struct cc_epa_entry *cc_entry = epa_entry->instance_data;
00954    ast_free(cc_entry);
00955 }
00956 
00957 static const struct epa_static_data cc_epa_static_data  = {
00958    .event = CALL_COMPLETION,
00959    .name = "call-completion",
00960    .handle_error = cc_handle_publish_error,
00961    .destructor = cc_epa_destructor,
00962 };
00963 
00964 static const struct epa_static_data *find_static_data(const char * const event_package)
00965 {
00966    const struct epa_backend *backend = NULL;
00967 
00968    AST_LIST_LOCK(&epa_static_data_list);
00969    AST_LIST_TRAVERSE(&epa_static_data_list, backend, next) {
00970       if (!strcmp(backend->static_data->name, event_package)) {
00971          break;
00972       }
00973    }
00974    AST_LIST_UNLOCK(&epa_static_data_list);
00975    return backend ? backend->static_data : NULL;
00976 }
00977 
00978 static struct sip_epa_entry *create_epa_entry (const char * const event_package, const char * const destination)
00979 {
00980    struct sip_epa_entry *epa_entry;
00981    const struct epa_static_data *static_data;
00982 
00983    if (!(static_data = find_static_data(event_package))) {
00984       return NULL;
00985    }
00986 
00987    if (!(epa_entry = ao2_t_alloc(sizeof(*epa_entry), static_data->destructor, "Allocate new EPA entry"))) {
00988       return NULL;
00989    }
00990 
00991    epa_entry->static_data = static_data;
00992    ast_copy_string(epa_entry->destination, destination, sizeof(epa_entry->destination));
00993    return epa_entry;
00994 }
00995 
00996 /*!
00997  * Used to create new entity IDs by ESCs.
00998  */
00999 static int esc_etag_counter;
01000 static const int DEFAULT_PUBLISH_EXPIRES = 3600;
01001 
01002 #ifdef HAVE_LIBXML2
01003 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);
01004 
01005 static const struct sip_esc_publish_callbacks cc_esc_publish_callbacks = {
01006    .initial_handler = cc_esc_publish_handler,
01007    .modify_handler = cc_esc_publish_handler,
01008 };
01009 #endif
01010 
01011 /*!
01012  * \brief The Event State Compositors
01013  *
01014  * An Event State Compositor is an entity which
01015  * accepts PUBLISH requests and acts appropriately
01016  * based on these requests.
01017  *
01018  * The actual event_state_compositor structure is simply
01019  * an ao2_container of sip_esc_entrys. When an incoming
01020  * PUBLISH is received, we can match the appropriate sip_esc_entry
01021  * using the entity ID of the incoming PUBLISH.
01022  */
01023 static struct event_state_compositor {
01024    enum subscriptiontype event;
01025    const char * name;
01026    const struct sip_esc_publish_callbacks *callbacks;
01027    struct ao2_container *compositor;
01028 } event_state_compositors [] = {
01029 #ifdef HAVE_LIBXML2
01030    {CALL_COMPLETION, "call-completion", &cc_esc_publish_callbacks},
01031 #endif
01032 };
01033 
01034 static const int ESC_MAX_BUCKETS = 37;
01035 
01036 static void esc_entry_destructor(void *obj)
01037 {
01038    struct sip_esc_entry *esc_entry = obj;
01039    if (esc_entry->sched_id > -1) {
01040       AST_SCHED_DEL(sched, esc_entry->sched_id);
01041    }
01042 }
01043 
01044 static int esc_hash_fn(const void *obj, const int flags)
01045 {
01046    const struct sip_esc_entry *entry = obj;
01047    return ast_str_hash(entry->entity_tag);
01048 }
01049 
01050 static int esc_cmp_fn(void *obj, void *arg, int flags)
01051 {
01052    struct sip_esc_entry *entry1 = obj;
01053    struct sip_esc_entry *entry2 = arg;
01054 
01055    return (!strcmp(entry1->entity_tag, entry2->entity_tag)) ? (CMP_MATCH | CMP_STOP) : 0;
01056 }
01057 
01058 static struct event_state_compositor *get_esc(const char * const event_package) {
01059    int i;
01060    for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
01061       if (!strcasecmp(event_package, event_state_compositors[i].name)) {
01062          return &event_state_compositors[i];
01063       }
01064    }
01065    return NULL;
01066 }
01067 
01068 static struct sip_esc_entry *get_esc_entry(const char * entity_tag, struct event_state_compositor *esc) {
01069    struct sip_esc_entry *entry;
01070    struct sip_esc_entry finder;
01071 
01072    ast_copy_string(finder.entity_tag, entity_tag, sizeof(finder.entity_tag));
01073 
01074    entry = ao2_find(esc->compositor, &finder, OBJ_POINTER);
01075 
01076    return entry;
01077 }
01078 
01079 static int publish_expire(const void *data)
01080 {
01081    struct sip_esc_entry *esc_entry = (struct sip_esc_entry *) data;
01082    struct event_state_compositor *esc = get_esc(esc_entry->event);
01083 
01084    ast_assert(esc != NULL);
01085 
01086    ao2_unlink(esc->compositor, esc_entry);
01087    ao2_ref(esc_entry, -1);
01088    return 0;
01089 }
01090 
01091 static void create_new_sip_etag(struct sip_esc_entry *esc_entry, int is_linked)
01092 {
01093    int new_etag = ast_atomic_fetchadd_int(&esc_etag_counter, +1);
01094    struct event_state_compositor *esc = get_esc(esc_entry->event);
01095 
01096    ast_assert(esc != NULL);
01097    if (is_linked) {
01098       ao2_unlink(esc->compositor, esc_entry);
01099    }
01100    snprintf(esc_entry->entity_tag, sizeof(esc_entry->entity_tag), "%d", new_etag);
01101    ao2_link(esc->compositor, esc_entry);
01102 }
01103 
01104 static struct sip_esc_entry *create_esc_entry(struct event_state_compositor *esc, struct sip_request *req, const int expires)
01105 {
01106    struct sip_esc_entry *esc_entry;
01107    int expires_ms;
01108 
01109    if (!(esc_entry = ao2_alloc(sizeof(*esc_entry), esc_entry_destructor))) {
01110       return NULL;
01111    }
01112 
01113    esc_entry->event = esc->name;
01114 
01115    expires_ms = expires * 1000;
01116    /* Bump refcount for scheduler */
01117    ao2_ref(esc_entry, +1);
01118    esc_entry->sched_id = ast_sched_add(sched, expires_ms, publish_expire, esc_entry);
01119 
01120    /* Note: This links the esc_entry into the ESC properly */
01121    create_new_sip_etag(esc_entry, 0);
01122 
01123    return esc_entry;
01124 }
01125 
01126 static int initialize_escs(void)
01127 {
01128    int i, res = 0;
01129    for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
01130       if (!((event_state_compositors[i].compositor) =
01131                ao2_container_alloc(ESC_MAX_BUCKETS, esc_hash_fn, esc_cmp_fn))) {
01132          res = -1;
01133       }
01134    }
01135    return res;
01136 }
01137 
01138 static void destroy_escs(void)
01139 {
01140    int i;
01141    for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
01142       ao2_ref(event_state_compositors[i].compositor, -1);
01143    }
01144 }
01145 
01146 struct state_notify_data {
01147    int state;
01148    struct ao2_container *device_state_info;
01149    int presence_state;
01150    const char *presence_subtype;
01151    const char *presence_message;
01152 };
01153 
01154 /*!
01155  * \details
01156  * Here we implement the container for dialogs which are in the
01157  * dialog_needdestroy state to iterate only through the dialogs
01158  * unlink them instead of iterate through all dialogs
01159  */
01160 struct ao2_container *dialogs_needdestroy;
01161 
01162 /*!
01163  * \details
01164  * Here we implement the container for dialogs which have rtp
01165  * traffic and rtptimeout, rtpholdtimeout or rtpkeepalive
01166  * set. We use this container instead the whole dialog list.
01167  */
01168 struct ao2_container *dialogs_rtpcheck;
01169 
01170 /*!
01171  * \details
01172  * Here we implement the container for dialogs (sip_pvt), defining
01173  * generic wrapper functions to ease the transition from the current
01174  * implementation (a single linked list) to a different container.
01175  * In addition to a reference to the container, we need functions to lock/unlock
01176  * the container and individual items, and functions to add/remove
01177  * references to the individual items.
01178  */
01179 static struct ao2_container *dialogs;
01180 #define sip_pvt_lock(x) ao2_lock(x)
01181 #define sip_pvt_trylock(x) ao2_trylock(x)
01182 #define sip_pvt_unlock(x) ao2_unlock(x)
01183 
01184 /*! \brief  The table of TCP threads */
01185 static struct ao2_container *threadt;
01186 
01187 /*! \brief  The peer list: Users, Peers and Friends */
01188 static struct ao2_container *peers;
01189 static struct ao2_container *peers_by_ip;
01190 
01191 /*! \brief  A bogus peer, to be used when authentication should fail */
01192 static struct sip_peer *bogus_peer;
01193 /*! \brief  We can recognise the bogus peer by this invalid MD5 hash */
01194 #define BOGUS_PEER_MD5SECRET "intentionally_invalid_md5_string"
01195 
01196 /*! \brief  The register list: Other SIP proxies we register with and receive calls from */
01197 static struct ast_register_list {
01198    ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
01199    int recheck;
01200 } regl;
01201 
01202 /*! \brief  The MWI subscription list */
01203 static struct ast_subscription_mwi_list {
01204    ASTOBJ_CONTAINER_COMPONENTS(struct sip_subscription_mwi);
01205 } submwil;
01206 static int temp_pvt_init(void *);
01207 static void temp_pvt_cleanup(void *);
01208 
01209 /*! \brief A per-thread temporary pvt structure */
01210 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
01211 
01212 /*! \brief A per-thread buffer for transport to string conversion */
01213 AST_THREADSTORAGE(sip_transport_str_buf);
01214 
01215 /*! \brief Size of the SIP transport buffer */
01216 #define SIP_TRANSPORT_STR_BUFSIZE 128
01217 
01218 /*! \brief Authentication container for realm authentication */
01219 static struct sip_auth_container *authl = NULL;
01220 /*! \brief Global authentication container protection while adjusting the references. */
01221 AST_MUTEX_DEFINE_STATIC(authl_lock);
01222 
01223 /* --- Sockets and networking --------------*/
01224 
01225 /*! \brief Main socket for UDP SIP communication.
01226  *
01227  * sipsock is shared between the SIP manager thread (which handles reload
01228  * requests), the udp io handler (sipsock_read()) and the user routines that
01229  * issue udp writes (using __sip_xmit()).
01230  * The socket is -1 only when opening fails (this is a permanent condition),
01231  * or when we are handling a reload() that changes its address (this is
01232  * a transient situation during which we might have a harmless race, see
01233  * below). Because the conditions for the race to be possible are extremely
01234  * rare, we don't want to pay the cost of locking on every I/O.
01235  * Rather, we remember that when the race may occur, communication is
01236  * bound to fail anyways, so we just live with this event and let
01237  * the protocol handle this above us.
01238  */
01239 static int sipsock  = -1;
01240 
01241 struct ast_sockaddr bindaddr; /*!< UDP: The address we bind to */
01242 
01243 /*! \brief our (internal) default address/port to put in SIP/SDP messages
01244  *  internip is initialized picking a suitable address from one of the
01245  * interfaces, and the same port number we bind to. It is used as the
01246  * default address/port in SIP messages, and as the default address
01247  * (but not port) in SDP messages.
01248  */
01249 static struct ast_sockaddr internip;
01250 
01251 /*! \brief our external IP address/port for SIP sessions.
01252  * externaddr.sin_addr is only set when we know we might be behind
01253  * a NAT, and this is done using a variety of (mutually exclusive)
01254  * ways from the config file:
01255  *
01256  * + with "externaddr = host[:port]" we specify the address/port explicitly.
01257  *   The address is looked up only once when (re)loading the config file;
01258  *
01259  * + with "externhost = host[:port]" we do a similar thing, but the
01260  *   hostname is stored in externhost, and the hostname->IP mapping
01261  *   is refreshed every 'externrefresh' seconds;
01262  *
01263  * Other variables (externhost, externexpire, externrefresh) are used
01264  * to support the above functions.
01265  */
01266 static struct ast_sockaddr externaddr;      /*!< External IP address if we are behind NAT */
01267 static struct ast_sockaddr media_address; /*!< External RTP IP address if we are behind NAT */
01268 
01269 static char externhost[MAXHOSTNAMELEN];   /*!< External host name */
01270 static time_t externexpire;             /*!< Expiration counter for re-resolving external host name in dynamic DNS */
01271 static int externrefresh = 10;          /*!< Refresh timer for DNS-based external address (dyndns) */
01272 static uint16_t externtcpport;          /*!< external tcp port */
01273 static uint16_t externtlsport;          /*!< external tls port */
01274 
01275 /*! \brief  List of local networks
01276  * We store "localnet" addresses from the config file into an access list,
01277  * marked as 'DENY', so the call to ast_apply_ha() will return
01278  * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
01279  * (i.e. presumably public) addresses.
01280  */
01281 static struct ast_ha *localaddr;    /*!< List of local networks, on the same side of NAT as this Asterisk */
01282 
01283 static int ourport_tcp;             /*!< The port used for TCP connections */
01284 static int ourport_tls;             /*!< The port used for TCP/TLS connections */
01285 static struct ast_sockaddr debugaddr;
01286 
01287 static struct ast_config *notify_types = NULL;    /*!< The list of manual NOTIFY types we know how to send */
01288 
01289 /*! some list management macros. */
01290 
01291 #define UNLINK(element, head, prev) do {  \
01292    if (prev)            \
01293       (prev)->next = (element)->next;  \
01294    else              \
01295       (head) = (element)->next;  \
01296    } while (0)
01297 
01298 struct show_peers_context;
01299 
01300 /*---------------------------- Forward declarations of functions in chan_sip.c */
01301 /* Note: This is added to help splitting up chan_sip.c into several files
01302    in coming releases. */
01303 
01304 /*--- PBX interface functions */
01305 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);
01306 static int sip_devicestate(const char *data);
01307 static int sip_sendtext(struct ast_channel *ast, const char *text);
01308 static int sip_call(struct ast_channel *ast, const char *dest, int timeout);
01309 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
01310 static int sip_hangup(struct ast_channel *ast);
01311 static int sip_answer(struct ast_channel *ast);
01312 static struct ast_frame *sip_read(struct ast_channel *ast);
01313 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
01314 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
01315 static int sip_transfer(struct ast_channel *ast, const char *dest);
01316 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
01317 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
01318 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
01319 static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen);
01320 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
01321 static const char *sip_get_callid(struct ast_channel *chan);
01322 
01323 static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr);
01324 static int sip_standard_port(enum sip_transport type, int port);
01325 static int sip_prepare_socket(struct sip_pvt *p);
01326 static int get_address_family_filter(unsigned int transport);
01327 
01328 /*--- Transmitting responses and requests */
01329 static int sipsock_read(int *id, int fd, short events, void *ignore);
01330 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data);
01331 static int __sip_reliable_xmit(struct sip_pvt *p, uint32_t seqno, int resp, struct ast_str *data, int fatal, int sipmethod);
01332 static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp);
01333 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
01334 static int retrans_pkt(const void *data);
01335 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);
01336 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01337 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01338 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01339 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);
01340 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
01341 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);
01342 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
01343 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
01344 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable);
01345 static int transmit_request(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch);
01346 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch);
01347 static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri);
01348 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri);
01349 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
01350 static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded);
01351 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
01352 static int transmit_info_with_vidupdate(struct sip_pvt *p);
01353 static int transmit_message(struct sip_pvt *p, int init, int auth);
01354 static int transmit_refer(struct sip_pvt *p, const char *dest);
01355 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
01356 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
01357 static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state);
01358 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
01359 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno);
01360 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno);
01361 static void copy_request(struct sip_request *dst, const struct sip_request *src);
01362 static void receive_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
01363 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward);
01364 static int sip_send_mwi_to_peer(struct sip_peer *peer, int cache_only);
01365 
01366 /* Misc dialog routines */
01367 static int __sip_autodestruct(const void *data);
01368 static void *registry_unref(struct sip_registry *reg, char *tag);
01369 static int update_call_counter(struct sip_pvt *fup, int event);
01370 static int auto_congest(const void *arg);
01371 static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method);
01372 static void free_old_route(struct sip_route *route);
01373 static void list_route(struct sip_route *route);
01374 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards, int resp);
01375 static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
01376                      struct sip_request *req, const char *uri);
01377 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
01378 static void check_pendings(struct sip_pvt *p);
01379 static void *sip_park_thread(void *stuff);
01380 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);
01381 
01382 static void *sip_pickup_thread(void *stuff);
01383 static int sip_pickup(struct ast_channel *chan);
01384 
01385 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
01386 static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method);
01387 
01388 /*--- Codec handling / SDP */
01389 static void try_suggested_sip_codec(struct sip_pvt *p);
01390 static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
01391 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
01392 static int find_sdp(struct sip_request *req);
01393 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
01394 static int process_sdp_o(const char *o, struct sip_pvt *p);
01395 static int process_sdp_c(const char *c, struct ast_sockaddr *addr);
01396 static int process_sdp_a_sendonly(const char *a, int *sendonly);
01397 static int process_sdp_a_ice(const char *a, struct sip_pvt *p, struct ast_rtp_instance *instance);
01398 static int process_sdp_a_dtls(const char *a, struct sip_pvt *p, struct ast_rtp_instance *instance);
01399 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec);
01400 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec);
01401 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);
01402 static int process_sdp_a_image(const char *a, struct sip_pvt *p);
01403 static void add_ice_to_sdp(struct ast_rtp_instance *instance, struct ast_str **a_buf);
01404 static void add_dtls_to_sdp(struct ast_rtp_instance *instance, struct ast_str **a_buf);
01405 static void start_ice(struct ast_rtp_instance *instance);
01406 static void add_codec_to_sdp(const struct sip_pvt *p, struct ast_format *codec,
01407               struct ast_str **m_buf, struct ast_str **a_buf,
01408               int debug, int *min_packet_size);
01409 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
01410             struct ast_str **m_buf, struct ast_str **a_buf,
01411             int debug);
01412 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
01413 static void do_setnat(struct sip_pvt *p);
01414 static void stop_media_flows(struct sip_pvt *p);
01415 
01416 /*--- Authentication stuff */
01417 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
01418 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
01419 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
01420                 const char *secret, const char *md5secret, int sipmethod,
01421                 const char *uri, enum xmittype reliable);
01422 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
01423                      int sipmethod, const char *uri, enum xmittype reliable,
01424                      struct ast_sockaddr *addr, struct sip_peer **authpeer);
01425 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr);
01426 
01427 /*--- Domain handling */
01428 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
01429 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
01430 static void clear_sip_domains(void);
01431 
01432 /*--- SIP realm authentication */
01433 static void add_realm_authentication(struct sip_auth_container **credentials, const char *configuration, int lineno);
01434 static struct sip_auth *find_realm_authentication(struct sip_auth_container *credentials, const char *realm);
01435 
01436 /*--- Misc functions */
01437 static int check_rtp_timeout(struct sip_pvt *dialog, time_t t);
01438 static int reload_config(enum channelreloadreason reason);
01439 static void add_diversion(struct sip_request *req, struct sip_pvt *pvt);
01440 static int expire_register(const void *data);
01441 static void *do_monitor(void *data);
01442 static int restart_monitor(void);
01443 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
01444 static struct ast_variable *copy_vars(struct ast_variable *src);
01445 static int dialog_find_multiple(void *obj, void *arg, int flags);
01446 static struct ast_channel *sip_pvt_lock_full(struct sip_pvt *pvt);
01447 /* static int sip_addrcmp(char *name, struct sockaddr_in *sin);   Support for peer matching */
01448 static int sip_refer_alloc(struct sip_pvt *p);
01449 static int sip_notify_alloc(struct sip_pvt *p);
01450 static void ast_quiet_chan(struct ast_channel *chan);
01451 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
01452 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
01453 static void set_peer_nat(const struct sip_pvt *p, struct sip_peer *peer);
01454 static void check_for_nat(const struct ast_sockaddr *them, struct sip_pvt *p);
01455 
01456 /*--- Device monitoring and Device/extension state/event handling */
01457 static int extensionstate_update(const char *context, const char *exten, struct state_notify_data *data, struct sip_pvt *p, int force);
01458 static int cb_extensionstate(char *context, char *exten, struct ast_state_cb_info *info, void *data);
01459 static int sip_poke_noanswer(const void *data);
01460 static int sip_poke_peer(struct sip_peer *peer, int force);
01461 static void sip_poke_all_peers(void);
01462 static void sip_peer_hold(struct sip_pvt *p, int hold);
01463 static void mwi_event_cb(const struct ast_event *, void *);
01464 static void network_change_event_cb(const struct ast_event *, void *);
01465 static void acl_change_event_cb(const struct ast_event *event, void *userdata);
01466 static void sip_keepalive_all_peers(void);
01467 
01468 /*--- Applications, functions, CLI and manager command helpers */
01469 static const char *sip_nat_mode(const struct sip_pvt *p);
01470 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01471 static char *transfermode2str(enum transfermodes mode) attribute_const;
01472 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
01473 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01474 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01475 static struct sip_peer *_sip_show_peers_one(int fd, struct mansession *s, struct show_peers_context *cont, struct sip_peer *peer);
01476 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01477 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01478 static void  print_group(int fd, ast_group_t group, int crlf);
01479 static void  print_named_groups(int fd, struct ast_namedgroups *groups, int crlf);
01480 static const char *dtmfmode2str(int mode) attribute_const;
01481 static int str2dtmfmode(const char *str) attribute_unused;
01482 static const char *insecure2str(int mode) attribute_const;
01483 static const char *allowoverlap2str(int mode) attribute_const;
01484 static void cleanup_stale_contexts(char *new, char *old);
01485 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
01486 static const char *domain_mode_to_text(const enum domain_mode mode);
01487 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01488 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01489 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01490 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01491 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01492 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01493 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01494 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01495 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01496 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
01497 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
01498 static char *complete_sip_peer(const char *word, int state, int flags2);
01499 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
01500 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
01501 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
01502 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
01503 static char *complete_sip_notify(const char *line, const char *word, int pos, int state);
01504 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01505 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01506 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01507 static char *sip_do_debug_ip(int fd, const char *arg);
01508 static char *sip_do_debug_peer(int fd, const char *arg);
01509 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01510 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01511 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01512 static int sip_dtmfmode(struct ast_channel *chan, const char *data);
01513 static int sip_addheader(struct ast_channel *chan, const char *data);
01514 static int sip_do_reload(enum channelreloadreason reason);
01515 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01516 static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
01517                   const char *name, int flag, int family);
01518 static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
01519                   const char *name, int flag);
01520 static int ast_sockaddr_resolve_first_transport(struct ast_sockaddr *addr,
01521                   const char *name, int flag, unsigned int transport);
01522 
01523 /*--- Debugging
01524    Functions for enabling debug per IP or fully, or enabling history logging for
01525    a SIP dialog
01526 */
01527 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to debuglog at end of dialog, before destroying data */
01528 static inline int sip_debug_test_addr(const struct ast_sockaddr *addr);
01529 static inline int sip_debug_test_pvt(struct sip_pvt *p);
01530 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
01531 static void sip_dump_history(struct sip_pvt *dialog);
01532 
01533 /*--- Device object handling */
01534 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
01535 static int update_call_counter(struct sip_pvt *fup, int event);
01536 static void sip_destroy_peer(struct sip_peer *peer);
01537 static void sip_destroy_peer_fn(void *peer);
01538 static void set_peer_defaults(struct sip_peer *peer);
01539 static struct sip_peer *temp_peer(const char *name);
01540 static void register_peer_exten(struct sip_peer *peer, int onoff);
01541 static int sip_poke_peer_s(const void *data);
01542 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
01543 static void reg_source_db(struct sip_peer *peer);
01544 static void destroy_association(struct sip_peer *peer);
01545 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
01546 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
01547 static void set_socket_transport(struct sip_socket *socket, int transport);
01548 static int peer_ipcmp_cb_full(void *obj, void *arg, void *data, int flags);
01549 
01550 /* Realtime device support */
01551 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);
01552 static void update_peer(struct sip_peer *p, int expire);
01553 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
01554 static const char *get_name_from_variable(const struct ast_variable *var);
01555 static struct sip_peer *realtime_peer(const char *peername, struct ast_sockaddr *sin, char *callbackexten, int devstate_only, int which_objects);
01556 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01557 
01558 /*--- Internal UA client handling (outbound registrations) */
01559 static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p);
01560 static void sip_registry_destroy(struct sip_registry *reg);
01561 static int sip_register(const char *value, int lineno);
01562 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
01563 static int sip_reregister(const void *data);
01564 static int __sip_do_register(struct sip_registry *r);
01565 static int sip_reg_timeout(const void *data);
01566 static void sip_send_all_registers(void);
01567 static int sip_reinvite_retry(const void *data);
01568 
01569 /*--- Parsing SIP requests and responses */
01570 static int determine_firstline_parts(struct sip_request *req);
01571 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
01572 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
01573 static int find_sip_method(const char *msg);
01574 static unsigned int parse_allowed_methods(struct sip_request *req);
01575 static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req);
01576 static int parse_request(struct sip_request *req);
01577 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
01578 static int method_match(enum sipmethod id, const char *name);
01579 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
01580 static void parse_oli(struct sip_request *req, struct ast_channel *chan);
01581 static const char *find_alias(const char *name, const char *_default);
01582 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
01583 static void lws2sws(struct ast_str *msgbuf);
01584 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
01585 static char *remove_uri_parameters(char *uri);
01586 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
01587 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
01588 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
01589 static int set_address_from_contact(struct sip_pvt *pvt);
01590 static void check_via(struct sip_pvt *p, const struct sip_request *req);
01591 static int get_rpid(struct sip_pvt *p, struct sip_request *oreq);
01592 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason);
01593 static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id);
01594 static int transmit_state_notify(struct sip_pvt *p, struct state_notify_data *data, int full, int timeout);
01595 static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen);
01596 static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen);
01597 static int get_domain(const char *str, char *domain, int len);
01598 static void get_realm(struct sip_pvt *p, const struct sip_request *req);
01599 static char *get_content(struct sip_request *req);
01600 
01601 /*-- TCP connection handling ---*/
01602 static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session);
01603 static void *sip_tcp_worker_fn(void *);
01604 
01605 /*--- Constructing requests and responses */
01606 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
01607 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
01608 static void deinit_req(struct sip_request *req);
01609 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, uint32_t seqno, int newbranch);
01610 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri);
01611 static int init_resp(struct sip_request *resp, const char *msg);
01612 static inline int resp_needs_contact(const char *msg, enum sipmethod method);
01613 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
01614 static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p);
01615 static void build_via(struct sip_pvt *p);
01616 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
01617 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog);
01618 static char *generate_random_string(char *buf, size_t size);
01619 static void build_callid_pvt(struct sip_pvt *pvt);
01620 static void change_callid_pvt(struct sip_pvt *pvt, const char *callid);
01621 static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain);
01622 static void build_localtag_registry(struct sip_registry *reg);
01623 static void make_our_tag(struct sip_pvt *pvt);
01624 static int add_header(struct sip_request *req, const char *var, const char *value);
01625 static int add_max_forwards(struct sip_pvt *dialog, struct sip_request *req);
01626 static int add_content(struct sip_request *req, const char *line);
01627 static int finalize_content(struct sip_request *req);
01628 static void destroy_msg_headers(struct sip_pvt *pvt);
01629 static int add_text(struct sip_request *req, struct sip_pvt *p);
01630 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
01631 static int add_rpid(struct sip_request *req, struct sip_pvt *p);
01632 static int add_vidupdate(struct sip_request *req);
01633 static void add_route(struct sip_request *req, struct sip_route *route);
01634 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
01635 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
01636 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
01637 static void set_destination(struct sip_pvt *p, char *uri);
01638 static void add_date(struct sip_request *req);
01639 static void add_expires(struct sip_request *req, int expires);
01640 static void build_contact(struct sip_pvt *p);
01641 
01642 /*------Request handling functions */
01643 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock);
01644 static int handle_request_update(struct sip_pvt *p, struct sip_request *req);
01645 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);
01646 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, uint32_t seqno, int *nounlock);
01647 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
01648 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *sin, const char *e);
01649 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
01650 static int handle_request_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
01651 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
01652 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
01653 static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
01654 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, int *nounlock);
01655 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
01656 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, uint32_t seqno, int *nounlock);
01657 
01658 /*------Response handling functions */
01659 static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01660 static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01661 static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01662 static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01663 static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01664 static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01665 static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01666 
01667 /*------ SRTP Support -------- */
01668 static int setup_srtp(struct sip_srtp **srtp);
01669 static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct sip_srtp **srtp, const char *a);
01670 
01671 /*------ T38 Support --------- */
01672 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
01673 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
01674 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
01675 static void change_t38_state(struct sip_pvt *p, int state);
01676 
01677 /*------ Session-Timers functions --------- */
01678 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
01679 static int  proc_session_timer(const void *vp);
01680 static void stop_session_timer(struct sip_pvt *p);
01681 static void start_session_timer(struct sip_pvt *p);
01682 static void restart_session_timer(struct sip_pvt *p);
01683 static const char *strefresherparam2str(enum st_refresher r);
01684 static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher_param *const p_ref);
01685 static int parse_minse(const char *p_hdrval, int *const p_interval);
01686 static int st_get_se(struct sip_pvt *, int max);
01687 static enum st_refresher st_get_refresher(struct sip_pvt *);
01688 static enum st_mode st_get_mode(struct sip_pvt *, int no_cached);
01689 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
01690 
01691 /*------- RTP Glue functions -------- */
01692 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);
01693 
01694 /*!--- SIP MWI Subscription support */
01695 static int sip_subscribe_mwi(const char *value, int lineno);
01696 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi);
01697 static void sip_send_all_mwi_subscriptions(void);
01698 static int sip_subscribe_mwi_do(const void *data);
01699 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
01700 
01701 /*! \brief Definition of this channel for PBX channel registration */
01702 struct ast_channel_tech sip_tech = {
01703    .type = "SIP",
01704    .description = "Session Initiation Protocol (SIP)",
01705    .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
01706    .requester = sip_request_call,         /* called with chan unlocked */
01707    .devicestate = sip_devicestate,        /* called with chan unlocked (not chan-specific) */
01708    .call = sip_call,       /* called with chan locked */
01709    .send_html = sip_sendhtml,
01710    .hangup = sip_hangup,         /* called with chan locked */
01711    .answer = sip_answer,         /* called with chan locked */
01712    .read = sip_read,       /* called with chan locked */
01713    .write = sip_write,        /* called with chan locked */
01714    .write_video = sip_write,     /* called with chan locked */
01715    .write_text = sip_write,
01716    .indicate = sip_indicate,     /* called with chan locked */
01717    .transfer = sip_transfer,     /* called with chan locked */
01718    .fixup = sip_fixup,        /* called with chan locked */
01719    .send_digit_begin = sip_senddigit_begin,  /* called with chan unlocked */
01720    .send_digit_end = sip_senddigit_end,
01721    .bridge = ast_rtp_instance_bridge,        /* XXX chan unlocked ? */
01722    .early_bridge = ast_rtp_instance_early_bridge,
01723    .send_text = sip_sendtext,    /* called with chan locked */
01724    .func_channel_read = sip_acf_channel_read,
01725    .setoption = sip_setoption,
01726    .queryoption = sip_queryoption,
01727    .get_pvt_uniqueid = sip_get_callid,
01728 };
01729 
01730 /*! \brief This version of the sip channel tech has no send_digit_begin
01731  * callback so that the core knows that the channel does not want
01732  * DTMF BEGIN frames.
01733  * The struct is initialized just before registering the channel driver,
01734  * and is for use with channels using SIP INFO DTMF.
01735  */
01736 struct ast_channel_tech sip_tech_info;
01737 
01738 /*------- CC Support -------- */
01739 static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan);
01740 static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent);
01741 static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent);
01742 static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason);
01743 static int sip_cc_agent_status_request(struct ast_cc_agent *agent);
01744 static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent);
01745 static int sip_cc_agent_recall(struct ast_cc_agent *agent);
01746 static void sip_cc_agent_destructor(struct ast_cc_agent *agent);
01747 
01748 static struct ast_cc_agent_callbacks sip_cc_agent_callbacks = {
01749    .type = "SIP",
01750    .init = sip_cc_agent_init,
01751    .start_offer_timer = sip_cc_agent_start_offer_timer,
01752    .stop_offer_timer = sip_cc_agent_stop_offer_timer,
01753    .respond = sip_cc_agent_respond,
01754    .status_request = sip_cc_agent_status_request,
01755    .start_monitoring = sip_cc_agent_start_monitoring,
01756    .callee_available = sip_cc_agent_recall,
01757    .destructor = sip_cc_agent_destructor,
01758 };
01759 
01760 static int find_by_notify_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->notify_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
01767 }
01768 
01769 static struct ast_cc_agent *find_sip_cc_agent_by_notify_uri(const char * const uri)
01770 {
01771    struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_notify_uri_helper, (char *)uri, "SIP");
01772    return agent;
01773 }
01774 
01775 static int find_by_subscribe_uri_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    const char *uri = arg;
01780 
01781    return !sip_uri_cmp(agent_pvt->subscribe_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
01782 }
01783 
01784 static struct ast_cc_agent *find_sip_cc_agent_by_subscribe_uri(const char * const uri)
01785 {
01786    struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_subscribe_uri_helper, (char *)uri, "SIP");
01787    return agent;
01788 }
01789 
01790 static int find_by_callid_helper(void *obj, void *arg, int flags)
01791 {
01792    struct ast_cc_agent *agent = obj;
01793    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01794    struct sip_pvt *call_pvt = arg;
01795 
01796    return !strcmp(agent_pvt->original_callid, call_pvt->callid) ? CMP_MATCH | CMP_STOP : 0;
01797 }
01798 
01799 static struct ast_cc_agent *find_sip_cc_agent_by_original_callid(struct sip_pvt *pvt)
01800 {
01801    struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_callid_helper, pvt, "SIP");
01802    return agent;
01803 }
01804 
01805 static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan)
01806 {
01807    struct sip_cc_agent_pvt *agent_pvt = ast_calloc(1, sizeof(*agent_pvt));
01808    struct sip_pvt *call_pvt = ast_channel_tech_pvt(chan);
01809 
01810    if (!agent_pvt) {
01811       return -1;
01812    }
01813 
01814    ast_assert(!strcmp(ast_channel_tech(chan)->type, "SIP"));
01815 
01816    ast_copy_string(agent_pvt->original_callid, call_pvt->callid, sizeof(agent_pvt->original_callid));
01817    ast_copy_string(agent_pvt->original_exten, call_pvt->exten, sizeof(agent_pvt->original_exten));
01818    agent_pvt->offer_timer_id = -1;
01819    agent->private_data = agent_pvt;
01820    sip_pvt_lock(call_pvt);
01821    ast_set_flag(&call_pvt->flags[0], SIP_OFFER_CC);
01822    sip_pvt_unlock(call_pvt);
01823    return 0;
01824 }
01825 
01826 static int sip_offer_timer_expire(const void *data)
01827 {
01828    struct ast_cc_agent *agent = (struct ast_cc_agent *) data;
01829    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01830 
01831    agent_pvt->offer_timer_id = -1;
01832 
01833    return ast_cc_failed(agent->core_id, "SIP agent %s's offer timer expired", agent->device_name);
01834 }
01835 
01836 static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent)
01837 {
01838    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01839    int when;
01840 
01841    when = ast_get_cc_offer_timer(agent->cc_params) * 1000;
01842    agent_pvt->offer_timer_id = ast_sched_add(sched, when, sip_offer_timer_expire, agent);
01843    return 0;
01844 }
01845 
01846 static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent)
01847 {
01848    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01849 
01850    AST_SCHED_DEL(sched, agent_pvt->offer_timer_id);
01851    return 0;
01852 }
01853 
01854 static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason)
01855 {
01856    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01857 
01858    sip_pvt_lock(agent_pvt->subscribe_pvt);
01859    ast_set_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
01860    if (reason == AST_CC_AGENT_RESPONSE_SUCCESS || !ast_strlen_zero(agent_pvt->notify_uri)) {
01861       /* The second half of this if statement may be a bit hard to grasp,
01862        * so here's an explanation. When a subscription comes into
01863        * chan_sip, as long as it is not malformed, it will be passed
01864        * to the CC core. If the core senses an out-of-order state transition,
01865        * then the core will call this callback with the "reason" set to a
01866        * failure condition.
01867        * However, an out-of-order state transition will occur during a resubscription
01868        * for CC. In such a case, we can see that we have already generated a notify_uri
01869        * and so we can detect that this isn't a *real* failure. Rather, it is just
01870        * something the core doesn't recognize as a legitimate SIP state transition.
01871        * Thus we respond with happiness and flowers.
01872        */
01873       transmit_response(agent_pvt->subscribe_pvt, "200 OK", &agent_pvt->subscribe_pvt->initreq);
01874       transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_QUEUED);
01875    } else {
01876       transmit_response(agent_pvt->subscribe_pvt, "500 Internal Error", &agent_pvt->subscribe_pvt->initreq);
01877    }
01878    sip_pvt_unlock(agent_pvt->subscribe_pvt);
01879    agent_pvt->is_available = TRUE;
01880 }
01881 
01882 static int sip_cc_agent_status_request(struct ast_cc_agent *agent)
01883 {
01884    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01885    enum ast_device_state state = agent_pvt->is_available ? AST_DEVICE_NOT_INUSE : AST_DEVICE_INUSE;
01886    return ast_cc_agent_status_response(agent->core_id, state);
01887 }
01888 
01889 static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent)
01890 {
01891    /* To start monitoring just means to wait for an incoming PUBLISH
01892     * to tell us that the caller has become available again. No special
01893     * action is needed
01894     */
01895    return 0;
01896 }
01897 
01898 static int sip_cc_agent_recall(struct ast_cc_agent *agent)
01899 {
01900    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01901    /* If we have received a PUBLISH beforehand stating that the caller in question
01902     * is not available, we can save ourself a bit of effort here and just report
01903     * the caller as busy
01904     */
01905    if (!agent_pvt->is_available) {
01906       return ast_cc_agent_caller_busy(agent->core_id, "Caller %s is busy, reporting to the core",
01907             agent->device_name);
01908    }
01909    /* Otherwise, we transmit a NOTIFY to the caller and await either
01910     * a PUBLISH or an INVITE
01911     */
01912    sip_pvt_lock(agent_pvt->subscribe_pvt);
01913    transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_READY);
01914    sip_pvt_unlock(agent_pvt->subscribe_pvt);
01915    return 0;
01916 }
01917 
01918 static void sip_cc_agent_destructor(struct ast_cc_agent *agent)
01919 {
01920    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01921 
01922    if (!agent_pvt) {
01923       /* The agent constructor probably failed. */
01924       return;
01925    }
01926 
01927    sip_cc_agent_stop_offer_timer(agent);
01928    if (agent_pvt->subscribe_pvt) {
01929       sip_pvt_lock(agent_pvt->subscribe_pvt);
01930       if (!ast_test_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
01931          /* If we haven't sent a 200 OK for the SUBSCRIBE dialog yet, then we need to send a response letting
01932           * the subscriber know something went wrong
01933           */
01934          transmit_response(agent_pvt->subscribe_pvt, "500 Internal Server Error", &agent_pvt->subscribe_pvt->initreq);
01935       }
01936       sip_pvt_unlock(agent_pvt->subscribe_pvt);
01937       agent_pvt->subscribe_pvt = dialog_unref(agent_pvt->subscribe_pvt, "SIP CC agent destructor: Remove ref to subscription");
01938    }
01939    ast_free(agent_pvt);
01940 }
01941 
01942 struct ao2_container *sip_monitor_instances;
01943 
01944 static int sip_monitor_instance_hash_fn(const void *obj, const int flags)
01945 {
01946    const struct sip_monitor_instance *monitor_instance = obj;
01947    return monitor_instance->core_id;
01948 }
01949 
01950 static int sip_monitor_instance_cmp_fn(void *obj, void *arg, int flags)
01951 {
01952    struct sip_monitor_instance *monitor_instance1 = obj;
01953    struct sip_monitor_instance *monitor_instance2 = arg;
01954 
01955    return monitor_instance1->core_id == monitor_instance2->core_id ? CMP_MATCH | CMP_STOP : 0;
01956 }
01957 
01958 static void sip_monitor_instance_destructor(void *data)
01959 {
01960    struct sip_monitor_instance *monitor_instance = data;
01961    if (monitor_instance->subscription_pvt) {
01962       sip_pvt_lock(monitor_instance->subscription_pvt);
01963       monitor_instance->subscription_pvt->expiry = 0;
01964       transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 0, monitor_instance->subscribe_uri);
01965       sip_pvt_unlock(monitor_instance->subscription_pvt);
01966       dialog_unref(monitor_instance->subscription_pvt, "Unref monitor instance ref of subscription pvt");
01967    }
01968    if (monitor_instance->suspension_entry) {
01969       monitor_instance->suspension_entry->body[0] = '\0';
01970       transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_REMOVE ,monitor_instance->notify_uri);
01971       ao2_t_ref(monitor_instance->suspension_entry, -1, "Decrementing suspension entry refcount in sip_monitor_instance_destructor");
01972    }
01973    ast_string_field_free_memory(monitor_instance);
01974 }
01975 
01976 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)
01977 {
01978    struct sip_monitor_instance *monitor_instance = ao2_alloc(sizeof(*monitor_instance), sip_monitor_instance_destructor);
01979 
01980    if (!monitor_instance) {
01981       return NULL;
01982    }
01983 
01984    if (ast_string_field_init(monitor_instance, 256)) {
01985       ao2_ref(monitor_instance, -1);
01986       return NULL;
01987    }
01988 
01989    ast_string_field_set(monitor_instance, subscribe_uri, subscribe_uri);
01990    ast_string_field_set(monitor_instance, peername, peername);
01991    ast_string_field_set(monitor_instance, device_name, device_name);
01992    monitor_instance->core_id = core_id;
01993    ao2_link(sip_monitor_instances, monitor_instance);
01994    return monitor_instance;
01995 }
01996 
01997 static int find_sip_monitor_instance_by_subscription_pvt(void *obj, void *arg, int flags)
01998 {
01999    struct sip_monitor_instance *monitor_instance = obj;
02000    return monitor_instance->subscription_pvt == arg ? CMP_MATCH | CMP_STOP : 0;
02001 }
02002 
02003 static int find_sip_monitor_instance_by_suspension_entry(void *obj, void *arg, int flags)
02004 {
02005    struct sip_monitor_instance *monitor_instance = obj;
02006    return monitor_instance->suspension_entry == arg ? CMP_MATCH | CMP_STOP : 0;
02007 }
02008 
02009 static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id);
02010 static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor);
02011 static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor);
02012 static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id);
02013 static void sip_cc_monitor_destructor(void *private_data);
02014 
02015 static struct ast_cc_monitor_callbacks sip_cc_monitor_callbacks = {
02016    .type = "SIP",
02017    .request_cc = sip_cc_monitor_request_cc,
02018    .suspend = sip_cc_monitor_suspend,
02019    .unsuspend = sip_cc_monitor_unsuspend,
02020    .cancel_available_timer = sip_cc_monitor_cancel_available_timer,
02021    .destructor = sip_cc_monitor_destructor,
02022 };
02023 
02024 static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id)
02025 {
02026    struct sip_monitor_instance *monitor_instance = monitor->private_data;
02027    enum ast_cc_service_type service = monitor->service_offered;
02028    int when;
02029 
02030    if (!monitor_instance) {
02031       return -1;
02032    }
02033 
02034    if (!(monitor_instance->subscription_pvt = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL, NULL))) {
02035       return -1;
02036    }
02037 
02038    when = service == AST_CC_CCBS ? ast_get_ccbs_available_timer(monitor->interface->config_params) :
02039       ast_get_ccnr_available_timer(monitor->interface->config_params);
02040 
02041    sip_pvt_lock(monitor_instance->subscription_pvt);
02042    ast_set_flag(&monitor_instance->subscription_pvt->flags[0], SIP_OUTGOING);
02043    create_addr(monitor_instance->subscription_pvt, monitor_instance->peername, 0, 1);
02044    ast_sip_ouraddrfor(&monitor_instance->subscription_pvt->sa, &monitor_instance->subscription_pvt->ourip, monitor_instance->subscription_pvt);
02045    monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
02046    monitor_instance->subscription_pvt->expiry = when;
02047 
02048    transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 2, monitor_instance->subscribe_uri);
02049    sip_pvt_unlock(monitor_instance->subscription_pvt);
02050 
02051    ao2_t_ref(monitor, +1, "Adding a ref to the monitor for the scheduler");
02052    *available_timer_id = ast_sched_add(sched, when * 1000, ast_cc_available_timer_expire, monitor);
02053    return 0;
02054 }
02055 
02056 static int construct_pidf_body(enum sip_cc_publish_state state, char *pidf_body, size_t size, const char *presentity)
02057 {
02058    struct ast_str *body = ast_str_alloca(size);
02059    char tuple_id[32];
02060 
02061    generate_random_string(tuple_id, sizeof(tuple_id));
02062 
02063    /* We'll make this a bare-bones pidf body. In state_notify_build_xml, the PIDF
02064     * body gets a lot more extra junk that isn't necessary, so we'll leave it out here.
02065     */
02066    ast_str_append(&body, 0, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
02067    /* XXX The entity attribute is currently set to the peer name associated with the
02068     * dialog. This is because we currently only call this function for call-completion
02069     * PUBLISH bodies. In such cases, the entity is completely disregarded. For other
02070     * event packages, it may be crucial to have a proper URI as the presentity so this
02071     * should be revisited as support is expanded.
02072     */
02073    ast_str_append(&body, 0, "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" entity=\"%s\">\n", presentity);
02074    ast_str_append(&body, 0, "<tuple id=\"%s\">\n", tuple_id);
02075    ast_str_append(&body, 0, "<status><basic>%s</basic></status>\n", state == CC_OPEN ? "open" : "closed");
02076    ast_str_append(&body, 0, "</tuple>\n");
02077    ast_str_append(&body, 0, "</presence>\n");
02078    ast_copy_string(pidf_body, ast_str_buffer(body), size);
02079    return 0;
02080 }
02081 
02082 static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor)
02083 {
02084    struct sip_monitor_instance *monitor_instance = monitor->private_data;
02085    enum sip_publish_type publish_type;
02086    struct cc_epa_entry *cc_entry;
02087 
02088    if (!monitor_instance) {
02089       return -1;
02090    }
02091 
02092    if (!monitor_instance->suspension_entry) {
02093       /* We haven't yet allocated the suspension entry, so let's give it a shot */
02094       if (!(monitor_instance->suspension_entry = create_epa_entry("call-completion", monitor_instance->peername))) {
02095          ast_log(LOG_WARNING, "Unable to allocate sip EPA entry for call-completion\n");
02096          ao2_ref(monitor_instance, -1);
02097          return -1;
02098       }
02099       if (!(cc_entry = ast_calloc(1, sizeof(*cc_entry)))) {
02100          ast_log(LOG_WARNING, "Unable to allocate space for instance data of EPA entry for call-completion\n");
02101          ao2_ref(monitor_instance, -1);
02102          return -1;
02103       }
02104       cc_entry->core_id = monitor->core_id;
02105       monitor_instance->suspension_entry->instance_data = cc_entry;
02106       publish_type = SIP_PUBLISH_INITIAL;
02107    } else {
02108       publish_type = SIP_PUBLISH_MODIFY;
02109       cc_entry = monitor_instance->suspension_entry->instance_data;
02110    }
02111 
02112    cc_entry->current_state = CC_CLOSED;
02113 
02114    if (ast_strlen_zero(monitor_instance->notify_uri)) {
02115       /* If we have no set notify_uri, then what this means is that we have
02116        * not received a NOTIFY from this destination stating that he is
02117        * currently available.
02118        *
02119        * This situation can arise when the core calls the suspend callbacks
02120        * of multiple destinations. If one of the other destinations aside
02121        * from this one notified Asterisk that he is available, then there
02122        * is no reason to take any suspension action on this device. Rather,
02123        * we should return now and if we receive a NOTIFY while monitoring
02124        * is still "suspended" then we can immediately respond with the
02125        * proper PUBLISH to let this endpoint know what is going on.
02126        */
02127       return 0;
02128    }
02129    construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
02130    return transmit_publish(monitor_instance->suspension_entry, publish_type, monitor_instance->notify_uri);
02131 }
02132 
02133 static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor)
02134 {
02135    struct sip_monitor_instance *monitor_instance = monitor->private_data;
02136    struct cc_epa_entry *cc_entry;
02137 
02138    if (!monitor_instance) {
02139       return -1;
02140    }
02141 
02142    ast_assert(monitor_instance->suspension_entry != NULL);
02143 
02144    cc_entry = monitor_instance->suspension_entry->instance_data;
02145    cc_entry->current_state = CC_OPEN;
02146    if (ast_strlen_zero(monitor_instance->notify_uri)) {
02147       /* This means we are being asked to unsuspend a call leg we never
02148        * sent a PUBLISH on. As such, there is no reason to send another
02149        * PUBLISH at this point either. We can just return instead.
02150        */
02151       return 0;
02152    }
02153    construct_pidf_body(CC_OPEN, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
02154    return transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_MODIFY, monitor_instance->notify_uri);
02155 }
02156 
02157 static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id)
02158 {
02159    if (*sched_id != -1) {
02160       AST_SCHED_DEL(sched, *sched_id);
02161       ao2_t_ref(monitor, -1, "Removing scheduler's reference to the monitor");
02162    }
02163    return 0;
02164 }
02165 
02166 static void sip_cc_monitor_destructor(void *private_data)
02167 {
02168    struct sip_monitor_instance *monitor_instance = private_data;
02169    ao2_unlink(sip_monitor_instances, monitor_instance);
02170    ast_module_unref(ast_module_info->self);
02171 }
02172 
02173 static int sip_get_cc_information(struct sip_request *req, char *subscribe_uri, size_t size, enum ast_cc_service_type *service)
02174 {
02175    char *call_info = ast_strdupa(sip_get_header(req, "Call-Info"));
02176    char *uri;
02177    char *purpose;
02178    char *service_str;
02179    static const char cc_purpose[] = "purpose=call-completion";
02180    static const int cc_purpose_len = sizeof(cc_purpose) - 1;
02181 
02182    if (ast_strlen_zero(call_info)) {
02183       /* No Call-Info present. Definitely no CC offer */
02184       return -1;
02185    }
02186 
02187    uri = strsep(&call_info, ";");
02188 
02189    while ((purpose = strsep(&call_info, ";"))) {
02190       if (!strncmp(purpose, cc_purpose, cc_purpose_len)) {
02191          break;
02192       }
02193    }
02194    if (!purpose) {
02195       /* We didn't find the appropriate purpose= parameter. Oh well */
02196       return -1;
02197    }
02198 
02199    /* Okay, call-completion has been offered. Let's figure out what type of service this is */
02200    while ((service_str = strsep(&call_info, ";"))) {
02201       if (!strncmp(service_str, "m=", 2)) {
02202          break;
02203       }
02204    }
02205    if (!service_str) {
02206       /* So they didn't offer a particular service, We'll just go with CCBS since it really
02207        * doesn't matter anyway
02208        */
02209       service_str = "BS";
02210    } else {
02211       /* We already determined that there is an "m=" so no need to check
02212        * the result of this strsep
02213        */
02214       strsep(&service_str, "=");
02215    }
02216 
02217    if ((*service = service_string_to_service_type(service_str)) == AST_CC_NONE) {
02218       /* Invalid service offered */
02219       return -1;
02220    }
02221 
02222    ast_copy_string(subscribe_uri, get_in_brackets(uri), size);
02223 
02224    return 0;
02225 }
02226 
02227 /*
02228  * \brief Determine what, if any, CC has been offered and queue a CC frame if possible
02229  *
02230  * After taking care of some formalities to be sure that this call is eligible for CC,
02231  * we first try to see if we can make use of native CC. We grab the information from
02232  * the passed-in sip_request (which is always a response to an INVITE). If we can
02233  * use native CC monitoring for the call, then so be it.
02234  *
02235  * If native cc monitoring is not possible or not supported, then we will instead attempt
02236  * to use generic monitoring. Falling back to generic from a failed attempt at using native
02237  * monitoring will only work if the monitor policy of the endpoint is "always"
02238  *
02239  * \param pvt The current dialog. Contains CC parameters for the endpoint
02240  * \param req The response to the INVITE we want to inspect
02241  * \param service The service to use if generic monitoring is to be used. For native
02242  * monitoring, we get the service from the SIP response itself
02243  */
02244 static void sip_handle_cc(struct sip_pvt *pvt, struct sip_request *req, enum ast_cc_service_type service)
02245 {
02246    enum ast_cc_monitor_policies monitor_policy = ast_get_cc_monitor_policy(pvt->cc_params);
02247    int core_id;
02248    char interface_name[AST_CHANNEL_NAME];
02249 
02250    if (monitor_policy == AST_CC_MONITOR_NEVER) {
02251       /* Don't bother, just return */
02252       return;
02253    }
02254 
02255    if ((core_id = ast_cc_get_current_core_id(pvt->owner)) == -1) {
02256       /* For some reason, CC is invalid, so don't try it! */
02257       return;
02258    }
02259 
02260    ast_channel_get_device_name(pvt->owner, interface_name, sizeof(interface_name));
02261 
02262    if (monitor_policy == AST_CC_MONITOR_ALWAYS || monitor_policy == AST_CC_MONITOR_NATIVE) {
02263       char subscribe_uri[SIPBUFSIZE];
02264       char device_name[AST_CHANNEL_NAME];
02265       enum ast_cc_service_type offered_service;
02266       struct sip_monitor_instance *monitor_instance;
02267       if (sip_get_cc_information(req, subscribe_uri, sizeof(subscribe_uri), &offered_service)) {
02268          /* If CC isn't being offered to us, or for some reason the CC offer is
02269           * not formatted correctly, then it may still be possible to use generic
02270           * call completion since the monitor policy may be "always"
02271           */
02272          goto generic;
02273       }
02274       ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
02275       if (!(monitor_instance = sip_monitor_instance_init(core_id, subscribe_uri, pvt->peername, device_name))) {
02276          /* Same deal. We can try using generic still */
02277          goto generic;
02278       }
02279       /* We bump the refcount of chan_sip because once we queue this frame, the CC core
02280        * will have a reference to callbacks in this module. We decrement the module
02281        * refcount once the monitor destructor is called
02282        */
02283       ast_module_ref(ast_module_info->self);
02284       ast_queue_cc_frame(pvt->owner, "SIP", pvt->dialstring, offered_service, monitor_instance);
02285       ao2_ref(monitor_instance, -1);
02286       return;
02287    }
02288 
02289 generic:
02290    if (monitor_policy == AST_CC_MONITOR_GENERIC || monitor_policy == AST_CC_MONITOR_ALWAYS) {
02291       ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE, interface_name, service, NULL);
02292    }
02293 }
02294 
02295 /*! \brief Working TLS connection configuration */
02296 static struct ast_tls_config sip_tls_cfg;
02297 
02298 /*! \brief Default TLS connection configuration */
02299 static struct ast_tls_config default_tls_cfg;
02300 
02301 /*! \brief The TCP server definition */
02302 static struct ast_tcptls_session_args sip_tcp_desc = {
02303    .accept_fd = -1,
02304    .master = AST_PTHREADT_NULL,
02305    .tls_cfg = NULL,
02306    .poll_timeout = -1,
02307    .name = "SIP TCP server",
02308    .accept_fn = ast_tcptls_server_root,
02309    .worker_fn = sip_tcp_worker_fn,
02310 };
02311 
02312 /*! \brief The TCP/TLS server definition */
02313 static struct ast_tcptls_session_args sip_tls_desc = {
02314    .accept_fd = -1,
02315    .master = AST_PTHREADT_NULL,
02316    .tls_cfg = &sip_tls_cfg,
02317    .poll_timeout = -1,
02318    .name = "SIP TLS server",
02319    .accept_fn = ast_tcptls_server_root,
02320    .worker_fn = sip_tcp_worker_fn,
02321 };
02322 
02323 /*! \brief Append to SIP dialog history
02324    \return Always returns 0 */
02325 #define append_history(p, event, fmt , args... )   append_history_full(p, "%-15s " fmt, event, ## args)
02326 
02327 struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, const char *tag, char *file, int line, const char *func)
02328 {
02329    if (p)
02330 #ifdef REF_DEBUG
02331       __ao2_ref_debug(p, 1, tag, file, line, func);
02332 #else
02333       ao2_ref(p, 1);
02334 #endif
02335    else
02336       ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
02337    return p;
02338 }
02339 
02340 struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, const char *tag, char *file, int line, const char *func)
02341 {
02342    if (p)
02343 #ifdef REF_DEBUG
02344       __ao2_ref_debug(p, -1, tag, file, line, func);
02345 #else
02346       ao2_ref(p, -1);
02347 #endif
02348    return NULL;
02349 }
02350 
02351 /*! \brief map from an integer value to a string.
02352  * If no match is found, return errorstring
02353  */
02354 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
02355 {
02356    const struct _map_x_s *cur;
02357 
02358    for (cur = table; cur->s; cur++) {
02359       if (cur->x == x) {
02360          return cur->s;
02361       }
02362    }
02363    return errorstring;
02364 }
02365 
02366 /*! \brief map from a string to an integer value, case insensitive.
02367  * If no match is found, return errorvalue.
02368  */
02369 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
02370 {
02371    const struct _map_x_s *cur;
02372 
02373    for (cur = table; cur->s; cur++) {
02374       if (!strcasecmp(cur->s, s)) {
02375          return cur->x;
02376       }
02377    }
02378    return errorvalue;
02379 }
02380 
02381 static enum AST_REDIRECTING_REASON sip_reason_str_to_code(const char *text)
02382 {
02383    enum AST_REDIRECTING_REASON ast = AST_REDIRECTING_REASON_UNKNOWN;
02384    int i;
02385 
02386    for (i = 0; i < ARRAY_LEN(sip_reason_table); ++i) {
02387       if (!strcasecmp(text, sip_reason_table[i].text)) {
02388          ast = sip_reason_table[i].code;
02389          break;
02390       }
02391    }
02392 
02393    return ast;
02394 }
02395 
02396 static const char *sip_reason_code_to_str(enum AST_REDIRECTING_REASON code)
02397 {
02398    if (code >= 0 && code < ARRAY_LEN(sip_reason_table)) {
02399       return sip_reason_table[code].text;
02400    }
02401 
02402    return "unknown";
02403 }
02404 
02405 /*!
02406  * \brief generic function for determining if a correct transport is being
02407  * used to contact a peer
02408  *
02409  * this is done as a macro so that the "tmpl" var can be passed either a
02410  * sip_request or a sip_peer
02411  */
02412 #define check_request_transport(peer, tmpl) ({ \
02413    int ret = 0; \
02414    if (peer->socket.type == tmpl->socket.type) \
02415       ; \
02416    else if (!(peer->transports & tmpl->socket.type)) {\
02417       ast_log(LOG_ERROR, \
02418          "'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
02419          sip_get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
02420          ); \
02421       ret = 1; \
02422    } else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
02423       ast_log(LOG_WARNING, \
02424          "peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
02425          peer->name, sip_get_transport(tmpl->socket.type) \
02426       ); \
02427    } else { \
02428       ast_debug(1, \
02429          "peer '%s' has contacted us over %s even though we prefer %s.\n", \
02430          peer->name, sip_get_transport(tmpl->socket.type), sip_get_transport(peer->socket.type) \
02431       ); \
02432    }\
02433    (ret); \
02434 })
02435 
02436 /*! \brief
02437  * duplicate a list of channel variables, \return the copy.
02438  */
02439 static struct ast_variable *copy_vars(struct ast_variable *src)
02440 {
02441    struct ast_variable *res = NULL, *tmp, *v = NULL;
02442 
02443    for (v = src ; v ; v = v->next) {
02444       if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
02445          tmp->next = res;
02446          res = tmp;
02447       }
02448    }
02449    return res;
02450 }
02451 
02452 static void tcptls_packet_destructor(void *obj)
02453 {
02454    struct tcptls_packet *packet = obj;
02455 
02456    ast_free(packet->data);
02457 }
02458 
02459 static void sip_tcptls_client_args_destructor(void *obj)
02460 {
02461    struct ast_tcptls_session_args *args = obj;
02462    if (args->tls_cfg) {
02463       ast_free(args->tls_cfg->certfile);
02464       ast_free(args->tls_cfg->pvtfile);
02465       ast_free(args->tls_cfg->cipher);
02466       ast_free(args->tls_cfg->cafile);
02467       ast_free(args->tls_cfg->capath);
02468 
02469       ast_ssl_teardown(args->tls_cfg);
02470    }
02471    ast_free(args->tls_cfg);
02472    ast_free((char *) args->name);
02473 }
02474 
02475 static void sip_threadinfo_destructor(void *obj)
02476 {
02477    struct sip_threadinfo *th = obj;
02478    struct tcptls_packet *packet;
02479 
02480    if (th->alert_pipe[1] > -1) {
02481       close(th->alert_pipe[0]);
02482    }
02483    if (th->alert_pipe[1] > -1) {
02484       close(th->alert_pipe[1]);
02485    }
02486    th->alert_pipe[0] = th->alert_pipe[1] = -1;
02487 
02488    while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
02489       ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
02490    }
02491 
02492    if (th->tcptls_session) {
02493       ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
02494    }
02495 }
02496 
02497 /*! \brief creates a sip_threadinfo object and links it into the threadt table. */
02498 static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
02499 {
02500    struct sip_threadinfo *th;
02501 
02502    if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
02503       return NULL;
02504    }
02505 
02506    th->alert_pipe[0] = th->alert_pipe[1] = -1;
02507 
02508    if (pipe(th->alert_pipe) == -1) {
02509       ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
02510       ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
02511       return NULL;
02512    }
02513    ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
02514    th->tcptls_session = tcptls_session;
02515    th->type = transport ? transport : (tcptls_session->ssl ? SIP_TRANSPORT_TLS: SIP_TRANSPORT_TCP);
02516    ao2_t_link(threadt, th, "Adding new tcptls helper thread");
02517    ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
02518    return th;
02519 }
02520 
02521 /*! \brief used to indicate to a tcptls thread that data is ready to be written */
02522 static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
02523 {
02524    int res = len;
02525    struct sip_threadinfo *th = NULL;
02526    struct tcptls_packet *packet = NULL;
02527    struct sip_threadinfo tmp = {
02528       .tcptls_session = tcptls_session,
02529    };
02530    enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
02531 
02532    if (!tcptls_session) {
02533       return XMIT_ERROR;
02534    }
02535 
02536    ao2_lock(tcptls_session);
02537 
02538    if ((tcptls_session->fd == -1) ||
02539       !(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
02540       !(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
02541       !(packet->data = ast_str_create(len))) {
02542       goto tcptls_write_setup_error;
02543    }
02544 
02545    /* goto tcptls_write_error should _NOT_ be used beyond this point */
02546    ast_str_set(&packet->data, 0, "%s", (char *) buf);
02547    packet->len = len;
02548 
02549    /* alert tcptls thread handler that there is a packet to be sent.
02550     * must lock the thread info object to guarantee control of the
02551     * packet queue */
02552    ao2_lock(th);
02553    if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
02554       ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
02555       ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
02556       packet = NULL;
02557       res = XMIT_ERROR;
02558    } else { /* it is safe to queue the frame after issuing the alert when we hold the threadinfo lock */
02559       AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
02560    }
02561    ao2_unlock(th);
02562 
02563    ao2_unlock(tcptls_session);
02564    ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
02565    return res;
02566 
02567 tcptls_write_setup_error:
02568    if (th) {
02569       ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
02570    }
02571    if (packet) {
02572       ao2_t_ref(packet, -1, "could not allocate packet's data");
02573    }
02574    ao2_unlock(tcptls_session);
02575 
02576    return XMIT_ERROR;
02577 }
02578 
02579 /*! \brief SIP TCP connection handler */
02580 static void *sip_tcp_worker_fn(void *data)
02581 {
02582    struct ast_tcptls_session_instance *tcptls_session = data;
02583 
02584    return _sip_tcp_helper_thread(tcptls_session);
02585 }
02586 
02587 /*! \brief SIP WebSocket connection handler */
02588 static void sip_websocket_callback(struct ast_websocket *session, struct ast_variable *parameters, struct ast_variable *headers)
02589 {
02590    int res;
02591 
02592    if (ast_websocket_set_nonblock(session)) {
02593       goto end;
02594    }
02595 
02596    while ((res = ast_wait_for_input(ast_websocket_fd(session), -1)) > 0) {
02597       char *payload;
02598       uint64_t payload_len;
02599       enum ast_websocket_opcode opcode;
02600       int fragmented;
02601 
02602       if (ast_websocket_read(session, &payload, &payload_len, &opcode, &fragmented)) {
02603          /* We err on the side of caution and terminate the session if any error occurs */
02604          break;
02605       }
02606 
02607       if (opcode == AST_WEBSOCKET_OPCODE_TEXT || opcode == AST_WEBSOCKET_OPCODE_BINARY) {
02608          struct sip_request req = { 0, };
02609 
02610          if (!(req.data = ast_str_create(payload_len + 1))) {
02611             goto end;
02612          }
02613 
02614          if (ast_str_set(&req.data, -1, "%s", payload) == AST_DYNSTR_BUILD_FAILED) {
02615             deinit_req(&req);
02616             goto end;
02617          }
02618 
02619          req.socket.fd = ast_websocket_fd(session);
02620          set_socket_transport(&req.socket, ast_websocket_is_secure(session) ? SIP_TRANSPORT_WSS : SIP_TRANSPORT_WS);
02621          req.socket.ws_session = session;
02622 
02623          handle_request_do(&req, ast_websocket_remote_address(session));
02624          deinit_req(&req);
02625 
02626       } else if (opcode == AST_WEBSOCKET_OPCODE_CLOSE) {
02627          break;
02628       }
02629    }
02630 
02631 end:
02632    ast_websocket_unref(session);
02633 }
02634 
02635 /*! \brief Check if the authtimeout has expired.
02636  * \param start the time when the session started
02637  *
02638  * \retval 0 the timeout has expired
02639  * \retval -1 error
02640  * \return the number of milliseconds until the timeout will expire
02641  */
02642 static int sip_check_authtimeout(time_t start)
02643 {
02644    int timeout;
02645    time_t now;
02646    if(time(&now) == -1) {
02647       ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
02648       return -1;
02649    }
02650 
02651    timeout = (authtimeout - (now - start)) * 1000;
02652    if (timeout < 0) {
02653       /* we have timed out */
02654       return 0;
02655    }
02656 
02657    return timeout;
02658 }
02659 
02660 /*!
02661  * \brief Read a SIP request or response from a TLS connection
02662  *
02663  * Because TLS operations are hidden from view via a FILE handle, the
02664  * logic for reading data is a bit complex, and we have to make periodic
02665  * checks to be sure we aren't taking too long to perform the necessary
02666  * action.
02667  *
02668  * \todo XXX This should be altered in the future not to use a FILE pointer
02669  *
02670  * \param req The request structure to fill in
02671  * \param tcptls_session The TLS connection on which the data is being received
02672  * \param authenticated A flag indicating whether authentication has occurred yet.
02673  *        This is only relevant in a server role.
02674  * \param start The time at which we started attempting to read data. Used in
02675  *        determining if there has been a timeout.
02676  * \param me Thread info. Used as a means of determining if the session needs to be stoppped.
02677  * \retval -1 Failed to read data
02678  * \retval 0 Succeeded in reading data
02679  */
02680 static int sip_tls_read(struct sip_request *req, struct sip_request *reqcpy, struct ast_tcptls_session_instance *tcptls_session,
02681          int authenticated, time_t start, struct sip_threadinfo *me)
02682 {
02683    int res, content_length, after_poll = 1, need_poll = 1;
02684    size_t datalen = ast_str_strlen(req->data);
02685    char buf[1024] = "";
02686    int timeout = -1;
02687  
02688    /* Read in headers one line at a time */
02689    while (datalen < 4 || strncmp(REQ_OFFSET_TO_STR(req, data->used - 4), "\r\n\r\n", 4)) {
02690       if (!tcptls_session->client && !authenticated) {
02691          if ((timeout = sip_check_authtimeout(start)) < 0) {
02692             ast_debug(2, "SIP TLS server failed to determine authentication timeout\n");
02693             return -1;
02694          }
02695 
02696          if (timeout == 0) {
02697             ast_debug(2, "SIP TLS server timed out\n");
02698             return -1;
02699          }
02700       } else {
02701          timeout = -1;
02702       }
02703 
02704       /* special polling behavior is required for TLS
02705        * sockets because of the buffering done in the
02706        * TLS layer */
02707       if (need_poll) {
02708          need_poll = 0;
02709          after_poll = 1;
02710          res = ast_wait_for_input(tcptls_session->fd, timeout);
02711          if (res < 0) {
02712             ast_debug(2, "SIP TLS server :: ast_wait_for_input returned %d\n", res);
02713             return -1;
02714          } else if (res == 0) {
02715             /* timeout */
02716             ast_debug(2, "SIP TLS server timed out\n");
02717             return -1;
02718          }
02719       }
02720 
02721       ao2_lock(tcptls_session);
02722       if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
02723          ao2_unlock(tcptls_session);
02724          if (after_poll) {
02725             return -1;
02726          } else {
02727             need_poll = 1;
02728             continue;
02729          }
02730       }
02731       ao2_unlock(tcptls_session);
02732       after_poll = 0;
02733       if (me->stop) {
02734          return -1;
02735       }
02736       ast_str_append(&req->data, 0, "%s", buf);
02737 
02738       datalen = ast_str_strlen(req->data);
02739       if (datalen > SIP_MAX_PACKET_SIZE) {
02740          ast_log(LOG_WARNING, "Rejecting TLS packet from '%s' because way too large: %zu\n",
02741             ast_sockaddr_stringify(&tcptls_session->remote_address), datalen);
02742          return -1;
02743       }
02744    }
02745    copy_request(reqcpy, req);
02746    parse_request(reqcpy);
02747    /* In order to know how much to read, we need the content-length header */
02748    if (sscanf(sip_get_header(reqcpy, "Content-Length"), "%30d", &content_length)) {
02749       while (content_length > 0) {
02750          size_t bytes_read;
02751          if (!tcptls_session->client && !authenticated) {
02752             if ((timeout = sip_check_authtimeout(start)) < 0) {
02753                return -1;
02754             }
02755 
02756             if (timeout == 0) {
02757                ast_debug(2, "SIP TLS server timed out\n");
02758                return -1;
02759             }
02760          } else {
02761             timeout = -1;
02762          }
02763 
02764          if (need_poll) {
02765             need_poll = 0;
02766             after_poll = 1;
02767             res = ast_wait_for_input(tcptls_session->fd, timeout);
02768             if (res < 0) {
02769                ast_debug(2, "SIP TLS server :: ast_wait_for_input returned %d\n", res);
02770                return -1;
02771             } else if (res == 0) {
02772                /* timeout */
02773                ast_debug(2, "SIP TLS server timed out\n");
02774                return -1;
02775             }
02776          }
02777 
02778          ao2_lock(tcptls_session);
02779          if (!(bytes_read = fread(buf, 1, MIN(sizeof(buf) - 1, content_length), tcptls_session->f))) {
02780             ao2_unlock(tcptls_session);
02781             if (after_poll) {
02782                return -1;
02783             } else {
02784                need_poll = 1;
02785                continue;
02786             }
02787          }
02788          buf[bytes_read] = '\0';
02789          ao2_unlock(tcptls_session);
02790          after_poll = 0;
02791          if (me->stop) {
02792             return -1;
02793          }
02794          content_length -= strlen(buf);
02795          ast_str_append(&req->data, 0, "%s", buf);
02796       
02797          datalen = ast_str_strlen(req->data);
02798          if (datalen > SIP_MAX_PACKET_SIZE) {
02799             ast_log(LOG_WARNING, "Rejecting TLS packet from '%s' because way too large: %zu\n",
02800                ast_sockaddr_stringify(&tcptls_session->remote_address), datalen);
02801             return -1;
02802          }
02803       }
02804    }
02805    /*! \todo XXX If there's no Content-Length or if the content-length and what
02806                we receive is not the same - we should generate an error */
02807    return 0;
02808 }
02809 
02810 /*!
02811  * \brief Indication of a TCP message's integrity
02812  */
02813 enum message_integrity {
02814    /*!
02815     * The message has an error in it with
02816     * regards to its Content-Length header
02817     */
02818    MESSAGE_INVALID,
02819    /*!
02820     * The message is incomplete
02821     */
02822    MESSAGE_FRAGMENT,
02823    /*!
02824     * The data contains a complete message
02825     * plus a fragment of another.
02826     */
02827    MESSAGE_FRAGMENT_COMPLETE,
02828    /*!
02829     * The message is complete
02830     */
02831    MESSAGE_COMPLETE,
02832 };
02833 
02834 /*!
02835  * \brief
02836  * Get the content length from an unparsed SIP message
02837  *
02838  * \param message The unparsed SIP message headers
02839  * \return The value of the Content-Length header or -1 if message is invalid
02840  */
02841 static int read_raw_content_length(const char *message)
02842 {
02843    char *content_length_str;
02844    int content_length = -1;
02845 
02846    struct ast_str *msg_copy;
02847    char *msg;
02848 
02849    /* Using a ast_str because lws2sws takes one of those */
02850    if (!(msg_copy = ast_str_create(strlen(message) + 1))) {
02851       return -1;
02852    }
02853    ast_str_set(&msg_copy, 0, "%s", message);
02854 
02855    if (sip_cfg.pedanticsipchecking) {
02856       lws2sws(msg_copy);
02857    }
02858 
02859    msg = ast_str_buffer(msg_copy);
02860 
02861    /* Let's find a Content-Length header */
02862    if ((content_length_str = strcasestr(msg, "\nContent-Length:"))) {
02863       content_length_str += sizeof("\nContent-Length:") - 1;
02864    } else if ((content_length_str = strcasestr(msg, "\nl:"))) {
02865       content_length_str += sizeof("\nl:") - 1;
02866    } else {
02867       /* RFC 3261 18.3
02868        * "In the case of stream-oriented transports such as TCP, the Content-
02869        *  Length header field indicates the size of the body.  The Content-
02870        *  Length header field MUST be used with stream oriented transports."
02871        */
02872       goto done;
02873    }
02874 
02875    /* Double-check that this is a complete header */
02876    if (!strchr(content_length_str, '\n')) {
02877       goto done;
02878    }
02879 
02880    if (sscanf(content_length_str, "%30d", &content_length) != 1) {
02881       content_length = -1;
02882    }
02883 
02884 done:
02885    ast_free(msg_copy);
02886    return content_length;
02887 }
02888 
02889 /*!
02890  * \brief Check that a message received over TCP is a full message
02891  *
02892  * This will take the information read in and then determine if
02893  * 1) The message is a full SIP request
02894  * 2) The message is a partial SIP request
02895  * 3) The message contains a full SIP request along with another partial request
02896  * \param data The unparsed incoming SIP message.
02897  * \param request The resulting request with extra fragments removed.
02898  * \param overflow If the message contains more than a full request, this is the remainder of the message
02899  * \return The resulting integrity of the message
02900  */
02901 static enum message_integrity check_message_integrity(struct ast_str **request, struct ast_str **overflow)
02902 {
02903    char *message = ast_str_buffer(*request);
02904    char *body;
02905    int content_length;
02906    int message_len = ast_str_strlen(*request);
02907    int body_len;
02908 
02909    /* Important pieces to search for in a SIP request are \r\n\r\n. This
02910     * marks either
02911     * 1) The division between the headers and body
02912     * 2) The end of the SIP request
02913     */
02914    body = strstr(message, "\r\n\r\n");
02915    if (!body) {
02916       /* This is clearly a partial message since we haven't reached an end
02917        * yet.
02918        */
02919       return MESSAGE_FRAGMENT;
02920    }
02921    body += sizeof("\r\n\r\n") - 1;
02922    body_len = message_len - (body - message);
02923 
02924    body[-1] = '\0';
02925    content_length = read_raw_content_length(message);
02926    body[-1] = '\n';
02927 
02928    if (content_length < 0) {
02929       return MESSAGE_INVALID;
02930    } else if (content_length == 0) {
02931       /* We've definitely received an entire message. We need
02932        * to check if there's also a fragment of another message
02933        * in addition.
02934        */
02935       if (body_len == 0) {
02936          return MESSAGE_COMPLETE;
02937       } else {
02938          ast_str_append(overflow, 0, "%s", body);
02939          ast_str_truncate(*request, message_len - body_len);
02940          return MESSAGE_FRAGMENT_COMPLETE;
02941       }
02942    }
02943    /* Positive content length. Let's see what sort of
02944     * message body we're dealing with.
02945     */
02946    if (body_len < content_length) {
02947       /* We don't have the full message body yet */
02948       return MESSAGE_FRAGMENT;
02949    } else if (body_len > content_length) {
02950       /* We have the full message plus a fragment of a further
02951        * message
02952        */
02953       ast_str_append(overflow, 0, "%s", body + content_length);
02954       ast_str_truncate(*request, message_len - (body_len - content_length));
02955       return MESSAGE_FRAGMENT_COMPLETE;
02956    } else {
02957       /* Yay! Full message with no extra content */
02958       return MESSAGE_COMPLETE;
02959    }
02960 }
02961 
02962 /*!
02963  * \brief Read SIP request or response from a TCP connection
02964  *
02965  * \param req The request structure to be filled in
02966  * \param tcptls_session The TCP connection from which to read
02967  * \retval -1 Failed to read data
02968  * \retval 0 Successfully read data
02969  */
02970 static int sip_tcp_read(struct sip_request *req, struct ast_tcptls_session_instance *tcptls_session,
02971       int authenticated, time_t start)
02972 {
02973    enum message_integrity message_integrity = MESSAGE_FRAGMENT;
02974 
02975    while (message_integrity == MESSAGE_FRAGMENT) {
02976       size_t datalen;
02977 
02978       if (ast_str_strlen(tcptls_session->overflow_buf) == 0) {
02979          char readbuf[4097];
02980          int timeout;
02981          int res;
02982          if (!tcptls_session->client && !authenticated) {
02983             if ((timeout = sip_check_authtimeout(start)) < 0) {
02984                return -1;
02985             }
02986 
02987             if (timeout == 0) {
02988                ast_debug(2, "SIP TCP server timed out\n");
02989                return -1;
02990             }
02991          } else {
02992             timeout = -1;
02993          }
02994          res = ast_wait_for_input(tcptls_session->fd, timeout);
02995          if (res < 0) {
02996             ast_debug(2, "SIP TCP server :: ast_wait_for_input returned %d\n", res);
02997             return -1;
02998          } else if (res == 0) {
02999             ast_debug(2, "SIP TCP server timed out\n");
03000             return -1;
03001          }
03002 
03003          res = recv(tcptls_session->fd, readbuf, sizeof(readbuf) - 1, 0);
03004          if (res < 0) {
03005             ast_debug(2, "SIP TCP server error when receiving data\n");
03006             return -1;
03007          } else if (res == 0) {
03008             ast_debug(2, "SIP TCP server has shut down\n");
03009             return -1;
03010          }
03011          readbuf[res] = '\0';
03012          ast_str_append(&req->data, 0, "%s", readbuf);
03013       } else {
03014          ast_str_append(&req->data, 0, "%s", ast_str_buffer(tcptls_session->overflow_buf));
03015          ast_str_reset(tcptls_session->overflow_buf);
03016       }
03017       
03018       datalen = ast_str_strlen(req->data);
03019       if (datalen > SIP_MAX_PACKET_SIZE) {
03020          ast_log(LOG_WARNING, "Rejecting TCP packet from '%s' because way too large: %zu\n",
03021             ast_sockaddr_stringify(&tcptls_session->remote_address), datalen);
03022          return -1;
03023       }
03024 
03025       message_integrity = check_message_integrity(&req->data, &tcptls_session->overflow_buf);
03026    }
03027 
03028    return 0;
03029 }
03030 
03031 /*! \brief SIP TCP thread management function
03032    This function reads from the socket, parses the packet into a request
03033 */
03034 static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session)
03035 {
03036    int res, timeout = -1, authenticated = 0, flags;
03037    time_t start;
03038    struct sip_request req = { 0, } , reqcpy = { 0, };
03039    struct sip_threadinfo *me = NULL;
03040    char buf[1024] = "";
03041    struct pollfd fds[2] = { { 0 }, { 0 }, };
03042    struct ast_tcptls_session_args *ca = NULL;
03043 
03044    /* If this is a server session, then the connection has already been
03045     * setup. Check if the authlimit has been reached and if not create the
03046     * threadinfo object so we can access this thread for writing.
03047     *
03048     * if this is a client connection more work must be done.
03049     * 1. We own the parent session args for a client connection.  This pointer needs
03050     *    to be held on to so we can decrement it's ref count on thread destruction.
03051     * 2. The threadinfo object was created before this thread was launched, however
03052     *    it must be found within the threadt table.
03053     * 3. Last, the tcptls_session must be started.
03054     */
03055    if (!tcptls_session->client) {
03056       if (ast_atomic_fetchadd_int(&unauth_sessions, +1) >= authlimit) {
03057          /* unauth_sessions is decremented in the cleanup code */
03058          goto cleanup;
03059       }
03060 
03061       if ((flags = fcntl(tcptls_session->fd, F_GETFL)) == -1) {
03062          ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
03063          goto cleanup;
03064       }
03065 
03066       flags |= O_NONBLOCK;
03067       if (fcntl(tcptls_session->fd, F_SETFL, flags) == -1) {
03068          ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
03069          goto cleanup;
03070       }
03071 
03072       if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? SIP_TRANSPORT_TLS : SIP_TRANSPORT_TCP))) {
03073          goto cleanup;
03074       }
03075       ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
03076    } else {
03077       struct sip_threadinfo tmp = {
03078          .tcptls_session = tcptls_session,
03079       };
03080 
03081       if ((!(ca = tcptls_session->parent)) ||
03082          (!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
03083          (!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
03084          goto cleanup;
03085       }
03086    }
03087 
03088    flags = 1;
03089    if (setsockopt(tcptls_session->fd, SOL_SOCKET, SO_KEEPALIVE, &flags, sizeof(flags))) {
03090       ast_log(LOG_ERROR, "error enabling TCP keep-alives on sip socket: %s\n", strerror(errno));
03091       goto cleanup;
03092    }
03093 
03094    me->threadid = pthread_self();
03095    ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "TLS" : "TCP");
03096 
03097    /* set up pollfd to watch for reads on both the socket and the alert_pipe */
03098    fds[0].fd = tcptls_session->fd;
03099    fds[1].fd = me->alert_pipe[0];
03100    fds[0].events = fds[1].events = POLLIN | POLLPRI;
03101 
03102    if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
03103       goto cleanup;
03104    }
03105    if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET))) {
03106       goto cleanup;
03107    }
03108 
03109    if(time(&start) == -1) {
03110       ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
03111       goto cleanup;
03112    }
03113 
03114    for (;;) {
03115       struct ast_str *str_save;
03116 
03117       if (!tcptls_session->client && req.authenticated && !authenticated) {
03118          authenticated = 1;
03119          ast_atomic_fetchadd_int(&unauth_sessions, -1);
03120       }
03121 
03122       /* calculate the timeout for unauthenticated server sessions */
03123       if (!tcptls_session->client && !authenticated ) {
03124          if ((timeout = sip_check_authtimeout(start)) < 0) {
03125             goto cleanup;
03126          }
03127 
03128          if (timeout == 0) {
03129             ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "TLS": "TCP");
03130             goto cleanup;
03131          }
03132       } else {
03133          timeout = -1;
03134       }
03135 
03136       if (ast_str_strlen(tcptls_session->overflow_buf) == 0) {
03137          res = ast_poll(fds, 2, timeout); /* polls for both socket and alert_pipe */
03138          if (res < 0) {
03139             ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "TLS": "TCP", res);
03140             goto cleanup;
03141          } else if (res == 0) {
03142             /* timeout */
03143             ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "TLS": "TCP");
03144             goto cleanup;
03145          }
03146       }
03147 
03148       /* 
03149        * handle the socket event, check for both reads from the socket fd or TCP overflow buffer,
03150        * and writes from alert_pipe fd.
03151        */
03152       if (fds[0].revents || (ast_str_strlen(tcptls_session->overflow_buf) > 0)) { /* there is data on the socket to be read */
03153          fds[0].revents = 0;
03154 
03155          /* clear request structure */
03156          str_save = req.data;
03157          memset(&req, 0, sizeof(req));
03158          req.data = str_save;
03159          ast_str_reset(req.data);
03160 
03161          str_save = reqcpy.data;
03162          memset(&reqcpy, 0, sizeof(reqcpy));
03163          reqcpy.data = str_save;
03164          ast_str_reset(reqcpy.data);
03165 
03166          memset(buf, 0, sizeof(buf));
03167 
03168          if (tcptls_session->ssl) {
03169             set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
03170             req.socket.port = htons(ourport_tls);
03171          } else {
03172             set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
03173             req.socket.port = htons(ourport_tcp);
03174          }
03175          req.socket.fd = tcptls_session->fd;
03176          if (tcptls_session->ssl) {
03177             res = sip_tls_read(&req, &reqcpy, tcptls_session, authenticated, start, me);
03178          } else {
03179             res = sip_tcp_read(&req, tcptls_session, authenticated, start);
03180          }
03181 
03182          if (res < 0) {
03183             goto cleanup;
03184          }
03185 
03186          req.socket.tcptls_session = tcptls_session;
03187          req.socket.ws_session = NULL;
03188          handle_request_do(&req, &tcptls_session->remote_address);
03189       }
03190 
03191       if (fds[1].revents) { /* alert_pipe indicates there is data in the send queue to be sent */
03192          enum sip_tcptls_alert alert;
03193          struct tcptls_packet *packet;
03194 
03195          fds[1].revents = 0;
03196 
03197          if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
03198             ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
03199             continue;
03200          }
03201 
03202          switch (alert) {
03203          case TCPTLS_ALERT_STOP:
03204             goto cleanup;
03205          case TCPTLS_ALERT_DATA:
03206             ao2_lock(me);
03207             if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
03208                ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty\n");
03209             }
03210             ao2_unlock(me);
03211 
03212             if (packet) {
03213                if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
03214                   ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
03215                }
03216                ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
03217             }
03218             break;
03219          default:
03220             ast_log(LOG_ERROR, "Unknown tcptls thread alert '%d'\n", alert);
03221          }
03222       }
03223    }
03224 
03225    ast_debug(2, "Shutting down thread for %s server\n", tcptls_session->ssl ? "TLS" : "TCP");
03226 
03227 cleanup:
03228    if (tcptls_session && !tcptls_session->client && !authenticated) {
03229       ast_atomic_fetchadd_int(&unauth_sessions, -1);
03230    }
03231 
03232    if (me) {
03233       ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
03234       ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
03235    }
03236    deinit_req(&reqcpy);
03237    deinit_req(&req);
03238 
03239    /* if client, we own the parent session arguments and must decrement ref */
03240    if (ca) {
03241       ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
03242    }
03243 
03244    if (tcptls_session) {
03245       ao2_lock(tcptls_session);
03246       ast_tcptls_close_session_file(tcptls_session);
03247       tcptls_session->parent = NULL;
03248       ao2_unlock(tcptls_session);
03249 
03250       ao2_ref(tcptls_session, -1);
03251       tcptls_session = NULL;
03252    }
03253    return NULL;
03254 }
03255 
03256 #ifdef REF_DEBUG
03257 struct sip_peer *_ref_peer(struct sip_peer *peer, char *tag, char *file, int line, const char *func)
03258 {
03259    if (peer)
03260       __ao2_ref_debug(peer, 1, tag, file, line, func);
03261    else
03262       ast_log(LOG_ERROR, "Attempt to Ref a null peer pointer\n");
03263    return peer;
03264 }
03265 
03266 void *_unref_peer(struct sip_peer *peer, char *tag, char *file, int line, const char *func)
03267 {
03268    if (peer)
03269       __ao2_ref_debug(peer, -1, tag, file, line, func);
03270    return NULL;
03271 }
03272 #else
03273 /*!
03274  * helper functions to unreference various types of objects.
03275  * By handling them this way, we don't have to declare the
03276  * destructor on each call, which removes the chance of errors.
03277  */
03278 void *sip_unref_peer(struct sip_peer *peer, char *tag)
03279 {
03280    ao2_t_ref(peer, -1, tag);
03281    return NULL;
03282 }
03283 
03284 struct sip_peer *sip_ref_peer(struct sip_peer *peer, char *tag)
03285 {
03286    ao2_t_ref(peer, 1, tag);
03287    return peer;
03288 }
03289 #endif /* REF_DEBUG */
03290 
03291 static void peer_sched_cleanup(struct sip_peer *peer)
03292 {
03293    if (peer->pokeexpire != -1) {
03294       AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
03295             sip_unref_peer(peer, "removing poke peer ref"));
03296    }
03297    if (peer->expire != -1) {
03298       AST_SCHED_DEL_UNREF(sched, peer->expire,
03299             sip_unref_peer(peer, "remove register expire ref"));
03300    }
03301    if (peer->keepalivesend != -1) {
03302       AST_SCHED_DEL_UNREF(sched, peer->keepalivesend,
03303                 sip_unref_peer(peer, "remove keepalive peer ref"));
03304    }
03305 }
03306 
03307 typedef enum {
03308    SIP_PEERS_MARKED,
03309    SIP_PEERS_ALL,
03310 } peer_unlink_flag_t;
03311 
03312 /* this func is used with ao2_callback to unlink/delete all marked or linked
03313    peers, depending on arg */
03314 static int match_and_cleanup_peer_sched(void *peerobj, void *arg, int flags)
03315 {
03316    struct sip_peer *peer = peerobj;
03317    peer_unlink_flag_t which = *(peer_unlink_flag_t *)arg;
03318 
03319    if (which == SIP_PEERS_ALL || peer->the_mark) {
03320       peer_sched_cleanup(peer);
03321       if (peer->dnsmgr) {
03322          ast_dnsmgr_release(peer->dnsmgr);
03323          peer->dnsmgr = NULL;
03324          sip_unref_peer(peer, "Release peer from dnsmgr");
03325       }
03326       return CMP_MATCH;
03327    }
03328    return 0;
03329 }
03330 
03331 static void unlink_peers_from_tables(peer_unlink_flag_t flag)
03332 {
03333    ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
03334       match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
03335    ao2_t_callback(peers_by_ip, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
03336       match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
03337 }
03338 
03339 /* \brief Unlink all marked peers from ao2 containers */
03340 static void unlink_marked_peers_from_tables(void)
03341 {
03342    unlink_peers_from_tables(SIP_PEERS_MARKED);
03343 }
03344 
03345 static void unlink_all_peers_from_tables(void)
03346 {
03347    unlink_peers_from_tables(SIP_PEERS_ALL);
03348 }
03349 
03350 /* \brief Unlink single peer from all ao2 containers */
03351 static void unlink_peer_from_tables(struct sip_peer *peer)
03352 {
03353    ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
03354    if (!ast_sockaddr_isnull(&peer->addr)) {
03355       ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
03356    }
03357 }
03358 
03359 /*! \brief maintain proper refcounts for a sip_pvt's outboundproxy
03360  *
03361  * This function sets pvt's outboundproxy pointer to the one referenced
03362  * by the proxy parameter. Because proxy may be a refcounted object, and
03363  * because pvt's old outboundproxy may also be a refcounted object, we need
03364  * to maintain the proper refcounts.
03365  *
03366  * \param pvt The sip_pvt for which we wish to set the outboundproxy
03367  * \param proxy The sip_proxy which we will point pvt towards.
03368  * \return Returns void
03369  */
03370 static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
03371 {
03372    struct sip_proxy *old_obproxy = pvt->outboundproxy;
03373    /* The sip_cfg.outboundproxy is statically allocated, and so
03374     * we don't ever need to adjust refcounts for it
03375     */
03376    if (proxy && proxy != &sip_cfg.outboundproxy) {
03377       ao2_ref(proxy, +1);
03378    }
03379    pvt->outboundproxy = proxy;
03380    if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
03381       ao2_ref(old_obproxy, -1);
03382    }
03383 }
03384 
03385 /*!
03386  * \brief Unlink a dialog from the dialogs container, as well as any other places
03387  * that it may be currently stored.
03388  *
03389  * \note A reference to the dialog must be held before calling this function, and this
03390  * function does not release that reference.
03391  */
03392 void dialog_unlink_all(struct sip_pvt *dialog)
03393 {
03394    struct sip_pkt *cp;
03395    struct ast_channel *owner;
03396 
03397    dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
03398 
03399    ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
03400    ao2_t_unlink(dialogs_needdestroy, dialog, "unlinking dialog_needdestroy via ao2_unlink");
03401    ao2_t_unlink(dialogs_rtpcheck, dialog, "unlinking dialog_rtpcheck via ao2_unlink");
03402 
03403    /* Unlink us from the owner (channel) if we have one */
03404    owner = sip_pvt_lock_full(dialog);
03405    if (owner) {
03406       ast_debug(1, "Detaching from channel %s\n", ast_channel_name(owner));
03407       ast_channel_tech_pvt_set(owner, dialog_unref(ast_channel_tech_pvt(owner), "resetting channel dialog ptr in unlink_all"));
03408       ast_channel_unlock(owner);
03409       ast_channel_unref(owner);
03410       dialog->owner = NULL;
03411    }
03412    sip_pvt_unlock(dialog);
03413 
03414    if (dialog->registry) {
03415       if (dialog->registry->call == dialog) {
03416          dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
03417       }
03418       dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
03419    }
03420    if (dialog->stateid != -1) {
03421       ast_extension_state_del(dialog->stateid, cb_extensionstate);
03422       dialog->stateid = -1;
03423    }
03424    /* Remove link from peer to subscription of MWI */
03425    if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog) {
03426       dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
03427    }
03428    if (dialog->relatedpeer && dialog->relatedpeer->call == dialog) {
03429       dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
03430    }
03431 
03432    /* remove all current packets in this dialog */
03433    while((cp = dialog->packets)) {
03434       dialog->packets = dialog->packets->next;
03435       AST_SCHED_DEL(sched, cp->retransid);
03436       dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
03437       if (cp->data) {
03438          ast_free(cp->data);
03439       }
03440       ast_free(cp);
03441    }
03442 
03443    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"));
03444 
03445    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"));
03446    
03447    if (dialog->autokillid > -1) {
03448       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"));
03449    }
03450 
03451    if (dialog->request_queue_sched_id > -1) {
03452       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"));
03453    }
03454 
03455    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"));
03456 
03457    if (dialog->t38id > -1) {
03458       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"));
03459    }
03460 
03461    if (dialog->stimer) {
03462       stop_session_timer(dialog);
03463    }
03464 
03465    dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
03466 }
03467 
03468 void *registry_unref(struct sip_registry *reg, char *tag)
03469 {
03470    ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
03471    ASTOBJ_UNREF(reg, sip_registry_destroy);
03472    return NULL;
03473 }
03474 
03475 /*! \brief Add object reference to SIP registry */
03476 static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
03477 {
03478    ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
03479    return ASTOBJ_REF(reg); /* Add pointer to registry in packet */
03480 }
03481 
03482 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
03483 static struct ast_udptl_protocol sip_udptl = {
03484    .type = "SIP",
03485    .get_udptl_info = sip_get_udptl_peer,
03486    .set_udptl_peer = sip_set_udptl_peer,
03487 };
03488 
03489 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03490    __attribute__((format(printf, 2, 3)));
03491 
03492 
03493 /*! \brief Convert transfer status to string */
03494 static const char *referstatus2str(enum referstatus rstatus)
03495 {
03496    return map_x_s(referstatusstrings, rstatus, "");
03497 }
03498 
03499 static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
03500 {
03501    if (pvt->final_destruction_scheduled) {
03502       return; /* This is already scheduled for final destruction, let the scheduler take care of it. */
03503    }
03504    append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
03505    if (!pvt->needdestroy) {
03506       pvt->needdestroy = 1;
03507       ao2_t_link(dialogs_needdestroy, pvt, "link pvt into dialogs_needdestroy container");
03508    }
03509 }
03510 
03511 /*! \brief Initialize the initital request packet in the pvt structure.
03512    This packet is used for creating replies and future requests in
03513    a dialog */
03514 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
03515 {
03516    if (p->initreq.headers) {
03517       ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
03518    } else {
03519       ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
03520    }
03521    /* Use this as the basis */
03522    copy_request(&p->initreq, req);
03523    parse_request(&p->initreq);
03524    if (req->debug) {
03525       ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
03526    }
03527 }
03528 
03529 /*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
03530 static void sip_alreadygone(struct sip_pvt *dialog)
03531 {
03532    ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
03533    dialog->alreadygone = 1;
03534 }
03535 
03536 /*! Resolve DNS srv name or host name in a sip_proxy structure */
03537 static int proxy_update(struct sip_proxy *proxy)
03538 {
03539    /* if it's actually an IP address and not a name,
03540            there's no need for a managed lookup */
03541    if (!ast_sockaddr_parse(&proxy->ip, proxy->name, 0)) {
03542       /* Ok, not an IP address, then let's check if it's a domain or host */
03543       /* XXX Todo - if we have proxy port, don't do SRV */
03544       proxy->ip.ss.ss_family = get_address_family_filter(SIP_TRANSPORT_UDP); /* Filter address family */
03545       if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
03546             ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
03547             return FALSE;
03548       }
03549 
03550    }
03551 
03552    ast_sockaddr_set_port(&proxy->ip, proxy->port);
03553 
03554    proxy->last_dnsupdate = time(NULL);
03555    return TRUE;
03556 }
03557 
03558 /*! \brief Parse proxy string and return an ao2_alloc'd proxy. If dest is
03559  *         non-NULL, no allocation is performed and dest is used instead.
03560  *         On error NULL is returned. */
03561 static struct sip_proxy *proxy_from_config(const char *proxy, int sipconf_lineno, struct sip_proxy *dest)
03562 {
03563    char *mutable_proxy, *sep, *name;
03564    int allocated = 0;
03565 
03566    if (!dest) {
03567       dest = ao2_alloc(sizeof(struct sip_proxy), NULL);
03568       if (!dest) {
03569          ast_log(LOG_WARNING, "Unable to allocate config storage for proxy\n");
03570          return NULL;
03571       }
03572       allocated = 1;
03573    }
03574 
03575    /* Format is: [transport://]name[:port][,force] */
03576    mutable_proxy = ast_skip_blanks(ast_strdupa(proxy));
03577    sep = strchr(mutable_proxy, ',');
03578    if (sep) {
03579       *sep++ = '\0';
03580       dest->force = !strncasecmp(ast_skip_blanks(sep), "force", 5);
03581    } else {
03582       dest->force = FALSE;
03583    }
03584 
03585    sip_parse_host(mutable_proxy, sipconf_lineno, &name, &dest->port, &dest->transport);
03586 
03587    /* Check that there is a name at all */
03588    if (ast_strlen_zero(name)) {
03589       if (allocated) {
03590          ao2_ref(dest, -1);
03591       } else {
03592          dest->name[0] = '\0';
03593       }
03594       return NULL;
03595    }
03596    ast_copy_string(dest->name, name, sizeof(dest->name));
03597 
03598    /* Resolve host immediately */
03599    proxy_update(dest);
03600 
03601    return dest;
03602 }
03603 
03604 /*! \brief converts ascii port to int representation. If no
03605  *  pt buffer is provided or the pt has errors when being converted
03606  *  to an int value, the port provided as the standard is used.
03607  */
03608 unsigned int port_str2int(const char *pt, unsigned int standard)
03609 {
03610    int port = standard;
03611    if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
03612       port = standard;
03613    }
03614 
03615    return port;
03616 }
03617 
03618 /*! \brief Get default outbound proxy or global proxy */
03619 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
03620 {
03621    if (dialog && dialog->options && dialog->options->outboundproxy) {
03622       if (sipdebug) {
03623          ast_debug(1, "OBPROXY: Applying dialplan set OBproxy to this call\n");
03624       }
03625       append_history(dialog, "OBproxy", "Using dialplan obproxy %s", dialog->options->outboundproxy->name);
03626       return dialog->options->outboundproxy;
03627    }
03628    if (peer && peer->outboundproxy) {
03629       if (sipdebug) {
03630          ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
03631       }
03632       append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
03633       return peer->outboundproxy;
03634    }
03635    if (sip_cfg.outboundproxy.name[0]) {
03636       if (sipdebug) {
03637          ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
03638       }
03639       append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
03640       return &sip_cfg.outboundproxy;
03641    }
03642    if (sipdebug) {
03643       ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
03644    }
03645    return NULL;
03646 }
03647 
03648 /*! \brief returns true if 'name' (with optional trailing whitespace)
03649  * matches the sip method 'id'.
03650  * Strictly speaking, SIP methods are case SENSITIVE, but we do
03651  * a case-insensitive comparison to be more tolerant.
03652  * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
03653  */
03654 static int method_match(enum sipmethod id, const char *name)
03655 {
03656    int len = strlen(sip_methods[id].text);
03657    int l_name = name ? strlen(name) : 0;
03658    /* true if the string is long enough, and ends with whitespace, and matches */
03659    return (l_name >= len && name && name[len] < 33 &&
03660       !strncasecmp(sip_methods[id].text, name, len));
03661 }
03662 
03663 /*! \brief  find_sip_method: Find SIP method from header */
03664 static int find_sip_method(const char *msg)
03665 {
03666    int i, res = 0;
03667    
03668    if (ast_strlen_zero(msg)) {
03669       return 0;
03670    }
03671    for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
03672       if (method_match(i, msg)) {
03673          res = sip_methods[i].id;
03674       }
03675    }
03676    return res;
03677 }
03678 
03679 /*! \brief See if we pass debug IP filter */
03680 static inline int sip_debug_test_addr(const struct ast_sockaddr *addr)
03681 {
03682    /* Can't debug if sipdebug is not enabled */
03683    if (!sipdebug) {
03684       return 0;
03685    }
03686 
03687    /* A null debug_addr means we'll debug any address */
03688    if (ast_sockaddr_isnull(&debugaddr)) {
03689       return 1;
03690    }
03691 
03692    /* If no port was specified for a debug address, just compare the
03693     * addresses, otherwise compare the address and port
03694     */
03695    if (ast_sockaddr_port(&debugaddr)) {
03696       return !ast_sockaddr_cmp(&debugaddr, addr);
03697    } else {
03698       return !ast_sockaddr_cmp_addr(&debugaddr, addr);
03699    }
03700 }
03701 
03702 /*! \brief The real destination address for a write */
03703 static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p)
03704 {
03705    if (p->outboundproxy) {
03706       return &p->outboundproxy->ip;
03707    }
03708 
03709    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;
03710 }
03711 
03712 /*! \brief Display SIP nat mode */
03713 static const char *sip_nat_mode(const struct sip_pvt *p)
03714 {
03715    return ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) ? "NAT" : "no NAT";
03716 }
03717 
03718 /*! \brief Test PVT for debugging output */
03719 static inline int sip_debug_test_pvt(struct sip_pvt *p)
03720 {
03721    if (!sipdebug) {
03722       return 0;
03723    }
03724    return sip_debug_test_addr(sip_real_dst(p));
03725 }
03726 
03727 /*! \brief Return int representing a bit field of transport types found in const char *transport */
03728 static int get_transport_str2enum(const char *transport)
03729 {
03730    int res = 0;
03731 
03732    if (ast_strlen_zero(transport)) {
03733       return res;
03734    }
03735 
03736    if (!strcasecmp(transport, "udp")) {
03737       res |= SIP_TRANSPORT_UDP;
03738    }
03739    if (!strcasecmp(transport, "tcp")) {
03740       res |= SIP_TRANSPORT_TCP;
03741    }
03742    if (!strcasecmp(transport, "tls")) {
03743       res |= SIP_TRANSPORT_TLS;
03744    }
03745    if (!strcasecmp(transport, "ws")) {
03746       res |= SIP_TRANSPORT_WS;
03747    }
03748    if (!strcasecmp(transport, "wss")) {
03749       res |= SIP_TRANSPORT_WSS;
03750    }
03751 
03752    return res;
03753 }
03754 
03755 /*! \brief Return configuration of transports for a device */
03756 static inline const char *get_transport_list(unsigned int transports)
03757 {
03758    char *buf;
03759 
03760    if (!transports) {
03761       return "UNKNOWN";
03762    }
03763 
03764    if (!(buf = ast_threadstorage_get(&sip_transport_str_buf, SIP_TRANSPORT_STR_BUFSIZE))) {
03765       return "";
03766    }
03767 
03768    memset(buf, 0, SIP_TRANSPORT_STR_BUFSIZE);
03769 
03770    if (transports & SIP_TRANSPORT_UDP) {
03771       strncat(buf, "UDP,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
03772    }
03773    if (transports & SIP_TRANSPORT_TCP) {
03774       strncat(buf, "TCP,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
03775    }
03776    if (transports & SIP_TRANSPORT_TLS) {
03777       strncat(buf, "TLS,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
03778    }
03779    if (transports & SIP_TRANSPORT_WS) {
03780       strncat(buf, "WS,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
03781    }
03782    if (transports & SIP_TRANSPORT_WSS) {
03783       strncat(buf, "WSS,", SIP_TRANSPORT_STR_BUFSIZE - strlen(buf));
03784    }
03785 
03786    /* Remove the trailing ',' if present */
03787    if (strlen(buf)) {
03788       buf[strlen(buf) - 1] = 0;
03789    }
03790 
03791    return buf;
03792 }
03793 
03794 /*! \brief Return transport as string */
03795 const char *sip_get_transport(enum sip_transport t)
03796 {
03797    switch (t) {
03798    case SIP_TRANSPORT_UDP:
03799       return "UDP";
03800    case SIP_TRANSPORT_TCP:
03801       return "TCP";
03802    case SIP_TRANSPORT_TLS:
03803       return "TLS";
03804    case SIP_TRANSPORT_WS:
03805    case SIP_TRANSPORT_WSS:
03806       return "WS";
03807    }
03808 
03809    return "UNKNOWN";
03810 }
03811 
03812 /*! \brief Return protocol string for srv dns query */
03813 static inline const char *get_srv_protocol(enum sip_transport t)
03814 {
03815    switch (t) {
03816    case SIP_TRANSPORT_UDP:
03817       return "udp";
03818    case SIP_TRANSPORT_WS:
03819       return "ws";
03820    case SIP_TRANSPORT_TLS:
03821    case SIP_TRANSPORT_TCP:
03822       return "tcp";
03823    case SIP_TRANSPORT_WSS:
03824       return "wss";
03825    }
03826 
03827    return "udp";
03828 }
03829 
03830 /*! \brief Return service string for srv dns query */
03831 static inline const char *get_srv_service(enum sip_transport t)
03832 {
03833    switch (t) {
03834    case SIP_TRANSPORT_TCP:
03835    case SIP_TRANSPORT_UDP:
03836    case SIP_TRANSPORT_WS:
03837       return "sip";
03838    case SIP_TRANSPORT_TLS:
03839    case SIP_TRANSPORT_WSS:
03840       return "sips";
03841    }
03842    return "sip";
03843 }
03844 
03845 /*! \brief Return transport of dialog.
03846    \note this is based on a false assumption. We don't always use the
03847    outbound proxy for all requests in a dialog. It depends on the
03848    "force" parameter. The FIRST request is always sent to the ob proxy.
03849    \todo Fix this function to work correctly
03850 */
03851 static inline const char *get_transport_pvt(struct sip_pvt *p)
03852 {
03853    if (p->outboundproxy && p->outboundproxy->transport) {
03854       set_socket_transport(&p->socket, p->outboundproxy->transport);
03855    }
03856 
03857    return sip_get_transport(p->socket.type);
03858 }
03859 
03860 /*!
03861  * \internal
03862  * \brief Transmit SIP message
03863  *
03864  * \details
03865  * Sends a SIP request or response on a given socket (in the pvt)
03866  * \note
03867  * Called by retrans_pkt, send_request, send_response and __sip_reliable_xmit
03868  *
03869  * \return length of transmitted message, XMIT_ERROR on known network failures -1 on other failures.
03870  */
03871 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data)
03872 {
03873    int res = 0;
03874    const struct ast_sockaddr *dst = sip_real_dst(p);
03875 
03876    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));
03877 
03878    if (sip_prepare_socket(p) < 0) {
03879       return XMIT_ERROR;
03880    }
03881 
03882    if (p->socket.type == SIP_TRANSPORT_UDP) {
03883       res = ast_sendto(p->socket.fd, ast_str_buffer(data), ast_str_strlen(data), 0, dst);
03884    } else if (p->socket.tcptls_session) {
03885       res = sip_tcptls_write(p->socket.tcptls_session, ast_str_buffer(data), ast_str_strlen(data));
03886    } else if (p->socket.ws_session) {
03887       if (!(res = ast_websocket_write(p->socket.ws_session, AST_WEBSOCKET_OPCODE_TEXT, ast_str_buffer(data), ast_str_strlen(data)))) {
03888          /* The WebSocket API just returns 0 on success and -1 on failure, while this code expects the payload length to be returned */
03889          res = ast_str_strlen(data);
03890       }
03891    } else {
03892       ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
03893       return XMIT_ERROR;
03894    }
03895 
03896    if (res == -1) {
03897       switch (errno) {
03898       case EBADF:    /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
03899       case EHOSTUNREACH:   /* Host can't be reached */
03900       case ENETDOWN:    /* Interface down */
03901       case ENETUNREACH: /* Network failure */
03902       case ECONNREFUSED:      /* ICMP port unreachable */
03903          res = XMIT_ERROR; /* Don't bother with trying to transmit again */
03904       }
03905    }
03906    if (res != ast_str_strlen(data)) {
03907       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));
03908    }
03909 
03910    return res;
03911 }
03912 
03913 /*! \brief Build a Via header for a request */
03914 static void build_via(struct sip_pvt *p)
03915 {
03916    /* Work around buggy UNIDEN UIP200 firmware */
03917    const char *rport = (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) || ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)) ? ";rport" : "";
03918 
03919    /* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
03920    snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s;branch=z9hG4bK%08x%s",
03921        get_transport_pvt(p),
03922        ast_sockaddr_stringify_remote(&p->ourip),
03923        (int) p->branch, rport);
03924 }
03925 
03926 /*! \brief NAT fix - decide which IP address to use for Asterisk server?
03927  *
03928  * Using the localaddr structure built up with localnet statements in sip.conf
03929  * apply it to their address to see if we need to substitute our
03930  * externaddr or can get away with our internal bindaddr
03931  * 'us' is always overwritten.
03932  */
03933 static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p)
03934 {
03935    struct ast_sockaddr theirs;
03936 
03937    /* Set want_remap to non-zero if we want to remap 'us' to an externally
03938     * reachable IP address and port. This is done if:
03939     * 1. we have a localaddr list (containing 'internal' addresses marked
03940     *    as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
03941     *    and AST_SENSE_ALLOW on 'external' ones);
03942     * 2. externaddr is set, so we know what to use as the
03943     *    externally visible address;
03944     * 3. the remote address, 'them', is external;
03945     * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
03946     *    when passed to ast_apply_ha() so it does need to be remapped.
03947     *    This fourth condition is checked later.
03948     */
03949    int want_remap = 0;
03950 
03951    ast_sockaddr_copy(us, &internip); /* starting guess for the internal address */
03952    /* now ask the system what would it use to talk to 'them' */
03953    ast_ouraddrfor(them, us);
03954    ast_sockaddr_copy(&theirs, them);
03955 
03956    if (ast_sockaddr_is_ipv6(&theirs)) {
03957       if (localaddr && !ast_sockaddr_isnull(&externaddr) && !ast_sockaddr_is_any(&bindaddr)) {
03958          ast_log(LOG_WARNING, "Address remapping activated in sip.conf "
03959             "but we're using IPv6, which doesn't need it. Please "
03960             "remove \"localnet\" and/or \"externaddr\" settings.\n");
03961       }
03962    } else {
03963       want_remap = localaddr &&
03964          !ast_sockaddr_isnull(&externaddr) &&
03965          ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
03966    }
03967 
03968    if (want_remap &&
03969        (!sip_cfg.matchexternaddrlocally || !ast_apply_ha(localaddr, us)) ) {
03970       /* if we used externhost, see if it is time to refresh the info */
03971       if (externexpire && time(NULL) >= externexpire) {
03972          if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
03973             ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
03974          }
03975          externexpire = time(NULL) + externrefresh;
03976       }
03977       if (!ast_sockaddr_isnull(&externaddr)) {
03978          ast_sockaddr_copy(us, &externaddr);
03979          switch (p->socket.type) {
03980          case SIP_TRANSPORT_TCP:
03981             if (!externtcpport && ast_sockaddr_port(&externaddr)) {
03982                /* for consistency, default to the externaddr port */
03983                externtcpport = ast_sockaddr_port(&externaddr);
03984             }
03985             ast_sockaddr_set_port(us, externtcpport);
03986             break;
03987          case SIP_TRANSPORT_TLS:
03988             ast_sockaddr_set_port(us, externtlsport);
03989             break;
03990          case SIP_TRANSPORT_UDP:
03991             if (!ast_sockaddr_port(&externaddr)) {
03992                ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
03993             }
03994             break;
03995          default:
03996             break;
03997          }
03998       }
03999       ast_debug(1, "Target address %s is not local, substituting externaddr\n",
04000            ast_sockaddr_stringify(them));
04001    } else {
04002       /* no remapping, but we bind to a specific address, so use it. */
04003       switch (p->socket.type) {
04004       case SIP_TRANSPORT_TCP:
04005          if (!ast_sockaddr_is_any(&sip_tcp_desc.local_address)) {
04006             ast_sockaddr_copy(us,
04007                     &sip_tcp_desc.local_address);
04008          } else {
04009             ast_sockaddr_set_port(us,
04010                         ast_sockaddr_port(&sip_tcp_desc.local_address));
04011          }
04012          break;
04013       case SIP_TRANSPORT_TLS:
04014          if (!ast_sockaddr_is_any(&sip_tls_desc.local_address)) {
04015             ast_sockaddr_copy(us,
04016                     &sip_tls_desc.local_address);
04017          } else {
04018             ast_sockaddr_set_port(us,
04019                         ast_sockaddr_port(&sip_tls_desc.local_address));
04020          }
04021          break;
04022       case SIP_TRANSPORT_UDP:
04023          /* fall through on purpose */
04024       default:
04025          if (!ast_sockaddr_is_any(&bindaddr)) {
04026             ast_sockaddr_copy(us, &bindaddr);
04027          }
04028          if (!ast_sockaddr_port(us)) {
04029             ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
04030          }
04031       }
04032    }
04033    ast_debug(3, "Setting SIP_TRANSPORT_%s with address %s\n", sip_get_transport(p->socket.type), ast_sockaddr_stringify(us));
04034 }
04035 
04036 /*! \brief Append to SIP dialog history with arg list  */
04037 static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
04038 {
04039    char buf[80], *c = buf; /* max history length */
04040    struct sip_history *hist;
04041    int l;
04042 
04043    vsnprintf(buf, sizeof(buf), fmt, ap);
04044    strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
04045    l = strlen(buf) + 1;
04046    if (!(hist = ast_calloc(1, sizeof(*hist) + l))) {
04047       return;
04048    }
04049    if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
04050       ast_free(hist);
04051       return;
04052    }
04053    memcpy(hist->event, buf, l);
04054    if (p->history_entries == MAX_HISTORY_ENTRIES) {
04055       struct sip_history *oldest;
04056       oldest = AST_LIST_REMOVE_HEAD(p->history, list);
04057       p->history_entries--;
04058       ast_free(oldest);
04059    }
04060    AST_LIST_INSERT_TAIL(p->history, hist, list);
04061    p->history_entries++;
04062 }
04063 
04064 /*! \brief Append to SIP dialog history with arg list  */
04065 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
04066 {
04067    va_list ap;
04068 
04069    if (!p) {
04070       return;
04071    }
04072 
04073    if (!p->do_history && !recordhistory && !dumphistory) {
04074       return;
04075    }
04076 
04077    va_start(ap, fmt);
04078    append_history_va(p, fmt, ap);
04079    va_end(ap);
04080 
04081    return;
04082 }
04083 
04084 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
04085 static int retrans_pkt(const void *data)
04086 {
04087    struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
04088    int reschedule = DEFAULT_RETRANS;
04089    int xmitres = 0;
04090    /* how many ms until retrans timeout is reached */
04091    int64_t diff = pkt->retrans_stop_time - ast_tvdiff_ms(ast_tvnow(), pkt->time_sent);
04092 
04093    /* Do not retransmit if time out is reached. This will be negative if the time between
04094     * the first transmission and now is larger than our timeout period. This is a fail safe
04095     * check in case the scheduler gets behind or the clock is changed. */
04096    if ((diff <= 0) || (diff > pkt->retrans_stop_time)) {
04097       pkt->retrans_stop = 1;
04098    }
04099 
04100    /* Lock channel PVT */
04101    sip_pvt_lock(pkt->owner);
04102 
04103    if (!pkt->retrans_stop) {
04104       pkt->retrans++;
04105       if (!pkt->timer_t1) {   /* Re-schedule using timer_a and timer_t1 */
04106          if (sipdebug) {
04107             ast_debug(4, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n",
04108                pkt->retransid,
04109                sip_methods[pkt->method].text,
04110                pkt->method);
04111          }
04112       } else {
04113          int siptimer_a;
04114 
04115          if (sipdebug) {
04116             ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n",
04117                pkt->retransid,
04118                pkt->retrans,
04119                sip_methods[pkt->method].text,
04120                pkt->method);
04121          }
04122          if (!pkt->timer_a) {
04123             pkt->timer_a = 2 ;
04124          } else {
04125             pkt->timer_a = 2 * pkt->timer_a;
04126          }
04127 
04128          /* For non-invites, a maximum of 4 secs */
04129          siptimer_a = pkt->timer_t1 * pkt->timer_a;   /* Double each time */
04130          if (pkt->method != SIP_INVITE && siptimer_a > 4000) {
04131             siptimer_a = 4000;
04132          }
04133 
04134          /* Reschedule re-transmit */
04135          reschedule = siptimer_a;
04136          ast_debug(4, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n",
04137             pkt->retrans + 1,
04138             siptimer_a,
04139             pkt->timer_t1,
04140             pkt->retransid);
04141       }
04142 
04143       if (sip_debug_test_pvt(pkt->owner)) {
04144          const struct ast_sockaddr *dst = sip_real_dst(pkt->owner);
04145          ast_verbose("Retransmitting #%d (%s) to %s:\n%s\n---\n",
04146             pkt->retrans, sip_nat_mode(pkt->owner),
04147             ast_sockaddr_stringify(dst),
04148             ast_str_buffer(pkt->data));
04149       }
04150 
04151       append_history(pkt->owner, "ReTx", "%d %s", reschedule, ast_str_buffer(pkt->data));
04152       xmitres = __sip_xmit(pkt->owner, pkt->data);
04153 
04154       /* If there was no error during the network transmission, schedule the next retransmission,
04155        * but if the next retransmission is going to be beyond our timeout period, mark the packet's
04156        * stop_retrans value and set the next retransmit to be the exact time of timeout.  This will
04157        * allow any responses to the packet to be processed before the packet is destroyed on the next
04158        * call to this function by the scheduler. */
04159       if (xmitres != XMIT_ERROR) {
04160          if (reschedule >= diff) {
04161             pkt->retrans_stop = 1;
04162             reschedule = diff;
04163          }
04164          sip_pvt_unlock(pkt->owner);
04165          return  reschedule;
04166       }
04167    }
04168 
04169    /* At this point, either the packet's retransmission timed out, or there was a
04170     * transmission error, either way destroy the scheduler item and this packet. */
04171 
04172    pkt->retransid = -1; /* Kill this scheduler item */
04173 
04174    if (pkt->method != SIP_OPTIONS && xmitres == 0) {
04175       if (pkt->is_fatal || sipdebug) { /* Tell us if it's critical or if we're debugging */
04176          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"
04177             "Packet timed out after %dms with no response\n",
04178             pkt->owner->callid,
04179             pkt->seqno,
04180             pkt->is_fatal ? "Critical" : "Non-critical",
04181             pkt->is_resp ? "Response" : "Request",
04182             (int) ast_tvdiff_ms(ast_tvnow(), pkt->time_sent));
04183       }
04184    } else if (pkt->method == SIP_OPTIONS && sipdebug) {
04185       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);
04186    }
04187 
04188    if (xmitres == XMIT_ERROR) {
04189       ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
04190       append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
04191    } else {
04192       append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
04193    }
04194 
04195    if (pkt->is_fatal) {
04196       while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
04197          sip_pvt_unlock(pkt->owner);   /* SIP_PVT, not channel */
04198          usleep(1);
04199          sip_pvt_lock(pkt->owner);
04200       }
04201       if (pkt->owner->owner && !ast_channel_hangupcause(pkt->owner->owner)) {
04202          ast_channel_hangupcause_set(pkt->owner->owner, AST_CAUSE_NO_USER_RESPONSE);
04203       }
04204       if (pkt->owner->owner) {
04205          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);
04206 
04207          if (pkt->is_resp &&
04208             (pkt->response_code >= 200) &&
04209             (pkt->response_code < 300) &&
04210             pkt->owner->pendinginvite &&
04211             ast_test_flag(&pkt->owner->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
04212             /* This is a timeout of the 2XX response to a pending INVITE.  In this case terminate the INVITE
04213              * transaction just as if we received the ACK, but immediately hangup with a BYE (sip_hangup
04214              * will send the BYE as long as the dialog is not set as "alreadygone")
04215              * RFC 3261 section 13.3.1.4.
04216              * "If the server retransmits the 2xx response for 64*T1 seconds without receiving
04217              * an ACK, the dialog is confirmed, but the session SHOULD be terminated.  This is
04218              * accomplished with a BYE, as described in Section 15." */
04219             pkt->owner->invitestate = INV_TERMINATED;
04220             pkt->owner->pendinginvite = 0;
04221          } else {
04222             /* there is nothing left to do, mark the dialog as gone */
04223             sip_alreadygone(pkt->owner);
04224          }
04225          ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_NO_USER_RESPONSE);
04226          ast_channel_unlock(pkt->owner->owner);
04227       } else {
04228          /* If no channel owner, destroy now */
04229 
04230          /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
04231          if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
04232             pvt_set_needdestroy(pkt->owner, "no response to critical packet");
04233             sip_alreadygone(pkt->owner);
04234             append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
04235          }
04236       }
04237    }
04238 
04239    if (pkt->method == SIP_BYE) {
04240       /* We're not getting answers on SIP BYE's.  Tear down the call anyway. */
04241       sip_alreadygone(pkt->owner);
04242       if (pkt->owner->owner) {
04243          ast_channel_unlock(pkt->owner->owner);
04244       }
04245       append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
04246       pvt_set_needdestroy(pkt->owner, "no response to BYE");
04247    }
04248 
04249    /* Remove the packet */
04250    for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
04251       if (cur == pkt) {
04252          UNLINK(cur, pkt->owner->packets, prev);
04253          sip_pvt_unlock(pkt->owner);
04254          if (pkt->owner) {
04255             pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
04256          }
04257          if (pkt->data) {
04258             ast_free(pkt->data);
04259          }
04260          pkt->data = NULL;
04261          ast_free(pkt);
04262          return 0;
04263       }
04264    }
04265    /* error case */
04266    ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
04267    sip_pvt_unlock(pkt->owner);
04268    return 0;
04269 }
04270 
04271 /*!
04272  * \internal
04273  * \brief Transmit packet with retransmits
04274  * \return 0 on success, -1 on failure to allocate packet
04275  */
04276 static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, uint32_t seqno, int resp, struct ast_str *data, int fatal, int sipmethod)
04277 {
04278    struct sip_pkt *pkt = NULL;
04279    int siptimer_a = DEFAULT_RETRANS;
04280    int xmitres = 0;
04281    int respid;
04282 
04283    if (sipmethod == SIP_INVITE) {
04284       /* Note this is a pending invite */
04285       p->pendinginvite = seqno;
04286    }
04287 
04288    /* If the transport is something reliable (TCP or TLS) then don't really send this reliably */
04289    /* I removed the code from retrans_pkt that does the same thing so it doesn't get loaded into the scheduler */
04290    /*! \todo According to the RFC some packets need to be retransmitted even if its TCP, so this needs to get revisited */
04291    if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
04292       xmitres = __sip_xmit(p, data);   /* Send packet */
04293       if (xmitres == XMIT_ERROR) {  /* Serious network trouble, no need to try again */
04294          append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
04295          return AST_FAILURE;
04296       } else {
04297          return AST_SUCCESS;
04298       }
04299    }
04300 
04301    if (!(pkt = ast_calloc(1, sizeof(*pkt)))) {
04302       return AST_FAILURE;
04303    }
04304    /* copy data, add a terminator and save length */
04305    if (!(pkt->data = ast_str_create(ast_str_strlen(data)))) {
04306       ast_free(pkt);
04307       return AST_FAILURE;
04308    }
04309    ast_str_set(&pkt->data, 0, "%s%s", ast_str_buffer(data), "\0");
04310    /* copy other parameters from the caller */
04311    pkt->method = sipmethod;
04312    pkt->seqno = seqno;
04313    pkt->is_resp = resp;
04314    pkt->is_fatal = fatal;
04315    pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
04316    pkt->next = p->packets;
04317    p->packets = pkt; /* Add it to the queue */
04318    if (resp) {
04319       /* Parse out the response code */
04320       if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
04321          pkt->response_code = respid;
04322       }
04323    }
04324    pkt->timer_t1 = p->timer_t1;  /* Set SIP timer T1 */
04325    pkt->retransid = -1;
04326    if (pkt->timer_t1) {
04327       siptimer_a = pkt->timer_t1;
04328    }
04329 
04330    pkt->time_sent = ast_tvnow(); /* time packet was sent */
04331    pkt->retrans_stop_time = 64 * (pkt->timer_t1 ? pkt->timer_t1 : DEFAULT_TIMER_T1); /* time in ms after pkt->time_sent to stop retransmission */
04332 
04333    /* Schedule retransmission */
04334    AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
04335    if (sipdebug) {
04336       ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id  #%d\n", pkt->retransid);
04337    }
04338 
04339    xmitres = __sip_xmit(pkt->owner, pkt->data); /* Send packet */
04340 
04341    if (xmitres == XMIT_ERROR) {  /* Serious network trouble, no need to try again */
04342       append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
04343       ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
04344       AST_SCHED_DEL(sched, pkt->retransid);
04345       p->packets = pkt->next;
04346       pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
04347       ast_free(pkt->data);
04348       ast_free(pkt);
04349       return AST_FAILURE;
04350    } else {
04351       /* This is odd, but since the retrans timer starts at 500ms and the do_monitor thread
04352        * only wakes up every 1000ms by default, we have to poke the thread here to make
04353        * sure it successfully detects this must be retransmitted in less time than
04354        * it usually sleeps for. Otherwise it might not retransmit this packet for 1000ms. */
04355       if (monitor_thread != AST_PTHREADT_NULL) {
04356          pthread_kill(monitor_thread, SIGURG);
04357       }
04358       return AST_SUCCESS;
04359    }
04360 }
04361 
04362 /*! \brief Kill a SIP dialog (called only by the scheduler)
04363  * The scheduler has a reference to this dialog when p->autokillid != -1,
04364  * and we are called using that reference. So if the event is not
04365  * rescheduled, we need to call dialog_unref().
04366  */
04367 static int __sip_autodestruct(const void *data)
04368 {
04369    struct sip_pvt *p = (struct sip_pvt *)data;
04370    struct ast_channel *owner;
04371 
04372    /* If this is a subscription, tell the phone that we got a timeout */
04373    if (p->subscribed && p->subscribed != MWI_NOTIFICATION && p->subscribed != CALL_COMPLETION) {
04374       struct state_notify_data data = { 0, };
04375       data.state = AST_EXTENSION_DEACTIVATED;
04376 
04377       transmit_state_notify(p, &data, 1, TRUE); /* Send last notification */
04378       p->subscribed = NONE;
04379       append_history(p, "Subscribestatus", "timeout");
04380       ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
04381       return 10000;  /* Reschedule this destruction so that we know that it's gone */
04382    }
04383 
04384    /* If there are packets still waiting for delivery, delay the destruction */
04385    if (p->packets) {
04386       if (!p->needdestroy) {
04387          char method_str[31];
04388          ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
04389          append_history(p, "ReliableXmit", "timeout");
04390          if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
04391             if (p->ongoing_reinvite || method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
04392                pvt_set_needdestroy(p, "autodestruct");
04393             }
04394          }
04395          return 10000;
04396       } else {
04397          /* They've had their chance to respond. Time to bail */
04398          __sip_pretend_ack(p);
04399       }
04400    }
04401 
04402    /* Reset schedule ID */
04403    p->autokillid = -1;
04404 
04405    /*
04406     * Lock both the pvt and the channel safely so that we can queue up a frame.
04407     */
04408    owner = sip_pvt_lock_full(p);
04409    if (owner) {
04410       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);
04411       ast_queue_hangup_with_cause(owner, AST_CAUSE_PROTOCOL_ERROR);
04412       ast_channel_unlock(owner);
04413       ast_channel_unref(owner);
04414       sip_pvt_unlock(p);
04415       return 10000;
04416    } else if (p->refer && !p->alreadygone) {
04417       ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
04418       stop_media_flows(p);
04419       transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
04420       append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
04421       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
04422    } else {
04423       append_history(p, "AutoDestroy", "%s", p->callid);
04424       ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
04425       sip_pvt_unlock(p);
04426       dialog_unlink_all(p); /* once it's unlinked and unrefd everywhere, it'll be freed automagically */
04427       sip_pvt_lock(p);
04428       /* dialog_unref(p, "unref dialog-- no other matching conditions"); -- unlink all now should finish off the dialog's references and free it. */
04429       /* sip_destroy(p); */      /* Go ahead and destroy dialog. All attempts to recover is done */
04430       /* sip_destroy also absorbs the reference */
04431    }
04432 
04433    sip_pvt_unlock(p);
04434 
04435    dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
04436 
04437    return 0;
04438 }
04439 
04440 /*! \brief Schedule final destruction of SIP dialog.  This can not be canceled.
04441  *  This function is used to keep a dialog around for a period of time in order
04442  *  to properly respond to any retransmits. */
04443 void sip_scheddestroy_final(struct sip_pvt *p, int ms)
04444 {
04445    if (p->final_destruction_scheduled) {
04446       return; /* already set final destruction */
04447    }
04448 
04449    sip_scheddestroy(p, ms);
04450    if (p->autokillid != -1) {
04451       p->final_destruction_scheduled = 1;
04452    }
04453 }
04454 
04455 /*! \brief Schedule destruction of SIP dialog */
04456 void sip_scheddestroy(struct sip_pvt *p, int ms)
04457 {
04458    if (p->final_destruction_scheduled) {
04459       return; /* already set final destruction */
04460    }
04461 
04462    if (ms < 0) {
04463       if (p->timer_t1 == 0) {
04464          p->timer_t1 = global_t1;   /* Set timer T1 if not set (RFC 3261) */
04465       }
04466       if (p->timer_b == 0) {
04467          p->timer_b = global_timer_b;  /* Set timer B if not set (RFC 3261) */
04468       }
04469       ms = p->timer_t1 * 64;
04470    }
04471    if (sip_debug_test_pvt(p)) {
04472       ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
04473    }
04474    if (sip_cancel_destroy(p)) {
04475       ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
04476    }
04477 
04478    if (p->do_history) {
04479       append_history(p, "SchedDestroy", "%d ms", ms);
04480    }
04481    p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
04482 
04483    if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0) {
04484       stop_session_timer(p);
04485    }
04486 }
04487 
04488 /*! \brief Cancel destruction of SIP dialog.
04489  * Be careful as this also absorbs the reference - if you call it
04490  * from within the scheduler, this might be the last reference.
04491  */
04492 int sip_cancel_destroy(struct sip_pvt *p)
04493 {
04494    if (p->final_destruction_scheduled) {
04495       return 0;
04496    }
04497 
04498    if (p->autokillid > -1) {
04499       append_history(p, "CancelDestroy", "");
04500       AST_SCHED_DEL_UNREF(sched, p->autokillid, dialog_unref(p, "remove ref for autokillid"));
04501    }
04502    return 0;
04503 }
04504 
04505 /*! \brief Acknowledges receipt of a packet and stops retransmission
04506  * called with p locked*/
04507 int __sip_ack(struct sip_pvt *p, uint32_t seqno, int resp, int sipmethod)
04508 {
04509    struct sip_pkt *cur, *prev = NULL;
04510    const char *msg = "Not Found";   /* used only for debugging */
04511    int res = FALSE;
04512 
04513    /* If we have an outbound proxy for this dialog, then delete it now since
04514      the rest of the requests in this dialog needs to follow the routing.
04515      If obforcing is set, we will keep the outbound proxy during the whole
04516      dialog, regardless of what the SIP rfc says
04517    */
04518    if (p->outboundproxy && !p->outboundproxy->force){
04519       ref_proxy(p, NULL);
04520    }
04521 
04522    for (cur = p->packets; cur; prev = cur, cur = cur->next) {
04523       if (cur->seqno != seqno || cur->is_resp != resp) {
04524          continue;
04525       }
04526       if (cur->is_resp || cur->method == sipmethod) {
04527          res = TRUE;
04528          msg = "Found";
04529          if (!resp && (seqno == p->pendinginvite)) {
04530             ast_debug(1, "Acked pending invite %u\n", p->pendinginvite);
04531             p->pendinginvite = 0;
04532          }
04533          if (cur->retransid > -1) {
04534             if (sipdebug)
04535                ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
04536          }
04537          /* This odd section is designed to thwart a
04538           * race condition in the packet scheduler. There are
04539           * two conditions under which deleting the packet from the
04540           * scheduler can fail.
04541           *
04542           * 1. The packet has been removed from the scheduler because retransmission
04543           * is being attempted. The problem is that if the packet is currently attempting
04544           * retransmission and we are at this point in the code, then that MUST mean
04545           * that retrans_pkt is waiting on p's lock. Therefore we will relinquish the
04546           * lock temporarily to allow retransmission.
04547           *
04548           * 2. The packet has reached its maximum number of retransmissions and has
04549           * been permanently removed from the packet scheduler. If this is the case, then
04550           * the packet's retransid will be set to -1. The atomicity of the setting and checking
04551           * of the retransid to -1 is ensured since in both cases p's lock is held.
04552           */
04553          while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
04554             sip_pvt_unlock(p);
04555             usleep(1);
04556             sip_pvt_lock(p);
04557          }
04558          UNLINK(cur, p->packets, prev);
04559          dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
04560          if (cur->data) {
04561             ast_free(cur->data);
04562          }
04563          ast_free(cur);
04564          break;
04565       }
04566    }
04567    ast_debug(1, "Stopping retransmission on '%s' of %s %u: Match %s\n",
04568       p->callid, resp ? "Response" : "Request", seqno, msg);
04569    return res;
04570 }
04571 
04572 /*! \brief Pretend to ack all packets
04573  * called with p locked */
04574 void __sip_pretend_ack(struct sip_pvt *p)
04575 {
04576    struct sip_pkt *cur = NULL;
04577 
04578    while (p->packets) {
04579       int method;
04580       if (cur == p->packets) {
04581          ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
04582          return;
04583       }
04584       cur = p->packets;
04585       method = (cur->method) ? cur->method : find_sip_method(ast_str_buffer(cur->data));
04586       __sip_ack(p, cur->seqno, cur->is_resp, method);
04587    }
04588 }
04589 
04590 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
04591 int __sip_semi_ack(struct sip_pvt *p, uint32_t seqno, int resp, int sipmethod)
04592 {
04593    struct sip_pkt *cur;
04594    int res = FALSE;
04595 
04596    for (cur = p->packets; cur; cur = cur->next) {
04597       if (cur->seqno == seqno && cur->is_resp == resp &&
04598          (cur->is_resp || method_match(sipmethod, ast_str_buffer(cur->data)))) {
04599          /* this is our baby */
04600          if (cur->retransid > -1) {
04601             if (sipdebug)
04602                ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
04603          }
04604          AST_SCHED_DEL(sched, cur->retransid);
04605          res = TRUE;
04606          break;
04607       }
04608    }
04609    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");
04610    return res;
04611 }
04612 
04613 
04614 /*! \brief Copy SIP request, parse it */
04615 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
04616 {
04617    copy_request(dst, src);
04618    parse_request(dst);
04619 }
04620 
04621 /*! \brief add a blank line if no body */
04622 static void add_blank(struct sip_request *req)
04623 {
04624    if (!req->lines) {
04625       /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
04626       ast_str_append(&req->data, 0, "\r\n");
04627    }
04628 }
04629 
04630 static int send_provisional_keepalive_full(struct sip_pvt *pvt, int with_sdp)
04631 {
04632    const char *msg = NULL;
04633    struct ast_channel *chan;
04634    int res = 0;
04635    int old_sched_id = pvt->provisional_keepalive_sched_id;
04636 
04637    chan = sip_pvt_lock_full(pvt);
04638    /* Check that nothing has changed while we were waiting for the lock */
04639    if (old_sched_id != pvt->provisional_keepalive_sched_id) {
04640       /* Keepalive has been cancelled or rescheduled, clean up and leave */
04641       if (chan) {
04642          ast_channel_unlock(chan);
04643          chan = ast_channel_unref(chan);
04644       }
04645       sip_pvt_unlock(pvt);
04646       dialog_unref(pvt, "dialog ref for provisional keepalive");
04647       return 0;
04648    }
04649 
04650    if (!pvt->last_provisional || !strncasecmp(pvt->last_provisional, "100", 3)) {
04651       msg = "183 Session Progress";
04652    }
04653 
04654    if (pvt->invitestate < INV_COMPLETED) {
04655       if (with_sdp) {
04656          transmit_response_with_sdp(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq, XMIT_UNRELIABLE, FALSE, FALSE);
04657       } else {
04658          transmit_response(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq);
04659       }
04660       res = PROVIS_KEEPALIVE_TIMEOUT;
04661    }
04662 
04663    if (chan) {
04664       ast_channel_unlock(chan);
04665       chan = ast_channel_unref(chan);
04666    }
04667 
04668    if (!res) {
04669       pvt->provisional_keepalive_sched_id = -1;
04670    }
04671 
04672    sip_pvt_unlock(pvt);
04673 
04674    if (!res) {
04675       dialog_unref(pvt, "dialog ref for provisional keepalive");
04676    }
04677    return res;
04678 }
04679 
04680 static int send_provisional_keepalive(const void *data)
04681 {
04682    struct sip_pvt *pvt = (struct sip_pvt *) data;
04683 
04684    return send_provisional_keepalive_full(pvt, 0);
04685 }
04686 
04687 static int send_provisional_keepalive_with_sdp(const void *data)
04688 {
04689    struct sip_pvt *pvt = (void *) data;
04690 
04691    return send_provisional_keepalive_full(pvt, 1);
04692 }
04693 
04694 static void update_provisional_keepalive(struct sip_pvt *pvt, int with_sdp)
04695 {
04696    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"));
04697 
04698    pvt->provisional_keepalive_sched_id = ast_sched_add(sched, PROVIS_KEEPALIVE_TIMEOUT,
04699       with_sdp ? send_provisional_keepalive_with_sdp : send_provisional_keepalive, dialog_ref(pvt, "Increment refcount to pass dialog pointer to sched callback"));
04700 }
04701 
04702 static void add_required_respheader(struct sip_request *req)
04703 {
04704    struct ast_str *str;
04705    int i;
04706 
04707    if (!req->reqsipoptions) {
04708       return;
04709    }
04710 
04711    str = ast_str_create(32);
04712 
04713    for (i = 0; i < ARRAY_LEN(sip_options); ++i) {
04714       if (!(req->reqsipoptions & sip_options[i].id)) {
04715          continue;
04716       }
04717       if (ast_str_strlen(str) > 0) {
04718          ast_str_append(&str, 0, ", ");
04719       }
04720       ast_str_append(&str, 0, "%s", sip_options[i].text);
04721    }
04722 
04723    if (ast_str_strlen(str) > 0) {
04724       add_header(req, "Require", ast_str_buffer(str));
04725    }
04726 
04727    ast_free(str);
04728 }
04729 
04730 /*! \brief Transmit response on SIP request*/
04731 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno)
04732 {
04733    int res;
04734 
04735    finalize_content(req);
04736    add_blank(req);
04737    if (sip_debug_test_pvt(p)) {
04738       const struct ast_sockaddr *dst = sip_real_dst(p);
04739 
04740       ast_verbose("\n<--- %sTransmitting (%s) to %s --->\n%s\n<------------>\n",
04741          reliable ? "Reliably " : "", sip_nat_mode(p),
04742          ast_sockaddr_stringify(dst),
04743          ast_str_buffer(req->data));
04744    }
04745    if (p->do_history) {
04746       struct sip_request tmp = { .rlpart1 = 0, };
04747       parse_copy(&tmp, req);
04748       append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", ast_str_buffer(tmp.data), sip_get_header(&tmp, "CSeq"),
04749          (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? REQ_OFFSET_TO_STR(&tmp, rlpart2) : sip_methods[tmp.method].text);
04750       deinit_req(&tmp);
04751    }
04752 
04753    /* If we are sending a final response to an INVITE, stop retransmitting provisional responses */
04754    if (p->initreq.method == SIP_INVITE && reliable == XMIT_CRITICAL) {
04755       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"));
04756    }
04757 
04758    res = (reliable) ?
04759        __sip_reliable_xmit(p, seqno, 1, req->data, (reliable == XMIT_CRITICAL), req->method) :
04760       __sip_xmit(p, req->data);
04761    deinit_req(req);
04762    if (res > 0) {
04763       return 0;
04764    }
04765    return res;
04766 }
04767 
04768 /*!
04769  * \internal
04770  * \brief Send SIP Request to the other part of the dialogue
04771  * \return see \ref __sip_xmit
04772  */
04773 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno)
04774 {
04775    int res;
04776 
04777    /* If we have an outbound proxy, reset peer address
04778       Only do this once.
04779    */
04780    if (p->outboundproxy) {
04781       p->sa = p->outboundproxy->ip;
04782    }
04783 
04784    finalize_content(req);
04785    add_blank(req);
04786    if (sip_debug_test_pvt(p)) {
04787       if (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT)) {
04788          ast_verbose("%sTransmitting (NAT) to %s:\n%s\n---\n", reliable ? "Reliably " : "", ast_sockaddr_stringify(&p->recv), ast_str_buffer(req->data));
04789       } else {
04790          ast_verbose("%sTransmitting (no NAT) to %s:\n%s\n---\n", reliable ? "Reliably " : "", ast_sockaddr_stringify(&p->sa), ast_str_buffer(req->data));
04791       }
04792    }
04793    if (p->do_history) {
04794       struct sip_request tmp = { .rlpart1 = 0, };
04795       parse_copy(&tmp, req);
04796       append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", ast_str_buffer(tmp.data), sip_get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
04797       deinit_req(&tmp);
04798    }
04799    res = (reliable) ?
04800       __sip_reliable_xmit(p, seqno, 0, req->data, (reliable == XMIT_CRITICAL), req->method) :
04801       __sip_xmit(p, req->data);
04802    deinit_req(req);
04803    return res;
04804 }
04805 
04806 static void enable_dsp_detect(struct sip_pvt *p)
04807 {
04808    int features = 0;
04809 
04810    if (p->dsp) {
04811       return;
04812    }
04813 
04814    if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
04815        (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
04816       if (p->rtp) {
04817          ast_rtp_instance_dtmf_mode_set(p->rtp, AST_RTP_DTMF_MODE_INBAND);
04818       }
04819       features |= DSP_FEATURE_DIGIT_DETECT;
04820    }
04821 
04822    if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
04823       features |= DSP_FEATURE_FAX_DETECT;
04824    }
04825 
04826    if (!features) {
04827       return;
04828    }
04829 
04830    if (!(p->dsp = ast_dsp_new())) {
04831       return;
04832    }
04833 
04834    ast_dsp_set_features(p->dsp, features);
04835    if (global_relaxdtmf) {
04836       ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
04837    }
04838 }
04839 
04840 static void disable_dsp_detect(struct sip_pvt *p)
04841 {
04842    if (p->dsp) {
04843       ast_dsp_free(p->dsp);
04844       p->dsp = NULL;
04845    }
04846 }
04847 
04848 /*! \brief Set an option on a SIP dialog */
04849 static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen)
04850 {
04851    int res = -1;
04852    struct sip_pvt *p = ast_channel_tech_pvt(chan);
04853 
04854         if (!p) {
04855       ast_log(LOG_ERROR, "Attempt to Ref a null pointer.  sip private structure is gone!\n");
04856       return -1;
04857         }
04858 
04859    sip_pvt_lock(p);
04860 
04861    switch (option) {
04862    case AST_OPTION_FORMAT_READ:
04863       if (p->rtp) {
04864          res = ast_rtp_instance_set_read_format(p->rtp, (struct ast_format *) data);
04865       }
04866       break;
04867    case AST_OPTION_FORMAT_WRITE:
04868       if (p->rtp) {
04869          res = ast_rtp_instance_set_write_format(p->rtp, (struct ast_format *) data);
04870       }
04871       break;
04872    case AST_OPTION_MAKE_COMPATIBLE:
04873       if (p->rtp) {
04874          res = ast_rtp_instance_make_compatible(chan, p->rtp, (struct ast_channel *) data);
04875       }
04876       break;
04877    case AST_OPTION_DIGIT_DETECT:
04878       if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
04879           (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
04880          char *cp = (char *) data;
04881 
04882          ast_debug(1, "%sabling digit detection on %s\n", *cp ? "En" : "Dis", ast_channel_name(chan));
04883          if (*cp) {
04884             enable_dsp_detect(p);
04885          } else {
04886             disable_dsp_detect(p);
04887          }
04888          res = 0;
04889       }
04890       break;
04891    case AST_OPTION_SECURE_SIGNALING:
04892       p->req_secure_signaling = *(unsigned int *) data;
04893       res = 0;
04894       break;
04895    case AST_OPTION_SECURE_MEDIA:
04896       ast_set2_flag(&p->flags[1], *(unsigned int *) data, SIP_PAGE2_USE_SRTP);
04897       res = 0;
04898       break;
04899    default:
04900       break;
04901    }
04902 
04903    sip_pvt_unlock(p);
04904 
04905    return res;
04906 }
04907 
04908 /*! \brief Query an option on a SIP dialog */
04909 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
04910 {
04911    int res = -1;
04912    enum ast_t38_state state = T38_STATE_UNAVAILABLE;
04913    struct sip_pvt *p = (struct sip_pvt *) ast_channel_tech_pvt(chan);
04914    char *cp;
04915 
04916    sip_pvt_lock(p);
04917 
04918    switch (option) {
04919    case AST_OPTION_T38_STATE:
04920       /* Make sure we got an ast_t38_state enum passed in */
04921       if (*datalen != sizeof(enum ast_t38_state)) {
04922          ast_log(LOG_ERROR, "Invalid datalen for AST_OPTION_T38_STATE option. Expected %d, got %d\n", (int)sizeof(enum ast_t38_state), *datalen);
04923          break;
04924       }
04925 
04926       /* 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 */
04927       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
04928          switch (p->t38.state) {
04929          case T38_LOCAL_REINVITE:
04930          case T38_PEER_REINVITE:
04931             state = T38_STATE_NEGOTIATING;
04932             break;
04933          case T38_ENABLED:
04934             state = T38_STATE_NEGOTIATED;
04935             break;
04936          case T38_REJECTED:
04937             state = T38_STATE_REJECTED;
04938             break;
04939          default:
04940             state = T38_STATE_UNKNOWN;
04941          }
04942       }
04943 
04944       *((enum ast_t38_state *) data) = state;
04945       res = 0;
04946 
04947       break;
04948    case AST_OPTION_DIGIT_DETECT:
04949       cp = (char *) data;
04950       *cp = p->dsp ? 1 : 0;
04951       ast_debug(1, "Reporting digit detection %sabled on %s\n", *cp ? "en" : "dis", ast_channel_name(chan));
04952       break;
04953    case AST_OPTION_SECURE_SIGNALING:
04954       *((unsigned int *) data) = p->req_secure_signaling;
04955       res = 0;
04956       break;
04957    case AST_OPTION_SECURE_MEDIA:
04958       *((unsigned int *) data) = ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP) ? 1 : 0;
04959       res = 0;
04960       break;
04961    case AST_OPTION_DEVICE_NAME:
04962       if (p && p->outgoing_call) {
04963          cp = (char *) data;
04964          ast_copy_string(cp, p->dialstring, *datalen);
04965          res = 0;
04966       }
04967       /* We purposely break with a return of -1 in the
04968        * implied else case here
04969        */
04970       break;
04971    default:
04972       break;
04973    }
04974 
04975    sip_pvt_unlock(p);
04976 
04977    return res;
04978 }
04979 
04980 /*! \brief Locate closing quote in a string, skipping escaped quotes.
04981  * optionally with a limit on the search.
04982  * start must be past the first quote.
04983  */
04984 const char *find_closing_quote(const char *start, const char *lim)
04985 {
04986    char last_char = '\0';
04987    const char *s;
04988    for (s = start; *s && s != lim; last_char = *s++) {
04989       if (*s == '"' && last_char != '\\')
04990          break;
04991    }
04992    return s;
04993 }
04994 
04995 /*! \brief Send message with Access-URL header, if this is an HTML URL only! */
04996 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
04997 {
04998    struct sip_pvt *p = ast_channel_tech_pvt(chan);
04999 
05000    if (subclass != AST_HTML_URL)
05001       return -1;
05002 
05003    ast_string_field_build(p, url, "<%s>;mode=active", data);
05004 
05005    if (sip_debug_test_pvt(p))
05006       ast_debug(1, "Send URL %s, state = %d!\n", data, ast_channel_state(chan));
05007 
05008    switch (ast_channel_state(chan)) {
05009    case AST_STATE_RING:
05010       transmit_response(p, "100 Trying", &p->initreq);
05011       break;
05012    case AST_STATE_RINGING:
05013       transmit_response(p, "180 Ringing", &p->initreq);
05014       break;
05015    case AST_STATE_UP:
05016       if (!p->pendinginvite) {      /* We are up, and have no outstanding invite */
05017          transmit_reinvite_with_sdp(p, FALSE, FALSE);
05018       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
05019          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
05020       }
05021       break;
05022    default:
05023       ast_log(LOG_WARNING, "Don't know how to send URI when state is %d!\n", ast_channel_state(chan));
05024    }
05025 
05026    return 0;
05027 }
05028 
05029 /*! \brief Deliver SIP call ID for the call */
05030 static const char *sip_get_callid(struct ast_channel *chan)
05031 {
05032    return ast_channel_tech_pvt(chan) ? ((struct sip_pvt *) ast_channel_tech_pvt(chan))->callid : "";
05033 }
05034 
05035 /*!
05036  * \internal
05037  * \brief Send SIP MESSAGE text within a call
05038  * \note Called from PBX core sendtext() application
05039  */
05040 static int sip_sendtext(struct ast_channel *ast, const char *text)
05041 {
05042    struct sip_pvt *dialog = ast_channel_tech_pvt(ast);
05043    int debug;
05044 
05045    if (!dialog) {
05046       return -1;
05047    }
05048    /* NOT ast_strlen_zero, because a zero-length message is specifically
05049     * allowed by RFC 3428 (See section 10, Examples) */
05050    if (!text) {
05051       return 0;
05052    }
05053    if(!is_method_allowed(&dialog->allowed_methods, SIP_MESSAGE)) {
05054       ast_debug(2, "Trying to send MESSAGE to device that does not support it.\n");
05055       return 0;
05056    }
05057 
05058    debug = sip_debug_test_pvt(dialog);
05059    if (debug) {
05060       ast_verbose("Sending text %s on %s\n", text, ast_channel_name(ast));
05061    }
05062 
05063    /* Setup to send text message */
05064    sip_pvt_lock(dialog);
05065    destroy_msg_headers(dialog);
05066    ast_string_field_set(dialog, msg_body, text);
05067    transmit_message(dialog, 0, 0);
05068    sip_pvt_unlock(dialog);
05069    return 0;
05070 }
05071 
05072 /*! \brief Update peer object in realtime storage
05073    If the Asterisk system name is set in asterisk.conf, we will use
05074    that name and store that in the "regserver" field in the sippeers
05075    table to facilitate multi-server setups.
05076 */
05077 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)
05078 {
05079    char port[10];
05080    char ipaddr[INET6_ADDRSTRLEN];
05081    char regseconds[20];
05082    char *tablename = NULL;
05083    char str_lastms[20];
05084 
05085    const char *sysname = ast_config_AST_SYSTEM_NAME;
05086    char *syslabel = NULL;
05087 
05088    time_t nowtime = time(NULL) + expirey;
05089    const char *fc = fullcontact ? "fullcontact" : NULL;
05090 
05091    int realtimeregs = ast_check_realtime("sipregs");
05092 
05093    tablename = realtimeregs ? "sipregs" : "sippeers";
05094 
05095    snprintf(str_lastms, sizeof(str_lastms), "%d", lastms);
05096    snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);  /* Expiration time */
05097    ast_copy_string(ipaddr, ast_sockaddr_isnull(addr) ? "" : ast_sockaddr_stringify_addr(addr), sizeof(ipaddr));
05098    ast_copy_string(port, ast_sockaddr_port(addr) ? ast_sockaddr_stringify_port(addr) : "", sizeof(port));
05099 
05100    if (ast_strlen_zero(sysname)) /* No system name, disable this */
05101       sysname = NULL;
05102    else if (sip_cfg.rtsave_sysname)
05103       syslabel = "regserver";
05104 
05105    /* XXX IMPORTANT: Anytime you add a new parameter to be updated, you
05106          *  must also add it to contrib/scripts/asterisk.ldap-schema,
05107          *  contrib/scripts/asterisk.ldif,
05108          *  and to configs/res_ldap.conf.sample as described in
05109          *  bugs 15156 and 15895
05110          */
05111    if (fc) {
05112       ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
05113          "port", port, "regseconds", regseconds,
05114          deprecated_username ? "username" : "defaultuser", defaultuser,
05115          "useragent", useragent, "lastms", str_lastms,
05116          fc, fullcontact, syslabel, sysname, SENTINEL); /* note fc and syslabel _can_ be NULL */
05117    } else {
05118       ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
05119          "port", port, "regseconds", regseconds,
05120          "useragent", useragent, "lastms", str_lastms,
05121          deprecated_username ? "username" : "defaultuser", defaultuser,
05122          syslabel, sysname, SENTINEL); /* note syslabel _can_ be NULL */
05123    }
05124 }
05125 
05126 /*! \brief Automatically add peer extension to dial plan */
05127 static void register_peer_exten(struct sip_peer *peer, int onoff)
05128 {
05129    char multi[256];
05130    char *stringp, *ext, *context;
05131    struct pbx_find_info q = { .stacklen = 0 };
05132 
05133    /* XXX note that sip_cfg.regcontext is both a global 'enable' flag and
05134     * the name of the global regexten context, if not specified
05135     * individually.
05136     */
05137    if (ast_strlen_zero(sip_cfg.regcontext))
05138       return;
05139 
05140    ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
05141    stringp = multi;
05142    while ((ext = strsep(&stringp, "&"))) {
05143       if ((context = strchr(ext, '@'))) {
05144          *context++ = '\0';   /* split ext@context */
05145          if (!ast_context_find(context)) {
05146             ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
05147             continue;
05148          }
05149       } else {
05150          context = sip_cfg.regcontext;
05151       }
05152       if (onoff) {
05153          if (!ast_exists_extension(NULL, context, ext, 1, NULL)) {
05154             ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
05155                 ast_strdup(peer->name), ast_free_ptr, "SIP");
05156          }
05157       } else if (pbx_find_extension(NULL, NULL, &q, context, ext, 1, NULL, "", E_MATCH)) {
05158          ast_context_remove_extension(context, ext, 1, NULL);
05159       }
05160    }
05161 }
05162 
05163 /*! Destroy mailbox subscriptions */
05164 static void destroy_mailbox(struct sip_mailbox *mailbox)
05165 {
05166    if (mailbox->event_sub)
05167       ast_event_unsubscribe(mailbox->event_sub);
05168    ast_free(mailbox);
05169 }
05170 
05171 /*! Destroy all peer-related mailbox subscriptions */
05172 static void clear_peer_mailboxes(struct sip_peer *peer)
05173 {
05174    struct sip_mailbox *mailbox;
05175 
05176    while ((mailbox = AST_LIST_REMOVE_HEAD(&peer->mailboxes, entry)))
05177       destroy_mailbox(mailbox);
05178 }
05179 
05180 static void sip_destroy_peer_fn(void *peer)
05181 {
05182    sip_destroy_peer(peer);
05183 }
05184 
05185 /*! \brief Destroy peer object from memory */
05186 static void sip_destroy_peer(struct sip_peer *peer)
05187 {
05188    ast_debug(3, "Destroying SIP peer %s\n", peer->name);
05189 
05190    /*
05191     * Remove any mailbox event subscriptions for this peer before
05192     * we destroy anything.  An event subscription callback may be
05193     * happening right now.
05194     */
05195    clear_peer_mailboxes(peer);
05196 
05197    if (peer->outboundproxy) {
05198       ao2_ref(peer->outboundproxy, -1);
05199       peer->outboundproxy = NULL;
05200    }
05201 
05202    /* Delete it, it needs to disappear */
05203    if (peer->call) {
05204       dialog_unlink_all(peer->call);
05205       peer->call = dialog_unref(peer->call, "peer->call is being unset");
05206    }
05207 
05208    if (peer->mwipvt) {  /* We have an active subscription, delete it */
05209       dialog_unlink_all(peer->mwipvt);
05210       peer->mwipvt = dialog_unref(peer->mwipvt, "unreffing peer->mwipvt");
05211    }
05212 
05213    if (peer->chanvars) {
05214       ast_variables_destroy(peer->chanvars);
05215       peer->chanvars = NULL;
05216    }
05217 
05218    register_peer_exten(peer, FALSE);
05219    ast_free_acl_list(peer->acl);
05220    ast_free_acl_list(peer->directmediaacl);
05221    if (peer->selfdestruct)
05222       ast_atomic_fetchadd_int(&apeerobjs, -1);
05223    else if (!ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->is_realtime) {
05224       ast_atomic_fetchadd_int(&rpeerobjs, -1);
05225       ast_debug(3, "-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
05226    } else
05227       ast_atomic_fetchadd_int(&speerobjs, -1);
05228    if (peer->auth) {
05229       ao2_t_ref(peer->auth, -1, "Removing peer authentication");
05230       peer->auth = NULL;
05231    }
05232 
05233    if (peer->socket.tcptls_session) {
05234       ao2_ref(peer->socket.tcptls_session, -1);
05235       peer->socket.tcptls_session = NULL;
05236    } else if (peer->socket.ws_session) {
05237       ast_websocket_unref(peer->socket.ws_session);
05238       peer->socket.ws_session = NULL;
05239    }
05240 
05241    peer->named_callgroups = ast_unref_namedgroups(peer->named_callgroups);
05242    peer->named_pickupgroups = ast_unref_namedgroups(peer->named_pickupgroups);
05243 
05244    ast_cc_config_params_destroy(peer->cc_params);
05245 
05246    ast_string_field_free_memory(peer);
05247 
05248    peer->caps = ast_format_cap_destroy(peer->caps);
05249 
05250    ast_rtp_dtls_cfg_free(&peer->dtls_cfg);
05251 }
05252 
05253 /*! \brief Update peer data in database (if used) */
05254 static void update_peer(struct sip_peer *p, int expire)
05255 {
05256    int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
05257    if (sip_cfg.peer_rtupdate &&
05258        (p->is_realtime || rtcachefriends)) {
05259       realtime_update_peer(p->name, &p->addr, p->username, p->fullcontact, p->useragent, expire, p->deprecated_username, p->lastms);
05260    }
05261 }
05262 
05263 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *cfg)
05264 {
05265    struct ast_variable *var = NULL;
05266    struct ast_flags flags = {0};
05267    char *cat = NULL;
05268    const char *insecure;
05269    while ((cat = ast_category_browse(cfg, cat))) {
05270       insecure = ast_variable_retrieve(cfg, cat, "insecure");
05271       set_insecure_flags(&flags, insecure, -1);
05272       if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
05273          var = ast_category_root(cfg, cat);
05274          break;
05275       }
05276    }
05277    return var;
05278 }
05279 
05280 static struct ast_variable *get_insecure_variable_from_sippeers(const char *column, const char *value)
05281 {
05282    struct ast_config *peerlist;
05283    struct ast_variable *var = NULL;
05284    if ((peerlist = ast_load_realtime_multientry("sippeers", column, value, "insecure LIKE", "%port%", SENTINEL))) {
05285       if ((var = get_insecure_variable_from_config(peerlist))) {
05286          /* Must clone, because var will get freed along with
05287           * peerlist. */
05288          var = ast_variables_dup(var);
05289       }
05290       ast_config_destroy(peerlist);
05291    }
05292    return var;
05293 }
05294 
05295 /* Yes.. the only column that makes sense to pass is "ipaddr", but for
05296  * consistency's sake, we require the column name to be passed. As extra
05297  * argument, we take a pointer to var. We already got the info, so we better
05298  * return it and save the caller a query. If return value is nonzero, then *var
05299  * is nonzero too (and the other way around). */
05300 static struct ast_variable *get_insecure_variable_from_sipregs(const char *column, const char *value, struct ast_variable **var)
05301 {
05302    struct ast_variable *varregs = NULL;
05303    struct ast_config *regs, *peers;
05304    char *regscat;
05305    const char *regname;
05306 
05307    if (!(regs = ast_load_realtime_multientry("sipregs", column, value, SENTINEL))) {
05308       return NULL;
05309    }
05310 
05311    /* Load *all* peers that are probably insecure=port */
05312    if (!(peers = ast_load_realtime_multientry("sippeers", "insecure LIKE", "%port%", SENTINEL))) {
05313       ast_config_destroy(regs);
05314       return NULL;
05315    }
05316 
05317    /* Loop over the sipregs that match IP address and attempt to find an
05318     * insecure=port match to it in sippeers. */
05319    regscat = NULL;
05320    while ((regscat = ast_category_browse(regs, regscat)) && (regname = ast_variable_retrieve(regs, regscat, "name"))) {
05321       char *peerscat;
05322       const char *peername;
05323 
05324       peerscat = NULL;
05325       while ((peerscat = ast_category_browse(peers, peerscat)) && (peername = ast_variable_retrieve(peers, peerscat, "name"))) {
05326          if (!strcasecmp(regname, peername)) {
05327             /* Ensure that it really is insecure=port and
05328              * not something else. */
05329             const char *insecure = ast_variable_retrieve(peers, peerscat, "insecure");
05330             struct ast_flags flags = {0};
05331             set_insecure_flags(&flags, insecure, -1);
05332             if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
05333                /* ENOMEM checks till the bitter end. */
05334                if ((varregs = ast_variables_dup(ast_category_root(regs, regscat)))) {
05335                   if (!(*var = ast_variables_dup(ast_category_root(peers, peerscat)))) {
05336                      ast_variables_destroy(varregs);
05337                      varregs = NULL;
05338                   }
05339                }
05340                goto done;
05341             }
05342          }
05343       }
05344    }
05345 
05346 done:
05347    ast_config_destroy(regs);
05348    ast_config_destroy(peers);
05349    return varregs;
05350 }
05351 
05352 static const char *get_name_from_variable(const struct ast_variable *var)
05353 {
05354    /* Don't expect this to return non-NULL. Both NULL and empty
05355     * values can cause the option to get removed from the variable
05356     * list. This is called on ast_variables gotten from both
05357     * ast_load_realtime and ast_load_realtime_multientry.
05358     * - ast_load_realtime removes options with empty values
05359     * - ast_load_realtime_multientry does not!
05360     * For consistent behaviour, we check for the empty name and
05361     * return NULL instead. */
05362    const struct ast_variable *tmp;
05363    for (tmp = var; tmp; tmp = tmp->next) {
05364       if (!strcasecmp(tmp->name, "name")) {
05365          if (!ast_strlen_zero(tmp->value)) {
05366             return tmp->value;
05367          }
05368          break;
05369       }
05370    }
05371    return NULL;
05372 }
05373 
05374 /* If varregs is NULL, we don't use sipregs.
05375  * Using empty if-bodies instead of goto's while avoiding unnecessary indents */
05376 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)
05377 {
05378    /* Peer by name and host=dynamic */
05379    if ((*var = ast_load_realtime("sippeers", "name", *name, "host", "dynamic", SENTINEL))) {
05380       ;
05381    /* Peer by name and host=IP */
05382    } else if (addr && !(*var = ast_load_realtime("sippeers", "name", *name, "host", ipaddr, SENTINEL))) {
05383       ;
05384    /* Peer by name and host=HOSTNAME */
05385    } else if ((*var = ast_load_realtime("sippeers", "name", *name, SENTINEL))) {
05386       /*!\note
05387        * If this one loaded something, then we need to ensure that the host
05388        * field matched.  The only reason why we can't have this as a criteria
05389        * is because we only have the IP address and the host field might be
05390        * set as a name (and the reverse PTR might not match).
05391        */
05392       if (addr) {
05393          struct ast_variable *tmp;
05394          for (tmp = *var; tmp; tmp = tmp->next) {
05395             if (!strcasecmp(tmp->name, "host")) {
05396                struct ast_sockaddr *addrs = NULL;
05397 
05398                if (ast_sockaddr_resolve(&addrs,
05399                          tmp->value,
05400                          PARSE_PORT_FORBID,
05401                          get_address_family_filter(SIP_TRANSPORT_UDP)) <= 0 ||
05402                          ast_sockaddr_cmp(&addrs[0], addr)) {
05403                   /* No match */
05404                   ast_variables_destroy(*var);
05405                   *var = NULL;
05406                }
05407                ast_free(addrs);
05408                break;
05409             }
05410          }
05411       }
05412    }
05413 
05414    /* Did we find anything? */
05415    if (*var) {
05416       if (varregs) {
05417          *varregs = ast_load_realtime("sipregs", "name", *name, SENTINEL);
05418       }
05419       return 1;
05420    }
05421    return 0;
05422 }
05423 
05424 /* Another little helper function for backwards compatibility: this
05425  * checks/fetches the sippeer that belongs to the sipreg. If none is
05426  * found, we free the sipreg and return false. This way we can do the
05427  * check inside the if-condition below. In the old code, not finding
05428  * the sippeer also had it continue look for another match, so we do
05429  * the same. */
05430 static struct ast_variable *realtime_peer_get_sippeer_helper(const char **name, struct ast_variable **varregs) {
05431    struct ast_variable *var = NULL;
05432    const char *old_name = *name;
05433    *name = get_name_from_variable(*varregs);
05434    if (!*name || !(var = ast_load_realtime("sippeers", "name", *name, SENTINEL))) {
05435       if (!*name) {
05436          ast_log(LOG_WARNING, "Found sipreg but it has no name\n");
05437       }
05438       ast_variables_destroy(*varregs);
05439       *varregs = NULL;
05440       *name = old_name;
05441    }
05442    return var;
05443 }
05444 
05445 /* If varregs is NULL, we don't use sipregs. If we return true, then *name is
05446  * set. Using empty if-bodies instead of goto's while avoiding unnecessary
05447  * indents. */
05448 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)
05449 {
05450    char portstring[6]; /* up to 5 digits plus null terminator */
05451    ast_copy_string(portstring, ast_sockaddr_stringify_port(addr), sizeof(portstring));
05452 
05453    /* We're not finding this peer by this name anymore. Reset it. */
05454    *name = NULL;
05455 
05456    /* First check for fixed IP hosts with matching callbackextensions, if specified */
05457    if (!ast_strlen_zero(callbackexten) && (*var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, "callbackextension", callbackexten, SENTINEL))) {
05458       ;
05459    /* Check for fixed IP hosts */
05460    } else if ((*var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, SENTINEL))) {
05461       ;
05462    /* Check for registered hosts (in sipregs) */
05463    } else if (varregs && (*varregs = ast_load_realtime("sipregs", "ipaddr", ipaddr, "port", portstring, SENTINEL)) &&
05464          (*var = realtime_peer_get_sippeer_helper(name, varregs))) {
05465       ;
05466    /* Check for registered hosts (in sippeers) */
05467    } else if (!varregs && (*var = ast_load_realtime("sippeers", "ipaddr", ipaddr, "port", portstring, SENTINEL))) {
05468       ;
05469    /* We couldn't match on ipaddress and port, so we need to check if port is insecure */
05470    } else if ((*var = get_insecure_variable_from_sippeers("host", ipaddr))) {
05471       ;
05472    /* Same as above, but try the IP address field (in sipregs)
05473     * Observe that it fetches the name/var at the same time, without the
05474     * realtime_peer_get_sippeer_helper. Also note that it is quite inefficient.
05475     * Avoid sipregs if possible. */
05476    } else if (varregs && (*varregs = get_insecure_variable_from_sipregs("ipaddr", ipaddr, var))) {
05477       ;
05478    /* Same as above, but try the IP address field (in sippeers) */
05479    } else if (!varregs && (*var = get_insecure_variable_from_sippeers("ipaddr", ipaddr))) {
05480       ;
05481    }
05482 
05483    /* Nothing found? */
05484    if (!*var) {
05485       return 0;
05486    }
05487 
05488    /* Check peer name. It must not be empty. There may exist a
05489     * different match that does have a name, but it's too late for
05490     * that now. */
05491    if (!*name && !(*name = get_name_from_variable(*var))) {
05492       ast_log(LOG_WARNING, "Found peer for IP %s but it has no name\n", ipaddr);
05493       ast_variables_destroy(*var);
05494       *var = NULL;
05495       if (varregs && *varregs) {
05496          ast_variables_destroy(*varregs);
05497          *varregs = NULL;
05498       }
05499       return 0;
05500    }
05501 
05502    /* Make sure varregs is populated if var is. The inverse,
05503     * ensuring that var is set when varregs is, is taken
05504     * care of by realtime_peer_get_sippeer_helper(). */
05505    if (varregs && !*varregs) {
05506       *varregs = ast_load_realtime("sipregs", "name", *name, SENTINEL);
05507    }
05508    return 1;
05509 }
05510 
05511 static int register_realtime_peers_with_callbackextens(void)
05512 {
05513    struct ast_config *cfg;
05514    char *cat = NULL;
05515 
05516    if (!(ast_check_realtime("sippeers"))) {
05517       return 0;
05518    }
05519 
05520    /* This is hacky. We want name to be the cat, so it is the first property */
05521    if (!(cfg = ast_load_realtime_multientry("sippeers", "name LIKE", "%", "callbackextension LIKE", "%", SENTINEL))) {
05522       return -1;
05523    }
05524 
05525    while ((cat = ast_category_browse(cfg, cat))) {
05526       struct sip_peer *peer;
05527       struct ast_variable *var = ast_category_root(cfg, cat);
05528 
05529       if (!(peer = build_peer(cat, var, NULL, TRUE, FALSE))) {
05530          continue;
05531       }
05532       ast_log(LOG_NOTICE, "Created realtime peer '%s' for registration\n", peer->name);
05533 
05534       peer->is_realtime = 1;
05535       sip_unref_peer(peer, "register_realtime_peers: Done registering releasing");
05536    }
05537 
05538    ast_config_destroy(cfg);
05539 
05540    return 0;
05541 }
05542 
05543 /*! \brief  realtime_peer: Get peer from realtime storage
05544  * Checks the "sippeers" realtime family from extconfig.conf
05545  * Checks the "sipregs" realtime family from extconfig.conf if it's configured.
05546  * This returns a pointer to a peer and because we use build_peer, we can rest
05547  * assured that the refcount is bumped.
05548  * 
05549  * \note This is never called with both newpeername and addr at the same time.
05550  * If you do, be prepared to get a peer with a different name than newpeername.
05551  */
05552 static struct sip_peer *realtime_peer(const char *newpeername, struct ast_sockaddr *addr, char *callbackexten, int devstate_only, int which_objects)
05553 {
05554    struct sip_peer *peer = NULL;
05555    struct ast_variable *var = NULL;
05556    struct ast_variable *varregs = NULL;
05557    char ipaddr[INET6_ADDRSTRLEN];
05558    int realtimeregs = ast_check_realtime("sipregs");
05559 
05560    if (addr) {
05561       ast_copy_string(ipaddr, ast_sockaddr_stringify_addr(addr), sizeof(ipaddr));
05562    } else {
05563       ipaddr[0] = '\0';
05564    }
05565 
05566    if (newpeername && realtime_peer_by_name(&newpeername, addr, ipaddr, &var, realtimeregs ? &varregs : NULL)) {
05567       ;
05568    } else if (addr && realtime_peer_by_addr(&newpeername, addr, ipaddr, callbackexten, &var, realtimeregs ? &varregs : NULL)) {
05569       ;
05570    } else {
05571       return NULL;
05572    }
05573 
05574    /* If we're looking for users, don't return peers (although this check
05575     * should probably be done in realtime_peer_by_* instead...) */
05576    if (which_objects == FINDUSERS) {
05577       struct ast_variable *tmp;
05578       for (tmp = var; tmp; tmp = tmp->next) {
05579          if (!strcasecmp(tmp->name, "type") && (!strcasecmp(tmp->value, "peer"))) {
05580             goto cleanup;
05581          }
05582       }
05583    }
05584 
05585    /* Peer found in realtime, now build it in memory */
05586    peer = build_peer(newpeername, var, varregs, TRUE, devstate_only);
05587    if (!peer) {
05588       goto cleanup;
05589    }
05590 
05591    /* Previous versions of Asterisk did not require the type field to be
05592     * set for real time peers.  This statement preserves that behavior. */
05593    if  (peer->type == 0) {
05594       if (which_objects == FINDUSERS) {
05595          peer->type = SIP_TYPE_USER;
05596       } else if (which_objects == FINDPEERS) {
05597          peer->type = SIP_TYPE_PEER;
05598       } else {
05599          peer->type = SIP_TYPE_PEER | SIP_TYPE_USER;
05600       }
05601    }
05602 
05603    ast_debug(3, "-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);
05604 
05605    if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && !devstate_only) {
05606       /* Cache peer */
05607       ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
05608       if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
05609          AST_SCHED_REPLACE_UNREF(peer->expire, sched, sip_cfg.rtautoclear * 1000, expire_register, peer,
05610                sip_unref_peer(_data, "remove registration ref"),
05611                sip_unref_peer(peer, "remove registration ref"),
05612                sip_ref_peer(peer, "add registration ref"));
05613       }
05614       ao2_t_link(peers, peer, "link peer into peers table");
05615       if (!ast_sockaddr_isnull(&peer->addr)) {
05616          ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
05617       }
05618    }
05619    peer->is_realtime = 1;
05620 
05621 cleanup:
05622    ast_variables_destroy(var);
05623    ast_variables_destroy(varregs);
05624    return peer;
05625 }
05626 
05627 /* Function to assist finding peers by name only */
05628 static int find_by_name(void *obj, void *arg, void *data, int flags)
05629 {
05630    struct sip_peer *search = obj, *match = arg;
05631    int *which_objects = data;
05632 
05633    /* Usernames in SIP uri's are case sensitive. Domains are not */
05634    if (strcmp(search->name, match->name)) {
05635       return 0;
05636    }
05637 
05638    switch (*which_objects) {
05639    case FINDUSERS:
05640       if (!(search->type & SIP_TYPE_USER)) {
05641          return 0;
05642       }
05643       break;
05644    case FINDPEERS:
05645       if (!(search->type & SIP_TYPE_PEER)) {
05646          return 0;
05647       }
05648       break;
05649    case FINDALLDEVICES:
05650       break;
05651    }
05652 
05653    return CMP_MATCH | CMP_STOP;
05654 }
05655 
05656 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)
05657 {
05658    struct sip_peer *p = NULL;
05659    struct sip_peer tmp_peer;
05660 
05661    if (peer) {
05662       ast_copy_string(tmp_peer.name, peer, sizeof(tmp_peer.name));
05663       p = ao2_t_callback_data(peers, OBJ_POINTER, find_by_name, &tmp_peer, &which_objects, "ao2_find in peers table");
05664    } else if (addr) { /* search by addr? */
05665       ast_sockaddr_copy(&tmp_peer.addr, addr);
05666       tmp_peer.flags[0].flags = 0;
05667       tmp_peer.transports = transport;
05668       p = ao2_t_callback_data(peers_by_ip, OBJ_POINTER, peer_ipcmp_cb_full, &tmp_peer, callbackexten, "ao2_find in peers_by_ip table");
05669       if (!p) {
05670          ast_set_flag(&tmp_peer.flags[0], SIP_INSECURE_PORT);
05671          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");
05672          if (p) {
05673             return p;
05674          }
05675       }
05676    }
05677 
05678    if (!p && (realtime || devstate_only)) {
05679       /* realtime_peer will return a peer with matching callbackexten if possible, otherwise one matching
05680        * without the callbackexten */
05681       p = realtime_peer(peer, addr, callbackexten, devstate_only, which_objects);
05682       if (p) {
05683          switch (which_objects) {
05684          case FINDUSERS:
05685             if (!(p->type & SIP_TYPE_USER)) {
05686                sip_unref_peer(p, "Wrong type of realtime SIP endpoint");
05687                return NULL;
05688             }
05689             break;
05690          case FINDPEERS:
05691             if (!(p->type & SIP_TYPE_PEER)) {
05692                sip_unref_peer(p, "Wrong type of realtime SIP endpoint");
05693                return NULL;
05694             }
05695             break;
05696          case FINDALLDEVICES:
05697             break;
05698          }
05699       }
05700    }
05701 
05702    return p;
05703 }
05704 
05705 /*!
05706  * \brief Locate device by name or ip address
05707  * \param peer, sin, realtime, devstate_only, transport
05708  * \param which_objects Define which objects should be matched when doing a lookup
05709  *        by name.  Valid options are FINDUSERS, FINDPEERS, or FINDALLDEVICES.
05710  *        Note that this option is not used at all when doing a lookup by IP.
05711  *
05712  * This is used on find matching device on name or ip/port.
05713  * If the device was declared as type=peer, we don't match on peer name on incoming INVITEs.
05714  *
05715  * \note Avoid using this function in new functions if there is a way to avoid it,
05716  * since it might cause a database lookup.
05717  */
05718 struct sip_peer *sip_find_peer(const char *peer, struct ast_sockaddr *addr, int realtime, int which_objects, int devstate_only, int transport)
05719 {
05720    return sip_find_peer_full(peer, addr, NULL, realtime, which_objects, devstate_only, transport);
05721 }
05722 
05723 static struct sip_peer *sip_find_peer_by_ip_and_exten(struct ast_sockaddr *addr, char *callbackexten, int transport)
05724 {
05725    return sip_find_peer_full(NULL, addr, callbackexten, TRUE, FINDPEERS, FALSE, transport);
05726 }
05727 
05728 /*! \brief Set nat mode on the various data sockets */
05729 static void do_setnat(struct sip_pvt *p)
05730 {
05731    const char *mode;
05732    int natflags;
05733 
05734    natflags = ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
05735    mode = natflags ? "On" : "Off";
05736 
05737    if (p->rtp) {
05738       ast_debug(1, "Setting NAT on RTP to %s\n", mode);
05739       ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_NAT, natflags);
05740    }
05741    if (p->vrtp) {
05742       ast_debug(1, "Setting NAT on VRTP to %s\n", mode);
05743       ast_rtp_instance_set_prop(p->vrtp, AST_RTP_PROPERTY_NAT, natflags);
05744    }
05745    if (p->udptl) {
05746       ast_debug(1, "Setting NAT on UDPTL to %s\n", mode);
05747       ast_udptl_setnat(p->udptl, natflags);
05748    }
05749    if (p->trtp) {
05750       ast_debug(1, "Setting NAT on TRTP to %s\n", mode);
05751       ast_rtp_instance_set_prop(p->trtp, AST_RTP_PROPERTY_NAT, natflags);
05752    }
05753 }
05754 
05755 /*! \brief Change the T38 state on a SIP dialog */
05756 static void change_t38_state(struct sip_pvt *p, int state)
05757 {
05758    int old = p->t38.state;
05759    struct ast_channel *chan = p->owner;
05760    struct ast_control_t38_parameters parameters = { .request_response = 0 };
05761 
05762    /* Don't bother changing if we are already in the state wanted */
05763    if (old == state)
05764       return;
05765 
05766    p->t38.state = state;
05767    ast_debug(2, "T38 state changed to %d on channel %s\n", p->t38.state, chan ? ast_channel_name(chan) : "<none>");
05768 
05769    /* If no channel was provided we can't send off a control frame */
05770    if (!chan)
05771       return;
05772 
05773    /* Given the state requested and old state determine what control frame we want to queue up */
05774    switch (state) {
05775    case T38_PEER_REINVITE:
05776       parameters = p->t38.their_parms;
05777       parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05778       parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
05779       ast_udptl_set_tag(p->udptl, "%s", ast_channel_name(chan));
05780       break;
05781    case T38_ENABLED:
05782       parameters = p->t38.their_parms;
05783       parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05784       parameters.request_response = AST_T38_NEGOTIATED;
05785       ast_udptl_set_tag(p->udptl, "%s", ast_channel_name(chan));
05786       break;
05787    case T38_REJECTED:
05788    case T38_DISABLED:
05789       if (old == T38_ENABLED) {
05790          parameters.request_response = AST_T38_TERMINATED;
05791       } else if (old == T38_LOCAL_REINVITE) {
05792          parameters.request_response = AST_T38_REFUSED;
05793       }
05794       break;
05795    case T38_LOCAL_REINVITE:
05796       /* wait until we get a peer response before responding to local reinvite */
05797       break;
05798    }
05799 
05800    /* Woot we got a message, create a control frame and send it on! */
05801    if (parameters.request_response)
05802       ast_queue_control_data(chan, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));
05803 }
05804 
05805 /*! \brief Set the global T38 capabilities on a SIP dialog structure */
05806 static void set_t38_capabilities(struct sip_pvt *p)
05807 {
05808    if (p->udptl) {
05809       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY) {
05810                         ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
05811       } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_FEC) {
05812          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
05813       } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL) {
05814          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
05815       }
05816    }
05817 }
05818 
05819 static void copy_socket_data(struct sip_socket *to_sock, const struct sip_socket *from_sock)
05820 {
05821    if (to_sock->tcptls_session) {
05822       ao2_ref(to_sock->tcptls_session, -1);
05823       to_sock->tcptls_session = NULL;
05824    } else if (to_sock->ws_session) {
05825       ast_websocket_unref(to_sock->ws_session);
05826       to_sock->ws_session = NULL;
05827    }
05828 
05829    if (from_sock->tcptls_session) {
05830       ao2_ref(from_sock->tcptls_session, +1);
05831    } else if (from_sock->ws_session) {
05832       ast_websocket_ref(from_sock->ws_session);
05833    }
05834 
05835    *to_sock = *from_sock;
05836 }
05837 
05838 /*! \brief Initialize DTLS-SRTP support on an RTP instance */
05839 static int dialog_initialize_dtls_srtp(const struct sip_pvt *dialog, struct ast_rtp_instance *rtp, struct sip_srtp **srtp)
05840 {
05841    struct ast_rtp_engine_dtls *dtls;
05842 
05843    if (!dialog->dtls_cfg.enabled) {
05844       return 0;
05845    }
05846 
05847    if (!ast_rtp_engine_srtp_is_registered()) {
05848       ast_log(LOG_ERROR, "No SRTP module loaded, can't setup SRTP session.\n");
05849       return -1;
05850    }
05851 
05852    if (!(dtls = ast_rtp_instance_get_dtls(rtp))) {
05853       ast_log(LOG_ERROR, "No DTLS-SRTP support present on engine for RTP instance '%p', was it compiled with support for it?\n",
05854          rtp);
05855       return -1;
05856    }
05857 
05858    if (dtls->set_configuration(rtp, &dialog->dtls_cfg)) {
05859       ast_log(LOG_ERROR, "Attempted to set an invalid DTLS-SRTP configuration on RTP instance '%p'\n",
05860          rtp);
05861       return -1;
05862    }
05863 
05864    if (!(*srtp = sip_srtp_alloc())) {
05865       ast_log(LOG_ERROR, "Failed to create required SRTP structure on RTP instance '%p'\n",
05866          rtp);
05867       return -1;
05868    }
05869 
05870    return 0;
05871 }
05872 
05873 /*! \brief Initialize RTP portion of a dialog
05874  * \return -1 on failure, 0 on success
05875  */
05876 static int dialog_initialize_rtp(struct sip_pvt *dialog)
05877 {
05878    struct ast_sockaddr bindaddr_tmp;
05879    struct ast_rtp_engine_ice *ice;
05880 
05881    if (!sip_methods[dialog->method].need_rtp) {
05882       return 0;
05883    }
05884 
05885    ast_sockaddr_copy(&bindaddr_tmp, &bindaddr);
05886    if (!(dialog->rtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
05887       return -1;
05888    }
05889 
05890    if (!ast_test_flag(&dialog->flags[2], SIP_PAGE3_ICE_SUPPORT) && (ice = ast_rtp_instance_get_ice(dialog->rtp))) {
05891       ice->stop(dialog->rtp);
05892    }
05893 
05894    if (dialog_initialize_dtls_srtp(dialog, dialog->rtp, &dialog->srtp)) {
05895       return -1;
05896    }
05897 
05898    if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) ||
05899          (ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) && (ast_format_cap_has_type(dialog->caps, AST_FORMAT_TYPE_VIDEO)))) {
05900       if (!(dialog->vrtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
05901          return -1;
05902       }
05903 
05904       if (!ast_test_flag(&dialog->flags[2], SIP_PAGE3_ICE_SUPPORT) && (ice = ast_rtp_instance_get_ice(dialog->vrtp))) {
05905          ice->stop(dialog->vrtp);
05906       }
05907 
05908       if (dialog_initialize_dtls_srtp(dialog, dialog->vrtp, &dialog->vsrtp)) {
05909          return -1;
05910       }
05911 
05912       ast_rtp_instance_set_timeout(dialog->vrtp, dialog->rtptimeout);
05913       ast_rtp_instance_set_hold_timeout(dialog->vrtp, dialog->rtpholdtimeout);
05914       ast_rtp_instance_set_keepalive(dialog->vrtp, dialog->rtpkeepalive);
05915 
05916       ast_rtp_instance_set_prop(dialog->vrtp, AST_RTP_PROPERTY_RTCP, 1);
05917       ast_rtp_instance_set_qos(dialog->vrtp, global_tos_video, global_cos_video, "SIP VIDEO");
05918    }
05919 
05920    if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT)) {
05921       if (!(dialog->trtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
05922          return -1;
05923       }
05924 
05925       if (!ast_test_flag(&dialog->flags[2], SIP_PAGE3_ICE_SUPPORT) && (ice = ast_rtp_instance_get_ice(dialog->trtp))) {
05926          ice->stop(dialog->trtp);
05927       }
05928 
05929       if (dialog_initialize_dtls_srtp(dialog, dialog->trtp, &dialog->tsrtp)) {
05930          return -1;
05931       }
05932 
05933       /* Do not timeout text as its not constant*/
05934       ast_rtp_instance_set_keepalive(dialog->trtp, dialog->rtpkeepalive);
05935 
05936       ast_rtp_instance_set_prop(dialog->trtp, AST_RTP_PROPERTY_RTCP, 1);
05937    }
05938 
05939    ast_rtp_instance_set_timeout(dialog->rtp, dialog->rtptimeout);
05940    ast_rtp_instance_set_hold_timeout(dialog->rtp, dialog->rtpholdtimeout);
05941    ast_rtp_instance_set_keepalive(dialog->rtp, dialog->rtpkeepalive);
05942 
05943    ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_RTCP, 1);
05944    ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
05945    ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
05946 
05947    ast_rtp_instance_set_qos(dialog->rtp, global_tos_audio, global_cos_audio, "SIP RTP");
05948 
05949    do_setnat(dialog);
05950 
05951    return 0;
05952 }
05953 
05954 /*! \brief Create address structure from peer reference.
05955  * This function copies data from peer to the dialog, so we don't have to look up the peer
05956  * again from memory or database during the life time of the dialog.
05957  *
05958  * \return -1 on error, 0 on success.
05959  *
05960  */
05961 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
05962 {
05963    struct sip_auth_container *credentials;
05964 
05965    /* this checks that the dialog is contacting the peer on a valid
05966     * transport type based on the peers transport configuration,
05967     * otherwise, this function bails out */
05968    if (dialog->socket.type && check_request_transport(peer, dialog))
05969       return -1;
05970    copy_socket_data(&dialog->socket, &peer->socket);
05971 
05972    if (!(ast_sockaddr_isnull(&peer->addr) && ast_sockaddr_isnull(&peer->defaddr)) &&
05973        (!peer->maxms || ((peer->lastms >= 0)  && (peer->lastms <= peer->maxms)))) {
05974       dialog->sa = ast_sockaddr_isnull(&peer->addr) ? peer->defaddr : peer->addr;
05975       dialog->recv = dialog->sa;
05976    } else
05977       return -1;
05978 
05979    /* XXX TODO: get flags directly from peer only as they are needed using dialog->relatedpeer */
05980    ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
05981    ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
05982    ast_copy_flags(&dialog->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
05983    ast_format_cap_copy(dialog->caps, peer->caps);
05984    dialog->prefs = peer->prefs;
05985    dialog->amaflags = peer->amaflags;
05986 
05987    ast_string_field_set(dialog, engine, peer->engine);
05988 
05989    ast_rtp_dtls_cfg_copy(&peer->dtls_cfg, &dialog->dtls_cfg);
05990 
05991    dialog->rtptimeout = peer->rtptimeout;
05992    dialog->rtpholdtimeout = peer->rtpholdtimeout;
05993    dialog->rtpkeepalive = peer->rtpkeepalive;
05994    if (dialog_initialize_rtp(dialog)) {
05995       return -1;
05996    }
05997 
05998    if (dialog->rtp) { /* Audio */
05999       ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
06000       ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
06001       /* Set Frame packetization */
06002       ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(dialog->rtp), dialog->rtp, &dialog->prefs);
06003       dialog->autoframing = peer->autoframing;
06004    }
06005 
06006    /* XXX TODO: get fields directly from peer only as they are needed using dialog->relatedpeer */
06007    ast_string_field_set(dialog, peername, peer->name);
06008    ast_string_field_set(dialog, authname, peer->username);
06009    ast_string_field_set(dialog, username, peer->username);
06010    ast_string_field_set(dialog, peersecret, peer->secret);
06011    ast_string_field_set(dialog, peermd5secret, peer->md5secret);
06012    ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
06013    ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
06014    ast_string_field_set(dialog, tohost, peer->tohost);
06015    ast_string_field_set(dialog, fullcontact, peer->fullcontact);
06016    ast_string_field_set(dialog, accountcode, peer->accountcode);
06017    ast_string_field_set(dialog, context, peer->context);
06018    ast_string_field_set(dialog, cid_num, peer->cid_num);
06019    ast_string_field_set(dialog, cid_name, peer->cid_name);
06020    ast_string_field_set(dialog, cid_tag, peer->cid_tag);
06021    ast_string_field_set(dialog, mwi_from, peer->mwi_from);
06022    if (!ast_strlen_zero(peer->parkinglot)) {
06023       ast_string_field_set(dialog, parkinglot, peer->parkinglot);
06024    }
06025    ast_string_field_set(dialog, engine, peer->engine);
06026    ref_proxy(dialog, obproxy_get(dialog, peer));
06027    dialog->callgroup = peer->callgroup;
06028    dialog->pickupgroup = peer->pickupgroup;
06029    ast_unref_namedgroups(dialog->named_callgroups);
06030    dialog->named_callgroups = ast_ref_namedgroups(peer->named_callgroups);
06031    ast_unref_namedgroups(dialog->named_pickupgroups);
06032    dialog->named_pickupgroups = ast_ref_namedgroups(peer->named_pickupgroups);
06033    ast_copy_string(dialog->zone, peer->zone, sizeof(dialog->zone));
06034    dialog->allowtransfer = peer->allowtransfer;
06035    dialog->jointnoncodeccapability = dialog->noncodeccapability;
06036 
06037    /* Update dialog authorization credentials */
06038    ao2_lock(peer);
06039    credentials = peer->auth;
06040    if (credentials) {
06041       ao2_t_ref(credentials, +1, "Ref peer auth for dialog");
06042    }
06043    ao2_unlock(peer);
06044    ao2_lock(dialog);
06045    if (dialog->peerauth) {
06046       ao2_t_ref(dialog->peerauth, -1, "Unref old dialog peer auth");
06047    }
06048    dialog->peerauth = credentials;
06049    ao2_unlock(dialog);
06050 
06051    dialog->maxcallbitrate = peer->maxcallbitrate;
06052    dialog->disallowed_methods = peer->disallowed_methods;
06053    ast_cc_copy_config_params(dialog->cc_params, peer->cc_params);
06054    if (ast_strlen_zero(dialog->tohost))
06055       ast_string_field_set(dialog, tohost, ast_sockaddr_stringify_host_remote(&dialog->sa));
06056    if (!ast_strlen_zero(peer->fromdomain)) {
06057       ast_string_field_set(dialog, fromdomain, peer->fromdomain);
06058       if (!dialog->initreq.headers) {
06059          char *new_callid;
06060          char *tmpcall = ast_strdupa(dialog->callid);
06061          /* this sure looks to me like we are going to change the callid on this dialog!! */
06062          new_callid = strchr(tmpcall, '@');
06063          if (new_callid) {
06064             int callid_size;
06065 
06066             *new_callid = '\0';
06067 
06068             /* Change the dialog callid. */
06069             callid_size = strlen(tmpcall) + strlen(peer->fromdomain) + 2;
06070             new_callid = ast_alloca(callid_size);
06071             snprintf(new_callid, callid_size, "%s@%s", tmpcall, peer->fromdomain);
06072             change_callid_pvt(dialog, new_callid);
06073          }
06074       }
06075    }
06076    if (!ast_strlen_zero(peer->fromuser))
06077       ast_string_field_set(dialog, fromuser, peer->fromuser);
06078    if (!ast_strlen_zero(peer->language))
06079       ast_string_field_set(dialog, language, peer->language);
06080    /* Set timer T1 to RTT for this peer (if known by qualify=) */
06081    /* Minimum is settable or default to 100 ms */
06082    /* If there is a maxms and lastms from a qualify use that over a manual T1
06083       value. Otherwise, use the peer's T1 value. */
06084    if (peer->maxms && peer->lastms)
06085       dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
06086    else
06087       dialog->timer_t1 = peer->timer_t1;
06088 
06089    /* Set timer B to control transaction timeouts, the peer setting is the default and overrides
06090       the known timer */
06091    if (peer->timer_b)
06092       dialog->timer_b = peer->timer_b;
06093    else
06094       dialog->timer_b = 64 * dialog->timer_t1;
06095 
06096    if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
06097        (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
06098       dialog->noncodeccapability |= AST_RTP_DTMF;
06099    else
06100       dialog->noncodeccapability &= ~AST_RTP_DTMF;
06101 
06102    dialog->directmediaacl = ast_duplicate_acl_list(peer->directmediaacl);
06103 
06104    if (peer->call_limit)
06105       ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
06106    if (!dialog->portinuri)
06107       dialog->portinuri = peer->portinuri;
06108    dialog->chanvars = copy_vars(peer->chanvars);
06109    if (peer->fromdomainport)
06110       dialog->fromdomainport = peer->fromdomainport;
06111    dialog->callingpres = peer->callingpres;
06112 
06113    return 0;
06114 }
06115 
06116 /*! \brief The default sip port for the given transport */
06117 static inline int default_sip_port(enum sip_transport type)
06118 {
06119    return type == SIP_TRANSPORT_TLS ? STANDARD_TLS_PORT : STANDARD_SIP_PORT;
06120 }
06121 
06122 /*! \brief create address structure from device name
06123  *      Or, if peer not found, find it in the global DNS
06124  *      returns TRUE (-1) on failure, FALSE on success */
06125 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog)
06126 {
06127    struct sip_peer *peer;
06128    char *peername, *peername2, *hostn;
06129    char host[MAXHOSTNAMELEN];
06130    char service[MAXHOSTNAMELEN];
06131    int srv_ret = 0;
06132    int tportno;
06133 
06134    AST_DECLARE_APP_ARGS(hostport,
06135       AST_APP_ARG(host);
06136       AST_APP_ARG(port);
06137    );
06138 
06139    peername = ast_strdupa(opeer);
06140    peername2 = ast_strdupa(opeer);
06141    AST_NONSTANDARD_RAW_ARGS(hostport, peername2, ':');
06142 
06143    if (hostport.port)
06144       dialog->portinuri = 1;
06145 
06146    dialog->timer_t1 = global_t1; /* Default SIP retransmission timer T1 (RFC 3261) */
06147    dialog->timer_b = global_timer_b; /* Default SIP transaction timer B (RFC 3261) */
06148    peer = sip_find_peer(peername, NULL, TRUE, FINDPEERS, FALSE, 0);
06149 
06150    if (peer) {
06151       int res;
06152       if (newdialog) {
06153          set_socket_transport(&dialog->socket, 0);
06154       }
06155       res = create_addr_from_peer(dialog, peer);
06156       dialog->relatedpeer = sip_ref_peer(peer, "create_addr: setting dialog's relatedpeer pointer");
06157       sip_unref_peer(peer, "create_addr: unref peer from sip_find_peer hashtab lookup");
06158       return res;
06159    } else if (ast_check_digits(peername)) {
06160       /* Although an IPv4 hostname *could* be represented as a 32-bit integer, it is uncommon and
06161        * it makes dialing SIP/${EXTEN} for a peer that isn't defined resolve to an IP that is
06162        * almost certainly not intended. It is much better to just reject purely numeric hostnames */
06163       ast_log(LOG_WARNING, "Purely numeric hostname (%s), and not a peer--rejecting!\n", peername);
06164       return -1;
06165    } else {
06166       dialog->rtptimeout = global_rtptimeout;
06167       dialog->rtpholdtimeout = global_rtpholdtimeout;
06168       dialog->rtpkeepalive = global_rtpkeepalive;
06169       if (dialog_initialize_rtp(dialog)) {
06170          return -1;
06171       }
06172    }
06173 
06174    ast_string_field_set(dialog, tohost, hostport.host);
06175    dialog->allowed_methods &= ~sip_cfg.disallowed_methods;
06176 
06177    /* Get the outbound proxy information */
06178    ref_proxy(dialog, obproxy_get(dialog, NULL));
06179 
06180    if (addr) {
06181       /* This address should be updated using dnsmgr */
06182       ast_sockaddr_copy(&dialog->sa, addr);
06183    } else {
06184 
06185       /* Let's see if we can find the host in DNS. First try DNS SRV records,
06186          then hostname lookup */
06187       /*! \todo Fix this function. When we ask for SRV, we should check all transports
06188            In the future, we should first check NAPTR to find out transport preference
06189        */
06190       hostn = peername;
06191       /* Section 4.2 of RFC 3263 specifies that if a port number is specified, then
06192        * an A record lookup should be used instead of SRV.
06193        */
06194       if (!hostport.port && sip_cfg.srvlookup) {
06195          snprintf(service, sizeof(service), "_%s._%s.%s", 
06196              get_srv_service(dialog->socket.type),
06197              get_srv_protocol(dialog->socket.type), peername);
06198          if ((srv_ret = ast_get_srv(NULL, host, sizeof(host), &tportno,
06199                      service)) > 0) {
06200             hostn = host;
06201          }
06202       }
06203 
06204       if (ast_sockaddr_resolve_first_transport(&dialog->sa, hostn, 0, dialog->socket.type ? dialog->socket.type : SIP_TRANSPORT_UDP)) {
06205          ast_log(LOG_WARNING, "No such host: %s\n", peername);
06206          return -1;
06207       }
06208 
06209       if (srv_ret > 0) {
06210          ast_sockaddr_set_port(&dialog->sa, tportno);
06211       }
06212    }
06213 
06214    if (!dialog->socket.type)
06215       set_socket_transport(&dialog->socket, SIP_TRANSPORT_UDP);
06216    if (!dialog->socket.port) {
06217       dialog->socket.port = htons(ast_sockaddr_port(&bindaddr));
06218    }
06219 
06220    if (!ast_sockaddr_port(&dialog->sa)) {
06221       ast_sockaddr_set_port(&dialog->sa, default_sip_port(dialog->socket.type));
06222    }
06223    ast_sockaddr_copy(&dialog->recv, &dialog->sa);
06224    return 0;
06225 }
06226 
06227 /*! \brief Scheduled congestion on a call.
06228  * Only called by the scheduler, must return the reference when done.
06229  */
06230 static int auto_congest(const void *arg)
06231 {
06232    struct sip_pvt *p = (struct sip_pvt *)arg;
06233 
06234    sip_pvt_lock(p);
06235    p->initid = -1;   /* event gone, will not be rescheduled */
06236    if (p->owner) {
06237       /* XXX fails on possible deadlock */
06238       if (!ast_channel_trylock(p->owner)) {
06239          append_history(p, "Cong", "Auto-congesting (timer)");
06240          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
06241          ast_channel_unlock(p->owner);
06242       }
06243 
06244       /* Give the channel a chance to act before we proceed with destruction */
06245       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06246    }
06247    sip_pvt_unlock(p);
06248    dialog_unref(p, "unreffing arg passed into auto_congest callback (p->initid)");
06249    return 0;
06250 }
06251 
06252 
06253 /*! \brief Initiate SIP call from PBX
06254  *      used from the dial() application      */
06255 static int sip_call(struct ast_channel *ast, const char *dest, int timeout)
06256 {
06257    int res;
06258    struct sip_pvt *p = ast_channel_tech_pvt(ast);  /* chan is locked, so the reference cannot go away */
06259    struct varshead *headp;
06260    struct ast_var_t *current;
06261    const char *referer = NULL;   /* SIP referrer */
06262    int cc_core_id;
06263    char uri[SIPBUFSIZE] = "";
06264 
06265    if ((ast_channel_state(ast) != AST_STATE_DOWN) && (ast_channel_state(ast) != AST_STATE_RESERVED)) {
06266       ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast_channel_name(ast));
06267       return -1;
06268    }
06269 
06270    if (ast_cc_is_recall(ast, &cc_core_id, "SIP")) {
06271       char device_name[AST_CHANNEL_NAME];
06272       struct ast_cc_monitor *recall_monitor;
06273       struct sip_monitor_instance *monitor_instance;
06274       ast_channel_get_device_name(ast, device_name, sizeof(device_name));
06275       if ((recall_monitor = ast_cc_get_monitor_by_recall_core_id(cc_core_id, device_name))) {
06276          monitor_instance = recall_monitor->private_data;
06277          ast_copy_string(uri, monitor_instance->notify_uri, sizeof(uri));
06278          ao2_t_ref(recall_monitor, -1, "Got the URI we need so unreffing monitor");
06279       }
06280    }
06281 
06282    /* Check whether there is vxml_url, distinctive ring variables */
06283    headp=ast_channel_varshead(ast);
06284    AST_LIST_TRAVERSE(headp, current, entries) {
06285       /* Check whether there is a VXML_URL variable */
06286       if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
06287          p->options->vxml_url = ast_var_value(current);
06288       } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
06289          p->options->uri_options = ast_var_value(current);
06290       } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
06291          /* Check whether there is a variable with a name starting with SIPADDHEADER */
06292          p->options->addsipheaders = 1;
06293       } else if (!strcasecmp(ast_var_name(current), "SIPFROMDOMAIN")) {
06294          ast_string_field_set(p, fromdomain, ast_var_value(current));
06295       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
06296          /* This is a transferred call */
06297          p->options->transfer = 1;
06298       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
06299          /* This is the referrer */
06300          referer = ast_var_value(current);
06301       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
06302          /* We're replacing a call. */
06303          p->options->replaces = ast_var_value(current);
06304       } else if (!strcasecmp(ast_var_name(current), "SIP_MAX_FORWARDS")) {
06305          if (sscanf(ast_var_value(current), "%30d", &(p->maxforwards)) != 1) {
06306             ast_log(LOG_WARNING, "The SIP_MAX_FORWARDS channel variable is not a valid integer.\n");
06307          }
06308       }
06309    }
06310 
06311    /* Check to see if we should try to force encryption */
06312    if (p->req_secure_signaling && p->socket.type != SIP_TRANSPORT_TLS) {
06313       ast_log(LOG_WARNING, "Encrypted signaling is required\n");
06314       ast_channel_hangupcause_set(ast, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
06315       return -1;
06316    }
06317 
06318    if (ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP)) {
06319       if (ast_test_flag(&p->flags[0], SIP_REINVITE)) {
06320          ast_debug(1, "Direct media not possible when using SRTP, ignoring canreinvite setting\n");
06321          ast_clear_flag(&p->flags[0], SIP_REINVITE);
06322       }
06323 
06324       if (p->rtp && !p->srtp && setup_srtp(&p->srtp) < 0) {
06325          ast_log(LOG_WARNING, "SRTP audio setup failed\n");
06326          return -1;
06327       }
06328 
06329       if (p->vrtp && !p->vsrtp && setup_srtp(&p->vsrtp) < 0) {
06330          ast_log(LOG_WARNING, "SRTP video setup failed\n");
06331          return -1;
06332       }
06333 
06334       if (p->trtp && !p->tsrtp && setup_srtp(&p->tsrtp) < 0) {
06335          ast_log(LOG_WARNING, "SRTP text setup failed\n");
06336          return -1;
06337       }
06338    }
06339 
06340    res = 0;
06341    ast_set_flag(&p->flags[0], SIP_OUTGOING);
06342 
06343    /* T.38 re-INVITE FAX detection should never be done for outgoing calls,
06344     * so ensure it is disabled.
06345     */
06346    ast_clear_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38);
06347 
06348    if (p->options->transfer) {
06349       char buf[SIPBUFSIZE/2];
06350 
06351       if (referer) {
06352          if (sipdebug)
06353             ast_debug(3, "Call for %s transferred by %s\n", p->username, referer);
06354          snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
06355       } else
06356          snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
06357       ast_string_field_set(p, cid_name, buf);
06358    }
06359    ast_debug(1, "Outgoing Call for %s\n", p->username);
06360 
06361    res = update_call_counter(p, INC_CALL_RINGING);
06362 
06363    if (res == -1) {
06364       ast_channel_hangupcause_set(ast, AST_CAUSE_USER_BUSY);
06365       return res;
06366    }
06367    p->callingpres = ast_party_id_presentation(&ast_channel_caller(ast)->id);
06368    ast_rtp_instance_available_formats(p->rtp, p->caps, p->prefcaps, p->jointcaps);
06369    p->jointnoncodeccapability = p->noncodeccapability;
06370 
06371    /* If there are no audio formats left to offer, punt */
06372    if (!(ast_format_cap_has_type(p->jointcaps, AST_FORMAT_TYPE_AUDIO))) {
06373       ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
06374       res = -1;
06375    } else {
06376       int xmitres;
06377       struct ast_party_connected_line connected;
06378       struct ast_set_party_connected_line update_connected;
06379 
06380       sip_pvt_lock(p);
06381 
06382       /* Supply initial connected line information if available. */
06383       memset(&update_connected, 0, sizeof(update_connected));
06384       ast_party_connected_line_init(&connected);
06385       if (!ast_strlen_zero(p->cid_num)
06386          || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
06387          update_connected.id.number = 1;
06388          connected.id.number.valid = 1;
06389          connected.id.number.str = (char *) p->cid_num;
06390          connected.id.number.presentation = p->callingpres;
06391       }
06392       if (!ast_strlen_zero(p->cid_name)
06393          || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
06394          update_connected.id.name = 1;
06395          connected.id.name.valid = 1;
06396          connected.id.name.str = (char *) p->cid_name;
06397          connected.id.name.presentation = p->callingpres;
06398       }
06399       if (update_connected.id.number || update_connected.id.name) {
06400          /* Invalidate any earlier private connected id representation */
06401          ast_set_party_id_all(&update_connected.priv);
06402 
06403          connected.id.tag = (char *) p->cid_tag;
06404          connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
06405          ast_channel_queue_connected_line_update(ast, &connected, &update_connected);
06406       }
06407 
06408       xmitres = transmit_invite(p, SIP_INVITE, 1, 2, uri);
06409       if (xmitres == XMIT_ERROR) {
06410          sip_pvt_unlock(p);
06411          return -1;
06412       }
06413       p->invitestate = INV_CALLING;
06414 
06415       /* Initialize auto-congest time */
06416       AST_SCHED_REPLACE_UNREF(p->initid, sched, p->timer_b, auto_congest, p,
06417                         dialog_unref(_data, "dialog ptr dec when SCHED_REPLACE del op succeeded"),
06418                         dialog_unref(p, "dialog ptr dec when SCHED_REPLACE add failed"),
06419                         dialog_ref(p, "dialog ptr inc when SCHED_REPLACE add succeeded") );
06420       sip_pvt_unlock(p);
06421    }
06422    return res;
06423 }
06424 
06425 /*! \brief Destroy registry object
06426    Objects created with the register= statement in static configuration */
06427 static void sip_registry_destroy(struct sip_registry *reg)
06428 {
06429    /* Really delete */
06430    ast_debug(3, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
06431 
06432    if (reg->call) {
06433       /* Clear registry before destroying to ensure
06434          we don't get reentered trying to grab the registry lock */
06435       reg->call->registry = registry_unref(reg->call->registry, "destroy reg->call->registry");
06436       ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
06437       dialog_unlink_all(reg->call);
06438       reg->call = dialog_unref(reg->call, "unref reg->call");
06439       /* reg->call = sip_destroy(reg->call); */
06440    }
06441    AST_SCHED_DEL(sched, reg->expire);
06442    AST_SCHED_DEL(sched, reg->timeout);
06443 
06444    ast_string_field_free_memory(reg);
06445    ast_atomic_fetchadd_int(&regobjs, -1);
06446    ast_free(reg);
06447 }
06448 
06449 /*! \brief Destroy MWI subscription object */
06450 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi)
06451 {
06452    if (mwi->call) {
06453       mwi->call->mwi = NULL;
06454       sip_destroy(mwi->call);
06455    }
06456    
06457    AST_SCHED_DEL(sched, mwi->resub);
06458    ast_string_field_free_memory(mwi);
06459    ast_free(mwi);
06460 }
06461 
06462 /*! \brief Destroy SDP media offer list */
06463 static void offered_media_list_destroy(struct sip_pvt *p)
06464 {
06465    struct offered_media *offer;
06466    while ((offer = AST_LIST_REMOVE_HEAD(&p->offered_media, next))) {
06467       ast_free(offer->decline_m_line);
06468       ast_free(offer);
06469    }
06470 }
06471 
06472 /*! \brief Execute destruction of SIP dialog structure, release memory */
06473 void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
06474 {
06475    struct sip_request *req;
06476 
06477    /* Destroy Session-Timers if allocated */
06478    if (p->stimer) {
06479       p->stimer->quit_flag = 1;
06480       stop_session_timer(p);
06481       ast_free(p->stimer);
06482       p->stimer = NULL;
06483    }
06484 
06485    if (sip_debug_test_pvt(p))
06486       ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
06487 
06488    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
06489       update_call_counter(p, DEC_CALL_LIMIT);
06490       ast_debug(2, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
06491    }
06492 
06493    /* Unlink us from the owner if we have one */
06494    if (p->owner) {
06495       if (lockowner)
06496          ast_channel_lock(p->owner);
06497       ast_debug(1, "Detaching from %s\n", ast_channel_name(p->owner));
06498       ast_channel_tech_pvt_set(p->owner, NULL);
06499       /* Make sure that the channel knows its backend is going away */
06500       ast_channel_softhangup_internal_flag_add(p->owner, AST_SOFTHANGUP_DEV);
06501       if (lockowner)
06502          ast_channel_unlock(p->owner);
06503       /* Give the channel a chance to react before deallocation */
06504       usleep(1);
06505    }
06506 
06507    /* Remove link from peer to subscription of MWI */
06508    if (p->relatedpeer && p->relatedpeer->mwipvt == p)
06509       p->relatedpeer->mwipvt = dialog_unref(p->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
06510    if (p->relatedpeer && p->relatedpeer->call == p)
06511       p->relatedpeer->call = dialog_unref(p->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
06512    
06513    if (p->relatedpeer)
06514       p->relatedpeer = sip_unref_peer(p->relatedpeer,"unsetting a dialog relatedpeer field in sip_destroy");
06515    
06516    if (p->registry) {
06517       if (p->registry->call == p)
06518          p->registry->call = dialog_unref(p->registry->call, "nulling out the registry's call dialog field in unlink_all");
06519       p->registry = registry_unref(p->registry, "delete p->registry");
06520    }
06521    
06522    if (p->mwi) {
06523       p->mwi->call = NULL;
06524       p->mwi = NULL;
06525    }
06526 
06527    if (dumphistory)
06528       sip_dump_history(p);
06529 
06530    if (p->options) {
06531       if (p->options->outboundproxy) {
06532          ao2_ref(p->options->outboundproxy, -1);
06533       }
06534       ast_free(p->options);
06535       p->options = NULL;
06536    }
06537 
06538    if (p->notify) {
06539       ast_variables_destroy(p->notify->headers);
06540       ast_free(p->notify->content);
06541       ast_free(p->notify);
06542       p->notify = NULL;
06543    }
06544    if (p->rtp) {
06545       ast_rtp_instance_destroy(p->rtp);
06546       p->rtp = NULL;
06547    }
06548    if (p->vrtp) {
06549       ast_rtp_instance_destroy(p->vrtp);
06550       p->vrtp = NULL;
06551    }
06552    if (p->trtp) {
06553       ast_rtp_instance_destroy(p->trtp);
06554       p->trtp = NULL;
06555    }
06556    if (p->udptl) {
06557       ast_udptl_destroy(p->udptl);
06558       p->udptl = NULL;
06559    }
06560    if (p->refer) {
06561       if (p->refer->refer_call) {
06562          p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
06563       }
06564       ast_string_field_free_memory(p->refer);
06565       ast_free(p->refer);
06566       p->refer = NULL;
06567    }
06568    if (p->route) {
06569       free_old_route(p->route);
06570       p->route = NULL;
06571    }
06572    deinit_req(&p->initreq);
06573 
06574    /* Clear history */
06575    if (p->history) {
06576       struct sip_history *hist;
06577       while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
06578          ast_free(hist);
06579          p->history_entries--;
06580       }
06581       ast_free(p->history);
06582       p->history = NULL;
06583    }
06584 
06585    while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
06586       ast_free(req);
06587    }
06588 
06589    offered_media_list_destroy(p);
06590 
06591    if (p->chanvars) {
06592       ast_variables_destroy(p->chanvars);
06593       p->chanvars = NULL;
06594    }
06595 
06596    destroy_msg_headers(p);
06597 
06598    if (p->srtp) {
06599       sip_srtp_destroy(p->srtp);
06600       p->srtp = NULL;
06601    }
06602 
06603    if (p->vsrtp) {
06604       sip_srtp_destroy(p->vsrtp);
06605       p->vsrtp = NULL;
06606    }
06607 
06608    if (p->tsrtp) {
06609       sip_srtp_destroy(p->tsrtp);
06610       p->tsrtp = NULL;
06611    }
06612 
06613    if (p->directmediaacl) {
06614       p->directmediaacl = ast_free_acl_list(p->directmediaacl);
06615    }
06616 
06617    ast_string_field_free_memory(p);
06618 
06619    ast_cc_config_params_destroy(p->cc_params);
06620    p->cc_params = NULL;
06621 
06622    if (p->epa_entry) {
06623       ao2_ref(p->epa_entry, -1);
06624       p->epa_entry = NULL;
06625    }
06626 
06627    if (p->socket.tcptls_session) {
06628       ao2_ref(p->socket.tcptls_session, -1);
06629       p->socket.tcptls_session = NULL;
06630    } else if (p->socket.ws_session) {
06631       ast_websocket_unref(p->socket.ws_session);
06632       p->socket.ws_session = NULL;
06633    }
06634 
06635    if (p->peerauth) {
06636       ao2_t_ref(p->peerauth, -1, "Removing active peer authentication");
06637       p->peerauth = NULL;
06638    }
06639 
06640    p->named_callgroups = ast_unref_namedgroups(p->named_callgroups);
06641    p->named_pickupgroups = ast_unref_namedgroups(p->named_pickupgroups);
06642 
06643    p->caps = ast_format_cap_destroy(p->caps);
06644    p->jointcaps = ast_format_cap_destroy(p->jointcaps);
06645    p->peercaps = ast_format_cap_destroy(p->peercaps);
06646    p->redircaps = ast_format_cap_destroy(p->redircaps);
06647    p->prefcaps = ast_format_cap_destroy(p->prefcaps);
06648 
06649    ast_rtp_dtls_cfg_free(&p->dtls_cfg);
06650 
06651    if (p->last_device_state_info) {
06652       ao2_ref(p->last_device_state_info, -1);
06653       p->last_device_state_info = NULL;
06654    }
06655 
06656    /* Lastly, kill the callid associated with the pvt */
06657    if (p->logger_callid) {
06658       ast_callid_unref(p->logger_callid);
06659    }
06660 }
06661 
06662 /*! \brief  update_call_counter: Handle call_limit for SIP devices
06663  * Setting a call-limit will cause calls above the limit not to be accepted.
06664  *
06665  * Remember that for a type=friend, there's one limit for the user and
06666  * another for the peer, not a combined call limit.
06667  * This will cause unexpected behaviour in subscriptions, since a "friend"
06668  * is *two* devices in Asterisk, not one.
06669  *
06670  * Thought: For realtime, we should probably update storage with inuse counter...
06671  *
06672  * \return 0 if call is ok (no call limit, below threshold)
06673  * -1 on rejection of call
06674  *
06675  */
06676 static int update_call_counter(struct sip_pvt *fup, int event)
06677 {
06678    char name[256];
06679    int *inuse = NULL, *call_limit = NULL, *ringing = NULL;
06680    int outgoing = fup->outgoing_call;
06681    struct sip_peer *p = NULL;
06682 
06683    ast_debug(3, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
06684 
06685 
06686    /* Test if we need to check call limits, in order to avoid
06687       realtime lookups if we do not need it */
06688    if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT) && !ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD))
06689       return 0;
06690 
06691    ast_copy_string(name, fup->username, sizeof(name));
06692 
06693    /* Check the list of devices */
06694    if (fup->relatedpeer) {
06695       p = sip_ref_peer(fup->relatedpeer, "ref related peer for update_call_counter");
06696       inuse = &p->inuse;
06697       call_limit = &p->call_limit;
06698       ringing = &p->ringing;
06699       ast_copy_string(name, fup->peername, sizeof(name));
06700    }
06701    if (!p) {
06702       ast_debug(2, "%s is not a local device, no call limit\n", name);
06703       return 0;
06704    }
06705 
06706    switch(event) {
06707    /* incoming and outgoing affects the inuse counter */
06708    case DEC_CALL_LIMIT:
06709       /* Decrement inuse count if applicable */
06710       if (inuse) {
06711          sip_pvt_lock(fup);
06712          ao2_lock(p);
06713          if (*inuse > 0) {
06714             if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
06715                (*inuse)--;
06716                ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
06717             }
06718          } else {
06719             *inuse = 0;
06720          }
06721          ao2_unlock(p);
06722          sip_pvt_unlock(fup);
06723       }
06724 
06725       /* Decrement ringing count if applicable */
06726       if (ringing) {
06727          sip_pvt_lock(fup);
06728          ao2_lock(p);
06729          if (*ringing > 0) {
06730             if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
06731                (*ringing)--;
06732                ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
06733             }
06734          } else {
06735             *ringing = 0;
06736          }
06737          ao2_unlock(p);
06738          sip_pvt_unlock(fup);
06739       }
06740 
06741       /* Decrement onhold count if applicable */
06742       sip_pvt_lock(fup);
06743       ao2_lock(p);
06744       if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && sip_cfg.notifyhold) {
06745          ast_clear_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD);
06746          ao2_unlock(p);
06747          sip_pvt_unlock(fup);
06748          sip_peer_hold(fup, FALSE);
06749       } else {
06750          ao2_unlock(p);
06751          sip_pvt_unlock(fup);
06752       }
06753       if (sipdebug)
06754          ast_debug(2, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
06755       break;
06756 
06757    case INC_CALL_RINGING:
06758    case INC_CALL_LIMIT:
06759       /* If call limit is active and we have reached the limit, reject the call */
06760       if (*call_limit > 0 ) {
06761          if (*inuse >= *call_limit) {
06762             ast_log(LOG_NOTICE, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
06763             sip_unref_peer(p, "update_call_counter: unref peer p, call limit exceeded");
06764             return -1;
06765          }
06766       }
06767       if (ringing && (event == INC_CALL_RINGING)) {
06768          sip_pvt_lock(fup);
06769          ao2_lock(p);
06770          if (!ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
06771             (*ringing)++;
06772             ast_set_flag(&fup->flags[0], SIP_INC_RINGING);
06773          }
06774          ao2_unlock(p);
06775          sip_pvt_unlock(fup);
06776       }
06777       if (inuse) {
06778          sip_pvt_lock(fup);
06779          ao2_lock(p);
06780          if (!ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
06781             (*inuse)++;
06782             ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
06783          }
06784          ao2_unlock(p);
06785          sip_pvt_unlock(fup);
06786       }
06787       if (sipdebug) {
06788          ast_debug(2, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", "peer", name, *inuse, *call_limit);
06789       }
06790       break;
06791 
06792    case DEC_CALL_RINGING:
06793       if (ringing) {
06794          sip_pvt_lock(fup);
06795          ao2_lock(p);
06796          if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
06797             if (*ringing > 0) {
06798                (*ringing)--;
06799             }
06800             ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
06801          }
06802          ao2_unlock(p);
06803          sip_pvt_unlock(fup);
06804       }
06805       break;
06806 
06807    default:
06808       ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
06809    }
06810 
06811    if (p) {
06812       ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", p->name);
06813       sip_unref_peer(p, "update_call_counter: sip_unref_peer from call counter");
06814    }
06815    return 0;
06816 }
06817 
06818 
06819 static void sip_destroy_fn(void *p)
06820 {
06821    sip_destroy(p);
06822 }
06823 
06824 /*! \brief Destroy SIP call structure.
06825  * Make it return NULL so the caller can do things like
06826  * foo = sip_destroy(foo);
06827  * and reduce the chance of bugs due to dangling pointers.
06828  */
06829 struct sip_pvt *sip_destroy(struct sip_pvt *p)
06830 {
06831    ast_debug(3, "Destroying SIP dialog %s\n", p->callid);
06832    __sip_destroy(p, TRUE, TRUE);
06833    return NULL;
06834 }
06835 
06836 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
06837 int hangup_sip2cause(int cause)
06838 {
06839    /* Possible values taken from causes.h */
06840 
06841    switch(cause) {
06842       case 401:   /* Unauthorized */
06843          return AST_CAUSE_CALL_REJECTED;
06844       case 403:   /* Not found */
06845          return AST_CAUSE_CALL_REJECTED;
06846       case 404:   /* Not found */
06847          return AST_CAUSE_UNALLOCATED;
06848       case 405:   /* Method not allowed */
06849          return AST_CAUSE_INTERWORKING;
06850       case 407:   /* Proxy authentication required */
06851          return AST_CAUSE_CALL_REJECTED;
06852       case 408:   /* No reaction */
06853          return AST_CAUSE_NO_USER_RESPONSE;
06854       case 409:   /* Conflict */
06855          return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
06856       case 410:   /* Gone */
06857          return AST_CAUSE_NUMBER_CHANGED;
06858       case 411:   /* Length required */
06859          return AST_CAUSE_INTERWORKING;
06860       case 413:   /* Request entity too large */
06861          return AST_CAUSE_INTERWORKING;
06862       case 414:   /* Request URI too large */
06863          return AST_CAUSE_INTERWORKING;
06864       case 415:   /* Unsupported media type */
06865          return AST_CAUSE_INTERWORKING;
06866       case 420:   /* Bad extension */
06867          return AST_CAUSE_NO_ROUTE_DESTINATION;
06868       case 480:   /* No answer */
06869          return AST_CAUSE_NO_ANSWER;
06870       case 481:   /* No answer */
06871          return AST_CAUSE_INTERWORKING;
06872       case 482:   /* Loop detected */
06873          return AST_CAUSE_INTERWORKING;
06874       case 483:   /* Too many hops */
06875          return AST_CAUSE_NO_ANSWER;
06876       case 484:   /* Address incomplete */
06877          return AST_CAUSE_INVALID_NUMBER_FORMAT;
06878       case 485:   /* Ambiguous */
06879          return AST_CAUSE_UNALLOCATED;
06880       case 486:   /* Busy everywhere */
06881          return AST_CAUSE_BUSY;
06882       case 487:   /* Request terminated */
06883          return AST_CAUSE_INTERWORKING;
06884       case 488:   /* No codecs approved */
06885          return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
06886       case 491:   /* Request pending */
06887          return AST_CAUSE_INTERWORKING;
06888       case 493:   /* Undecipherable */
06889          return AST_CAUSE_INTERWORKING;
06890       case 500:   /* Server internal failure */
06891          return AST_CAUSE_FAILURE;
06892       case 501:   /* Call rejected */
06893          return AST_CAUSE_FACILITY_REJECTED;
06894       case 502:
06895          return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
06896       case 503:   /* Service unavailable */
06897          return AST_CAUSE_CONGESTION;
06898       case 504:   /* Gateway timeout */
06899          return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
06900       case 505:   /* SIP version not supported */
06901          return AST_CAUSE_INTERWORKING;
06902       case 600:   /* Busy everywhere */
06903          return AST_CAUSE_USER_BUSY;
06904       case 603:   /* Decline */
06905          return AST_CAUSE_CALL_REJECTED;
06906       case 604:   /* Does not exist anywhere */
06907          return AST_CAUSE_UNALLOCATED;
06908       case 606:   /* Not acceptable */
06909          return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
06910       default:
06911          if (cause < 500 && cause >= 400) {
06912             /* 4xx class error that is unknown - someting wrong with our request */
06913             return AST_CAUSE_INTERWORKING;
06914          } else if (cause < 600 && cause >= 500) {
06915             /* 5xx class error - problem in the remote end */
06916             return AST_CAUSE_CONGESTION;
06917          } else if (cause < 700 && cause >= 600) {
06918             /* 6xx - global errors in the 4xx class */
06919             return AST_CAUSE_INTERWORKING;
06920          }
06921          return AST_CAUSE_NORMAL;
06922    }
06923    /* Never reached */
06924    return 0;
06925 }
06926 
06927 /*! \brief Convert Asterisk hangup causes to SIP codes
06928 \verbatim
06929  Possible values from causes.h
06930         AST_CAUSE_NOTDEFINED    AST_CAUSE_NORMAL        AST_CAUSE_BUSY
06931         AST_CAUSE_FAILURE       AST_CAUSE_CONGESTION    AST_CAUSE_UNALLOCATED
06932 
06933    In addition to these, a lot of PRI codes is defined in causes.h
06934    ...should we take care of them too ?
06935 
06936    Quote RFC 3398
06937 
06938    ISUP Cause value                        SIP response
06939    ----------------                        ------------
06940    1  unallocated number                   404 Not Found
06941    2  no route to network                  404 Not found
06942    3  no route to destination              404 Not found
06943    16 normal call clearing                 --- (*)
06944    17 user busy                            486 Busy here
06945    18 no user responding                   408 Request Timeout
06946    19 no answer from the user              480 Temporarily unavailable
06947    20 subscriber absent                    480 Temporarily unavailable
06948    21 call rejected                        403 Forbidden (+)
06949    22 number changed (w/o diagnostic)      410 Gone
06950    22 number changed (w/ diagnostic)       301 Moved Permanently
06951    23 redirection to new destination       410 Gone
06952    26 non-selected user clearing           404 Not Found (=)
06953    27 destination out of order             502 Bad Gateway
06954    28 address incomplete                   484 Address incomplete
06955    29 facility rejected                    501 Not implemented
06956    31 normal unspecified                   480 Temporarily unavailable
06957 \endverbatim
06958 */
06959 const char *hangup_cause2sip(int cause)
06960 {
06961    switch (cause) {
06962       case AST_CAUSE_UNALLOCATED:      /* 1 */
06963       case AST_CAUSE_NO_ROUTE_DESTINATION:   /* 3 IAX2: Can't find extension in context */
06964       case AST_CAUSE_NO_ROUTE_TRANSIT_NET:   /* 2 */
06965          return "404 Not Found";
06966       case AST_CAUSE_CONGESTION:    /* 34 */
06967       case AST_CAUSE_SWITCH_CONGESTION:   /* 42 */
06968          return "503 Service Unavailable";
06969       case AST_CAUSE_NO_USER_RESPONSE: /* 18 */
06970          return "408 Request Timeout";
06971       case AST_CAUSE_NO_ANSWER:     /* 19 */
06972       case AST_CAUSE_UNREGISTERED:        /* 20 */
06973          return "480 Temporarily unavailable";
06974       case AST_CAUSE_CALL_REJECTED:    /* 21 */
06975          return "403 Forbidden";
06976       case AST_CAUSE_NUMBER_CHANGED:      /* 22 */
06977          return "410 Gone";
06978       case AST_CAUSE_NORMAL_UNSPECIFIED:  /* 31 */
06979          return "480 Temporarily unavailable";
06980       case AST_CAUSE_INVALID_NUMBER_FORMAT:
06981          return "484 Address incomplete";
06982       case AST_CAUSE_USER_BUSY:
06983          return "486 Busy here";
06984       case AST_CAUSE_FAILURE:
06985          return "500 Server internal failure";
06986       case AST_CAUSE_FACILITY_REJECTED:   /* 29 */
06987          return "501 Not Implemented";
06988       case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
06989          return "503 Service Unavailable";
06990       /* Used in chan_iax2 */
06991       case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
06992          return "502 Bad Gateway";
06993       case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */
06994          return "488 Not Acceptable Here";
06995       case AST_CAUSE_INTERWORKING:  /* Unspecified Interworking issues */
06996          return "500 Network error";
06997 
06998       case AST_CAUSE_NOTDEFINED:
06999       default:
07000          ast_debug(1, "AST hangup cause %d (no match found in SIP)\n", cause);
07001          return NULL;
07002    }
07003 
07004    /* Never reached */
07005    return 0;
07006 }
07007 
07008 static int reinvite_timeout(const void *data)
07009 {
07010    struct sip_pvt *dialog = (struct sip_pvt *) data;
07011    struct ast_channel *owner = sip_pvt_lock_full(dialog);
07012    dialog->reinviteid = -1;
07013    check_pendings(dialog);
07014    if (owner) {
07015       ast_channel_unlock(owner);
07016       ast_channel_unref(owner);
07017    }
07018    ao2_unlock(dialog);
07019    dialog_unref(dialog, "unref for reinvite timeout");
07020    return 0;
07021 }
07022 
07023 /*! \brief  sip_hangup: Hangup SIP call
07024  * Part of PBX interface, called from ast_hangup */
07025 static int sip_hangup(struct ast_channel *ast)
07026 {
07027    struct sip_pvt *p = ast_channel_tech_pvt(ast);
07028    int needcancel = FALSE;
07029    int needdestroy = 0;
07030    struct ast_channel *oldowner = ast;
07031 
07032    if (!p) {
07033       ast_debug(1, "Asked to hangup channel that was not connected\n");
07034       return 0;
07035    }
07036    if (ast_channel_hangupcause(ast) == AST_CAUSE_ANSWERED_ELSEWHERE) {
07037       ast_debug(1, "This call was answered elsewhere\n");
07038       append_history(p, "Cancel", "Call answered elsewhere");
07039       p->answered_elsewhere = TRUE;
07040    }
07041 
07042    /* Store hangupcause locally in PVT so we still have it before disconnect */
07043    if (p->owner)
07044       p->hangupcause = ast_channel_hangupcause(p->owner);
07045 
07046    if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
07047       if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
07048          if (sipdebug)
07049             ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
07050          update_call_counter(p, DEC_CALL_LIMIT);
07051       }
07052       ast_debug(4, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
07053       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
07054       ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Really hang up next time */
07055       if (p->owner) {
07056          ast_channel_tech_pvt_set(p->owner, dialog_unref(ast_channel_tech_pvt(p->owner), "unref p->owner->tech_pvt"));
07057          sip_pvt_lock(p);
07058          p->owner = NULL;  /* Owner will be gone after we return, so take it away */
07059          sip_pvt_unlock(p);
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, dialog_unref(ast_channel_tech_pvt(ast), "unref ast->tech_pvt"));
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    return 0;
07228 }
07229 
07230 /*! \brief Try setting codec suggested by the SIP_CODEC channel variable */
07231 static void try_suggested_sip_codec(struct sip_pvt *p)
07232 {
07233    struct ast_format fmt;
07234    const char *codec;
07235 
07236    ast_format_clear(&fmt);
07237 
07238    if (p->outgoing_call) {
07239       codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC_OUTBOUND");
07240    } else if (!(codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC_INBOUND"))) {
07241       codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
07242    }
07243 
07244    if (!codec) 
07245       return;
07246 
07247    ast_getformatbyname(codec, &fmt);
07248    if (fmt.id) {
07249       ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
07250       if (ast_format_cap_iscompatible(p->jointcaps, &fmt)) {
07251          ast_format_cap_set(p->jointcaps, &fmt);
07252          ast_format_cap_set(p->caps, &fmt);
07253       } else
07254          ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
07255    } else
07256       ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
07257    return;
07258 }
07259 
07260 /*! \brief  sip_answer: Answer SIP call , send 200 OK on Invite
07261  * Part of PBX interface */
07262 static int sip_answer(struct ast_channel *ast)
07263 {
07264    int res = 0;
07265    struct sip_pvt *p = ast_channel_tech_pvt(ast);
07266    int oldsdp = FALSE;
07267 
07268    if (!p) {
07269       ast_debug(1, "Asked to answer channel %s without tech pvt; ignoring\n",
07270             ast_channel_name(ast));
07271       return res;
07272    }
07273    sip_pvt_lock(p);
07274    if (ast_channel_state(ast) != AST_STATE_UP) {
07275       try_suggested_sip_codec(p);
07276 
07277       if (ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT)) {
07278          oldsdp = TRUE;
07279       }
07280 
07281       ast_setstate(ast, AST_STATE_UP);
07282       ast_debug(1, "SIP answering channel: %s\n", ast_channel_name(ast));
07283       ast_rtp_instance_update_source(p->rtp);
07284       res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL, oldsdp, TRUE);
07285       ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
07286    }
07287    sip_pvt_unlock(p);
07288    return res;
07289 }
07290 
07291 /*! \brief Send frame to media channel (rtp) */
07292 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
07293 {
07294    struct sip_pvt *p = ast_channel_tech_pvt(ast);
07295    int res = 0;
07296 
07297    switch (frame->frametype) {
07298    case AST_FRAME_VOICE:
07299       if (!(ast_format_cap_iscompatible(ast_channel_nativeformats(ast), &frame->subclass.format))) {
07300          char s1[512];
07301          ast_log(LOG_WARNING, "Asked to transmit frame type %s, while native formats is %s read/write = %s/%s\n",
07302             ast_getformatname(&frame->subclass.format),
07303             ast_getformatname_multiple(s1, sizeof(s1), ast_channel_nativeformats(ast)),
07304             ast_getformatname(ast_channel_readformat(ast)),
07305             ast_getformatname(ast_channel_writeformat(ast)));
07306          return 0;
07307       }
07308       if (p) {
07309          sip_pvt_lock(p);
07310          if (p->t38.state == T38_ENABLED) {
07311             /* drop frame, can't sent VOICE frames while in T.38 mode */
07312             sip_pvt_unlock(p);
07313             break;
07314          } else if (p->rtp) {
07315             /* If channel is not up, activate early media session */
07316             if ((ast_channel_state(ast) != AST_STATE_UP) &&
07317                 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
07318                 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
07319                ast_rtp_instance_update_source(p->rtp);
07320                if (!global_prematuremediafilter) {
07321                   p->invitestate = INV_EARLY_MEDIA;
07322                   transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
07323                   ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
07324                }
07325             }
07326             p->lastrtptx = time(NULL);
07327             res = ast_rtp_instance_write(p->rtp, frame);
07328          }
07329          sip_pvt_unlock(p);
07330       }
07331       break;
07332    case AST_FRAME_VIDEO:
07333       if (p) {
07334          sip_pvt_lock(p);
07335          if (p->vrtp) {
07336             /* Activate video early media */
07337             if ((ast_channel_state(ast) != AST_STATE_UP) &&
07338                 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
07339                 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
07340                p->invitestate = INV_EARLY_MEDIA;
07341                transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
07342                ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
07343             }
07344             p->lastrtptx = time(NULL);
07345             res = ast_rtp_instance_write(p->vrtp, frame);
07346          }
07347          sip_pvt_unlock(p);
07348       }
07349       break;
07350    case AST_FRAME_TEXT:
07351       if (p) {
07352          sip_pvt_lock(p);
07353          if (p->red) {
07354             ast_rtp_red_buffer(p->trtp, frame);
07355          } else {
07356             if (p->trtp) {
07357                /* Activate text early media */
07358                if ((ast_channel_state(ast) != AST_STATE_UP) &&
07359                    !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
07360                    !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
07361                   p->invitestate = INV_EARLY_MEDIA;
07362                   transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
07363                   ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
07364                }
07365                p->lastrtptx = time(NULL);
07366                res = ast_rtp_instance_write(p->trtp, frame);
07367             }
07368          }
07369          sip_pvt_unlock(p);
07370       }
07371       break;
07372    case AST_FRAME_IMAGE:
07373       return 0;
07374       break;
07375    case AST_FRAME_MODEM:
07376       if (p) {
07377          sip_pvt_lock(p);
07378          /* UDPTL requires two-way communication, so early media is not needed here.
07379             we simply forget the frames if we get modem frames before the bridge is up.
07380             Fax will re-transmit.
07381          */
07382          if ((ast_channel_state(ast) == AST_STATE_UP) &&
07383              p->udptl &&
07384              (p->t38.state == T38_ENABLED)) {
07385             res = ast_udptl_write(p->udptl, frame);
07386          }
07387          sip_pvt_unlock(p);
07388       }
07389       break;
07390    default:
07391       ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
07392       return 0;
07393    }
07394 
07395    return res;
07396 }
07397 
07398 /*! \brief  sip_fixup: Fix up a channel:  If a channel is consumed, this is called.
07399         Basically update any ->owner links */
07400 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
07401 {
07402    int ret = -1;
07403    struct sip_pvt *p;
07404 
07405    if (newchan && ast_test_flag(ast_channel_flags(newchan), AST_FLAG_ZOMBIE))
07406       ast_debug(1, "New channel is zombie\n");
07407    if (oldchan && ast_test_flag(ast_channel_flags(oldchan), AST_FLAG_ZOMBIE))
07408       ast_debug(1, "Old channel is zombie\n");
07409 
07410    if (!newchan || !ast_channel_tech_pvt(newchan)) {
07411       if (!newchan)
07412          ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", ast_channel_name(oldchan));
07413       else
07414          ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", ast_channel_name(oldchan));
07415       return -1;
07416    }
07417    p = ast_channel_tech_pvt(newchan);
07418 
07419    sip_pvt_lock(p);
07420    append_history(p, "Masq", "Old channel: %s\n", ast_channel_name(oldchan));
07421    append_history(p, "Masq (cont)", "...new owner: %s\n", ast_channel_name(newchan));
07422    if (p->owner != oldchan)
07423       ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
07424    else {
07425       p->owner = newchan;
07426       /* Re-invite RTP back to Asterisk. Needed if channel is masqueraded out of a native
07427          RTP bridge (i.e., RTP not going through Asterisk): RTP bridge code might not be
07428          able to do this if the masquerade happens before the bridge breaks (e.g., AMI
07429          redirect of both channels). Note that a channel can not be masqueraded *into*
07430          a native bridge. So there is no danger that this breaks a native bridge that
07431          should stay up. */
07432       sip_set_rtp_peer(newchan, NULL, NULL, 0, 0, 0);
07433       ret = 0;
07434    }
07435    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));
07436 
07437    sip_pvt_unlock(p);
07438    return ret;
07439 }
07440 
07441 static int sip_senddigit_begin(struct ast_channel *ast, char digit)
07442 {
07443    struct sip_pvt *p = ast_channel_tech_pvt(ast);
07444    int res = 0;
07445 
07446    if (!p) {
07447       ast_debug(1, "Asked to begin DTMF digit on channel %s with no pvt; ignoring\n",
07448             ast_channel_name(ast));
07449       return res;
07450    }
07451 
07452    sip_pvt_lock(p);
07453    switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
07454    case SIP_DTMF_INBAND:
07455       res = -1; /* Tell Asterisk to generate inband indications */
07456       break;
07457    case SIP_DTMF_RFC2833:
07458       if (p->rtp)
07459          ast_rtp_instance_dtmf_begin(p->rtp, digit);
07460       break;
07461    default:
07462       break;
07463    }
07464    sip_pvt_unlock(p);
07465 
07466    return res;
07467 }
07468 
07469 /*! \brief Send DTMF character on SIP channel
07470    within one call, we're able to transmit in many methods simultaneously */
07471 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
07472 {
07473    struct sip_pvt *p = ast_channel_tech_pvt(ast);
07474    int res = 0;
07475 
07476    if (!p) {
07477       ast_debug(1, "Asked to end DTMF digit on channel %s with no pvt; ignoring\n",
07478             ast_channel_name(ast));
07479       return res;
07480    }
07481 
07482    sip_pvt_lock(p);
07483    switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
07484    case SIP_DTMF_INFO:
07485    case SIP_DTMF_SHORTINFO:
07486       transmit_info_with_digit(p, digit, duration);
07487       break;
07488    case SIP_DTMF_RFC2833:
07489       if (p->rtp)
07490          ast_rtp_instance_dtmf_end_with_duration(p->rtp, digit, duration);
07491       break;
07492    case SIP_DTMF_INBAND:
07493       res = -1; /* Tell Asterisk to stop inband indications */
07494       break;
07495    }
07496    sip_pvt_unlock(p);
07497 
07498    return res;
07499 }
07500 
07501 /*! \brief Transfer SIP call */
07502 static int sip_transfer(struct ast_channel *ast, const char *dest)
07503 {
07504    struct sip_pvt *p = ast_channel_tech_pvt(ast);
07505    int res;
07506 
07507    if (!p) {
07508       ast_debug(1, "Asked to transfer channel %s with no pvt; ignoring\n",
07509             ast_channel_name(ast));
07510       return -1;
07511    }
07512 
07513    if (dest == NULL) /* functions below do not take a NULL */
07514       dest = "";
07515    sip_pvt_lock(p);
07516    if (ast_channel_state(ast) == AST_STATE_RING)
07517       res = sip_sipredirect(p, dest);
07518    else
07519       res = transmit_refer(p, dest);
07520    sip_pvt_unlock(p);
07521    return res;
07522 }
07523 
07524 /*! \brief Helper function which updates T.38 capability information and triggers a reinvite */
07525 static int interpret_t38_parameters(struct sip_pvt *p, const struct ast_control_t38_parameters *parameters)
07526 {
07527    int res = 0;
07528 
07529    if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) || !p->udptl) {
07530       return -1;
07531    }
07532    switch (parameters->request_response) {
07533    case AST_T38_NEGOTIATED:
07534    case AST_T38_REQUEST_NEGOTIATE:         /* Request T38 */
07535       /* Negotiation can not take place without a valid max_ifp value. */
07536       if (!parameters->max_ifp) {
07537          if (p->t38.state == T38_PEER_REINVITE) {
07538             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"));
07539             transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
07540          }
07541          change_t38_state(p, T38_REJECTED);
07542          break;
07543       } else 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          p->t38.our_parms = *parameters;
07546          /* modify our parameters to conform to the peer's parameters,
07547           * based on the rules in the ITU T.38 recommendation
07548           */
07549          if (!p->t38.their_parms.fill_bit_removal) {
07550             p->t38.our_parms.fill_bit_removal = FALSE;
07551          }
07552          if (!p->t38.their_parms.transcoding_mmr) {
07553             p->t38.our_parms.transcoding_mmr = FALSE;
07554          }
07555          if (!p->t38.their_parms.transcoding_jbig) {
07556             p->t38.our_parms.transcoding_jbig = FALSE;
07557          }
07558          p->t38.our_parms.version = MIN(p->t38.our_parms.version, p->t38.their_parms.version);
07559          p->t38.our_parms.rate_management = p->t38.their_parms.rate_management;
07560          ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
07561          change_t38_state(p, T38_ENABLED);
07562          transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
07563       } else if (p->t38.state != T38_ENABLED) {
07564          p->t38.our_parms = *parameters;
07565          ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
07566          change_t38_state(p, T38_LOCAL_REINVITE);
07567          if (!p->pendinginvite) {
07568             transmit_reinvite_with_sdp(p, TRUE, FALSE);
07569          } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
07570             ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
07571          }
07572       }
07573       break;
07574    case AST_T38_TERMINATED:
07575    case AST_T38_REFUSED:
07576    case AST_T38_REQUEST_TERMINATE:         /* Shutdown T38 */
07577       if (p->t38.state == T38_PEER_REINVITE) {
07578          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"));
07579          change_t38_state(p, T38_REJECTED);
07580          transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
07581       } else if (p->t38.state == T38_ENABLED)
07582          transmit_reinvite_with_sdp(p, FALSE, FALSE);
07583       break;
07584    case AST_T38_REQUEST_PARMS: {    /* Application wants remote's parameters re-sent */
07585       struct ast_control_t38_parameters parameters = p->t38.their_parms;
07586 
07587       if (p->t38.state == T38_PEER_REINVITE) {
07588          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"));
07589          parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
07590          parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
07591          if (p->owner) {
07592             ast_queue_control_data(p->owner, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));
07593          }
07594          /* we need to return a positive value here, so that applications that
07595           * send this request can determine conclusively whether it was accepted or not...
07596           * older versions of chan_sip would just silently accept it and return zero.
07597           */
07598          res = AST_T38_REQUEST_PARMS;
07599       }
07600       break;
07601    }
07602    default:
07603       res = -1;
07604       break;
07605    }
07606 
07607    return res;
07608 }
07609 
07610 /*! \internal \brief Create and initialize UDPTL for the specified dialog
07611  * \param p SIP private structure to create UDPTL object for
07612  * \pre p is locked
07613  * \pre p->owner is locked
07614  *
07615  * \note In the case of failure, SIP_PAGE2_T38SUPPORT is cleared on p
07616  *
07617  * \return 0 on success, any other value on failure
07618  */
07619 static int initialize_udptl(struct sip_pvt *p)
07620 {
07621    int natflags = ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
07622 
07623    if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
07624       return 1;
07625    }
07626 
07627    /* If we've already initialized T38, don't take any further action */
07628    if (p->udptl) {
07629       return 0;
07630    }
07631 
07632    /* T38 can be supported by this dialog, create it and set the derived properties */
07633    if ((p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, &bindaddr))) {
07634       if (p->owner) {
07635          ast_channel_set_fd(p->owner, 5, ast_udptl_fd(p->udptl));
07636       }
07637 
07638       ast_udptl_setqos(p->udptl, global_tos_audio, global_cos_audio);
07639       p->t38_maxdatagram = p->relatedpeer ? p->relatedpeer->t38_maxdatagram : global_t38_maxdatagram;
07640       set_t38_capabilities(p);
07641 
07642       ast_debug(1, "Setting NAT on UDPTL to %s\n", natflags ? "On" : "Off");
07643       ast_udptl_setnat(p->udptl, natflags);
07644    } else {
07645       ast_log(AST_LOG_WARNING, "UDPTL creation failed - disabling T38 for this dialog\n");
07646       ast_clear_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT);
07647       return 1;
07648    }
07649 
07650    return 0;
07651 }
07652 
07653 
07654 static int sipinfo_send(
07655       struct ast_channel *chan,
07656       struct ast_variable *headers,
07657       const char *content_type,
07658       const char *content,
07659       const char *useragent_filter)
07660 {
07661    struct sip_pvt *p;
07662    struct ast_variable *var;
07663    struct sip_request req;
07664    int res = -1;
07665 
07666    ast_channel_lock(chan);
07667 
07668    if (ast_channel_tech(chan) != &sip_tech) {
07669       ast_log(LOG_WARNING, "Attempted to send a custom INFO on a non-SIP channel %s\n", ast_channel_name(chan));
07670       ast_channel_unlock(chan);
07671       return res;
07672    }
07673 
07674    p = ast_channel_tech_pvt(chan);
07675    sip_pvt_lock(p);
07676 
07677    if (!(ast_strlen_zero(useragent_filter))) {
07678       int match = (strstr(p->useragent, useragent_filter)) ? 1 : 0;
07679       if (!match) {
07680          goto cleanup;
07681       }
07682    }
07683 
07684    reqprep(&req, p, SIP_INFO, 0, 1);
07685    for (var = headers; var; var = var->next) {
07686       add_header(&req, var->name, var->value);
07687    }
07688    if (!ast_strlen_zero(content) && !ast_strlen_zero(content_type)) {
07689       add_header(&req, "Content-Type", content_type);
07690       add_content(&req, content);
07691    }
07692 
07693    res = send_request(p, &req, XMIT_RELIABLE, p->ocseq);
07694 
07695 cleanup:
07696    sip_pvt_unlock(p);
07697    ast_channel_unlock(chan);
07698    return res;
07699 }
07700 /*! \brief Play indication to user
07701  * With SIP a lot of indications is sent as messages, letting the device play
07702    the indication - busy signal, congestion etc
07703    \return -1 to force ast_indicate to send indication in audio, 0 if SIP can handle the indication by sending a message
07704 */
07705 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
07706 {
07707    struct sip_pvt *p = ast_channel_tech_pvt(ast);
07708    int res = 0;
07709 
07710    if (!p) {
07711       ast_debug(1, "Asked to indicate condition on channel %s with no pvt; ignoring\n",
07712             ast_channel_name(ast));
07713       return res;
07714    }
07715 
07716    sip_pvt_lock(p);
07717    switch(condition) {
07718    case AST_CONTROL_RINGING:
07719       if (ast_channel_state(ast) == AST_STATE_RING) {
07720          p->invitestate = INV_EARLY_MEDIA;
07721          if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
07722              (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {            
07723             /* Send 180 ringing if out-of-band seems reasonable */
07724             transmit_provisional_response(p, "180 Ringing", &p->initreq, 0);
07725             ast_set_flag(&p->flags[0], SIP_RINGING);
07726             if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
07727                break;
07728          } else {
07729             /* Well, if it's not reasonable, just send in-band */
07730          }
07731       }
07732       res = -1;
07733       break;
07734    case AST_CONTROL_BUSY:
07735       if (ast_channel_state(ast) != AST_STATE_UP) {
07736          transmit_response_reliable(p, "486 Busy Here", &p->initreq);
07737          p->invitestate = INV_COMPLETED;
07738          sip_alreadygone(p);
07739          ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
07740          break;
07741       }
07742       res = -1;
07743       break;
07744    case AST_CONTROL_CONGESTION:
07745       if (ast_channel_state(ast) != AST_STATE_UP) {
07746          transmit_response_reliable(p, "503 Service Unavailable", &p->initreq);
07747          p->invitestate = INV_COMPLETED;
07748          sip_alreadygone(p);
07749          ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
07750          break;
07751       }
07752       res = -1;
07753       break;
07754    case AST_CONTROL_INCOMPLETE:
07755       if (ast_channel_state(ast) != AST_STATE_UP) {
07756          switch (ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)) {
07757          case SIP_PAGE2_ALLOWOVERLAP_YES:
07758             transmit_response_reliable(p, "484 Address Incomplete", &p->initreq);
07759             p->invitestate = INV_COMPLETED;
07760             sip_alreadygone(p);
07761             ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
07762             break;
07763          case SIP_PAGE2_ALLOWOVERLAP_DTMF:
07764             /* Just wait for inband DTMF digits */
07765             break;
07766          default:
07767             /* it actually means no support for overlap */
07768             transmit_response_reliable(p, "404 Not Found", &p->initreq);
07769             p->invitestate = INV_COMPLETED;
07770             sip_alreadygone(p);
07771             ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
07772             break;
07773          }
07774       }
07775       break;
07776    case AST_CONTROL_PROCEEDING:
07777       if ((ast_channel_state(ast) != AST_STATE_UP) &&
07778           !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
07779           !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
07780          transmit_response(p, "100 Trying", &p->initreq);
07781          p->invitestate = INV_PROCEEDING;
07782          break;
07783       }
07784       res = -1;
07785       break;
07786    case AST_CONTROL_PROGRESS:
07787       if ((ast_channel_state(ast) != AST_STATE_UP) &&
07788           !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
07789           !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
07790          p->invitestate = INV_EARLY_MEDIA;
07791          transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
07792          ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
07793          break;
07794       }
07795       res = -1;
07796       break;
07797    case AST_CONTROL_HOLD:
07798       ast_rtp_instance_update_source(p->rtp);
07799       ast_moh_start(ast, data, p->mohinterpret);
07800       break;
07801    case AST_CONTROL_UNHOLD:
07802       ast_rtp_instance_update_source(p->rtp);
07803       ast_moh_stop(ast);
07804       break;
07805    case AST_CONTROL_VIDUPDATE:   /* Request a video frame update */
07806       if (p->vrtp && !p->novideo) {
07807          transmit_info_with_vidupdate(p);
07808          /* ast_rtcp_send_h261fur(p->vrtp); */
07809       } else
07810          res = -1;
07811       break;
07812    case AST_CONTROL_T38_PARAMETERS:
07813       res = -1;
07814       if (datalen != sizeof(struct ast_control_t38_parameters)) {
07815          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);
07816       } else {
07817          const struct ast_control_t38_parameters *parameters = data;
07818          if (!initialize_udptl(p)) {
07819             res = interpret_t38_parameters(p, parameters);
07820          }
07821       }
07822       break;
07823    case AST_CONTROL_SRCUPDATE:
07824       ast_rtp_instance_update_source(p->rtp);
07825       break;
07826    case AST_CONTROL_SRCCHANGE:
07827       ast_rtp_instance_change_source(p->rtp);
07828       break;
07829    case AST_CONTROL_CONNECTED_LINE:
07830       update_connectedline(p, data, datalen);
07831       break;
07832    case AST_CONTROL_REDIRECTING:
07833       update_redirecting(p, data, datalen);
07834       break;
07835    case AST_CONTROL_AOC:
07836       {
07837          struct ast_aoc_decoded *decoded = ast_aoc_decode((struct ast_aoc_encoded *) data, datalen, ast);
07838          if (!decoded) {
07839             ast_log(LOG_ERROR, "Error decoding indicated AOC data\n");
07840             res = -1;
07841             break;
07842          }
07843          switch (ast_aoc_get_msg_type(decoded)) {
07844          case AST_AOC_REQUEST:
07845             if (ast_aoc_get_termination_request(decoded)) {
07846                /* TODO, once there is a way to get AOC-E on hangup, attempt that here
07847                 * before hanging up the channel.*/
07848 
07849                /* The other side has already initiated the hangup. This frame
07850                 * just says they are waiting to get AOC-E before completely tearing
07851                 * the call down.  Since SIP does not support this at the moment go
07852                 * ahead and terminate the call here to avoid an unnecessary timeout. */
07853                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));
07854                ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
07855             }
07856             break;
07857          case AST_AOC_D:
07858          case AST_AOC_E:
07859             if (ast_test_flag(&p->flags[2], SIP_PAGE3_SNOM_AOC)) {
07860                transmit_info_with_aoc(p, decoded);
07861             }
07862             break;
07863          case AST_AOC_S: /* S not supported yet */
07864          default:
07865             break;
07866          }
07867          ast_aoc_destroy_decoded(decoded);
07868       }
07869       break;
07870    case AST_CONTROL_UPDATE_RTP_PEER: /* Absorb this since it is handled by the bridge */
07871       break;
07872    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. */
07873       res = -1;
07874       break;
07875    case AST_CONTROL_PVT_CAUSE_CODE: /* these should be handled by the code in channel.c */
07876    case -1:
07877       res = -1;
07878       break;
07879    default:
07880       ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
07881       res = -1;
07882       break;
07883    }
07884    sip_pvt_unlock(p);
07885    return res;
07886 }
07887 
07888 /*!
07889  * \brief Initiate a call in the SIP channel
07890  *
07891  * \note called from sip_request_call (calls from the pbx ) for
07892  * outbound channels and from handle_request_invite for inbound
07893  * channels
07894  *
07895  * \pre i is locked
07896  *
07897  * \return New ast_channel locked.
07898  */
07899 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title, const char *linkedid, struct ast_callid *callid)
07900 {
07901    struct ast_channel *tmp;
07902    struct ast_variable *v = NULL;
07903    struct ast_format fmt;
07904    struct ast_format_cap *what = NULL; /* SHALLOW COPY DO NOT DESTROY! */
07905    int needvideo = 0;
07906    int needtext = 0;
07907    char buf[SIPBUFSIZE];
07908    char *exten;
07909 
07910    {
07911       const char *my_name; /* pick a good name */
07912    
07913       if (title) {
07914          my_name = title;
07915       } else {
07916          my_name = ast_strdupa(i->fromdomain);
07917       }
07918 
07919       sip_pvt_unlock(i);
07920       /* Don't hold a sip pvt lock while we allocate a channel */
07921       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, ast_atomic_fetchadd_int((int *)&chan_idx, +1));
07922    }
07923    if (!tmp) {
07924       ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
07925       sip_pvt_lock(i);
07926       return NULL;
07927    }
07928 
07929    /* If we sent in a callid, bind it to the channel. */
07930    if (callid) {
07931       ast_channel_callid_set(tmp, callid);
07932    }
07933 
07934    ast_channel_lock(tmp);
07935    sip_pvt_lock(i);
07936    ast_channel_cc_params_init(tmp, i->cc_params);
07937    ast_channel_caller(tmp)->id.tag = ast_strdup(i->cid_tag);
07938 
07939    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);
07940 
07941    /* Select our native format based on codec preference until we receive
07942       something from another device to the contrary. */
07943    if (!(ast_format_cap_is_empty(i->jointcaps))) { /* The joint capabilities of us and peer */
07944       what = i->jointcaps;
07945    } else if (!(ast_format_cap_is_empty(i->caps))) {     /* Our configured capability for this peer */
07946       what = i->caps;
07947    } else {
07948       what = sip_cfg.caps;
07949    }
07950 
07951    /* Set the native formats */
07952    ast_format_cap_copy(ast_channel_nativeformats(tmp), what);
07953    /* choose and use only the best audio format for our native formats */
07954    ast_codec_choose(&i->prefs, ast_channel_nativeformats(tmp), 1, &fmt); /* get the best audio format */
07955    ast_format_cap_remove_bytype(ast_channel_nativeformats(tmp), AST_FORMAT_TYPE_AUDIO); /* remove only the other audio formats */
07956    ast_format_cap_add(ast_channel_nativeformats(tmp), &fmt); /* add our best choice back */
07957 
07958    ast_debug(3, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, ast_channel_nativeformats(tmp)));
07959    ast_debug(3, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->jointcaps));
07960    ast_debug(3, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->caps));
07961    ast_debug(3, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname(&fmt));
07962    if (!ast_format_cap_is_empty(i->prefcaps)) {
07963       ast_debug(3, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->prefcaps));
07964    }
07965 
07966    /* If we have a prefcodec setting, we have an inbound channel that set a
07967       preferred format for this call. Otherwise, we check the jointcapability
07968       We also check for vrtp. If it's not there, we are not allowed do any video anyway.
07969     */
07970    if (i->vrtp) {
07971       if (ast_test_flag(&i->flags[1], SIP_PAGE2_VIDEOSUPPORT))
07972          needvideo = 1;
07973       else if (!ast_format_cap_is_empty(i->prefcaps))
07974          needvideo = ast_format_cap_has_type(i->prefcaps, AST_FORMAT_TYPE_VIDEO);   /* Outbound call */
07975       else
07976          needvideo = ast_format_cap_has_type(i->jointcaps, AST_FORMAT_TYPE_VIDEO);  /* Inbound call */
07977    }
07978 
07979    if (i->trtp) {
07980       if (!ast_format_cap_is_empty(i->prefcaps))
07981          needtext = ast_format_cap_has_type(i->prefcaps, AST_FORMAT_TYPE_TEXT);  /* Outbound call */
07982       else
07983          needtext = ast_format_cap_has_type(i->jointcaps, AST_FORMAT_TYPE_TEXT); /* Inbound call */
07984    }
07985 
07986    if (needvideo) {
07987       ast_debug(3, "This channel can handle video! HOLLYWOOD next!\n");
07988    } else {
07989       ast_debug(3, "This channel will not be able to handle video.\n");
07990    }
07991 
07992    enable_dsp_detect(i);
07993 
07994    if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
07995        (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
07996       if (i->rtp) {
07997          ast_rtp_instance_dtmf_mode_set(i->rtp, AST_RTP_DTMF_MODE_INBAND);
07998       }
07999    } else if (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) {
08000       if (i->rtp) {
08001          ast_rtp_instance_dtmf_mode_set(i->rtp, AST_RTP_DTMF_MODE_RFC2833);
08002       }
08003    }
08004 
08005    /* Set file descriptors for audio, video, and realtime text.  Since
08006     * UDPTL is created as needed in the lifetime of a dialog, its file
08007     * descriptor is set in initialize_udptl */
08008    if (i->rtp) {
08009       ast_channel_set_fd(tmp, 0, ast_rtp_instance_fd(i->rtp, 0));
08010       ast_channel_set_fd(tmp, 1, ast_rtp_instance_fd(i->rtp, 1));
08011       ast_rtp_instance_set_write_format(i->rtp, &fmt);
08012       ast_rtp_instance_set_read_format(i->rtp, &fmt);
08013    }
08014    if (needvideo && i->vrtp) {
08015       ast_channel_set_fd(tmp, 2, ast_rtp_instance_fd(i->vrtp, 0));
08016       ast_channel_set_fd(tmp, 3, ast_rtp_instance_fd(i->vrtp, 1));
08017    }
08018    if (needtext && i->trtp) {
08019       ast_channel_set_fd(tmp, 4, ast_rtp_instance_fd(i->trtp, 0));
08020    }
08021    if (i->udptl) {
08022       ast_channel_set_fd(tmp, 5, ast_udptl_fd(i->udptl));
08023    }
08024 
08025    if (state == AST_STATE_RING) {
08026       ast_channel_rings_set(tmp, 1);
08027    }
08028    ast_channel_adsicpe_set(tmp, AST_ADSI_UNAVAILABLE);
08029 
08030    ast_format_copy(ast_channel_writeformat(tmp), &fmt);
08031    ast_format_copy(ast_channel_rawwriteformat(tmp), &fmt);
08032 
08033    ast_format_copy(ast_channel_readformat(tmp), &fmt);
08034    ast_format_copy(ast_channel_rawreadformat(tmp), &fmt);
08035 
08036    ast_channel_tech_pvt_set(tmp, dialog_ref(i, "sip_new: set chan->tech_pvt to i"));
08037 
08038    ast_channel_callgroup_set(tmp, i->callgroup);
08039    ast_channel_pickupgroup_set(tmp, i->pickupgroup);
08040 
08041    ast_channel_named_callgroups_set(tmp, i->named_callgroups);
08042    ast_channel_named_pickupgroups_set(tmp, i->named_pickupgroups);
08043 
08044    ast_channel_caller(tmp)->id.name.presentation = i->callingpres;
08045    ast_channel_caller(tmp)->id.number.presentation = i->callingpres;
08046    if (!ast_strlen_zero(i->parkinglot)) {
08047       ast_channel_parkinglot_set(tmp, i->parkinglot);
08048    }
08049    if (!ast_strlen_zero(i->accountcode)) {
08050       ast_channel_accountcode_set(tmp, i->accountcode);
08051    }
08052    if (i->amaflags) {
08053       ast_channel_amaflags_set(tmp, i->amaflags);
08054    }
08055    if (!ast_strlen_zero(i->language)) {
08056       ast_channel_language_set(tmp, i->language);
08057    }
08058    if (!ast_strlen_zero(i->zone)) {
08059       struct ast_tone_zone *zone;
08060       if (!(zone = ast_get_indication_zone(i->zone))) {
08061          ast_log(LOG_ERROR, "Unknown country code '%s' for tonezone. Check indications.conf for available country codes.\n", i->zone);
08062       } 
08063       ast_channel_zone_set(tmp, zone);
08064    }
08065    i->owner = tmp;
08066    ast_module_ref(ast_module_info->self);
08067    ast_channel_context_set(tmp, i->context);
08068    /*Since it is valid to have extensions in the dialplan that have unescaped characters in them
08069     * we should decode the uri before storing it in the channel, but leave it encoded in the sip_pvt
08070     * structure so that there aren't issues when forming URI's
08071     */
08072    exten = ast_strdupa(i->exten);
08073    sip_pvt_unlock(i);
08074    ast_channel_unlock(tmp);
08075    if (!ast_exists_extension(NULL, i->context, i->exten, 1, i->cid_num)) {
08076       ast_uri_decode(exten, ast_uri_sip_user);
08077    }
08078    ast_channel_lock(tmp);
08079    sip_pvt_lock(i);
08080    ast_channel_exten_set(tmp, exten);
08081 
08082    /* Don't use ast_set_callerid() here because it will
08083     * generate an unnecessary NewCallerID event  */
08084    if (!ast_strlen_zero(i->cid_num)) {
08085       ast_channel_caller(tmp)->ani.number.valid = 1;
08086       ast_channel_caller(tmp)->ani.number.str = ast_strdup(i->cid_num);
08087    }
08088    if (!ast_strlen_zero(i->rdnis)) {
08089       ast_channel_redirecting(tmp)->from.number.valid = 1;
08090       ast_channel_redirecting(tmp)->from.number.str = ast_strdup(i->rdnis);
08091    }
08092 
08093    if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s")) {
08094       ast_channel_dialed(tmp)->number.str = ast_strdup(i->exten);
08095    }
08096 
08097    ast_channel_priority_set(tmp, 1);
08098    if (!ast_strlen_zero(i->uri)) {
08099       pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
08100    }
08101    if (!ast_strlen_zero(i->domain)) {
08102       pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
08103    }
08104    if (!ast_strlen_zero(i->callid)) {
08105       pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
08106    }
08107    if (i->rtp) {
08108       ast_jb_configure(tmp, &global_jbconf);
08109    }
08110 
08111    if (!i->relatedpeer) {
08112       ast_set_flag(ast_channel_flags(tmp), AST_FLAG_DISABLE_DEVSTATE_CACHE);
08113    }
08114    /* Set channel variables for this call from configuration */
08115    for (v = i->chanvars ; v ; v = v->next) {
08116       char valuebuf[1024];
08117       pbx_builtin_setvar_helper(tmp, v->name, ast_get_encoded_str(v->value, valuebuf, sizeof(valuebuf)));
08118    }
08119 
08120    if (i->do_history) {
08121       append_history(i, "NewChan", "Channel %s - from %s", ast_channel_name(tmp), i->callid);
08122    }
08123 
08124    /* Inform manager user about new channel and their SIP call ID */
08125    if (sip_cfg.callevents) {
08126       manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
08127          "Channel: %s\r\nUniqueid: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\n",
08128          ast_channel_name(tmp), ast_channel_uniqueid(tmp), "SIP", i->callid, i->fullcontact);
08129    }
08130 
08131    return tmp;
08132 }
08133 
08134 /*! \brief Lookup 'name' in the SDP starting
08135  * at the 'start' line. Returns the matching line, and 'start'
08136  * is updated with the next line number.
08137  */
08138 static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
08139 {
08140    int len = strlen(name);
08141    const char *line;
08142 
08143    while (*start < (req->sdp_start + req->sdp_count)) {
08144       line = REQ_OFFSET_TO_STR(req, line[(*start)++]);
08145       if (!strncasecmp(line, name, len) && line[len] == '=') {
08146          return ast_skip_blanks(line + len + 1);
08147       }
08148    }
08149 
08150    /* if the line was not found, ensure that *start points past the SDP */
08151    (*start)++;
08152 
08153    return "";
08154 }
08155 
08156 /*! \brief Fetches the next valid SDP line between the 'start' line
08157  * (inclusive) and the 'stop' line (exclusive). Returns the type
08158  * ('a', 'c', ...) and matching line in reference 'start' is updated
08159  * with the next line number.
08160  */
08161 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value)
08162 {
08163    char type = '\0';
08164    const char *line = NULL;
08165 
08166    if (stop > (req->sdp_start + req->sdp_count)) {
08167       stop = req->sdp_start + req->sdp_count;
08168    }
08169 
08170    while (*start < stop) {
08171       line = REQ_OFFSET_TO_STR(req, line[(*start)++]);
08172       if (line[1] == '=') {
08173          type = line[0];
08174          *value = ast_skip_blanks(line + 2);
08175          break;
08176       }
08177    }
08178 
08179    return type;
08180 }
08181 
08182 /*! \brief Get a specific line from the message content */
08183 static char *get_content_line(struct sip_request *req, char *name, char delimiter)
08184 {
08185    int i;
08186    int len = strlen(name);
08187    const char *line;
08188 
08189    for (i = 0; i < req->lines; i++) {
08190       line = REQ_OFFSET_TO_STR(req, line[i]);
08191       if (!strncasecmp(line, name, len) && line[len] == delimiter) {
08192          return ast_skip_blanks(line + len + 1);
08193       }
08194    }
08195 
08196    return "";
08197 }
08198 
08199 /*! \brief Structure for conversion between compressed SIP and "normal" SIP headers */
08200 struct cfalias {
08201    const char *fullname;
08202    const char *shortname;
08203 };
08204 static const struct cfalias aliases[] = {
08205    { "Content-Type",           "c" },
08206    { "Content-Encoding",       "e" },
08207    { "From",                   "f" },
08208    { "Call-ID",                "i" },
08209    { "Contact",                "m" },
08210    { "Content-Length",         "l" },
08211    { "Subject",                "s" },
08212    { "To",                     "t" },
08213    { "Supported",              "k" },
08214    { "Refer-To",               "r" },
08215    { "Referred-By",            "b" },
08216    { "Allow-Events",           "u" },
08217    { "Event",                  "o" },
08218    { "Via",                    "v" },
08219    { "Accept-Contact",         "a" },
08220    { "Reject-Contact",         "j" },
08221    { "Request-Disposition",    "d" },
08222    { "Session-Expires",        "x" },
08223    { "Identity",               "y" },
08224    { "Identity-Info",          "n" },
08225 };
08226 
08227 /*! \brief Find compressed SIP alias */
08228 static const char *find_alias(const char *name, const char *_default)
08229 {
08230    int x;
08231 
08232    for (x = 0; x < ARRAY_LEN(aliases); x++) {
08233       if (!strcasecmp(aliases[x].fullname, name))
08234          return aliases[x].shortname;
08235    }
08236 
08237    return _default;
08238 }
08239 
08240 /*! \brief Find full SIP alias */
08241 static const char *find_full_alias(const char *name, const char *_default)
08242 {
08243    int x;
08244 
08245    if (strlen(name) == 1) {
08246       /* We have a short header name to convert. */
08247       for (x = 0; x < ARRAY_LEN(aliases); ++x) {
08248          if (!strcasecmp(aliases[x].shortname, name))
08249             return aliases[x].fullname;
08250       }
08251    }
08252 
08253    return _default;
08254 }
08255 
08256 static const char *__get_header(const struct sip_request *req, const char *name, int *start)
08257 {
08258    /*
08259     * Technically you can place arbitrary whitespace both before and after the ':' in
08260     * a header, although RFC3261 clearly says you shouldn't before, and place just
08261     * one afterwards.  If you shouldn't do it, what absolute idiot decided it was
08262     * a good idea to say you can do it, and if you can do it, why in the hell would.
08263     * you say you shouldn't.
08264     * Anyways, pedanticsipchecking controls whether we allow spaces before ':',
08265     * and we always allow spaces after that for compatibility.
08266     */
08267    const char *sname = find_alias(name, NULL);
08268    int x, len = strlen(name), slen = (sname ? 1 : 0);
08269    for (x = *start; x < req->headers; x++) {
08270       const char *header = REQ_OFFSET_TO_STR(req, header[x]);
08271       int smatch = 0, match = !strncasecmp(header, name, len);
08272       if (slen) {
08273          smatch = !strncasecmp(header, sname, slen);
08274       }
08275       if (match || smatch) {
08276          /* skip name */
08277          const char *r = header + (match ? len : slen );
08278          if (sip_cfg.pedanticsipchecking) {
08279             r = ast_skip_blanks(r);
08280          }
08281 
08282          if (*r == ':') {
08283             *start = x+1;
08284             return ast_skip_blanks(r+1);
08285          }
08286       }
08287    }
08288 
08289    /* Don't return NULL, so sip_get_header is always a valid pointer */
08290    return "";
08291 }
08292 
08293 /*! \brief Get header from SIP request
08294    \return Always return something, so don't check for NULL because it won't happen :-)
08295 */
08296 const char *sip_get_header(const struct sip_request *req, const char *name)
08297 {
08298    int start = 0;
08299    return __get_header(req, name, &start);
08300 }
08301 
08302 
08303 AST_THREADSTORAGE(sip_content_buf);
08304 
08305 /*! \brief Get message body content */
08306 static char *get_content(struct sip_request *req)
08307 {
08308    struct ast_str *str;
08309    int i;
08310 
08311    if (!(str = ast_str_thread_get(&sip_content_buf, 128))) {
08312       return NULL;
08313    }
08314 
08315    ast_str_reset(str);
08316 
08317    for (i = 0; i < req->lines; i++) {
08318       if (ast_str_append(&str, 0, "%s\n", REQ_OFFSET_TO_STR(req, line[i])) < 0) {
08319          return NULL;
08320       }
08321    }
08322 
08323    return ast_str_buffer(str);
08324 }
08325 
08326 /*! \brief Read RTP from network */
08327 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
08328 {
08329    /* Retrieve audio/etc from channel.  Assumes p->lock is already held. */
08330    struct ast_frame *f;
08331    
08332    if (!p->rtp) {
08333       /* We have no RTP allocated for this channel */
08334       return &ast_null_frame;
08335    }
08336 
08337    switch(ast_channel_fdno(ast)) {
08338    case 0:
08339       f = ast_rtp_instance_read(p->rtp, 0);  /* RTP Audio */
08340       break;
08341    case 1:
08342       f = ast_rtp_instance_read(p->rtp, 1);  /* RTCP Control Channel */
08343       break;
08344    case 2:
08345       f = ast_rtp_instance_read(p->vrtp, 0); /* RTP Video */
08346       break;
08347    case 3:
08348       f = ast_rtp_instance_read(p->vrtp, 1); /* RTCP Control Channel for video */
08349       break;
08350    case 4:
08351       f = ast_rtp_instance_read(p->trtp, 0); /* RTP Text */
08352       if (sipdebug_text) {
08353          struct ast_str *out = ast_str_create(f->datalen * 4 + 6);
08354          int i;
08355          unsigned char* arr = f->data.ptr;
08356          do {
08357             if (!out) {
08358                break;
08359             }
08360             for (i = 0; i < f->datalen; i++) {
08361                ast_str_append(&out, 0, "%c", (arr[i] > ' ' && arr[i] < '}') ? arr[i] : '.');
08362             }
08363             ast_str_append(&out, 0, " -> ");
08364             for (i = 0; i < f->datalen; i++) {
08365                ast_str_append(&out, 0, "%02X ", arr[i]);
08366             }
08367             ast_verb(0, "%s\n", ast_str_buffer(out));
08368             ast_free(out);
08369          } while (0);
08370       }
08371       break;
08372    case 5:
08373       f = ast_udptl_read(p->udptl); /* UDPTL for T.38 */
08374       break;
08375    default:
08376       f = &ast_null_frame;
08377    }
08378    /* Don't forward RFC2833 if we're not supposed to */
08379    if (f && (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) &&
08380        (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833)) {
08381       ast_debug(1, "Ignoring DTMF (%c) RTP frame because dtmfmode is not RFC2833\n", f->subclass.integer);
08382       ast_frfree(f);
08383       return &ast_null_frame;
08384    }
08385 
08386    /* We already hold the channel lock */
08387    if (!p->owner || (f && f->frametype != AST_FRAME_VOICE)) {
08388       return f;
08389    }
08390 
08391    if (f && !ast_format_cap_iscompatible(ast_channel_nativeformats(p->owner), &f->subclass.format)) {
08392       if (!ast_format_cap_iscompatible(p->jointcaps, &f->subclass.format)) {
08393          ast_debug(1, "Bogus frame of format '%s' received from '%s'!\n",
08394             ast_getformatname(&f->subclass.format), ast_channel_name(p->owner));
08395          ast_frfree(f);
08396          return &ast_null_frame;
08397       }
08398       ast_debug(1, "Oooh, format changed to %s\n",
08399          ast_getformatname(&f->subclass.format));
08400       ast_format_cap_remove_bytype(ast_channel_nativeformats(p->owner), AST_FORMAT_TYPE_AUDIO);
08401       ast_format_cap_add(ast_channel_nativeformats(p->owner), &f->subclass.format);
08402       ast_set_read_format(p->owner, ast_channel_readformat(p->owner));
08403       ast_set_write_format(p->owner, ast_channel_writeformat(p->owner));
08404    }
08405 
08406    if (f && p->dsp) {
08407       f = ast_dsp_process(p->owner, p->dsp, f);
08408       if (f && f->frametype == AST_FRAME_DTMF) {
08409          if (f->subclass.integer == 'f') {
08410             ast_debug(1, "Fax CNG detected on %s\n", ast_channel_name(ast));
08411             *faxdetect = 1;
08412             /* If we only needed this DSP for fax detection purposes we can just drop it now */
08413             if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
08414                ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
08415             } else {
08416                ast_dsp_free(p->dsp);
08417                p->dsp = NULL;
08418             }
08419          } else {
08420             ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass.integer);
08421          }
08422       }
08423    }
08424 
08425    return f;
08426 }
08427 
08428 /*! \brief Read SIP RTP from channel */
08429 static struct ast_frame *sip_read(struct ast_channel *ast)
08430 {
08431    struct ast_frame *fr;
08432    struct sip_pvt *p = ast_channel_tech_pvt(ast);
08433    int faxdetected = FALSE;
08434 
08435    sip_pvt_lock(p);
08436    fr = sip_rtp_read(ast, p, &faxdetected);
08437    p->lastrtprx = time(NULL);
08438 
08439    /* If we detect a CNG tone and fax detection is enabled then send us off to the fax extension */
08440    if (faxdetected && ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
08441       if (strcmp(ast_channel_exten(ast), "fax")) {
08442          const char *target_context = S_OR(ast_channel_macrocontext(ast), ast_channel_context(ast));
08443          /* We need to unlock 'ast' here because
08444           * ast_exists_extension has the potential to start and
08445           * stop an autoservice on the channel. Such action is
08446           * prone to deadlock if the channel is locked.
08447           */
08448          sip_pvt_unlock(p);
08449          ast_channel_unlock(ast);
08450          if (ast_exists_extension(ast, target_context, "fax", 1,
08451             S_COR(ast_channel_caller(ast)->id.number.valid, ast_channel_caller(ast)->id.number.str, NULL))) {
08452             ast_channel_lock(ast);
08453             sip_pvt_lock(p);
08454             ast_verb(2, "Redirecting '%s' to fax extension due to CNG detection\n", ast_channel_name(ast));
08455             pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast_channel_exten(ast));
08456             if (ast_async_goto(ast, target_context, "fax", 1)) {
08457                ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast_channel_name(ast), target_context);
08458             }
08459             ast_frfree(fr);
08460             fr = &ast_null_frame;
08461          } else {
08462             ast_channel_lock(ast);
08463             sip_pvt_lock(p);
08464             ast_log(LOG_NOTICE, "FAX CNG detected but no fax extension\n");
08465          }
08466       }
08467    }
08468 
08469    /* Only allow audio through if they sent progress with SDP, or if the channel is actually answered */
08470    if (fr && fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast_channel_state(ast) != AST_STATE_UP) {
08471       ast_frfree(fr);
08472       fr = &ast_null_frame;
08473    }
08474 
08475    sip_pvt_unlock(p);
08476 
08477    return fr;
08478 }
08479 
08480 
08481 /*! \brief Generate 32 byte random string for callid's etc */
08482 static char *generate_random_string(char *buf, size_t size)
08483 {
08484    long val[4];
08485    int x;
08486 
08487    for (x=0; x<4; x++)
08488       val[x] = ast_random();
08489    snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
08490 
08491    return buf;
08492 }
08493 
08494 static char *generate_uri(struct sip_pvt *pvt, char *buf, size_t size)
08495 {
08496    struct ast_str *uri = ast_str_alloca(size);
08497    ast_str_set(&uri, 0, "%s", pvt->socket.type == SIP_TRANSPORT_TLS ? "sips:" : "sip:");
08498    /* Here would be a great place to generate a UUID, but for now we'll
08499     * use the handy random string generation function we already have
08500     */
08501    ast_str_append(&uri, 0, "%s", generate_random_string(buf, size));
08502    ast_str_append(&uri, 0, "@%s", ast_sockaddr_stringify_remote(&pvt->ourip));
08503    ast_copy_string(buf, ast_str_buffer(uri), size);
08504    return buf;
08505 }
08506 
08507 /*!
08508  * \brief Build SIP Call-ID value for a non-REGISTER transaction
08509  *
08510  * \note The passed in pvt must not be in a dialogs container
08511  * since this function changes the hash key used by the
08512  * container.
08513  */
08514 static void build_callid_pvt(struct sip_pvt *pvt)
08515 {
08516    char buf[33];
08517    const char *host = S_OR(pvt->fromdomain, ast_sockaddr_stringify_remote(&pvt->ourip));
08518 
08519    ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
08520 }
08521 
08522 /*! \brief Unlink the given object from the container and return TRUE if it was in the container. */
08523 #define CONTAINER_UNLINK(container, obj, tag)                        \
08524    ({                                                    \
08525       int found = 0;                                        \
08526       typeof((obj)) __removed_obj;                             \
08527       __removed_obj = ao2_t_callback((container),                    \
08528          OBJ_UNLINK | OBJ_POINTER, ao2_match_by_addr, (obj), (tag));    \
08529       if (__removed_obj) {                                  \
08530          ao2_ref(__removed_obj, -1);                              \
08531          found = 1;                                         \
08532       }                                                  \
08533       found;                                                \
08534    })
08535 
08536 /*!
08537  * \internal
08538  * \brief Safely change the callid of the given SIP dialog.
08539  *
08540  * \param pvt SIP private structure to change callid
08541  * \param callid Specified new callid to use.  NULL if generate new callid.
08542  *
08543  * \return Nothing
08544  */
08545 static void change_callid_pvt(struct sip_pvt *pvt, const char *callid)
08546 {
08547    int in_dialog_container;
08548    int in_rtp_container;
08549    char *oldid = ast_strdupa(pvt->callid);
08550 
08551    ao2_lock(dialogs);
08552    ao2_lock(dialogs_rtpcheck);
08553    in_dialog_container = CONTAINER_UNLINK(dialogs, pvt,
08554       "About to change the callid -- remove the old name");
08555    in_rtp_container = CONTAINER_UNLINK(dialogs_rtpcheck, pvt,
08556       "About to change the callid -- remove the old name");
08557    if (callid) {
08558       ast_string_field_set(pvt, callid, callid);
08559    } else {
08560       build_callid_pvt(pvt);
08561    }
08562    if (in_dialog_container) {
08563       ao2_t_link(dialogs, pvt, "New dialog callid -- inserted back into table");
08564    }
08565    if (in_rtp_container) {
08566       ao2_t_link(dialogs_rtpcheck, pvt, "New dialog callid -- inserted back into table");
08567    }
08568    ao2_unlock(dialogs_rtpcheck);
08569    ao2_unlock(dialogs);
08570 
08571    if (strcmp(oldid, pvt->callid)) {
08572       ast_debug(1, "SIP call-id changed from '%s' to '%s'\n", oldid, pvt->callid);
08573    }
08574 }
08575 
08576 /*! \brief Build SIP Call-ID value for a REGISTER transaction */
08577 static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain)
08578 {
08579    char buf[33];
08580 
08581    const char *host = S_OR(fromdomain, ast_sockaddr_stringify_host_remote(ourip));
08582 
08583    ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
08584 }
08585 
08586 /*! \brief Build SIP From tag value for REGISTER */
08587 static void build_localtag_registry(struct sip_registry *reg)
08588 {
08589    ast_string_field_build(reg, localtag, "as%08lx", ast_random());
08590 }
08591 
08592 /*! \brief Make our SIP dialog tag */
08593 static void make_our_tag(struct sip_pvt *pvt)
08594 {
08595    ast_string_field_build(pvt, tag, "as%08lx", ast_random());
08596 }
08597 
08598 /*! \brief Allocate Session-Timers struct w/in dialog */
08599 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p)
08600 {
08601    struct sip_st_dlg *stp;
08602 
08603    if (p->stimer) {
08604       ast_log(LOG_ERROR, "Session-Timer struct already allocated\n");
08605       return p->stimer;
08606    }
08607 
08608    if (!(stp = ast_calloc(1, sizeof(struct sip_st_dlg))))
08609       return NULL;
08610 
08611    p->stimer = stp;
08612 
08613    stp->st_schedid = -1;           /* Session-Timers ast_sched scheduler id */
08614 
08615    return p->stimer;
08616 }
08617 
08618 static void sip_pvt_callid_set(struct sip_pvt *pvt, struct ast_callid *callid)
08619 {
08620    if (pvt->logger_callid) {
08621       ast_callid_unref(pvt->logger_callid);
08622    }
08623    ast_callid_ref(callid);
08624    pvt->logger_callid = callid;
08625 }
08626 
08627 /*! \brief Allocate sip_pvt structure, set defaults and link in the container.
08628  * Returns a reference to the object so whoever uses it later must
08629  * remember to release the reference.
08630  */
08631 struct sip_pvt *sip_alloc(ast_string_field callid, struct ast_sockaddr *addr,
08632              int useglobal_nat, const int intended_method, struct sip_request *req, struct ast_callid *logger_callid)
08633 {
08634    struct sip_pvt *p;
08635 
08636    if (!(p = ao2_t_alloc(sizeof(*p), sip_destroy_fn, "allocate a dialog(pvt) struct")))
08637       return NULL;
08638 
08639    if (ast_string_field_init(p, 512)) {
08640       ao2_t_ref(p, -1, "failed to string_field_init, drop p");
08641       return NULL;
08642    }
08643 
08644    if (!(p->cc_params = ast_cc_config_params_init())) {
08645       ao2_t_ref(p, -1, "Yuck, couldn't allocate cc_params struct. Get rid o' p");
08646       return NULL;
08647    }
08648 
08649    if (logger_callid) {
08650       sip_pvt_callid_set(p, logger_callid);
08651    }
08652 
08653    p->caps = ast_format_cap_alloc_nolock();
08654    p->jointcaps = ast_format_cap_alloc_nolock();
08655    p->peercaps = ast_format_cap_alloc_nolock();
08656    p->redircaps = ast_format_cap_alloc_nolock();
08657    p->prefcaps = ast_format_cap_alloc_nolock();
08658 
08659    if (!p->caps|| !p->jointcaps || !p->peercaps || !p->redircaps) {
08660       p->caps = ast_format_cap_destroy(p->caps);
08661       p->jointcaps = ast_format_cap_destroy(p->jointcaps);
08662       p->peercaps = ast_format_cap_destroy(p->peercaps);
08663       p->redircaps = ast_format_cap_destroy(p->redircaps);
08664       p->prefcaps = ast_format_cap_destroy(p->prefcaps);
08665       ao2_t_ref(p, -1, "Yuck, couldn't allocate format capabilities. Get rid o' p");
08666       return NULL;
08667    }
08668 
08669 
08670    /* If this dialog is created as a result of a request or response, lets store
08671     * some information about it in the dialog. */
08672    if (req) {
08673       struct sip_via *via;
08674       const char *cseq = sip_get_header(req, "Cseq");
08675       uint32_t seqno;
08676 
08677       /* get branch parameter from initial Request that started this dialog */
08678       via = parse_via(sip_get_header(req, "Via"));
08679       if (via) {
08680          /* only store the branch if it begins with the magic prefix "z9hG4bK", otherwise
08681           * it is not useful to us to have it */
08682          if (!ast_strlen_zero(via->branch) && !strncasecmp(via->branch, "z9hG4bK", 7)) {
08683             ast_string_field_set(p, initviabranch, via->branch);
08684             ast_string_field_set(p, initviasentby, via->sent_by);
08685          }
08686          free_via(via);
08687       }
08688 
08689       /* Store initial incoming cseq. An error in sscanf here is ignored.  There is no approperiate
08690        * except not storing the number.  CSeq validation must take place before dialog creation in find_call */
08691       if (!ast_strlen_zero(cseq) && (sscanf(cseq, "%30u", &seqno) == 1)) {
08692          p->init_icseq = seqno;
08693       }
08694       /* Later in ast_sip_ouraddrfor we need this to choose the right ip and port for the specific transport */
08695       set_socket_transport(&p->socket, req->socket.type);
08696    } else {
08697       set_socket_transport(&p->socket, SIP_TRANSPORT_UDP);
08698    }
08699 
08700    p->socket.fd = -1;
08701    p->method = intended_method;
08702    p->initid = -1;
08703    p->waitid = -1;
08704    p->reinviteid = -1;
08705    p->autokillid = -1;
08706    p->request_queue_sched_id = -1;
08707    p->provisional_keepalive_sched_id = -1;
08708    p->t38id = -1;
08709    p->subscribed = NONE;
08710    p->stateid = -1;
08711    p->sessionversion_remote = -1;
08712    p->session_modify = TRUE;
08713    p->stimer = NULL;
08714    p->prefs = default_prefs;     /* Set default codecs for this call */
08715    ast_copy_string(p->zone, default_zone, sizeof(p->zone));
08716    p->maxforwards = sip_cfg.default_max_forwards;
08717 
08718    if (intended_method != SIP_OPTIONS) {  /* Peerpoke has it's own system */
08719       p->timer_t1 = global_t1;   /* Default SIP retransmission timer T1 (RFC 3261) */
08720       p->timer_b = global_timer_b;  /* Default SIP transaction timer B (RFC 3261) */
08721    }
08722 
08723    if (!addr) {
08724       p->ourip = internip;
08725    } else {
08726       ast_sockaddr_copy(&p->sa, addr);
08727       ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
08728    }
08729 
08730    /* Copy global flags to this PVT at setup. */
08731    ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
08732    ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
08733    ast_copy_flags(&p->flags[2], &global_flags[2], SIP_PAGE3_FLAGS_TO_COPY);
08734 
08735    p->do_history = recordhistory;
08736 
08737    p->branch = ast_random();  
08738    make_our_tag(p);
08739    p->ocseq = INITIAL_CSEQ;
08740    p->allowed_methods = UINT_MAX;
08741 
08742    if (sip_methods[intended_method].need_rtp) {
08743       p->maxcallbitrate = default_maxcallbitrate;
08744       p->autoframing = global_autoframing;
08745    }
08746 
08747    if (useglobal_nat && addr) {
08748       /* Setup NAT structure according to global settings if we have an address */
08749       ast_sockaddr_copy(&p->recv, addr);
08750       check_via(p, req);
08751       do_setnat(p);
08752    }
08753 
08754    if (p->method != SIP_REGISTER) {
08755       ast_string_field_set(p, fromdomain, default_fromdomain);
08756       p->fromdomainport = default_fromdomainport;
08757    }
08758    build_via(p);
08759    if (!callid)
08760       build_callid_pvt(p);
08761    else
08762       ast_string_field_set(p, callid, callid);
08763    /* Assign default music on hold class */
08764    ast_string_field_set(p, mohinterpret, default_mohinterpret);
08765    ast_string_field_set(p, mohsuggest, default_mohsuggest);
08766    ast_format_cap_copy(p->caps, sip_cfg.caps);
08767    p->allowtransfer = sip_cfg.allowtransfer;
08768    if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
08769        (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
08770       p->noncodeccapability |= AST_RTP_DTMF;
08771    }
08772    ast_string_field_set(p, context, sip_cfg.default_context);
08773    ast_string_field_set(p, parkinglot, default_parkinglot);
08774    ast_string_field_set(p, engine, default_engine);
08775 
08776    AST_LIST_HEAD_INIT_NOLOCK(&p->request_queue);
08777    AST_LIST_HEAD_INIT_NOLOCK(&p->offered_media);
08778 
08779    /* Add to active dialog list */
08780 
08781    ao2_t_link(dialogs, p, "link pvt into dialogs table");
08782 
08783    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");
08784    return p;
08785 }
08786 
08787 /*!
08788  * \brief Process the Via header according to RFC 3261 section 18.2.2.
08789  * \param p a sip_pvt structure that will be modified according to the received
08790  * header
08791  * \param req a sip request with a Via header to process
08792  *
08793  * This function will update the destination of the response according to the
08794  * Via header in the request and RFC 3261 section 18.2.2. We do not have a
08795  * transport layer so we ignore certain values like the 'received' param (we
08796  * set the destination address to the addres the request came from in the
08797  * respprep() function).
08798  *
08799  * \retval -1 error
08800  * \retval 0 success
08801  */
08802 static int process_via(struct sip_pvt *p, const struct sip_request *req)
08803 {
08804    struct sip_via *via = parse_via(sip_get_header(req, "Via"));
08805 
08806    if (!via) {
08807       ast_log(LOG_ERROR, "error processing via header\n");
08808       return -1;
08809    }
08810 
08811    if (via->maddr) {
08812       if (ast_sockaddr_resolve_first_transport(&p->sa, via->maddr, PARSE_PORT_FORBID, p->socket.type)) {
08813          ast_log(LOG_WARNING, "Can't find address for maddr '%s'\n", via->maddr);
08814          ast_log(LOG_ERROR, "error processing via header\n");
08815          free_via(via);
08816          return -1;
08817       }
08818 
08819       if (ast_sockaddr_is_ipv4_multicast(&p->sa)) {
08820          setsockopt(sipsock, IPPROTO_IP, IP_MULTICAST_TTL, &via->ttl, sizeof(via->ttl));
08821       }
08822    }
08823 
08824    ast_sockaddr_set_port(&p->sa, via->port ? via->port : STANDARD_SIP_PORT);
08825 
08826    free_via(via);
08827    return 0;
08828 }
08829 
08830 /* \brief arguments used for Request/Response to matching */
08831 struct match_req_args {
08832    int method;
08833    const char *callid;
08834    const char *totag;
08835    const char *fromtag;
08836    uint32_t seqno;
08837 
08838    /* Set if this method is a Response */
08839    int respid;
08840 
08841    /* Set if the method is a Request */
08842    const char *ruri;
08843    const char *viabranch;
08844    const char *viasentby;
08845 
08846    /* Set this if the Authentication header is present in the Request. */
08847    int authentication_present;
08848 };
08849 
08850 enum match_req_res {
08851    SIP_REQ_MATCH,
08852    SIP_REQ_NOT_MATCH,
08853    SIP_REQ_LOOP_DETECTED, /* multiple incoming requests with same call-id but different branch parameters have been detected */
08854    SIP_REQ_FORKED, /* An outgoing request has been forked as result of receiving two differing 200ok responses. */
08855 };
08856 
08857 /*
08858  * \brief Match a incoming Request/Response to a dialog
08859  *
08860  * \retval enum match_req_res indicating if the dialog matches the arg
08861  */
08862 static enum match_req_res match_req_to_dialog(struct sip_pvt *sip_pvt_ptr, struct match_req_args *arg)
08863 {
08864    const char *init_ruri = NULL;
08865    if (sip_pvt_ptr->initreq.headers) {
08866       init_ruri = REQ_OFFSET_TO_STR(&sip_pvt_ptr->initreq, rlpart2);
08867    }
08868 
08869    /*
08870     * Match Tags and call-id to Dialog
08871     */
08872    if (!ast_strlen_zero(arg->callid) && strcmp(sip_pvt_ptr->callid, arg->callid)) {
08873       /* call-id does not match. */
08874       return SIP_REQ_NOT_MATCH;
08875    }
08876    if (arg->method == SIP_RESPONSE) {
08877       /* Verify fromtag of response matches the tag we gave them. */
08878       if (strcmp(arg->fromtag, sip_pvt_ptr->tag)) {
08879          /* fromtag from response does not match our tag */
08880          return SIP_REQ_NOT_MATCH;
08881       }
08882 
08883       /* Verify totag if we have one stored for this dialog, but never be strict about this for
08884        * a response until the dialog is established */
08885       if (!ast_strlen_zero(sip_pvt_ptr->theirtag) && ast_test_flag(&sip_pvt_ptr->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
08886          if (ast_strlen_zero(arg->totag)) {
08887             /* missing totag when they already gave us one earlier */
08888             return SIP_REQ_NOT_MATCH;
08889          }
08890          /* compare the totag of response with the tag we have stored for them */
08891          if (strcmp(arg->totag, sip_pvt_ptr->theirtag)) {
08892             /* totag did not match what we had stored for them. */
08893             char invite_branch[32] = { 0, };
08894             if (sip_pvt_ptr->invite_branch) {
08895                snprintf(invite_branch, sizeof(invite_branch), "z9hG4bK%08x", (int) sip_pvt_ptr->invite_branch);
08896             }
08897             /* Forked Request Detection
08898              *
08899              * If this is a 200ok response and the totags do not match, this
08900              * might be a forked response to an outgoing Request. Detection of
08901              * a forked response must meet the criteria below.
08902              *
08903              * 1. must be a 2xx Response
08904              * 2. call-d equal to call-id of Request. this is done earlier
08905              * 3. from-tag equal to from-tag of Request. this is done earlier
08906              * 4. branch parameter equal to branch of inital Request
08907              * 5. to-tag _NOT_ equal to previous 2xx response that already established the dialog.
08908              */
08909             if ((arg->respid == 200) &&
08910                !ast_strlen_zero(invite_branch) &&
08911                !ast_strlen_zero(arg->viabranch) &&
08912                !strcmp(invite_branch, arg->viabranch)) {
08913                return SIP_REQ_FORKED;
08914             }
08915 
08916             /* The totag did not match the one we had stored, and this is not a Forked Request. */
08917             return SIP_REQ_NOT_MATCH;
08918          }
08919       }
08920    } else {
08921       /* Verify the fromtag of Request matches the tag they provided earlier.
08922        * If this is a Request with authentication credentials, forget their old
08923        * tag as it is not valid after the 401 or 407 response. */
08924       if (!arg->authentication_present && strcmp(arg->fromtag, sip_pvt_ptr->theirtag)) {
08925          /* their tag does not match the one was have stored for them */
08926          return SIP_REQ_NOT_MATCH;
08927       }
08928       /* Verify if totag is present in Request, that it matches what we gave them as our tag earlier */
08929       if (!ast_strlen_zero(arg->totag) && (strcmp(arg->totag, sip_pvt_ptr->tag))) {
08930          /* totag from Request does not match our tag */
08931          return SIP_REQ_NOT_MATCH;
08932       }
08933    }
08934 
08935    /*
08936     * Compare incoming request against initial transaction.
08937     * 
08938     * This is a best effort attempt at distinguishing forked requests from
08939     * our initial transaction.  If all the elements are NOT in place to evaluate
08940     * this, this block is ignored and the dialog match is made regardless.
08941     * Once the totag is established after the dialog is confirmed, this is not necessary.
08942     *
08943     * CRITERIA required for initial transaction matching.
08944     * 
08945     * 1. Is a Request
08946     * 2. Callid and theirtag match (this is done in the dialog matching block)
08947     * 3. totag is NOT present
08948     * 4. CSeq matchs our initial transaction's cseq number
08949     * 5. pvt has init via branch parameter stored
08950     */
08951    if ((arg->method != SIP_RESPONSE) &&                 /* must be a Request */
08952       ast_strlen_zero(arg->totag) &&                   /* must not have a totag */
08953       (sip_pvt_ptr->init_icseq == arg->seqno) &&       /* the cseq must be the same as this dialogs initial cseq */
08954       !ast_strlen_zero(sip_pvt_ptr->initviabranch) &&  /* The dialog must have started with a RFC3261 compliant branch tag */
08955       init_ruri) {                                     /* the dialog must have an initial request uri associated with it */
08956       /* This Request matches all the criteria required for Loop/Merge detection.
08957        * Now we must go down the path of comparing VIA's and RURIs. */
08958       if (ast_strlen_zero(arg->viabranch) ||
08959          strcmp(arg->viabranch, sip_pvt_ptr->initviabranch) ||
08960          ast_strlen_zero(arg->viasentby) ||
08961          strcmp(arg->viasentby, sip_pvt_ptr->initviasentby)) {
08962          /* At this point, this request does not match this Dialog.*/
08963 
08964          /* if methods are different this is just a mismatch */
08965          if ((sip_pvt_ptr->method != arg->method)) {
08966             return SIP_REQ_NOT_MATCH;
08967          }
08968 
08969          /* If RUIs are different, this is a forked request to a separate URI.
08970           * Returning a mismatch allows this Request to be processed separately. */
08971          if (sip_uri_cmp(init_ruri, arg->ruri)) {
08972             /* not a match, request uris are different */
08973             return SIP_REQ_NOT_MATCH;
08974          }
08975 
08976          /* Loop/Merge Detected
08977           *
08978           * ---Current Matches to Initial Request---
08979           * request uri
08980           * Call-id
08981           * their-tag
08982           * no totag present
08983           * method
08984           * cseq
08985           *
08986           * --- Does not Match Initial Request ---
08987           * Top Via
08988           *
08989           * Without the same Via, this can not match our initial transaction for this dialog,
08990           * but given that this Request matches everything else associated with that initial
08991           * Request this is most certainly a Forked request in which we have already received
08992           * part of the fork.
08993           */
08994          return SIP_REQ_LOOP_DETECTED;
08995       }
08996    } /* end of Request Via check */
08997 
08998    /* Match Authentication Request.
08999     *
09000     * A Request with an Authentication header must come back with the
09001     * same Request URI.  Otherwise it is not a match.
09002     */
09003    if ((arg->method != SIP_RESPONSE) &&      /* Must be a Request type to even begin checking this */
09004       ast_strlen_zero(arg->totag) &&        /* no totag is present to match */
09005       arg->authentication_present &&        /* Authentication header is present in Request */
09006       sip_uri_cmp(init_ruri, arg->ruri)) {  /* Compare the Request URI of both the last Request and this new one */
09007 
09008       /* Authentication was provided, but the Request URI did not match the last one on this dialog. */
09009       return SIP_REQ_NOT_MATCH;
09010    }
09011 
09012    return SIP_REQ_MATCH;
09013 }
09014 
09015 /*! \brief This function creates a dialog to handle a forked request.  This dialog
09016  * exists only to properly terminiate the the forked request immediately.
09017  */
09018 static void forked_invite_init(struct sip_request *req, const char *new_theirtag, struct sip_pvt *original, struct ast_sockaddr *addr)
09019 {
09020    struct sip_pvt *p;
09021    const char *callid;
09022    struct ast_callid *logger_callid;
09023 
09024    sip_pvt_lock(original);
09025    callid = ast_strdupa(original->callid);
09026    logger_callid = original->logger_callid;
09027    if (logger_callid) {
09028       ast_callid_ref(logger_callid);
09029    }
09030    sip_pvt_unlock(original);
09031 
09032    p = sip_alloc(callid, addr, 1, SIP_INVITE, req, logger_callid);
09033    if (logger_callid) {
09034       ast_callid_unref(logger_callid);
09035    }
09036    if (!p)  {
09037       return; /* alloc error */
09038    }
09039 
09040    /* Lock p and original private structures. */
09041    sip_pvt_lock(p);
09042    while (sip_pvt_trylock(original)) {
09043       /* Can't use DEADLOCK_AVOIDANCE since p is an ao2 object */
09044       sip_pvt_unlock(p);
09045       sched_yield();
09046       sip_pvt_lock(p);
09047    }
09048 
09049    p->invitestate = INV_TERMINATED;
09050    p->ocseq = original->ocseq;
09051    p->branch = original->branch;
09052 
09053    memcpy(&p->flags, &original->flags, sizeof(p->flags));
09054    copy_request(&p->initreq, &original->initreq);
09055    ast_string_field_set(p, theirtag, new_theirtag);
09056    ast_string_field_set(p, tag, original->tag);
09057    ast_string_field_set(p, uri, original->uri);
09058    ast_string_field_set(p, our_contact, original->our_contact);
09059    ast_string_field_set(p, fullcontact, original->fullcontact);
09060 
09061    sip_pvt_unlock(original);
09062 
09063    parse_ok_contact(p, req);
09064    build_route(p, req, 1, 0);
09065 
09066    transmit_request(p, SIP_ACK, p->ocseq, XMIT_UNRELIABLE, TRUE);
09067    transmit_request(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
09068 
09069    pvt_set_needdestroy(p, "forked request"); /* this dialog will terminate once the BYE is responed to or times out. */
09070    sip_pvt_unlock(p);
09071    dialog_unref(p, "setup forked invite termination");
09072 }
09073 
09074 /*! \internal
09075  *
09076  * \brief Locks both pvt and pvt owner if owner is present.
09077  *
09078  * \note This function gives a ref to pvt->owner if it is present and locked.
09079  *       This reference must be decremented after pvt->owner is unlocked.
09080  *
09081  * \note This function will never give you up,
09082  * \note This function will never let you down.
09083  * \note This function will run around and desert you.
09084  *
09085  * \pre pvt is not locked
09086  * \post pvt is locked
09087  * \post pvt->owner is locked and its reference count is increased (if pvt->owner is not NULL)
09088  *
09089  * \returns a pointer to the locked and reffed pvt->owner channel if it exists.
09090  */
09091 static struct ast_channel *sip_pvt_lock_full(struct sip_pvt *pvt)
09092 {
09093    struct ast_channel *chan;
09094 
09095    /* Locking is simple when it is done right.  If you see a deadlock resulting
09096     * in this function, it is not this function's fault, Your problem exists elsewhere.
09097     * This function is perfect... seriously. */
09098    for (;;) {
09099       /* First, get the channel and grab a reference to it */
09100       sip_pvt_lock(pvt);
09101       chan = pvt->owner;
09102       if (chan) {
09103          /* The channel can not go away while we hold the pvt lock.
09104           * Give the channel a ref so it will not go away after we let
09105           * the pvt lock go. */
09106          ast_channel_ref(chan);
09107       } else {
09108          /* no channel, return pvt locked */
09109          return NULL;
09110       }
09111 
09112       /* We had to hold the pvt lock while getting a ref to the owner channel
09113        * but now we have to let this lock go in order to preserve proper
09114        * locking order when grabbing the channel lock */
09115       sip_pvt_unlock(pvt);
09116 
09117       /* Look, no deadlock avoidance, hooray! */
09118       ast_channel_lock(chan);
09119       sip_pvt_lock(pvt);
09120 
09121       if (pvt->owner == chan) {
09122          /* done */
09123          break;
09124       }
09125 
09126       /* If the owner changed while everything was unlocked, no problem,
09127        * just start over and everthing will work.  This is rare, do not be
09128        * confused by this loop and think this it is an expensive operation.
09129        * The majority of the calls to this function will never involve multiple
09130        * executions of this loop. */
09131       ast_channel_unlock(chan);
09132       ast_channel_unref(chan);
09133       sip_pvt_unlock(pvt);
09134    }
09135 
09136    /* If owner exists, it is locked and reffed */
09137    return pvt->owner;
09138 }
09139 
09140 /*! \brief find or create a dialog structure for an incoming SIP message.
09141  * Connect incoming SIP message to current dialog or create new dialog structure
09142  * Returns a reference to the sip_pvt object, remember to give it back once done.
09143  *     Called by handle_request_do
09144  */
09145 static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method)
09146 {
09147    char totag[128];
09148    char fromtag[128];
09149    const char *callid = sip_get_header(req, "Call-ID");
09150    const char *from = sip_get_header(req, "From");
09151    const char *to = sip_get_header(req, "To");
09152    const char *cseq = sip_get_header(req, "Cseq");
09153    struct sip_pvt *sip_pvt_ptr;
09154    uint32_t seqno;
09155    /* Call-ID, to, from and Cseq are required by RFC 3261. (Max-forwards and via too - ignored now) */
09156    /* sip_get_header always returns non-NULL so we must use ast_strlen_zero() */
09157    if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
09158          ast_strlen_zero(from) || ast_strlen_zero(cseq) ||
09159          (sscanf(cseq, "%30u", &seqno) != 1)) {
09160 
09161       /* RFC 3261 section 24.4.1.   Send a 400 Bad Request if the request is malformed. */
09162       if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
09163          transmit_response_using_temp(callid, addr, 1, intended_method,
09164                        req, "400 Bad Request");
09165       }
09166       return NULL;   /* Invalid packet */
09167    }
09168 
09169    if (sip_cfg.pedanticsipchecking) {
09170       /* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
09171          we need more to identify a branch - so we have to check branch, from
09172          and to tags to identify a call leg.
09173          For Asterisk to behave correctly, you need to turn on pedanticsipchecking
09174          in sip.conf
09175          */
09176       if (gettag(req, "To", totag, sizeof(totag)))
09177          req->has_to_tag = 1; /* Used in handle_request/response */
09178       gettag(req, "From", fromtag, sizeof(fromtag));
09179 
09180       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);
09181 
09182       /* All messages must always have From: tag */
09183       if (ast_strlen_zero(fromtag)) {
09184          ast_debug(5, "%s request has no from tag, dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
09185          return NULL;
09186       }
09187       /* reject requests that must always have a To: tag */
09188       if (ast_strlen_zero(totag) && (req->method == SIP_ACK || req->method == SIP_BYE || req->method == SIP_INFO )) {
09189          if (req->method != SIP_ACK) {
09190             transmit_response_using_temp(callid, addr, 1, intended_method, req, "481 Call leg/transaction does not exist");
09191          }
09192          ast_debug(5, "%s must have a to tag. dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
09193          return NULL;
09194       }
09195    }
09196 
09197    if (!sip_cfg.pedanticsipchecking) {
09198       struct sip_pvt tmp_dialog = {
09199          .callid = callid,
09200       };
09201       sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find in dialogs");
09202       if (sip_pvt_ptr) {  /* well, if we don't find it-- what IS in there? */
09203          /* Found the call */
09204          return sip_pvt_ptr;
09205       }
09206    } else { /* in pedantic mode! -- do the fancy search */
09207       struct sip_pvt tmp_dialog = {
09208          .callid = callid,
09209       };
09210       /* if a Outbound forked Request is detected, this pvt will point
09211        * to the dialog the Request is forking off of. */
09212       struct sip_pvt *fork_pvt = NULL;
09213       struct match_req_args args = { 0, };
09214       int found;
09215       struct ao2_iterator *iterator = ao2_t_callback(dialogs,
09216          OBJ_POINTER | OBJ_MULTIPLE,
09217          dialog_find_multiple,
09218          &tmp_dialog,
09219          "pedantic ao2_find in dialogs");
09220       struct sip_via *via = NULL;
09221 
09222       args.method = req->method;
09223       args.callid = NULL; /* we already matched this. */
09224       args.totag = totag;
09225       args.fromtag = fromtag;
09226       args.seqno = seqno;
09227       /* get via header information. */
09228       args.ruri = REQ_OFFSET_TO_STR(req, rlpart2);
09229       via = parse_via(sip_get_header(req, "Via"));
09230       if (via) {
09231          args.viasentby = via->sent_by;
09232          args.viabranch = via->branch;
09233       }
09234       /* determine if this is a Request with authentication credentials. */
09235       if (!ast_strlen_zero(sip_get_header(req, "Authorization")) ||
09236          !ast_strlen_zero(sip_get_header(req, "Proxy-Authorization"))) {
09237          args.authentication_present = 1;
09238       }
09239       /* if it is a response, get the response code */
09240       if (req->method == SIP_RESPONSE) {
09241          const char* e = ast_skip_blanks(REQ_OFFSET_TO_STR(req, rlpart2));
09242          int respid;
09243          if (!ast_strlen_zero(e) && (sscanf(e, "%30d", &respid) == 1)) {
09244             args.respid = respid;
09245          }
09246       }
09247 
09248       /* Iterate a list of dialogs already matched by Call-id */
09249       while (iterator && (sip_pvt_ptr = ao2_iterator_next(iterator))) {
09250          sip_pvt_lock(sip_pvt_ptr);
09251          found = match_req_to_dialog(sip_pvt_ptr, &args);
09252          sip_pvt_unlock(sip_pvt_ptr);
09253 
09254          switch (found) {
09255          case SIP_REQ_MATCH:
09256             ao2_iterator_destroy(iterator);
09257             dialog_unref(fork_pvt, "unref fork_pvt");
09258             free_via(via);
09259             return sip_pvt_ptr; /* return pvt with ref */
09260          case SIP_REQ_LOOP_DETECTED:
09261             /* This is likely a forked Request that somehow resulted in us receiving multiple parts of the fork.
09262             * RFC 3261 section 8.2.2.2, Indicate that we want to merge requests by sending a 482 response. */
09263             transmit_response_using_temp(callid, addr, 1, intended_method, req, "482 (Loop Detected)");
09264             dialog_unref(sip_pvt_ptr, "pvt did not match incoming SIP msg, unref from search.");
09265             ao2_iterator_destroy(iterator);
09266             dialog_unref(fork_pvt, "unref fork_pvt");
09267             free_via(via);
09268             return NULL;
09269          case SIP_REQ_FORKED:
09270             dialog_unref(fork_pvt, "throwing way pvt to fork off of.");
09271             fork_pvt = dialog_ref(sip_pvt_ptr, "this pvt has a forked request, save this off to copy information into new dialog\n");
09272             /* fall through */
09273          case SIP_REQ_NOT_MATCH:
09274          default:
09275             dialog_unref(sip_pvt_ptr, "pvt did not match incoming SIP msg, unref from search");
09276             break;
09277          }
09278       }
09279       if (iterator) {
09280          ao2_iterator_destroy(iterator);
09281       }
09282 
09283       /* Handle any possible forked requests. This must be done only after transaction matching is complete. */
09284       if (fork_pvt) {
09285          /* XXX right now we only support handling forked INVITE Requests. Any other
09286           * forked request type must be added here. */
09287          if (fork_pvt->method == SIP_INVITE) {
09288             forked_invite_init(req, args.totag, fork_pvt, addr);
09289             dialog_unref(fork_pvt, "throwing way old forked pvt");
09290             free_via(via);
09291             return NULL;
09292          }
09293          fork_pvt = dialog_unref(fork_pvt, "throwing way pvt to fork off of");
09294       }
09295 
09296       free_via(via);
09297    } /* end of pedantic mode Request/Reponse to Dialog matching */
09298 
09299    /* See if the method is capable of creating a dialog */
09300    if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
09301       struct sip_pvt *p = NULL;
09302       struct ast_callid *logger_callid = NULL;
09303 
09304       if (intended_method == SIP_INVITE) {
09305          logger_callid = ast_create_callid();
09306       }
09307 
09308       /* Ok, time to create a new SIP dialog object, a pvt */
09309       if (!(p = sip_alloc(callid, addr, 1, intended_method, req, logger_callid)))  {
09310          /* We have a memory or file/socket error (can't allocate RTP sockets or something) so we're not
09311             getting a dialog from sip_alloc.
09312 
09313             Without a dialog we can't retransmit and handle ACKs and all that, but at least
09314             send an error message.
09315 
09316             Sorry, we apologize for the inconvienience
09317          */
09318          transmit_response_using_temp(callid, addr, 1, intended_method, req, "500 Server internal error");
09319          ast_debug(4, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
09320       }
09321       /* If we created an ast_callid for an invite, we need to free it now. */
09322       if (logger_callid) {
09323          ast_callid_unref(logger_callid);
09324       }
09325       return p; /* can be NULL */
09326    } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
09327       /* A method we do not support, let's take it on the volley */
09328       transmit_response_using_temp(callid, addr, 1, intended_method, req, "501 Method Not Implemented");
09329       ast_debug(2, "Got a request with unsupported SIP method.\n");
09330    } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
09331       /* This is a request outside of a dialog that we don't know about */
09332       transmit_response_using_temp(callid, addr, 1, intended_method, req, "481 Call leg/transaction does not exist");
09333       ast_debug(2, "That's odd...  Got a request in unknown dialog. Callid %s\n", callid ? callid : "<unknown>");
09334    }
09335    /* We do not respond to responses for dialogs that we don't know about, we just drop
09336       the session quickly */
09337    if (intended_method == SIP_RESPONSE)
09338       ast_debug(2, "That's odd...  Got a response on a call we don't know about. Callid %s\n", callid ? callid : "<unknown>");
09339 
09340    return NULL;
09341 }
09342 
09343 /*! \brief create sip_registry object from register=> line in sip.conf and link into reg container */
09344 static int sip_register(const char *value, int lineno)
09345 {
09346    struct sip_registry *reg, *tmp;
09347 
09348    if (!(reg = ast_calloc_with_stringfields(1, struct sip_registry, 256))) {
09349       ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
09350       return -1;
09351    }
09352 
09353    ASTOBJ_INIT(reg);
09354 
09355    ast_copy_string(reg->name, value, sizeof(reg->name));
09356    if (sip_parse_register_line(reg, default_expiry, value, lineno)) {
09357       registry_unref(reg, "failure to parse, unref the reg pointer");
09358       return -1;
09359    }
09360 
09361    /* set default expiry if necessary */
09362    if (reg->refresh && !reg->expiry && !reg->configured_expiry) {
09363       reg->refresh = reg->expiry = reg->configured_expiry = default_expiry;
09364    }
09365 
09366    /* Add the new registry entry to the list, but only if it isn't already there */
09367    if ((tmp = ASTOBJ_CONTAINER_FIND(&regl, reg->name))) {
09368       registry_unref(tmp, "throw away found registry");
09369    } else {
09370       ast_atomic_fetchadd_int(&regobjs, 1);
09371       ASTOBJ_CONTAINER_LINK(&regl, reg);
09372    }
09373 
09374    /* release the reference given by ASTOBJ_INIT. The container has another reference */
09375    registry_unref(reg, "unref the reg pointer");
09376 
09377    return 0;
09378 }
09379 
09380 /*! \brief Parse mwi=> line in sip.conf and add to list */
09381 static int sip_subscribe_mwi(const char *value, int lineno)
09382 {
09383    struct sip_subscription_mwi *mwi;
09384    int portnum = 0;
09385    enum sip_transport transport = SIP_TRANSPORT_UDP;
09386    char buf[256] = "";
09387    char *username = NULL, *hostname = NULL, *secret = NULL, *authuser = NULL, *porta = NULL, *mailbox = NULL;
09388 
09389    if (!value) {
09390       return -1;
09391    }
09392 
09393    ast_copy_string(buf, value, sizeof(buf));
09394 
09395    username = buf;
09396 
09397    if ((hostname = strrchr(buf, '@'))) {
09398       *hostname++ = '\0';
09399    } else {
09400       return -1;
09401    }
09402 
09403    if ((secret = strchr(username, ':'))) {
09404       *secret++ = '\0';
09405       if ((authuser = strchr(secret, ':'))) {
09406          *authuser++ = '\0';
09407       }
09408    }
09409 
09410    if ((mailbox = strchr(hostname, '/'))) {
09411       *mailbox++ = '\0';
09412    }
09413 
09414    if (ast_strlen_zero(username) || ast_strlen_zero(hostname) || ast_strlen_zero(mailbox)) {
09415       ast_log(LOG_WARNING, "Format for MWI subscription is user[:secret[:authuser]]@host[:port]/mailbox at line %d\n", lineno);
09416       return -1;
09417    }
09418 
09419    if ((porta = strchr(hostname, ':'))) {
09420       *porta++ = '\0';
09421       if (!(portnum = atoi(porta))) {
09422          ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
09423          return -1;
09424       }
09425    }
09426 
09427    if (!(mwi = ast_calloc_with_stringfields(1, struct sip_subscription_mwi, 256))) {
09428       return -1;
09429    }
09430 
09431    ASTOBJ_INIT(mwi);
09432    ast_string_field_set(mwi, username, username);
09433    if (secret) {
09434       ast_string_field_set(mwi, secret, secret);
09435    }
09436    if (authuser) {
09437       ast_string_field_set(mwi, authuser, authuser);
09438    }
09439    ast_string_field_set(mwi, hostname, hostname);
09440    ast_string_field_set(mwi, mailbox, mailbox);
09441    mwi->resub = -1;
09442    mwi->portno = portnum;
09443    mwi->transport = transport;
09444 
09445    ASTOBJ_CONTAINER_LINK(&submwil, mwi);
09446    ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
09447 
09448    return 0;
09449 }
09450 
09451 static void mark_method_allowed(unsigned int *allowed_methods, enum sipmethod method)
09452 {
09453    (*allowed_methods) |= (1 << method);
09454 }
09455 
09456 static void mark_method_unallowed(unsigned int *allowed_methods, enum sipmethod method)
09457 {
09458    (*allowed_methods) &= ~(1 << method);
09459 }
09460 
09461 /*! \brief Check if method is allowed for a device or a dialog */
09462 static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method)
09463 {
09464    return ((*allowed_methods) >> method) & 1;
09465 }
09466 
09467 static void mark_parsed_methods(unsigned int *methods, char *methods_str)
09468 {
09469    char *method;
09470    for (method = strsep(&methods_str, ","); !ast_strlen_zero(method); method = strsep(&methods_str, ",")) {
09471       int id = find_sip_method(ast_skip_blanks(method));
09472       if (id == SIP_UNKNOWN) {
09473          continue;
09474       }
09475       mark_method_allowed(methods, id);
09476    }
09477 }
09478 /*!
09479  * \brief parse the Allow header to see what methods the endpoint we
09480  * are communicating with allows.
09481  *
09482  * We parse the allow header on incoming Registrations and save the
09483  * result to the SIP peer that is registering. When the registration
09484  * expires, we clear what we know about the peer's allowed methods.
09485  * When the peer re-registers, we once again parse to see if the
09486  * list of allowed methods has changed.
09487  *
09488  * For peers that do not register, we parse the first message we receive
09489  * during a call to see what is allowed, and save the information
09490  * for the duration of the call.
09491  * \param req The SIP request we are parsing
09492  * \retval The methods allowed
09493  */
09494 static unsigned int parse_allowed_methods(struct sip_request *req)
09495 {
09496    char *allow = ast_strdupa(sip_get_header(req, "Allow"));
09497    unsigned int allowed_methods = SIP_UNKNOWN;
09498 
09499    if (ast_strlen_zero(allow)) {
09500       /* I have witnessed that REGISTER requests from Polycom phones do not
09501        * place the phone's allowed methods in an Allow header. Instead, they place the
09502        * allowed methods in a methods= parameter in the Contact header.
09503        */
09504       char *contact = ast_strdupa(sip_get_header(req, "Contact"));
09505       char *methods = strstr(contact, ";methods=");
09506 
09507       if (ast_strlen_zero(methods)) {
09508          /* RFC 3261 states:
09509           *
09510           * "The absence of an Allow header field MUST NOT be
09511           * interpreted to mean that the UA sending the message supports no
09512           * methods.   Rather, it implies that the UA is not providing any
09513           * information on what methods it supports."
09514           *
09515           * For simplicity, we'll assume that the peer allows all known
09516           * SIP methods if they have no Allow header. We can then clear out the necessary
09517           * bits if the peer lets us know that we have sent an unsupported method.
09518           */
09519          return UINT_MAX;
09520       }
09521       allow = ast_strip_quoted(methods + 9, "\"", "\"");
09522    }
09523    mark_parsed_methods(&allowed_methods, allow);
09524    return allowed_methods;
09525 }
09526 
09527 /*! A wrapper for parse_allowed_methods geared toward sip_pvts
09528  *
09529  * This function, in addition to setting the allowed methods for a sip_pvt
09530  * also will take into account the setting of the SIP_PAGE2_RPID_UPDATE flag.
09531  *
09532  * \param pvt The sip_pvt we are setting the allowed_methods for
09533  * \param req The request which we are parsing
09534  * \retval The methods alloweded by the sip_pvt
09535  */
09536 static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req)
09537 {
09538    pvt->allowed_methods = parse_allowed_methods(req);
09539    
09540    if (ast_test_flag(&pvt->flags[1], SIP_PAGE2_RPID_UPDATE)) {
09541       mark_method_allowed(&pvt->allowed_methods, SIP_UPDATE);
09542    }
09543    pvt->allowed_methods &= ~(pvt->disallowed_methods);
09544 
09545    return pvt->allowed_methods;
09546 }
09547 
09548 /*! \brief  Parse multiline SIP headers into one header
09549    This is enabled if pedanticsipchecking is enabled */
09550 static void lws2sws(struct ast_str *data)
09551 {
09552    char *msgbuf = data->str;
09553    int len = ast_str_strlen(data);
09554    int h = 0, t = 0;
09555    int lws = 0;
09556 
09557    for (; h < len;) {
09558       /* Eliminate all CRs */
09559       if (msgbuf[h] == '\r') {
09560          h++;
09561          continue;
09562       }
09563       /* Check for end-of-line */
09564       if (msgbuf[h] == '\n') {
09565          /* Check for end-of-message */
09566          if (h + 1 == len)
09567             break;
09568          /* Check for a continuation line */
09569          if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
09570             /* Merge continuation line */
09571             h++;
09572             continue;
09573          }
09574          /* Propagate LF and start new line */
09575          msgbuf[t++] = msgbuf[h++];
09576          lws = 0;
09577          continue;
09578       }
09579       if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
09580          if (lws) {
09581             h++;
09582             continue;
09583          }
09584          msgbuf[t++] = msgbuf[h++];
09585          lws = 1;
09586          continue;
09587       }
09588       msgbuf[t++] = msgbuf[h++];
09589       if (lws)
09590          lws = 0;
09591    }
09592    msgbuf[t] = '\0';
09593    data->used = t;
09594 }
09595 
09596 /*! \brief Parse a SIP message
09597    \note this function is used both on incoming and outgoing packets
09598 */
09599 static int parse_request(struct sip_request *req)
09600 {
09601    char *c = req->data->str;
09602    ptrdiff_t *dst = req->header;
09603    int i = 0, lim = SIP_MAX_HEADERS - 1;
09604    unsigned int skipping_headers = 0;
09605    ptrdiff_t current_header_offset = 0;
09606    char *previous_header = "";
09607 
09608    req->header[0] = 0;
09609    req->headers = -1;   /* mark that we are working on the header */
09610    for (; *c; c++) {
09611       if (*c == '\r') {    /* remove \r */
09612          *c = '\0';
09613       } else if (*c == '\n') {   /* end of this line */
09614          *c = '\0';
09615          current_header_offset = (c + 1) - ast_str_buffer(req->data);
09616          previous_header = ast_str_buffer(req->data) + dst[i];
09617          if (skipping_headers) {
09618             /* check to see if this line is blank; if so, turn off
09619                the skipping flag, so the next line will be processed
09620                as a body line */
09621             if (ast_strlen_zero(previous_header)) {
09622                skipping_headers = 0;
09623             }
09624             dst[i] = current_header_offset; /* record start of next line */
09625             continue;
09626          }
09627          if (sipdebug) {
09628             ast_debug(4, "%7s %2d [%3d]: %s\n",
09629                  req->headers < 0 ? "Header" : "Body",
09630                  i, (int) strlen(previous_header), previous_header);
09631          }
09632          if (ast_strlen_zero(previous_header) && req->headers < 0) {
09633             req->headers = i; /* record number of header lines */
09634             dst = req->line;  /* start working on the body */
09635             i = 0;
09636             lim = SIP_MAX_LINES - 1;
09637          } else { /* move to next line, check for overflows */
09638             if (i++ == lim) {
09639                /* if we're processing headers, then skip any remaining
09640                   headers and move on to processing the body, otherwise
09641                   we're done */
09642                if (req->headers != -1) {
09643                   break;
09644                } else {
09645                   req->headers = i;
09646                   dst = req->line;
09647                   i = 0;
09648                   lim = SIP_MAX_LINES - 1;
09649                   skipping_headers = 1;
09650                }
09651             }
09652          }
09653          dst[i] = current_header_offset; /* record start of next line */
09654       }
09655    }
09656 
09657    /* Check for last header or body line without CRLF. The RFC for SDP requires CRLF,
09658       but since some devices send without, we'll be generous in what we accept. However,
09659       if we've already reached the maximum number of lines for portion of the message
09660       we were parsing, we can't accept any more, so just ignore it.
09661    */
09662    previous_header = ast_str_buffer(req->data) + dst[i];
09663    if ((i < lim) && !ast_strlen_zero(previous_header)) {
09664       if (sipdebug) {
09665          ast_debug(4, "%7s %2d [%3d]: %s\n",
09666               req->headers < 0 ? "Header" : "Body",
09667               i, (int) strlen(previous_header), previous_header );
09668       }
09669       i++;
09670    }
09671 
09672    /* update count of header or body lines */
09673    if (req->headers >= 0) {   /* we are in the body */
09674       req->lines = i;
09675    } else {       /* no body */
09676       req->headers = i;
09677       req->lines = 0;
09678       /* req->data->used will be a NULL byte */
09679       req->line[0] = ast_str_strlen(req->data);
09680    }
09681 
09682    if (*c) {
09683       ast_log(LOG_WARNING, "Too many lines, skipping <%s>\n", c);
09684    }
09685 
09686    /* Split up the first line parts */
09687    return determine_firstline_parts(req);
09688 }
09689 
09690 /*!
09691   \brief Determine whether a SIP message contains an SDP in its body
09692   \param req the SIP request to process
09693   \return 1 if SDP found, 0 if not found
09694 
09695   Also updates req->sdp_start and req->sdp_count to indicate where the SDP
09696   lives in the message body.
09697 */
09698 static int find_sdp(struct sip_request *req)
09699 {
09700    const char *content_type;
09701    const char *content_length;
09702    const char *search;
09703    char *boundary;
09704    unsigned int x;
09705    int boundaryisquoted = FALSE;
09706    int found_application_sdp = FALSE;
09707    int found_end_of_headers = FALSE;
09708 
09709    content_length = sip_get_header(req, "Content-Length");
09710 
09711    if (!ast_strlen_zero(content_length)) {
09712       if (sscanf(content_length, "%30u", &x) != 1) {
09713          ast_log(LOG_WARNING, "Invalid Content-Length: %s\n", content_length);
09714          return 0;
09715       }
09716 
09717       /* Content-Length of zero means there can't possibly be an
09718          SDP here, even if the Content-Type says there is */
09719       if (x == 0)
09720          return 0;
09721    }
09722 
09723    content_type = sip_get_header(req, "Content-Type");
09724 
09725    /* if the body contains only SDP, this is easy */
09726    if (!strncasecmp(content_type, "application/sdp", 15)) {
09727       req->sdp_start = 0;
09728       req->sdp_count = req->lines;
09729       return req->lines ? 1 : 0;
09730    }
09731 
09732    /* if it's not multipart/mixed, there cannot be an SDP */
09733    if (strncasecmp(content_type, "multipart/mixed", 15))
09734       return 0;
09735 
09736    /* if there is no boundary marker, it's invalid */
09737    if ((search = strcasestr(content_type, ";boundary=")))
09738       search += 10;
09739    else if ((search = strcasestr(content_type, "; boundary=")))
09740       search += 11;
09741    else
09742       return 0;
09743 
09744    if (ast_strlen_zero(search))
09745       return 0;
09746 
09747    /* If the boundary is quoted with ", remove quote */
09748    if (*search == '\"')  {
09749       search++;
09750       boundaryisquoted = TRUE;
09751    }
09752 
09753    /* make a duplicate of the string, with two extra characters
09754       at the beginning */
09755    boundary = ast_strdupa(search - 2);
09756    boundary[0] = boundary[1] = '-';
09757    /* Remove final quote */
09758    if (boundaryisquoted)
09759       boundary[strlen(boundary) - 1] = '\0';
09760 
09761    /* search for the boundary marker, the empty line delimiting headers from
09762       sdp part and the end boundry if it exists */
09763 
09764    for (x = 0; x < (req->lines); x++) {
09765       const char *line = REQ_OFFSET_TO_STR(req, line[x]);
09766       if (!strncasecmp(line, boundary, strlen(boundary))){
09767          if (found_application_sdp && found_end_of_headers) {
09768             req->sdp_count = (x - 1) - req->sdp_start;
09769             return 1;
09770          }
09771          found_application_sdp = FALSE;
09772       }
09773       if (!strcasecmp(line, "Content-Type: application/sdp"))
09774          found_application_sdp = TRUE;
09775       
09776       if (ast_strlen_zero(line)) {
09777          if (found_application_sdp && !found_end_of_headers){
09778             req->sdp_start = x;
09779             found_end_of_headers = TRUE;
09780          }
09781       }
09782    }
09783    if (found_application_sdp && found_end_of_headers) {
09784       req->sdp_count = x - req->sdp_start;
09785       return TRUE;
09786    }
09787    return FALSE;
09788 }
09789 
09790 /*! \brief Change hold state for a call */
09791 static void change_hold_state(struct sip_pvt *dialog, struct sip_request *req, int holdstate, int sendonly)
09792 {
09793    if (sip_cfg.notifyhold && (!holdstate || !ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD)))
09794       sip_peer_hold(dialog, holdstate);
09795    if (sip_cfg.callevents)
09796       manager_event(EVENT_FLAG_CALL, "Hold",
09797                "Status: %s\r\n"
09798                "Channel: %s\r\n"
09799                "Uniqueid: %s\r\n",
09800                holdstate ? "On" : "Off",
09801                ast_channel_name(dialog->owner),
09802                ast_channel_uniqueid(dialog->owner));
09803    append_history(dialog, holdstate ? "Hold" : "Unhold", "%s", ast_str_buffer(req->data));
09804    if (!holdstate) { /* Put off remote hold */
09805       ast_clear_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD);   /* Clear both flags */
09806       return;
09807    }
09808    /* No address for RTP, we're on hold */
09809 
09810    /* Ensure hold flags are cleared so that overlapping flags do not conflict */
09811    ast_clear_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD);
09812 
09813    if (sendonly == 1)   /* One directional hold (sendonly/recvonly) */
09814       ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
09815    else if (sendonly == 2) /* Inactive stream */
09816       ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
09817    else
09818       ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
09819    return;
09820 }
09821 
09822 
09823 static int get_ip_and_port_from_sdp(struct sip_request *req, const enum media_type media, struct ast_sockaddr *addr)
09824 {
09825    const char *m;
09826    const char *c;
09827    int miterator = req->sdp_start;
09828    int citerator = req->sdp_start;
09829    int x = 0;
09830    int numberofports;
09831    int len;
09832    int af;
09833    char proto[4], host[258] = ""; /*Initialize to empty so we will know if we have any input */
09834 
09835    c = get_sdp_iterate(&citerator, req, "c");
09836    if (sscanf(c, "IN %3s %256s", proto, host) != 2) {
09837          ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
09838          /* Continue since there may be a valid host in a c= line specific to the audio stream */
09839    }
09840    /* We only want the m and c lines for audio */
09841    for (m = get_sdp_iterate(&miterator, req, "m"); !ast_strlen_zero(m); m = get_sdp_iterate(&miterator, req, "m")) {
09842       if ((media == SDP_AUDIO && ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
09843           (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0))) ||
09844          (media == SDP_VIDEO && ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
09845           (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len > 0)))) {
09846          /* See if there's a c= line for this media stream.
09847           * XXX There is no guarantee that we'll be grabbing the c= line for this
09848           * particular media stream here. However, this is the same logic used in process_sdp.
09849           */
09850          c = get_sdp_iterate(&citerator, req, "c");
09851          if (!ast_strlen_zero(c)) {
09852             sscanf(c, "IN %3s %256s", proto, host);
09853          }
09854          break;
09855       }
09856    }
09857 
09858    if (!strcmp("IP4", proto)) {
09859       af = AF_INET;
09860    } else if (!strcmp("IP6", proto)) {
09861       af = AF_INET6;
09862    } else {
09863       ast_log(LOG_WARNING, "Unknown protocol '%s'.\n", proto);
09864       return -1;
09865    }
09866 
09867    if (ast_strlen_zero(host) || x == 0) {
09868       ast_log(LOG_WARNING, "Failed to read an alternate host or port in SDP. Expect %s problems\n", media == SDP_AUDIO ? "audio" : "video");
09869       return -1;
09870    }
09871 
09872    if (ast_sockaddr_resolve_first_af(addr, host, 0, af)) {
09873       ast_log(LOG_WARNING, "Could not look up IP address of alternate hostname. Expect %s problems\n", media == SDP_AUDIO? "audio" : "video");
09874       return -1;
09875    }
09876 
09877    return 0;
09878 }
09879 
09880 /*! \internal
09881  * \brief Returns whether or not the address is null or ANY / unspecified (0.0.0.0 or ::)
09882  * \retval TRUE if the address is null or any
09883  * \retval FALSE if the address it not null or any
09884  * \note In some circumstances, calls should be placed on hold if either of these conditions exist.
09885  */
09886 static int sockaddr_is_null_or_any(const struct ast_sockaddr *addr)
09887 {
09888    return ast_sockaddr_isnull(addr) || ast_sockaddr_is_any(addr);
09889 }
09890 
09891 /*! \brief Check the media stream list to see if the given type already exists */
09892 static int has_media_stream(struct sip_pvt *p, enum media_type m)
09893 {
09894    struct offered_media *offer = NULL;
09895    AST_LIST_TRAVERSE(&p->offered_media, offer, next) {
09896       if (m == offer->type) {
09897          return 1;
09898       }
09899    }
09900    return 0;
09901 }
09902 
09903 /*! \brief Process SIP SDP offer, select formats and activate media channels
09904    If offer is rejected, we will not change any properties of the call
09905    Return 0 on success, a negative value on errors.
09906    Must be called after find_sdp().
09907 */
09908 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
09909 {
09910    int res = 0;
09911 
09912    /* Iterators for SDP parsing */
09913    int start = req->sdp_start;
09914    int next = start;
09915    int iterator = start;
09916 
09917    /* Temporary vars for SDP parsing */
09918    char type = '\0';
09919    const char *value = NULL;
09920    const char *m = NULL;           /* SDP media offer */
09921    const char *nextm = NULL;
09922    int len = -1;
09923    struct offered_media *offer;
09924 
09925    /* Host information */
09926    struct ast_sockaddr sessionsa;
09927    struct ast_sockaddr audiosa;
09928    struct ast_sockaddr videosa;
09929    struct ast_sockaddr textsa;
09930    struct ast_sockaddr imagesa;
09931    struct ast_sockaddr *sa = NULL;     /*!< RTP audio destination IP address */
09932    struct ast_sockaddr *vsa = NULL; /*!< RTP video destination IP address */
09933    struct ast_sockaddr *tsa = NULL; /*!< RTP text destination IP address */
09934    struct ast_sockaddr *isa = NULL; /*!< UDPTL image destination IP address */
09935    int portno = -1;        /*!< RTP audio destination port number */
09936    int vportno = -1;       /*!< RTP video destination port number */
09937    int tportno = -1;       /*!< RTP text destination port number */
09938    int udptlportno = -1;         /*!< UDPTL image destination port number */
09939 
09940    /* Peer capability is the capability in the SDP, non codec is RFC2833 DTMF (101) */
09941    struct ast_format_cap *peercapability = ast_format_cap_alloc_nolock();
09942    struct ast_format_cap *vpeercapability = ast_format_cap_alloc_nolock();
09943    struct ast_format_cap *tpeercapability = ast_format_cap_alloc_nolock();
09944 
09945    int peernoncodeccapability = 0, vpeernoncodeccapability = 0, tpeernoncodeccapability = 0;
09946 
09947    struct ast_rtp_codecs newaudiortp = { 0, }, newvideortp = { 0, }, newtextrtp = { 0, };
09948    struct ast_format_cap *newjointcapability = ast_format_cap_alloc_nolock(); /* Negotiated capability */
09949    struct ast_format_cap *newpeercapability = ast_format_cap_alloc_nolock();
09950    int newnoncodeccapability;
09951 
09952    const char *codecs;
09953    int codec;
09954 
09955    /* SRTP */
09956    int secure_audio = FALSE;
09957    int secure_video = FALSE;
09958 
09959    /* Others */
09960    int sendonly = -1;
09961    int numberofports;
09962    int last_rtpmap_codec = 0;
09963    int red_data_pt[10];    /* For T.140 RED */
09964    int red_num_gen = 0;    /* For T.140 RED */
09965    char red_fmtp[100] = "empty"; /* For T.140 RED */
09966    int debug = sip_debug_test_pvt(p);
09967 
09968    /* START UNKNOWN */
09969    char buf[SIPBUFSIZE];
09970    struct ast_format tmp_fmt;
09971    /* END UNKNOWN */
09972 
09973    /* Initial check */
09974    if (!p->rtp) {
09975       ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
09976       res = -1;
09977       goto process_sdp_cleanup;
09978    }
09979    if (!peercapability || !vpeercapability || !tpeercapability || !newpeercapability || !newjointcapability) {
09980       res = -1;
09981       goto process_sdp_cleanup;
09982    }
09983 
09984    if (ast_rtp_codecs_payloads_initialize(&newaudiortp) || ast_rtp_codecs_payloads_initialize(&newvideortp) ||
09985        ast_rtp_codecs_payloads_initialize(&newtextrtp)) {
09986       res = -1;
09987       goto process_sdp_cleanup;
09988    }
09989 
09990    /* Update our last rtprx when we receive an SDP, too */
09991    p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
09992 
09993    offered_media_list_destroy(p);
09994 
09995    /* Scan for the first media stream (m=) line to limit scanning of globals */
09996    nextm = get_sdp_iterate(&next, req, "m");
09997    if (ast_strlen_zero(nextm)) {
09998       ast_log(LOG_WARNING, "Insufficient information for SDP (m= not found)\n");
09999       res = -1;
10000       goto process_sdp_cleanup;
10001    }
10002 
10003    /* Scan session level SDP parameters (lines before first media stream) */
10004    while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
10005       int processed = FALSE;
10006       switch (type) {
10007       case 'o':
10008          /* If we end up receiving SDP that doesn't actually modify the session we don't want to treat this as a fatal
10009           * error. We just want to ignore the SDP and let the rest of the packet be handled as normal.
10010           */
10011          if (!process_sdp_o(value, p)) {
10012             res = (p->session_modify == FALSE) ? 0 : -1;
10013             goto process_sdp_cleanup;
10014          }
10015          processed = TRUE;
10016          break;
10017       case 'c':
10018          if (process_sdp_c(value, &sessionsa)) {
10019             processed = TRUE;
10020             sa = &sessionsa;
10021             vsa = sa;
10022             tsa = sa;
10023             isa = sa;
10024          }
10025          break;
10026       case 'a':
10027          if (process_sdp_a_sendonly(value, &sendonly)) {
10028             processed = TRUE;
10029          }
10030          else if (process_sdp_a_audio(value, p, &newaudiortp, &last_rtpmap_codec))
10031             processed = TRUE;
10032          else if (process_sdp_a_video(value, p, &newvideortp, &last_rtpmap_codec))
10033             processed = TRUE;
10034          else if (process_sdp_a_text(value, p, &newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
10035             processed = TRUE;
10036          else if (process_sdp_a_image(value, p))
10037             processed = TRUE;
10038 
10039          if (process_sdp_a_ice(value, p, p->rtp)) {
10040             processed = TRUE;
10041          }
10042          if (process_sdp_a_ice(value, p, p->vrtp)) {
10043             processed = TRUE;
10044          }
10045          if (process_sdp_a_ice(value, p, p->trtp)) {
10046             processed = TRUE;
10047          }
10048 
10049          if (process_sdp_a_dtls(value, p, p->rtp)) {
10050             processed = TRUE;
10051          }
10052          if (process_sdp_a_dtls(value, p, p->vrtp)) {
10053             processed = TRUE;
10054          }
10055          if (process_sdp_a_dtls(value, p, p->trtp)) {
10056             processed = TRUE;
10057          }
10058 
10059          break;
10060       }
10061 
10062       ast_debug(3, "Processing session-level SDP %c=%s... %s\n", type, value, (processed == TRUE)? "OK." : "UNSUPPORTED OR FAILED.");
10063    }
10064 
10065    /* default: novideo and notext set */
10066    p->novideo = TRUE;
10067    p->notext = TRUE;
10068 
10069    /* Scan media stream (m=) specific parameters loop */
10070    while (!ast_strlen_zero(nextm)) {
10071       int audio = FALSE;
10072       int video = FALSE;
10073       int image = FALSE;
10074       int text = FALSE;
10075       int processed_crypto = FALSE;
10076       char protocol[18] = {0,};
10077       int x;
10078       struct ast_rtp_engine_dtls *dtls;
10079 
10080       numberofports = 0;
10081       len = -1;
10082       start = next;
10083       m = nextm;
10084       iterator = next;
10085       nextm = get_sdp_iterate(&next, req, "m");
10086 
10087       if (!(offer = ast_calloc(1, sizeof(*offer)))) {
10088          ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer list\n");
10089          res = -1;
10090          goto process_sdp_cleanup;
10091       }
10092       AST_LIST_INSERT_TAIL(&p->offered_media, offer, next);
10093       offer->type = SDP_UNKNOWN;
10094 
10095       /* Check for 'audio' media offer */
10096       if (strncmp(m, "audio ", 6) == 0) {
10097          if ((sscanf(m, "audio %30u/%30u %17s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||
10098              (sscanf(m, "audio %30u %17s %n", &x, protocol, &len) == 2 && len > 0)) {
10099             codecs = m + len;
10100             /* produce zero-port m-line since it may be needed later
10101              * length is "m=audio 0 " + protocol + " " + codecs + "\r\n\0" */
10102             if (!(offer->decline_m_line = ast_malloc(10 + strlen(protocol) + 1 + strlen(codecs) + 3))) {
10103                ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer declination\n");
10104                res = -1;
10105                goto process_sdp_cleanup;
10106             }
10107             /* guaranteed to be exactly the right length */
10108             sprintf(offer->decline_m_line, "m=audio 0 %s %s\r\n", protocol, codecs);
10109 
10110             if (x == 0) {
10111                ast_log(LOG_WARNING, "Ignoring audio media offer because port number is zero\n");
10112                continue;
10113             }
10114 
10115             if (has_media_stream(p, SDP_AUDIO)) {
10116                ast_log(LOG_WARNING, "Declining non-primary audio stream: %s\n", m);
10117                continue;
10118             }
10119 
10120             /* Check number of ports offered for stream */
10121             if (numberofports > 1) {
10122                ast_log(LOG_WARNING, "%d ports offered for audio media, not supported by Asterisk. Will try anyway...\n", numberofports);
10123             }
10124 
10125             if ((!strcmp(protocol, "RTP/SAVPF") || !strcmp(protocol, "UDP/TLS/RTP/SAVPF")) && !ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
10126                if (req->method != SIP_RESPONSE) {
10127                   ast_log(LOG_NOTICE, "Received SAVPF profle in audio offer but AVPF is not enabled, enabling: %s\n", m);
10128                   secure_audio = 1;
10129                   ast_set_flag(&p->flags[2], SIP_PAGE3_USE_AVPF);
10130                }
10131                else {
10132 
10133                   ast_log(LOG_WARNING, "Received SAVPF profle in audio answer but AVPF is not enabled: %s\n", m);
10134                   continue;
10135                }
10136             } else if ((!strcmp(protocol, "RTP/SAVP") || !strcmp(protocol, "UDP/TLS/RTP/SAVP")) && ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
10137                if (req->method != SIP_RESPONSE) {
10138                   ast_log(LOG_NOTICE, "Received SAVP profle in audio offer but AVPF is enabled, disabling: %s\n", m);
10139                   secure_audio = 1;
10140                   ast_clear_flag(&p->flags[2], SIP_PAGE3_USE_AVPF);
10141                }
10142                else {
10143                   ast_log(LOG_WARNING, "Received SAVP profile in audio offer but AVPF is enabled: %s\n", m);
10144                   continue;
10145                }
10146             } else if (!strcmp(protocol, "UDP/TLS/RTP/SAVP") || !strcmp(protocol, "UDP/TLS/RTP/SAVPF")) {
10147                secure_audio = 1;
10148 
10149                if (p->srtp) {
10150                   ast_set_flag(p->srtp, SRTP_CRYPTO_OFFER_OK);
10151                }
10152             } else if (!strcmp(protocol, "RTP/SAVP") || !strcmp(protocol, "RTP/SAVPF")) {
10153                secure_audio = 1;
10154             } else if (!strcmp(protocol, "RTP/AVPF") && !ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
10155                if (req->method != SIP_RESPONSE) {
10156                   ast_log(LOG_NOTICE, "Received AVPF profile in audio offer but AVPF is not enabled, enabling: %s\n", m);
10157                   ast_set_flag(&p->flags[2], SIP_PAGE3_USE_AVPF);
10158                }
10159                else {
10160                   ast_log(LOG_WARNING, "Received AVP profile in audio answer but AVPF is enabled: %s\n", m);
10161                   continue;
10162                }
10163             } else if (!strcmp(protocol, "RTP/AVP") && ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
10164                if (req->method != SIP_RESPONSE) {
10165                   ast_log(LOG_NOTICE, "Received AVP profile in audio answer but AVPF is enabled, disabling: %s\n", m);
10166                   ast_clear_flag(&p->flags[2], SIP_PAGE3_USE_AVPF);
10167                }
10168                else {
10169                   ast_log(LOG_WARNING, "Received AVP profile in audio answer but AVPF is enabled: %s\n", m);
10170                   continue;
10171                }
10172             } else if ((!strcmp(protocol, "UDP/TLS/RTP/SAVP") || !strcmp(protocol, "UDP/TLS/RTP/SAVPF")) &&
10173                   (!(dtls = ast_rtp_instance_get_dtls(p->rtp)) || !dtls->active(p->rtp))) {
10174                ast_log(LOG_WARNING, "Received UDP/TLS in audio offer but DTLS is not enabled: %s\n", m);
10175                continue;
10176             } else if (strcmp(protocol, "RTP/AVP") && strcmp(protocol, "RTP/AVPF")) {
10177                ast_log(LOG_WARNING, "Unknown RTP profile in audio offer: %s\n", m);
10178                continue;
10179             }
10180 
10181             audio = TRUE;
10182             offer->type = SDP_AUDIO;
10183             portno = x;
10184 
10185             /* Scan through the RTP payload types specified in a "m=" line: */
10186             for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
10187                if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
10188                   ast_log(LOG_WARNING, "Invalid syntax in RTP audio format list: %s\n", codecs);
10189                   res = -1;
10190                   goto process_sdp_cleanup;
10191                }
10192                if (debug) {
10193                   ast_verbose("Found RTP audio format %d\n", codec);
10194                }
10195 
10196                ast_rtp_codecs_payloads_set_m_type(&newaudiortp, NULL, codec);
10197             }
10198          } else {
10199             ast_log(LOG_WARNING, "Rejecting audio media offer due to invalid or unsupported syntax: %s\n", m);
10200             res = -1;
10201             goto process_sdp_cleanup;
10202          }
10203       }
10204       /* Check for 'video' media offer */
10205       else if (strncmp(m, "video ", 6) == 0) {
10206          if ((sscanf(m, "video %30u/%30u %17s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||
10207              (sscanf(m, "video %30u %17s %n", &x, protocol, &len) == 2 && len > 0)) {
10208             codecs = m + len;
10209             /* produce zero-port m-line since it may be needed later
10210              * length is "m=video 0 " + protocol + " " + codecs + "\r\n\0" */
10211             if (!(offer->decline_m_line = ast_malloc(10 + strlen(protocol) + 1 + strlen(codecs) + 3))) {
10212                ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer declination\n");
10213                res = -1;
10214                goto process_sdp_cleanup;
10215             }
10216             /* guaranteed to be exactly the right length */
10217             sprintf(offer->decline_m_line, "m=video 0 %s %s\r\n", protocol, codecs);
10218 
10219             if (x == 0) {
10220                ast_log(LOG_WARNING, "Ignoring video stream offer because port number is zero\n");
10221                continue;
10222             }
10223 
10224             /* Check number of ports offered for stream */
10225             if (numberofports > 1) {
10226                ast_log(LOG_WARNING, "%d ports offered for video stream, not supported by Asterisk. Will try anyway...\n", numberofports);
10227             }
10228 
10229             if (has_media_stream(p, SDP_VIDEO)) {
10230                ast_log(LOG_WARNING, "Declining non-primary video stream: %s\n", m);
10231                continue;
10232             }
10233 
10234             if ((!strcmp(protocol, "RTP/SAVPF") || !strcmp(protocol, "UDP/TLS/RTP/SAVPF")) && !ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
10235                ast_log(LOG_WARNING, "Received SAVPF profle in video offer but AVPF is not enabled: %s\n", m);
10236                continue;
10237             } else if ((!strcmp(protocol, "RTP/SAVP") || !strcmp(protocol, "UDP/TLS/RTP/SAVP")) && ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
10238                ast_log(LOG_WARNING, "Received SAVP profile in video offer but AVPF is enabled: %s\n", m);
10239                continue;
10240             } else if (!strcmp(protocol, "UDP/TLS/RTP/SAVP") || !strcmp(protocol, "UDP/TLS/RTP/SAVPF")) {
10241                secure_video = 1;
10242 
10243                if (p->vsrtp || (p->vsrtp = sip_srtp_alloc())) {
10244                   ast_set_flag(p->vsrtp, SRTP_CRYPTO_OFFER_OK);
10245                }
10246             } else if (!strcmp(protocol, "RTP/SAVP") || !strcmp(protocol, "RTP/SAVPF")) {
10247                secure_video = 1;
10248             } else if (!strcmp(protocol, "RTP/AVPF") && !ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
10249                ast_log(LOG_WARNING, "Received AVPF profile in video offer but AVPF is not enabled: %s\n", m);
10250                continue;
10251             } else if (!strcmp(protocol, "RTP/AVP") && ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
10252                ast_log(LOG_WARNING, "Received AVP profile in video offer but AVPF is enabled: %s\n", m);
10253                continue;
10254             } else if (strcmp(protocol, "RTP/AVP") && strcmp(protocol, "RTP/AVPF")) {
10255                ast_log(LOG_WARNING, "Unknown RTP profile in video offer: %s\n", m);
10256                continue;
10257             }
10258 
10259             video = TRUE;
10260             p->novideo = FALSE;
10261             offer->type = SDP_VIDEO;
10262             vportno = x;
10263 
10264             /* Scan through the RTP payload types specified in a "m=" line: */
10265             for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
10266                if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
10267                   ast_log(LOG_WARNING, "Invalid syntax in RTP video format list: %s\n", codecs);
10268                   res = -1;
10269                   goto process_sdp_cleanup;
10270                }
10271                if (debug) {
10272                   ast_verbose("Found RTP video format %d\n", codec);
10273                }
10274                ast_rtp_codecs_payloads_set_m_type(&newvideortp, NULL, codec);
10275             }
10276          } else {
10277             ast_log(LOG_WARNING, "Rejecting video media offer due to invalid or unsupported syntax: %s\n", m);
10278             res = -1;
10279             goto process_sdp_cleanup;
10280          }
10281       }
10282       /* Check for 'text' media offer */
10283       else if (strncmp(m, "text ", 5) == 0) {
10284          if ((sscanf(m, "text %30u/%30u %17s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||
10285              (sscanf(m, "text %30u %17s %n", &x, protocol, &len) == 2 && len > 0)) {
10286             codecs = m + len;
10287             /* produce zero-port m-line since it may be needed later
10288              * length is "m=text 0 " + protocol + " " + codecs + "\r\n\0" */
10289             if (!(offer->decline_m_line = ast_malloc(9 + strlen(protocol) + 1 + strlen(codecs) + 3))) {
10290                ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer declination\n");
10291                res = -1;
10292                goto process_sdp_cleanup;
10293             }
10294             /* guaranteed to be exactly the right length */
10295             sprintf(offer->decline_m_line, "m=text 0 %s %s\r\n", protocol, codecs);
10296 
10297             if (x == 0) {
10298                ast_log(LOG_WARNING, "Ignoring text stream offer because port number is zero\n");
10299                continue;
10300             }
10301 
10302             /* Check number of ports offered for stream */
10303             if (numberofports > 1) {
10304                ast_log(LOG_WARNING, "%d ports offered for text stream, not supported by Asterisk. Will try anyway...\n", numberofports);
10305             }
10306 
10307             if (!strcmp(protocol, "RTP/AVPF") && !ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
10308                ast_log(LOG_WARNING, "Received AVPF profile in text offer but AVPF is not enabled: %s\n", m);
10309                continue;
10310             } else if (!strcmp(protocol, "RTP/AVP") && ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
10311                ast_log(LOG_WARNING, "Received AVP profile in text offer but AVPF is enabled: %s\n", m);
10312                continue;
10313             } else if (strcmp(protocol, "RTP/AVP") && strcmp(protocol, "RTP/AVPF")) {
10314                ast_log(LOG_WARNING, "Unknown RTP profile in text offer: %s\n", m);
10315                continue;
10316             }
10317 
10318             if (has_media_stream(p, SDP_TEXT)) {
10319                ast_log(LOG_WARNING, "Declining non-primary text stream: %s\n", m);
10320                continue;
10321             }
10322 
10323             text = TRUE;
10324             p->notext = FALSE;
10325             offer->type = SDP_TEXT;
10326             tportno = x;
10327 
10328             /* Scan through the RTP payload types specified in a "m=" line: */
10329             for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
10330                if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
10331                   ast_log(LOG_WARNING, "Invalid syntax in RTP video format list: %s\n", codecs);
10332                   res = -1;
10333                   goto process_sdp_cleanup;
10334                }
10335                if (debug) {
10336                   ast_verbose("Found RTP text format %d\n", codec);
10337                }
10338                ast_rtp_codecs_payloads_set_m_type(&newtextrtp, NULL, codec);
10339             }
10340          } else {
10341             ast_log(LOG_WARNING, "Rejecting text stream offer due to invalid or unsupported syntax: %s\n", m);
10342             res = -1;
10343             goto process_sdp_cleanup;
10344          }
10345       }
10346       /* Check for 'image' media offer */
10347       else if (strncmp(m, "image ", 6) == 0) {
10348          if (((sscanf(m, "image %30u udptl t38%n", &x, &len) == 1 && len > 0) ||
10349               (sscanf(m, "image %30u UDPTL t38%n", &x, &len) == 1 && len > 0))) {
10350             /* produce zero-port m-line since it may be needed later
10351              * length is "m=image 0 udptl t38" + "\r\n\0" */
10352             if (!(offer->decline_m_line = ast_malloc(22))) {
10353                ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer declination\n");
10354                res = -1;
10355                goto process_sdp_cleanup;
10356             }
10357             /* guaranteed to be exactly the right length */
10358             strcpy(offer->decline_m_line, "m=image 0 udptl t38\r\n");
10359 
10360             if (x == 0) {
10361                ast_log(LOG_WARNING, "Ignoring image stream offer because port number is zero\n");
10362                continue;
10363             }
10364 
10365             if (initialize_udptl(p)) {
10366                ast_log(LOG_WARNING, "Failed to initialize UDPTL, declining image stream\n");
10367                continue;
10368             }
10369 
10370             if (has_media_stream(p, SDP_IMAGE)) {
10371                ast_log(LOG_WARNING, "Declining non-primary image stream: %s\n", m);
10372                continue;
10373             }
10374 
10375             image = TRUE;
10376             if (debug) {
10377                ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
10378             }
10379 
10380             offer->type = SDP_IMAGE;
10381             udptlportno = x;
10382 
10383             if (p->t38.state != T38_ENABLED) {
10384                memset(&p->t38.their_parms, 0, sizeof(p->t38.their_parms));
10385 
10386                /* default EC to none, the remote end should
10387                 * respond with the EC they want to use */
10388                ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
10389             }
10390          } else if (sscanf(m, "image %30u %17s t38%n", &x, protocol, &len) == 2 && len > 0) {
10391             ast_log(LOG_WARNING, "Declining image stream due to unsupported transport: %s\n", m);
10392             /* produce zero-port m-line since this is guaranteed to be declined
10393              * length is "m=image 0 strlen(protocol) t38" + "\r\n\0" */
10394             if (!(offer->decline_m_line = ast_malloc(10 + strlen(protocol) + 7))) {
10395                ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer declination\n");
10396                res = -1;
10397                goto process_sdp_cleanup;
10398             }
10399             /* guaranteed to be exactly the right length */
10400             sprintf(offer->decline_m_line, "m=image 0 %s t38\r\n", protocol);
10401             continue;
10402          } else {
10403             ast_log(LOG_WARNING, "Rejecting image media offer due to invalid or unsupported syntax: %s\n", m);
10404             res = -1;
10405             goto process_sdp_cleanup;
10406          }
10407       } else {
10408          char type[20] = {0,};
10409          if ((sscanf(m, "%19s %30u/%30u %n", type, &x, &numberofports, &len) == 3 && len > 0) ||
10410               (sscanf(m, "%19s %30u %n", type, &x, &len) == 2 && len > 0)) {
10411             /* produce zero-port m-line since it may be needed later
10412              * length is "m=" + type + " 0 " + remainder + "\r\n\0" */
10413             if (!(offer->decline_m_line = ast_malloc(2 + strlen(type) + 3 + strlen(m + len) + 3))) {
10414                ast_log(LOG_WARNING, "Failed to allocate memory for SDP offer declination\n");
10415                res = -1;
10416                goto process_sdp_cleanup;
10417             }
10418             /* guaranteed to be long enough */
10419             sprintf(offer->decline_m_line, "m=%s 0 %s\r\n", type, m + len);
10420             continue;
10421          } else {
10422             ast_log(LOG_WARNING, "Unsupported top-level media type in offer: %s\n", m);
10423             res = -1;
10424             goto process_sdp_cleanup;
10425          }
10426       }
10427 
10428       /* Media stream specific parameters */
10429       while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
10430          int processed = FALSE;
10431 
10432          switch (type) {
10433          case 'c':
10434             if (audio) {
10435                if (process_sdp_c(value, &audiosa)) {
10436                   processed = TRUE;
10437                   sa = &audiosa;
10438                }
10439             } else if (video) {
10440                if (process_sdp_c(value, &videosa)) {
10441                   processed = TRUE;
10442                   vsa = &videosa;
10443                }
10444             } else if (text) {
10445                if (process_sdp_c(value, &textsa)) {
10446                   processed = TRUE;
10447                   tsa = &textsa;
10448                }
10449             } else if (image) {
10450                if (process_sdp_c(value, &imagesa)) {
10451                   processed = TRUE;
10452                   isa = &imagesa;
10453                }
10454             }
10455             break;
10456          case 'a':
10457             /* Audio specific scanning */
10458             if (audio) {
10459                if (process_sdp_a_ice(value, p, p->rtp)) {
10460                   processed = TRUE;
10461                } else if (process_sdp_a_dtls(value, p, p->rtp)) {
10462                   processed = TRUE;
10463                } else if (process_sdp_a_sendonly(value, &sendonly)) {
10464                   processed = TRUE;
10465                } else if (!processed_crypto && process_crypto(p, p->rtp, &p->srtp, value)) {
10466                   processed_crypto = TRUE;
10467                   processed = TRUE;
10468                } else if (process_sdp_a_audio(value, p, &newaudiortp, &last_rtpmap_codec)) {
10469                   processed = TRUE;
10470                }
10471             }
10472             /* Video specific scanning */
10473             else if (video) {
10474                if (process_sdp_a_ice(value, p, p->vrtp)) {
10475                   processed = TRUE;
10476                } else if (process_sdp_a_dtls(value, p, p->vrtp)) {
10477                   processed = TRUE;
10478                } else if (!processed_crypto && process_crypto(p, p->vrtp, &p->vsrtp, value)) {
10479                   processed_crypto = TRUE;
10480                   processed = TRUE;
10481                } else if (process_sdp_a_video(value, p, &newvideortp, &last_rtpmap_codec)) {
10482                   processed = TRUE;
10483                }
10484             }
10485             /* Text (T.140) specific scanning */
10486             else if (text) {
10487                if (process_sdp_a_ice(value, p, p->trtp)) {
10488                   processed = TRUE;
10489                } else if (process_sdp_a_text(value, p, &newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec)) {
10490                   processed = TRUE;
10491                } else if (!processed_crypto && process_crypto(p, p->trtp, &p->tsrtp, value)) {
10492                   processed_crypto = TRUE;
10493                   processed = TRUE;
10494                }
10495             }
10496             /* Image (T.38 FAX) specific scanning */
10497             else if (image) {
10498                if (process_sdp_a_image(value, p))
10499                   processed = TRUE;
10500             }
10501             break;
10502          }
10503 
10504          ast_debug(3, "Processing media-level (%s) SDP %c=%s... %s\n",
10505               (audio == TRUE)? "audio" : (video == TRUE)? "video" : (text == TRUE)? "text" : "image",
10506               type, value,
10507               (processed == TRUE)? "OK." : "UNSUPPORTED OR FAILED.");
10508       }
10509 
10510       /* Ensure crypto lines are provided where necessary */
10511       if (audio && secure_audio && !processed_crypto) {
10512          ast_log(LOG_WARNING, "Rejecting secure audio stream without encryption details: %s\n", m);
10513          return -1;
10514       } else if (video && secure_video && !processed_crypto) {
10515          ast_log(LOG_WARNING, "Rejecting secure video stream without encryption details: %s\n", m);
10516          return -1;
10517       }
10518    }
10519 
10520    /* Sanity checks */
10521    if (!sa && !vsa && !tsa && !isa) {
10522       ast_log(LOG_WARNING, "Insufficient information in SDP (c=)...\n");
10523       res = -1;
10524       goto process_sdp_cleanup;
10525    }
10526 
10527    if ((portno == -1) &&
10528        (vportno == -1) &&
10529        (tportno == -1) &&
10530        (udptlportno == -1)) {
10531       ast_log(LOG_WARNING, "Failing due to no acceptable offer found\n");
10532       res = -1;
10533       goto process_sdp_cleanup;
10534    }
10535 
10536    if (secure_audio && !(p->srtp && (ast_test_flag(p->srtp, SRTP_CRYPTO_OFFER_OK)))) {
10537       ast_log(LOG_WARNING, "Can't provide secure audio requested in SDP offer\n");
10538       res = -1;
10539       goto process_sdp_cleanup;
10540    }
10541 
10542    if (!secure_audio && p->srtp) {
10543       ast_log(LOG_WARNING, "We are requesting SRTP for audio, but they responded without it!\n");
10544       res = -1;
10545       goto process_sdp_cleanup;
10546    }
10547 
10548    if (secure_video && !(p->vsrtp && (ast_test_flag(p->vsrtp, SRTP_CRYPTO_OFFER_OK)))) {
10549       ast_log(LOG_WARNING, "Can't provide secure video requested in SDP offer\n");
10550       res = -1;
10551       goto process_sdp_cleanup;
10552    }
10553 
10554    if (!p->novideo && !secure_video && p->vsrtp) {
10555       ast_log(LOG_WARNING, "We are requesting SRTP for video, but they responded without it!\n");
10556       res = -1;
10557       goto process_sdp_cleanup;
10558    }
10559 
10560    if (!(secure_audio || secure_video) && ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP)) {
10561       ast_log(LOG_WARNING, "Matched device setup to use SRTP, but request was not!\n");
10562       res = -1;
10563       goto process_sdp_cleanup;
10564    }
10565 
10566    if (udptlportno == -1) {
10567       change_t38_state(p, T38_DISABLED);
10568    }
10569 
10570    /* Now gather all of the codecs that we are asked for: */
10571    ast_rtp_codecs_payload_formats(&newaudiortp, peercapability, &peernoncodeccapability);
10572    ast_rtp_codecs_payload_formats(&newvideortp, vpeercapability, &vpeernoncodeccapability);
10573    ast_rtp_codecs_payload_formats(&newtextrtp, tpeercapability, &tpeernoncodeccapability);
10574 
10575    ast_format_cap_append(newpeercapability, peercapability);
10576    ast_format_cap_append(newpeercapability, vpeercapability);
10577    ast_format_cap_append(newpeercapability, tpeercapability);
10578 
10579    ast_format_cap_joint_copy(p->caps, newpeercapability, newjointcapability);
10580    if (ast_format_cap_is_empty(newjointcapability) && udptlportno == -1) {
10581       ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
10582       /* Do NOT Change current setting */
10583       res = -1;
10584       goto process_sdp_cleanup;
10585    }
10586 
10587    newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
10588 
10589    if (debug) {
10590       /* shame on whoever coded this.... */
10591       char s1[SIPBUFSIZE], s2[SIPBUFSIZE], s3[SIPBUFSIZE], s4[SIPBUFSIZE], s5[SIPBUFSIZE];
10592 
10593       ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s/text=%s, combined - %s\n",
10594              ast_getformatname_multiple(s1, SIPBUFSIZE, p->caps),
10595              ast_getformatname_multiple(s2, SIPBUFSIZE, peercapability),
10596              ast_getformatname_multiple(s3, SIPBUFSIZE, vpeercapability),
10597              ast_getformatname_multiple(s4, SIPBUFSIZE, tpeercapability),
10598              ast_getformatname_multiple(s5, SIPBUFSIZE, newjointcapability));
10599    }
10600    if (debug) {
10601       struct ast_str *s1 = ast_str_alloca(SIPBUFSIZE);
10602       struct ast_str *s2 = ast_str_alloca(SIPBUFSIZE);
10603       struct ast_str *s3 = ast_str_alloca(SIPBUFSIZE);
10604 
10605       ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
10606              ast_rtp_lookup_mime_multiple2(s1, NULL, p->noncodeccapability, 0, 0),
10607              ast_rtp_lookup_mime_multiple2(s2, NULL, peernoncodeccapability, 0, 0),
10608              ast_rtp_lookup_mime_multiple2(s3, NULL, newnoncodeccapability, 0, 0));
10609    }
10610 
10611    if (portno != -1 || vportno != -1 || tportno != -1) {
10612       /* We are now ready to change the sip session and RTP structures with the offered codecs, since
10613          they are acceptable */
10614       ast_format_cap_copy(p->jointcaps, newjointcapability);                /* Our joint codec profile for this call */
10615       ast_format_cap_copy(p->peercaps, newpeercapability);                  /* The other side's capability in latest offer */
10616       p->jointnoncodeccapability = newnoncodeccapability;     /* DTMF capabilities */
10617 
10618       /* respond with single most preferred joint codec, limiting the other side's choice */
10619       if (ast_test_flag(&p->flags[1], SIP_PAGE2_PREFERRED_CODEC)) {
10620          ast_codec_choose(&p->prefs, p->jointcaps, 1, &tmp_fmt);
10621          ast_format_cap_set(p->jointcaps, &tmp_fmt);
10622       }
10623    }
10624 
10625    /* Setup audio address and port */
10626    if (p->rtp) {
10627       if (sa && portno > 0) {
10628          start_ice(p->rtp);
10629          ast_sockaddr_set_port(sa, portno);
10630          ast_rtp_instance_set_remote_address(p->rtp, sa);
10631          if (debug) {
10632             ast_verbose("Peer audio RTP is at port %s\n",
10633                    ast_sockaddr_stringify(sa));
10634          }
10635 
10636          ast_rtp_codecs_payloads_copy(&newaudiortp, ast_rtp_instance_get_codecs(p->rtp), p->rtp);
10637          /* Ensure RTCP is enabled since it may be inactive
10638             if we're coming back from a T.38 session */
10639          ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 1);
10640          /* Ensure audio RTCP reads are enabled */
10641          if (p->owner) {
10642             ast_channel_set_fd(p->owner, 1, ast_rtp_instance_fd(p->rtp, 1));
10643          }
10644 
10645          if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
10646             ast_clear_flag(&p->flags[0], SIP_DTMF);
10647             if (newnoncodeccapability & AST_RTP_DTMF) {
10648                /* XXX Would it be reasonable to drop the DSP at this point? XXX */
10649                ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
10650                /* Since RFC2833 is now negotiated we need to change some properties of the RTP stream */
10651                ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, 1);
10652                ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
10653             } else {
10654                ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
10655             }
10656          }
10657       } else if (udptlportno > 0) {
10658          if (debug)
10659             ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session.\n");
10660          /* Prevent audio RTCP reads */
10661          if (p->owner) {
10662             ast_channel_set_fd(p->owner, 1, -1);
10663          }
10664          /* Silence RTCP while audio RTP is inactive */
10665          ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 0);
10666       } else {
10667          ast_rtp_instance_stop(p->rtp);
10668          if (debug)
10669             ast_verbose("Peer doesn't provide audio\n");
10670       }
10671    }
10672 
10673    /* Setup video address and port */
10674    if (p->vrtp) {
10675       if (vsa && vportno > 0) {
10676          start_ice(p->vrtp);
10677          ast_sockaddr_set_port(vsa, vportno);
10678          ast_rtp_instance_set_remote_address(p->vrtp, vsa);
10679          if (debug) {
10680             ast_verbose("Peer video RTP is at port %s\n",
10681                    ast_sockaddr_stringify(vsa));
10682          }
10683          ast_rtp_codecs_payloads_copy(&newvideortp, ast_rtp_instance_get_codecs(p->vrtp), p->vrtp);
10684       } else {
10685          ast_rtp_instance_stop(p->vrtp);
10686          if (debug)
10687             ast_verbose("Peer doesn't provide video\n");
10688       }
10689    }
10690 
10691    /* Setup text address and port */
10692    if (p->trtp) {
10693       if (tsa && tportno > 0) {
10694          start_ice(p->trtp);
10695          ast_sockaddr_set_port(tsa, tportno);
10696          ast_rtp_instance_set_remote_address(p->trtp, tsa);
10697          if (debug) {
10698             ast_verbose("Peer T.140 RTP is at port %s\n",
10699                    ast_sockaddr_stringify(tsa));
10700          }
10701          if (ast_format_cap_iscompatible(p->jointcaps, ast_format_set(&tmp_fmt, AST_FORMAT_T140RED, 0))) {
10702             p->red = 1;
10703             ast_rtp_red_init(p->trtp, 300, red_data_pt, 2);
10704          } else {
10705             p->red = 0;
10706          }
10707          ast_rtp_codecs_payloads_copy(&newtextrtp, ast_rtp_instance_get_codecs(p->trtp), p->trtp);
10708       } else {
10709          ast_rtp_instance_stop(p->trtp);
10710          if (debug)
10711             ast_verbose("Peer doesn't provide T.140\n");
10712       }
10713    }
10714 
10715    /* Setup image address and port */
10716    if (p->udptl) {
10717       if (isa && udptlportno > 0) {
10718          if (ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP) && ast_test_flag(&p->flags[1], SIP_PAGE2_UDPTL_DESTINATION)) {
10719             ast_rtp_instance_get_remote_address(p->rtp, isa);
10720             if (!ast_sockaddr_isnull(isa) && debug) {
10721                ast_debug(1, "Peer T.38 UDPTL is set behind NAT and with destination, destination address now %s\n", ast_sockaddr_stringify(isa));
10722             }
10723          }
10724          ast_sockaddr_set_port(isa, udptlportno);
10725          ast_udptl_set_peer(p->udptl, isa);
10726          if (debug)
10727             ast_debug(1,"Peer T.38 UDPTL is at port %s\n", ast_sockaddr_stringify(isa));
10728 
10729          /* verify the far max ifp can be calculated. this requires far max datagram to be set. */
10730          if (!ast_udptl_get_far_max_datagram(p->udptl)) {
10731             /* setting to zero will force a default if none was provided by the SDP */
10732             ast_udptl_set_far_max_datagram(p->udptl, 0);
10733          }
10734 
10735          /* Remote party offers T38, we need to update state */
10736          if ((t38action == SDP_T38_ACCEPT) &&
10737              (p->t38.state == T38_LOCAL_REINVITE)) {
10738             change_t38_state(p, T38_ENABLED);
10739          } else if ((t38action == SDP_T38_INITIATE) &&
10740                p->owner && p->lastinvite) {
10741             change_t38_state(p, T38_PEER_REINVITE); /* T38 Offered in re-invite from remote party */
10742             /* If fax detection is enabled then send us off to the fax extension */
10743             if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38)) {
10744                ast_channel_lock(p->owner);
10745                if (strcmp(ast_channel_exten(p->owner), "fax")) {
10746                   const char *target_context = S_OR(ast_channel_macrocontext(p->owner), ast_channel_context(p->owner));
10747                   ast_channel_unlock(p->owner);
10748                   if (ast_exists_extension(p->owner, target_context, "fax", 1,
10749                      S_COR(ast_channel_caller(p->owner)->id.number.valid, ast_channel_caller(p->owner)->id.number.str, NULL))) {
10750                      ast_verb(2, "Redirecting '%s' to fax extension due to peer T.38 re-INVITE\n", ast_channel_name(p->owner));
10751                      pbx_builtin_setvar_helper(p->owner, "FAXEXTEN", ast_channel_exten(p->owner));
10752                      if (ast_async_goto(p->owner, target_context, "fax", 1)) {
10753                         ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast_channel_name(p->owner), target_context);
10754                      }
10755                   } else {
10756                      ast_log(LOG_NOTICE, "T.38 re-INVITE detected but no fax extension\n");
10757                   }
10758                } else {
10759                   ast_channel_unlock(p->owner);
10760                }
10761             }
10762          }
10763       } else {
10764          change_t38_state(p, T38_DISABLED);
10765          ast_udptl_stop(p->udptl);
10766          if (debug)
10767             ast_debug(1, "Peer doesn't provide T.38 UDPTL\n");
10768       }
10769    }
10770 
10771    if ((portno == -1) && (p->t38.state != T38_DISABLED) && (p->t38.state != T38_REJECTED)) {
10772       ast_debug(3, "Have T.38 but no audio, accepting offer anyway\n");
10773       res = 0;
10774       goto process_sdp_cleanup;
10775    }
10776 
10777    /* Ok, we're going with this offer */
10778    ast_debug(2, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, p->jointcaps));
10779 
10780    if (!p->owner) { /* There's no open channel owning us so we can return here. For a re-invite or so, we proceed */
10781       res = 0;
10782       goto process_sdp_cleanup;
10783    }
10784 
10785    ast_debug(4, "We have an owner, now see if we need to change this call\n");
10786    if (ast_format_cap_has_type(p->jointcaps, AST_FORMAT_TYPE_AUDIO)) {
10787       if (debug) {
10788          char s1[SIPBUFSIZE], s2[SIPBUFSIZE];
10789          ast_debug(1, "Setting native formats after processing SDP. peer joint formats %s, old nativeformats %s\n",
10790             ast_getformatname_multiple(s1, SIPBUFSIZE, p->jointcaps),
10791             ast_getformatname_multiple(s2, SIPBUFSIZE, ast_channel_nativeformats(p->owner)));
10792       }
10793 
10794       ast_codec_choose(&p->prefs, p->jointcaps, 1, &tmp_fmt);
10795 
10796       ast_format_cap_set(ast_channel_nativeformats(p->owner), &tmp_fmt);
10797       ast_format_cap_joint_append(p->caps, vpeercapability, ast_channel_nativeformats(p->owner));
10798       ast_format_cap_joint_append(p->caps, tpeercapability, ast_channel_nativeformats(p->owner));
10799 
10800       ast_set_read_format(p->owner, ast_channel_readformat(p->owner));
10801       ast_set_write_format(p->owner, ast_channel_writeformat(p->owner));
10802    }
10803 
10804    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)) {
10805       ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
10806       /* Activate a re-invite */
10807       ast_queue_frame(p->owner, &ast_null_frame);
10808       change_hold_state(p, req, FALSE, sendonly);
10809    } 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)) {
10810       ast_queue_control_data(p->owner, AST_CONTROL_HOLD,
10811                    S_OR(p->mohsuggest, NULL),
10812                    !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
10813       if (sendonly)
10814          ast_rtp_instance_stop(p->rtp);
10815       /* RTCP needs to go ahead, even if we're on hold!!! */
10816       /* Activate a re-invite */
10817       ast_queue_frame(p->owner, &ast_null_frame);
10818       change_hold_state(p, req, TRUE, sendonly);
10819    }
10820 
10821 process_sdp_cleanup:
10822    if (res) {
10823       offered_media_list_destroy(p);
10824    }
10825    ast_rtp_codecs_payloads_destroy(&newtextrtp);
10826    ast_rtp_codecs_payloads_destroy(&newvideortp);
10827    ast_rtp_codecs_payloads_destroy(&newaudiortp);
10828    ast_format_cap_destroy(peercapability);
10829    ast_format_cap_destroy(vpeercapability);
10830    ast_format_cap_destroy(tpeercapability);
10831    ast_format_cap_destroy(newjointcapability);
10832    ast_format_cap_destroy(newpeercapability);
10833    return res;
10834 }
10835 
10836 static int process_sdp_o(const char *o, struct sip_pvt *p)
10837 {
10838    char *o_copy;
10839    char *token;
10840    int64_t rua_version;
10841 
10842    /* Store the SDP version number of remote UA. This will allow us to
10843    distinguish between session modifications and session refreshes. If
10844    the remote UA does not send an incremented SDP version number in a
10845    subsequent RE-INVITE then that means its not changing media session.
10846    The RE-INVITE may have been sent to update connected party, remote
10847    target or to refresh the session (Session-Timers).  Asterisk must not
10848    change media session and increment its own version number in answer
10849    SDP in this case. */
10850 
10851    p->session_modify = TRUE;
10852 
10853    if (ast_strlen_zero(o)) {
10854       ast_log(LOG_WARNING, "SDP syntax error. SDP without an o= line\n");
10855       return FALSE;
10856    }
10857 
10858    o_copy = ast_strdupa(o);
10859    token = strsep(&o_copy, " ");  /* Skip username   */
10860    if (!o_copy) {
10861       ast_log(LOG_WARNING, "SDP syntax error in o= line username\n");
10862       return FALSE;
10863    }
10864    token = strsep(&o_copy, " ");  /* Skip session-id */
10865    if (!o_copy) {
10866       ast_log(LOG_WARNING, "SDP syntax error in o= line session-id\n");
10867       return FALSE;
10868    }
10869    token = strsep(&o_copy, " ");  /* Version         */
10870    if (!o_copy) {
10871       ast_log(LOG_WARNING, "SDP syntax error in o= line\n");
10872       return FALSE;
10873    }
10874    if (!sscanf(token, "%30" SCNd64, &rua_version)) {
10875       ast_log(LOG_WARNING, "SDP syntax error in o= line version\n");
10876       return FALSE;
10877    }
10878 
10879    /* we need to check the SDP version number the other end sent us;
10880     * our rules for deciding what to accept are a bit complex.
10881     *
10882     * 1) if 'ignoresdpversion' has been set for this dialog, then
10883     *    we will just accept whatever they sent and assume it is
10884     *    a modification of the session, even if it is not
10885     * 2) otherwise, if this is the first SDP we've seen from them
10886     *    we accept it
10887     * 3) otherwise, if the new SDP version number is higher than the
10888     *    old one, we accept it
10889     * 4) otherwise, if this SDP is in response to us requesting a switch
10890     *    to T.38, we accept the SDP, but also generate a warning message
10891     *    that this peer should have the 'ignoresdpversion' option set,
10892     *    because it is not following the SDP offer/answer RFC; if we did
10893     *    not request a switch to T.38, then we stop parsing the SDP, as it
10894     *    has not changed from the previous version
10895     */
10896 
10897    if (ast_test_flag(&p->flags[1], SIP_PAGE2_IGNORESDPVERSION) ||
10898        (p->sessionversion_remote < 0) ||
10899        (p->sessionversion_remote < rua_version)) {
10900       p->sessionversion_remote = rua_version;
10901    } else {
10902       if (p->t38.state == T38_LOCAL_REINVITE) {
10903          p->sessionversion_remote = rua_version;
10904          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);
10905       } else {
10906          p->session_modify = FALSE;
10907          ast_debug(2, "Call %s responded to our reinvite without changing SDP version; ignoring SDP.\n", p->callid);
10908          return FALSE;
10909       }
10910    }
10911 
10912    return TRUE;
10913 }
10914 
10915 static int process_sdp_c(const char *c, struct ast_sockaddr *addr)
10916 {
10917    char proto[4], host[258];
10918    int af;
10919 
10920    /* Check for Media-description-level-address */
10921    if (sscanf(c, "IN %3s %255s", proto, host) == 2) {
10922       if (!strcmp("IP4", proto)) {
10923          af = AF_INET;
10924       } else if (!strcmp("IP6", proto)) {
10925          af = AF_INET6;
10926       } else {
10927          ast_log(LOG_WARNING, "Unknown protocol '%s'.\n", proto);
10928          return FALSE;
10929       }
10930       if (ast_sockaddr_resolve_first_af(addr, host, 0, af)) {
10931          ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in c= line, '%s'\n", c);
10932          return FALSE;
10933       }
10934       return TRUE;
10935    } else {
10936       ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
10937       return FALSE;
10938    }
10939    return FALSE;
10940 }
10941 
10942 static int process_sdp_a_sendonly(const char *a, int *sendonly)
10943 {
10944    int found = FALSE;
10945 
10946    if (!strcasecmp(a, "sendonly")) {
10947       if (*sendonly == -1)
10948          *sendonly = 1;
10949       found = TRUE;
10950    } else if (!strcasecmp(a, "inactive")) {
10951       if (*sendonly == -1)
10952          *sendonly = 2;
10953       found = TRUE;
10954    }  else if (!strcasecmp(a, "sendrecv")) {
10955       if (*sendonly == -1)
10956          *sendonly = 0;
10957       found = TRUE;
10958    }
10959    return found;
10960 }
10961 
10962 static int process_sdp_a_ice(const char *a, struct sip_pvt *p, struct ast_rtp_instance *instance)
10963 {
10964    struct ast_rtp_engine_ice *ice;
10965    int found = FALSE;
10966    char ufrag[256], pwd[256], foundation[32], transport[4], address[46], cand_type[6], relay_address[46] = "";
10967    struct ast_rtp_engine_ice_candidate candidate = { 0, };
10968    int port, relay_port = 0;
10969 
10970    if (!instance || !(ice = ast_rtp_instance_get_ice(instance))) {
10971       return found;
10972    }
10973 
10974    if (sscanf(a, "ice-ufrag: %255s", ufrag) == 1) {
10975       ice->set_authentication(instance, ufrag, NULL);
10976       found = TRUE;
10977    } else if (sscanf(a, "ice-pwd: %255s", pwd) == 1) {
10978       ice->set_authentication(instance, NULL, pwd);
10979       found = TRUE;
10980    } else if (sscanf(a, "candidate: %31s %30u %3s %30u %23s %30u typ %5s %*s %23s %*s %30u", foundation, &candidate.id, transport, &candidate.priority,
10981            address, &port, cand_type, relay_address, &relay_port) >= 7) {
10982       candidate.foundation = foundation;
10983       candidate.transport = transport;
10984 
10985       ast_sockaddr_parse(&candidate.address, address, PARSE_PORT_FORBID);
10986       ast_sockaddr_set_port(&candidate.address, port);
10987 
10988       if (!strcasecmp(cand_type, "host")) {
10989          candidate.type = AST_RTP_ICE_CANDIDATE_TYPE_HOST;
10990       } else if (!strcasecmp(cand_type, "srflx")) {
10991          candidate.type = AST_RTP_ICE_CANDIDATE_TYPE_SRFLX;
10992       } else if (!strcasecmp(cand_type, "relay")) {
10993          candidate.type = AST_RTP_ICE_CANDIDATE_TYPE_RELAYED;
10994       } else {
10995          return found;
10996       }
10997 
10998       if (!ast_strlen_zero(relay_address)) {
10999          ast_sockaddr_parse(&candidate.relay_address, relay_address, PARSE_PORT_FORBID);
11000       }
11001 
11002       if (relay_port) {
11003          ast_sockaddr_set_port(&candidate.relay_address, relay_port);
11004       }
11005 
11006       ice->add_remote_candidate(instance, &candidate);
11007 
11008       found = TRUE;
11009    } else if (!strcasecmp(a, "ice-lite")) {
11010       ice->ice_lite(instance);
11011       found = TRUE;
11012    }
11013 
11014    return found;
11015 }
11016 
11017 static int process_sdp_a_dtls(const char *a, struct sip_pvt *p, struct ast_rtp_instance *instance)
11018 {
11019    struct ast_rtp_engine_dtls *dtls;
11020    int found = FALSE;
11021    char value[256], hash[6];
11022 
11023    if (!instance || !p->dtls_cfg.enabled || !(dtls = ast_rtp_instance_get_dtls(instance))) {
11024       return found;
11025    }
11026 
11027    if (sscanf(a, "setup: %255s", value) == 1) {
11028       found = TRUE;
11029 
11030       if (!strcasecmp(value, "active")) {
11031          dtls->set_setup(instance, AST_RTP_DTLS_SETUP_ACTIVE);
11032       } else if (!strcasecmp(value, "passive")) {
11033          dtls->set_setup(instance, AST_RTP_DTLS_SETUP_PASSIVE);
11034       } else if (!strcasecmp(value, "actpass")) {
11035          dtls->set_setup(instance, AST_RTP_DTLS_SETUP_ACTPASS);
11036       } else if (!strcasecmp(value, "holdconn")) {
11037          dtls->set_setup(instance, AST_RTP_DTLS_SETUP_HOLDCONN);
11038       } else {
11039          ast_log(LOG_WARNING, "Unsupported setup attribute value '%s' received on dialog '%s'\n",
11040             value, p->callid);
11041       }
11042    } else if (sscanf(a, "connection: %255s", value) == 1) {
11043       found = TRUE;
11044 
11045       if (!strcasecmp(value, "new")) {
11046          dtls->reset(instance);
11047       } else if (!strcasecmp(value, "existing")) {
11048          /* Since they want to just use what already exists we go on as if nothing happened */
11049       } else {
11050          ast_log(LOG_WARNING, "Unsupported connection attribute value '%s' received on dialog '%s'\n",
11051             value, p->callid);
11052       }
11053    } else if (sscanf(a, "fingerprint: %5s %255s", hash, value) == 2) {
11054       found = TRUE;
11055 
11056       if (!strcasecmp(hash, "sha-1")) {
11057          dtls->set_fingerprint(instance, AST_RTP_DTLS_HASH_SHA1, value);
11058       } else {
11059          ast_log(LOG_WARNING, "Unsupported fingerprint hash type '%s' received on dialog '%s'\n",
11060             hash, p->callid);
11061       }
11062    }
11063 
11064    return found;
11065 }
11066 
11067 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec)
11068 {
11069    int found = FALSE;
11070    int codec;
11071    char mimeSubtype[128];
11072    char fmtp_string[256];
11073    unsigned int sample_rate;
11074    int debug = sip_debug_test_pvt(p);
11075 
11076    if (!strncasecmp(a, "ptime", 5)) {
11077       char *tmp = strrchr(a, ':');
11078       long int framing = 0;
11079       if (tmp) {
11080          tmp++;
11081          framing = strtol(tmp, NULL, 10);
11082          if (framing == LONG_MIN || framing == LONG_MAX) {
11083             framing = 0;
11084             ast_debug(1, "Can't read framing from SDP: %s\n", a);
11085          }
11086       }
11087       if (framing && p->autoframing) {
11088          struct ast_codec_pref *pref = &ast_rtp_instance_get_codecs(p->rtp)->pref;
11089          int codec_n;
11090          for (codec_n = 0; codec_n < AST_RTP_MAX_PT; codec_n++) {
11091             struct ast_rtp_payload_type format = ast_rtp_codecs_payload_lookup(ast_rtp_instance_get_codecs(p->rtp), codec_n);
11092             if (!format.asterisk_format)  /* non-codec or not found */
11093                continue;
11094             ast_debug(1, "Setting framing for %s to %ld\n", ast_getformatname(&format.format), framing);
11095             ast_codec_pref_setsize(pref, &format.format, framing);
11096          }
11097          ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, pref);
11098       }
11099       found = TRUE;
11100    } else if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
11101       /* We have a rtpmap to handle */
11102       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
11103          if (!(ast_rtp_codecs_payloads_set_rtpmap_type_rate(newaudiortp, NULL, codec, "audio", mimeSubtype,
11104              ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0, sample_rate))) {
11105             if (debug)
11106                ast_verbose("Found audio description format %s for ID %d\n", mimeSubtype, codec);
11107             //found_rtpmap_codecs[last_rtpmap_codec] = codec;
11108             (*last_rtpmap_codec)++;
11109             found = TRUE;
11110          } else {
11111             ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
11112             if (debug)
11113                ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
11114          }
11115       } else {
11116          if (debug)
11117             ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
11118       }
11119    } else if (sscanf(a, "fmtp: %30u %255s", &codec, fmtp_string) == 2) {
11120       struct ast_format *format;
11121 
11122       if ((format = ast_rtp_codecs_get_payload_format(newaudiortp, codec))) {
11123          unsigned int bit_rate;
11124 
11125          if (!ast_format_sdp_parse(format, fmtp_string)) {
11126             found = TRUE;
11127          } else {
11128             ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
11129          }
11130 
11131          switch ((int) format->id) {
11132          case AST_FORMAT_SIREN7:
11133             if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
11134                if (bit_rate != 32000) {
11135                   ast_log(LOG_WARNING, "Got Siren7 offer at %d bps, but only 32000 bps supported; ignoring.\n", bit_rate);
11136                   ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
11137                } else {
11138                   found = TRUE;
11139                }
11140             }
11141             break;
11142          case AST_FORMAT_SIREN14:
11143             if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
11144                if (bit_rate != 48000) {
11145                   ast_log(LOG_WARNING, "Got Siren14 offer at %d bps, but only 48000 bps supported; ignoring.\n", bit_rate);
11146                   ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
11147                } else {
11148                   found = TRUE;
11149                }
11150             }
11151             break;
11152          case AST_FORMAT_G719:
11153             if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
11154                if (bit_rate != 64000) {
11155                   ast_log(LOG_WARNING, "Got G.719 offer at %d bps, but only 64000 bps supported; ignoring.\n", bit_rate);
11156                   ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
11157                } else {
11158                   found = TRUE;
11159                }
11160             }
11161             break;
11162          }
11163       }
11164    }
11165 
11166    return found;
11167 }
11168 
11169 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec)
11170 {
11171    int found = FALSE;
11172    int codec;
11173    char mimeSubtype[128];
11174    unsigned int sample_rate;
11175    int debug = sip_debug_test_pvt(p);
11176    char fmtp_string[256];
11177 
11178    if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
11179       /* We have a rtpmap to handle */
11180       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
11181          /* Note: should really look at the '#chans' params too */
11182          if (!strncasecmp(mimeSubtype, "H26", 3) || !strncasecmp(mimeSubtype, "MP4", 3)) {
11183             if (!(ast_rtp_codecs_payloads_set_rtpmap_type_rate(newvideortp, NULL, codec, "video", mimeSubtype, 0, sample_rate))) {
11184                if (debug)
11185                   ast_verbose("Found video description format %s for ID %d\n", mimeSubtype, codec);
11186                //found_rtpmap_codecs[last_rtpmap_codec] = codec;
11187                (*last_rtpmap_codec)++;
11188                found = TRUE;
11189             } else {
11190                ast_rtp_codecs_payloads_unset(newvideortp, NULL, codec);
11191                if (debug)
11192                   ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
11193             }
11194          }
11195       } else {
11196          if (debug)
11197             ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
11198       }
11199    } else if (sscanf(a, "fmtp: %30u %255s", &codec, fmtp_string) == 2) {
11200       struct ast_format *format;
11201 
11202       if ((format = ast_rtp_codecs_get_payload_format(newvideortp, codec))) {
11203          if (!ast_format_sdp_parse(format, fmtp_string)) {
11204             found = TRUE;
11205          } else {
11206             ast_rtp_codecs_payloads_unset(newvideortp, NULL, codec);
11207          }
11208       }
11209    }
11210 
11211    return found;
11212 }
11213 
11214 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)
11215 {
11216    int found = FALSE;
11217    int codec;
11218    char mimeSubtype[128];
11219    unsigned int sample_rate;
11220    char *red_cp;
11221    int debug = sip_debug_test_pvt(p);
11222 
11223    if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
11224       /* We have a rtpmap to handle */
11225       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
11226          if (!strncasecmp(mimeSubtype, "T140", 4)) { /* Text */
11227             if (p->trtp) {
11228                /* ast_verbose("Adding t140 mimeSubtype to textrtp struct\n"); */
11229                ast_rtp_codecs_payloads_set_rtpmap_type_rate(newtextrtp, NULL, codec, "text", mimeSubtype, 0, sample_rate);
11230                found = TRUE;
11231             }
11232          } else if (!strncasecmp(mimeSubtype, "RED", 3)) { /* Text with Redudancy */
11233             if (p->trtp) {
11234                ast_rtp_codecs_payloads_set_rtpmap_type_rate(newtextrtp, NULL, codec, "text", mimeSubtype, 0, sample_rate);
11235                sprintf(red_fmtp, "fmtp:%d ", codec);
11236                if (debug)
11237                   ast_verbose("RED submimetype has payload type: %d\n", codec);
11238                found = TRUE;
11239             }
11240          }
11241       } else {
11242          if (debug)
11243             ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
11244       }
11245    } else if (!strncmp(a, red_fmtp, strlen(red_fmtp))) {
11246       /* count numbers of generations in fmtp */
11247       red_cp = &red_fmtp[strlen(red_fmtp)];
11248       strncpy(red_fmtp, a, 100);
11249 
11250       sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
11251       red_cp = strtok(red_cp, "/");
11252       while (red_cp && (*red_num_gen)++ < AST_RED_MAX_GENERATION) {
11253          sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
11254          red_cp = strtok(NULL, "/");
11255       }
11256       red_cp = red_fmtp;
11257       found = TRUE;
11258    }
11259 
11260    return found;
11261 }
11262 
11263 static int process_sdp_a_image(const char *a, struct sip_pvt *p)
11264 {
11265    int found = FALSE;
11266    char s[256];
11267    unsigned int x;
11268    char *attrib = ast_strdupa(a);
11269    char *pos;
11270 
11271    if (initialize_udptl(p)) {
11272       return found;
11273    }
11274 
11275    /* Due to a typo in an IANA registration of one of the T.38 attributes,
11276     * RFC5347 section 2.5.2 recommends that all T.38 attributes be parsed in
11277     * a case insensitive manner. Hence, the importance of proof reading (and
11278     * code reviews).
11279     */
11280    for (pos = attrib; *pos; ++pos) {
11281       *pos = tolower(*pos);
11282    }
11283 
11284    if ((sscanf(attrib, "t38faxmaxbuffer:%30u", &x) == 1)) {
11285       ast_debug(3, "MaxBufferSize:%d\n", x);
11286       found = TRUE;
11287    } else if ((sscanf(attrib, "t38maxbitrate:%30u", &x) == 1) || (sscanf(attrib, "t38faxmaxrate:%30u", &x) == 1)) {
11288       ast_debug(3, "T38MaxBitRate: %d\n", x);
11289       switch (x) {
11290       case 14400:
11291          p->t38.their_parms.rate = AST_T38_RATE_14400;
11292          break;
11293       case 12000:
11294          p->t38.their_parms.rate = AST_T38_RATE_12000;
11295          break;
11296       case 9600:
11297          p->t38.their_parms.rate = AST_T38_RATE_9600;
11298          break;
11299       case 7200:
11300          p->t38.their_parms.rate = AST_T38_RATE_7200;
11301          break;
11302       case 4800:
11303          p->t38.their_parms.rate = AST_T38_RATE_4800;
11304          break;
11305       case 2400:
11306          p->t38.their_parms.rate = AST_T38_RATE_2400;
11307          break;
11308       }
11309       found = TRUE;
11310    } else if ((sscanf(attrib, "t38faxversion:%30u", &x) == 1)) {
11311       ast_debug(3, "FaxVersion: %u\n", x);
11312       p->t38.their_parms.version = x;
11313       found = TRUE;
11314    } else if ((sscanf(attrib, "t38faxmaxdatagram:%30u", &x) == 1) || (sscanf(attrib, "t38maxdatagram:%30u", &x) == 1)) {
11315       /* override the supplied value if the configuration requests it */
11316       if (((signed int) p->t38_maxdatagram >= 0) && ((unsigned int) p->t38_maxdatagram > x)) {
11317          ast_debug(1, "Overriding T38FaxMaxDatagram '%d' with '%d'\n", x, p->t38_maxdatagram);
11318          x = p->t38_maxdatagram;
11319       }
11320       ast_debug(3, "FaxMaxDatagram: %u\n", x);
11321       ast_udptl_set_far_max_datagram(p->udptl, x);
11322       found = TRUE;
11323    } else if ((strncmp(attrib, "t38faxfillbitremoval", 20) == 0)) {
11324       if (sscanf(attrib, "t38faxfillbitremoval:%30u", &x) == 1) {
11325          ast_debug(3, "FillBitRemoval: %d\n", x);
11326          if (x == 1) {
11327             p->t38.their_parms.fill_bit_removal = TRUE;
11328          }
11329       } else {
11330          ast_debug(3, "FillBitRemoval\n");
11331          p->t38.their_parms.fill_bit_removal = TRUE;
11332       }
11333       found = TRUE;
11334    } else if ((strncmp(attrib, "t38faxtranscodingmmr", 20) == 0)) {
11335       if (sscanf(attrib, "t38faxtranscodingmmr:%30u", &x) == 1) {
11336          ast_debug(3, "Transcoding MMR: %d\n", x);
11337          if (x == 1) {
11338             p->t38.their_parms.transcoding_mmr = TRUE;
11339          }
11340       } else {
11341          ast_debug(3, "Transcoding MMR\n");
11342          p->t38.their_parms.transcoding_mmr = TRUE;
11343       }
11344       found = TRUE;
11345    } else if ((strncmp(attrib, "t38faxtranscodingjbig", 21) == 0)) {
11346       if (sscanf(attrib, "t38faxtranscodingjbig:%30u", &x) == 1) {
11347          ast_debug(3, "Transcoding JBIG: %d\n", x);
11348          if (x == 1) {
11349             p->t38.their_parms.transcoding_jbig = TRUE;
11350          }
11351       } else {
11352          ast_debug(3, "Transcoding JBIG\n");
11353          p->t38.their_parms.transcoding_jbig = TRUE;
11354       }
11355       found = TRUE;
11356    } else if ((sscanf(attrib, "t38faxratemanagement:%255s", s) == 1)) {
11357       ast_debug(3, "RateManagement: %s\n", s);
11358       if (!strcasecmp(s, "localTCF"))
11359          p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_LOCAL_TCF;
11360       else if (!strcasecmp(s, "transferredTCF"))
11361          p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF;
11362       found = TRUE;
11363    } else if ((sscanf(attrib, "t38faxudpec:%255s", s) == 1)) {
11364       ast_debug(3, "UDP EC: %s\n", s);
11365       if (!strcasecmp(s, "t38UDPRedundancy")) {
11366          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
11367       } else if (!strcasecmp(s, "t38UDPFEC")) {
11368          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
11369       } else {
11370          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
11371       }
11372       found = TRUE;
11373    }
11374 
11375    return found;
11376 }
11377 
11378 /*! \brief Add "Supported" header to sip message.  Since some options may
11379  *  be disabled in the config, the sip_pvt must be inspected to determine what
11380  *  is supported for this dialog. */
11381 static int add_supported(struct sip_pvt *pvt, struct sip_request *req)
11382 {
11383    int res;
11384    if (st_get_mode(pvt, 0) != SESSION_TIMER_MODE_REFUSE) {
11385       res = add_header(req, "Supported", "replaces, timer");
11386    } else {
11387       res = add_header(req, "Supported", "replaces");
11388    }
11389    return res;
11390 }
11391 
11392 /*! \brief Add header to SIP message */
11393 static int add_header(struct sip_request *req, const char *var, const char *value)
11394 {
11395    if (req->headers == SIP_MAX_HEADERS) {
11396       ast_log(LOG_WARNING, "Out of SIP header space\n");
11397       return -1;
11398    }
11399 
11400    if (req->lines) {
11401       ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
11402       return -1;
11403    }
11404 
11405    if (sip_cfg.compactheaders) {
11406       var = find_alias(var, var);
11407    }
11408 
11409    ast_str_append(&req->data, 0, "%s: %s\r\n", var, value);
11410    req->header[req->headers] = ast_str_strlen(req->data);
11411 
11412    req->headers++;
11413 
11414    return 0;   
11415 }
11416 
11417 /*! 
11418  * \pre dialog is assumed to be locked while calling this function
11419  * \brief Add 'Max-Forwards' header to SIP message 
11420  */
11421 static int add_max_forwards(struct sip_pvt *dialog, struct sip_request *req)
11422 {
11423    char clen[10];
11424 
11425    snprintf(clen, sizeof(clen), "%d", dialog->maxforwards);
11426 
11427    return add_header(req, "Max-Forwards", clen);
11428 }
11429 
11430 /*! \brief Add 'Content-Length' header and content to SIP message */
11431 static int finalize_content(struct sip_request *req)
11432 {
11433    char clen[10];
11434 
11435    if (req->lines) {
11436       ast_log(LOG_WARNING, "finalize_content() called on a message that has already been finalized\n");
11437       return -1;
11438    }
11439 
11440    snprintf(clen, sizeof(clen), "%zd", ast_str_strlen(req->content));
11441    add_header(req, "Content-Length", clen);
11442 
11443    if (ast_str_strlen(req->content)) {
11444       ast_str_append(&req->data, 0, "\r\n%s", ast_str_buffer(req->content));
11445    }
11446    req->lines = ast_str_strlen(req->content) ? 1 : 0;
11447    return 0;
11448 }
11449 
11450 /*! \brief Add content (not header) to SIP message */
11451 static int add_content(struct sip_request *req, const char *line)
11452 {
11453    if (req->lines) {
11454       ast_log(LOG_WARNING, "Can't add more content when the content has been finalized\n");
11455       return -1;
11456    }
11457 
11458    ast_str_append(&req->content, 0, "%s", line);
11459    return 0;
11460 }
11461 
11462 /*! \brief Copy one header field from one request to another */
11463 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
11464 {
11465    const char *tmp = sip_get_header(orig, field);
11466 
11467    if (!ast_strlen_zero(tmp)) /* Add what we're responding to */
11468       return add_header(req, field, tmp);
11469    ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
11470    return -1;
11471 }
11472 
11473 /*! \brief Copy all headers from one request to another */
11474 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
11475 {
11476    int start = 0;
11477    int copied = 0;
11478    for (;;) {
11479       const char *tmp = __get_header(orig, field, &start);
11480 
11481       if (ast_strlen_zero(tmp))
11482          break;
11483       /* Add what we're responding to */
11484       add_header(req, field, tmp);
11485       copied++;
11486    }
11487    return copied ? 0 : -1;
11488 }
11489 
11490 /*! \brief Copy SIP VIA Headers from the request to the response
11491 \note If the client indicates that it wishes to know the port we received from,
11492    it adds ;rport without an argument to the topmost via header. We need to
11493    add the port number (from our point of view) to that parameter.
11494 \verbatim
11495    We always add ;received=<ip address> to the topmost via header.
11496 \endverbatim
11497    Received: RFC 3261, rport RFC 3581 */
11498 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
11499 {
11500    int copied = 0;
11501    int start = 0;
11502 
11503    for (;;) {
11504       char new[512];
11505       const char *oh = __get_header(orig, field, &start);
11506 
11507       if (ast_strlen_zero(oh))
11508          break;
11509 
11510       if (!copied) { /* Only check for empty rport in topmost via header */
11511          char leftmost[512], *others, *rport;
11512 
11513          /* Only work on leftmost value */
11514          ast_copy_string(leftmost, oh, sizeof(leftmost));
11515          others = strchr(leftmost, ',');
11516          if (others)
11517              *others++ = '\0';
11518 
11519          /* Find ;rport;  (empty request) */
11520          rport = strstr(leftmost, ";rport");
11521          if (rport && *(rport+6) == '=')
11522             rport = NULL;     /* We already have a parameter to rport */
11523 
11524          if (((ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT)) || (rport && ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)))) {
11525             /* We need to add received port - rport */
11526             char *end;
11527 
11528             rport = strstr(leftmost, ";rport");
11529 
11530             if (rport) {
11531                end = strchr(rport + 1, ';');
11532                if (end)
11533                   memmove(rport, end, strlen(end) + 1);
11534                else
11535                   *rport = '\0';
11536             }
11537 
11538             /* Add rport to first VIA header if requested */
11539             snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
11540                leftmost, ast_sockaddr_stringify_addr_remote(&p->recv),
11541                ast_sockaddr_port(&p->recv),
11542                others ? "," : "", others ? others : "");
11543          } else {
11544             /* We should *always* add a received to the topmost via */
11545             snprintf(new, sizeof(new), "%s;received=%s%s%s",
11546                leftmost, ast_sockaddr_stringify_addr_remote(&p->recv),
11547                others ? "," : "", others ? others : "");
11548          }
11549          oh = new;   /* the header to copy */
11550       }  /* else add the following via headers untouched */
11551       add_header(req, field, oh);
11552       copied++;
11553    }
11554    if (!copied) {
11555       ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
11556       return -1;
11557    }
11558    return 0;
11559 }
11560 
11561 /*! \brief Add route header into request per learned route */
11562 static void add_route(struct sip_request *req, struct sip_route *route)
11563 {
11564    char r[SIPBUFSIZE*2], *p;
11565    int n, rem = sizeof(r);
11566 
11567    if (!route)
11568       return;
11569 
11570    p = r;
11571    for (;route ; route = route->next) {
11572       n = strlen(route->hop);
11573       if (rem < n+3) /* we need room for ",<route>" */
11574          break;
11575       if (p != r) {  /* add a separator after fist route */
11576          *p++ = ',';
11577          --rem;
11578       }
11579       *p++ = '<';
11580       ast_copy_string(p, route->hop, rem); /* cannot fail */
11581       p += n;
11582       *p++ = '>';
11583       rem -= (n+2);
11584    }
11585    *p = '\0';
11586    add_header(req, "Route", r);
11587 }
11588 
11589 /*! \brief Set destination from SIP URI
11590  *
11591  * Parse uri to h (host) and port - uri is already just the part inside the <>
11592  * general form we are expecting is sip[s]:username[:password][;parameter]@host[:port][;...]
11593  * If there's a port given, turn NAPTR/SRV off. NAPTR might indicate SIPS preference even
11594  * for SIP: uri's
11595  *
11596  * If there's a sips: uri scheme, TLS will be required.
11597  */
11598 static void set_destination(struct sip_pvt *p, char *uri)
11599 {
11600    char *trans, *h, *maddr, hostname[256];
11601    int hn;
11602    int debug=sip_debug_test_pvt(p);
11603    int tls_on = FALSE;
11604 
11605    if (debug)
11606       ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
11607 
11608    if ((trans = strcasestr(uri, ";transport="))) {
11609       trans += strlen(";transport=");
11610 
11611       if (!strncasecmp(trans, "ws", 2)) {
11612          if (debug)
11613             ast_verbose("set_destination: URI is for WebSocket, we can't set destination\n");
11614          return;
11615       }
11616    }
11617 
11618    /* Find and parse hostname */
11619    h = strchr(uri, '@');
11620    if (h)
11621       ++h;
11622    else {
11623       h = uri;
11624       if (!strncasecmp(h, "sip:", 4)) {
11625          h += 4;
11626       } else if (!strncasecmp(h, "sips:", 5)) {
11627          h += 5;
11628          tls_on = TRUE;
11629       }
11630    }
11631    hn = strcspn(h, ";>") + 1;
11632    if (hn > sizeof(hostname))
11633       hn = sizeof(hostname);
11634    ast_copy_string(hostname, h, hn);
11635    /* XXX bug here if string has been trimmed to sizeof(hostname) */
11636    h += hn - 1;
11637 
11638    /*! \todo XXX If we have sip_cfg.srvlookup on, then look for NAPTR/SRV,
11639     * otherwise, just look for A records */
11640    if (ast_sockaddr_resolve_first_transport(&p->sa, hostname, 0, p->socket.type)) {
11641       ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
11642       return;
11643    }
11644 
11645    /* Got the hostname - but maybe there's a "maddr=" to override address? */
11646    maddr = strstr(h, "maddr=");
11647    if (maddr) {
11648       int port;
11649 
11650       maddr += 6;
11651       hn = strspn(maddr, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
11652                     "0123456789-.:[]") + 1;
11653       if (hn > sizeof(hostname))
11654          hn = sizeof(hostname);
11655       ast_copy_string(hostname, maddr, hn);
11656 
11657       port = ast_sockaddr_port(&p->sa);
11658 
11659       /*! \todo XXX If we have sip_cfg.srvlookup on, then look for
11660        * NAPTR/SRV, otherwise, just look for A records */
11661       if (ast_sockaddr_resolve_first_transport(&p->sa, hostname, PARSE_PORT_FORBID, p->socket.type)) {
11662          ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
11663          return;
11664       }
11665 
11666       ast_sockaddr_set_port(&p->sa, port);
11667    }
11668 
11669    if (!ast_sockaddr_port(&p->sa)) {
11670       ast_sockaddr_set_port(&p->sa, tls_on ?
11671                   STANDARD_TLS_PORT : STANDARD_SIP_PORT);
11672    }
11673 
11674    if (debug) {
11675       ast_verbose("set_destination: set destination to %s\n",
11676              ast_sockaddr_stringify(&p->sa));
11677    }
11678 }
11679 
11680 /*! \brief Initialize SIP response, based on SIP request */
11681 static int init_resp(struct sip_request *resp, const char *msg)
11682 {
11683    /* Initialize a response */
11684    memset(resp, 0, sizeof(*resp));
11685    resp->method = SIP_RESPONSE;
11686    if (!(resp->data = ast_str_create(SIP_MIN_PACKET)))
11687       goto e_return;
11688    if (!(resp->content = ast_str_create(SIP_MIN_PACKET)))
11689       goto e_free_data;
11690    resp->header[0] = 0;
11691    ast_str_set(&resp->data, 0, "SIP/2.0 %s\r\n", msg);
11692    resp->headers++;
11693    return 0;
11694 
11695 e_free_data:
11696    ast_free(resp->data);
11697    resp->data = NULL;
11698 e_return:
11699    return -1;
11700 }
11701 
11702 /*! \brief Initialize SIP request */
11703 static int init_req(struct sip_request *req, int sipmethod, const char *recip)
11704 {
11705    /* Initialize a request */
11706    memset(req, 0, sizeof(*req));
11707    if (!(req->data = ast_str_create(SIP_MIN_PACKET)))
11708       goto e_return;
11709    if (!(req->content = ast_str_create(SIP_MIN_PACKET)))
11710       goto e_free_data;
11711    req->method = sipmethod;
11712    req->header[0] = 0;
11713    ast_str_set(&req->data, 0, "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
11714    req->headers++;
11715    return 0;
11716 
11717 e_free_data:
11718    ast_free(req->data);
11719    req->data = NULL;
11720 e_return:
11721    return -1;
11722 }
11723 
11724 /*! \brief Deinitialize SIP response/request */
11725 static void deinit_req(struct sip_request *req)
11726 {
11727    if (req->data) {
11728       ast_free(req->data);
11729       req->data = NULL;
11730    }
11731    if (req->content) {
11732       ast_free(req->content);
11733       req->content = NULL;
11734    }
11735 }
11736 
11737 
11738 /*! \brief Test if this response needs a contact header */
11739 static inline int resp_needs_contact(const char *msg, enum sipmethod method) {
11740    /* Requirements for Contact header inclusion in responses generated
11741     * from the header tables found in the following RFCs.  Where the
11742     * Contact header was marked mandatory (m) or optional (o) this
11743     * function returns 1.
11744     *
11745     * - RFC 3261 (ACK, BYE, CANCEL, INVITE, OPTIONS, REGISTER)
11746     * - RFC 2976 (INFO)
11747     * - RFC 3262 (PRACK)
11748     * - RFC 3265 (SUBSCRIBE, NOTIFY)
11749     * - RFC 3311 (UPDATE)
11750     * - RFC 3428 (MESSAGE)
11751     * - RFC 3515 (REFER)
11752     * - RFC 3903 (PUBLISH)
11753     */
11754 
11755    switch (method) {
11756       /* 1xx, 2xx, 3xx, 485 */
11757       case SIP_INVITE:
11758       case SIP_UPDATE:
11759       case SIP_SUBSCRIBE:
11760       case SIP_NOTIFY:
11761          if ((msg[0] >= '1' && msg[0] <= '3') || !strncmp(msg, "485", 3))
11762             return 1;
11763          break;
11764 
11765       /* 2xx, 3xx, 485 */
11766       case SIP_REGISTER:
11767       case SIP_OPTIONS:
11768          if (msg[0] == '2' || msg[0] == '3' || !strncmp(msg, "485", 3))
11769             return 1;
11770          break;
11771 
11772       /* 3xx, 485 */
11773       case SIP_BYE:
11774       case SIP_PRACK:
11775       case SIP_MESSAGE:
11776       case SIP_PUBLISH:
11777          if (msg[0] == '3' || !strncmp(msg, "485", 3))
11778             return 1;
11779          break;
11780 
11781       /* 2xx, 3xx, 4xx, 5xx, 6xx */
11782       case SIP_REFER:
11783          if (msg[0] >= '2' && msg[0] <= '6')
11784             return 1;
11785          break;
11786 
11787       /* contact will not be included for everything else */
11788       case SIP_ACK:
11789       case SIP_CANCEL:
11790       case SIP_INFO:
11791       case SIP_PING:
11792       default:
11793          return 0;
11794    }
11795    return 0;
11796 }
11797 
11798 /*! \brief Prepare SIP response packet */
11799 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
11800 {
11801    char newto[256];
11802    const char *ot;
11803 
11804    init_resp(resp, msg);
11805    copy_via_headers(p, resp, req, "Via");
11806    if (msg[0] == '1' || msg[0] == '2')
11807       copy_all_header(resp, req, "Record-Route");
11808    copy_header(resp, req, "From");
11809    ot = sip_get_header(req, "To");
11810    if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
11811       /* Add the proper tag if we don't have it already.  If they have specified
11812          their tag, use it.  Otherwise, use our own tag */
11813       if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
11814          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
11815       else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
11816          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
11817       else
11818          ast_copy_string(newto, ot, sizeof(newto));
11819       ot = newto;
11820    }
11821    add_header(resp, "To", ot);
11822    copy_header(resp, req, "Call-ID");
11823    copy_header(resp, req, "CSeq");
11824    if (!ast_strlen_zero(global_useragent))
11825       add_header(resp, "Server", global_useragent);
11826    add_header(resp, "Allow", ALLOWED_METHODS);
11827    add_supported(p, resp);
11828 
11829    /* If this is an invite, add Session-Timers related headers if the feature is active for this session */
11830    if (p->method == SIP_INVITE && p->stimer && p->stimer->st_active == TRUE) {
11831       char se_hdr[256];
11832       snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
11833          p->stimer->st_ref == SESSION_TIMER_REFRESHER_US ? "uas" : "uac");
11834       add_header(resp, "Session-Expires", se_hdr);
11835       /* RFC 2048, Section 9
11836        * If the refresher parameter in the Session-Expires header field in the
11837        * 2xx response has a value of 'uac', the UAS MUST place a Require
11838        * header field into the response with the value 'timer'.
11839        * ...
11840        * If the refresher parameter in
11841        * the 2xx response has a value of 'uas' and the Supported header field
11842        * in the request contained the value 'timer', the UAS SHOULD place a
11843        * Require header field into the response with the value 'timer'
11844        */
11845       if (p->stimer->st_ref == SESSION_TIMER_REFRESHER_THEM ||
11846             (p->stimer->st_ref == SESSION_TIMER_REFRESHER_US &&
11847              p->stimer->st_active_peer_ua == TRUE)) {
11848          resp->reqsipoptions |= SIP_OPT_TIMER;
11849       }
11850    }
11851 
11852    if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_PUBLISH)) {
11853       /* For registration responses, we also need expiry and
11854          contact info */
11855       add_expires(resp, p->expiry);
11856       if (p->expiry) {  /* Only add contact if we have an expiry time */
11857          char contact[SIPBUFSIZE];
11858          const char *contact_uri = p->method == SIP_SUBSCRIBE ? p->our_contact : p->fullcontact;
11859          char *brackets = strchr(contact_uri, '<');
11860          snprintf(contact, sizeof(contact), "%s%s%s;expires=%d", brackets ? "" : "<", contact_uri, brackets ? "" : ">", p->expiry);
11861          add_header(resp, "Contact", contact);  /* Not when we unregister */
11862       }
11863    } else if (!ast_strlen_zero(p->our_contact) && resp_needs_contact(msg, p->method)) {
11864       add_header(resp, "Contact", p->our_contact);
11865    }
11866 
11867    if (!ast_strlen_zero(p->url)) {
11868       add_header(resp, "Access-URL", p->url);
11869       ast_string_field_set(p, url, NULL);
11870    }
11871 
11872    /* default to routing the response to the address where the request
11873     * came from.  Since we don't have a transport layer, we do this here.
11874     * The process_via() function will update the port to either the port
11875     * specified in the via header or the default port later on (per RFC
11876     * 3261 section 18.2.2).
11877     */
11878    p->sa = p->recv;
11879 
11880    if (process_via(p, req)) {
11881       ast_log(LOG_WARNING, "error processing via header, will send response to originating address\n");
11882    }
11883 
11884    return 0;
11885 }
11886 
11887 /*! \brief Initialize a SIP request message (not the initial one in a dialog) */
11888 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, uint32_t seqno, int newbranch)
11889 {
11890    struct sip_request *orig = &p->initreq;
11891    char stripped[80];
11892    char tmp[80];
11893    char newto[256];
11894    const char *c;
11895    const char *ot, *of;
11896    int is_strict = FALSE;     /*!< Strict routing flag */
11897    int is_outbound = ast_test_flag(&p->flags[0], SIP_OUTGOING);   /* Session direction */
11898 
11899    snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
11900 
11901    if (!seqno) {
11902       p->ocseq++;
11903       seqno = p->ocseq;
11904    }
11905 
11906    /* A CANCEL must have the same branch as the INVITE that it is canceling. */
11907    if (sipmethod == SIP_CANCEL) {
11908       p->branch = p->invite_branch;
11909       build_via(p);
11910    } else if (newbranch && (sipmethod == SIP_INVITE)) {
11911       p->branch ^= ast_random();
11912       p->invite_branch = p->branch;
11913       build_via(p);
11914    } else if (newbranch) {
11915       p->branch ^= ast_random();
11916       build_via(p);
11917    }
11918 
11919    /* Check for strict or loose router */
11920    if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop, ";lr") == NULL) {
11921       is_strict = TRUE;
11922       if (sipdebug)
11923          ast_debug(1, "Strict routing enforced for session %s\n", p->callid);
11924    }
11925 
11926    if (sipmethod == SIP_CANCEL)
11927       c = REQ_OFFSET_TO_STR(&p->initreq, rlpart2); /* Use original URI */
11928    else if (sipmethod == SIP_ACK) {
11929       /* Use URI from Contact: in 200 OK (if INVITE)
11930       (we only have the contacturi on INVITEs) */
11931       if (!ast_strlen_zero(p->okcontacturi))
11932          c = is_strict ? p->route->hop : p->okcontacturi;
11933       else
11934          c = REQ_OFFSET_TO_STR(&p->initreq, rlpart2);
11935    } else if (!ast_strlen_zero(p->okcontacturi))
11936       c = is_strict ? p->route->hop : p->okcontacturi; /* Use for BYE or REINVITE */
11937    else if (!ast_strlen_zero(p->uri))
11938       c = p->uri;
11939    else {
11940       char *n;
11941       /* We have no URI, use To: or From:  header as URI (depending on direction) */
11942       ast_copy_string(stripped, sip_get_header(orig, is_outbound ? "To" : "From"),
11943             sizeof(stripped));
11944       n = get_in_brackets(stripped);
11945       c = remove_uri_parameters(n);
11946    }  
11947    init_req(req, sipmethod, c);
11948 
11949    snprintf(tmp, sizeof(tmp), "%u %s", seqno, sip_methods[sipmethod].text);
11950 
11951    add_header(req, "Via", p->via);
11952    /*
11953     * Use the learned route set unless this is a CANCEL on an ACK for a non-2xx
11954     * final response. For a CANCEL or ACK, we have to send to the same destination
11955     * as the original INVITE.
11956     */
11957    if (p->route &&
11958          !(sipmethod == SIP_CANCEL ||
11959             (sipmethod == SIP_ACK && (p->invitestate == INV_COMPLETED || p->invitestate == INV_CANCELLED)))) {
11960       set_destination(p, p->route->hop);
11961       add_route(req, is_strict ? p->route->next : p->route);
11962    }
11963    add_max_forwards(p, req);
11964 
11965    ot = sip_get_header(orig, "To");
11966    of = sip_get_header(orig, "From");
11967 
11968    /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
11969       as our original request, including tag (or presumably lack thereof) */
11970    if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
11971       /* Add the proper tag if we don't have it already.  If they have specified
11972          their tag, use it.  Otherwise, use our own tag */
11973       if (is_outbound && !ast_strlen_zero(p->theirtag))
11974          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
11975       else if (!is_outbound)
11976          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
11977       else
11978          snprintf(newto, sizeof(newto), "%s", ot);
11979       ot = newto;
11980    }
11981 
11982    if (is_outbound) {
11983       add_header(req, "From", of);
11984       add_header(req, "To", ot);
11985    } else {
11986       add_header(req, "From", ot);
11987       add_header(req, "To", of);
11988    }
11989    /* Do not add Contact for MESSAGE, BYE and Cancel requests */
11990    if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
11991       add_header(req, "Contact", p->our_contact);
11992 
11993    copy_header(req, orig, "Call-ID");
11994    add_header(req, "CSeq", tmp);
11995 
11996    if (!ast_strlen_zero(global_useragent))
11997       add_header(req, "User-Agent", global_useragent);
11998 
11999    if (!ast_strlen_zero(p->url)) {
12000       add_header(req, "Access-URL", p->url);
12001       ast_string_field_set(p, url, NULL);
12002    }
12003 
12004    /* Add Session-Timers related headers if the feature is active for this session.
12005       An exception to this behavior is the ACK request. Since Asterisk never requires
12006       session-timers support from a remote end-point (UAS) in an INVITE, it must
12007       not send 'Require: timer' header in the ACK request.
12008       This should only be added in the INVITE transactions, not MESSAGE or REFER or other
12009       in-dialog messages.
12010    */
12011    if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE
12012        && sipmethod == SIP_INVITE) {
12013       char se_hdr[256];
12014       snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
12015          p->stimer->st_ref == SESSION_TIMER_REFRESHER_US ? "uac" : "uas");
12016       add_header(req, "Session-Expires", se_hdr);
12017       snprintf(se_hdr, sizeof(se_hdr), "%d", st_get_se(p, FALSE));
12018       add_header(req, "Min-SE", se_hdr);
12019    }
12020 
12021    return 0;
12022 }
12023 
12024 /*! \brief Base transmit response function */
12025 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
12026 {
12027    struct sip_request resp;
12028    uint32_t seqno = 0;
12029 
12030    if (reliable && (sscanf(sip_get_header(req, "CSeq"), "%30u ", &seqno) != 1)) {
12031       ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", sip_get_header(req, "CSeq"));
12032       return -1;
12033    }
12034    respprep(&resp, p, msg, req);
12035 
12036    if (ast_test_flag(&p->flags[0], SIP_SENDRPID)
12037          && ast_test_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND)
12038          && (!strncmp(msg, "180", 3) || !strncmp(msg, "183", 3))) {
12039       ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
12040       add_rpid(&resp, p);
12041    }
12042    if (ast_test_flag(&p->flags[0], SIP_OFFER_CC)) {
12043       add_cc_call_info_to_response(p, &resp);
12044    }
12045 
12046    /* If we are sending a 302 Redirect we can add a diversion header if the redirect information is set */
12047    if (!strncmp(msg, "302", 3)) {
12048       add_diversion(&resp, p);
12049    }
12050 
12051    /* If we are cancelling an incoming invite for some reason, add information
12052       about the reason why we are doing this in clear text */
12053    if (p->method == SIP_INVITE && msg[0] != '1') {
12054       char buf[20];
12055 
12056       if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON)) {
12057          int hangupcause = 0;
12058 
12059          if (p->owner && ast_channel_hangupcause(p->owner)) {
12060             hangupcause = ast_channel_hangupcause(p->owner);
12061          } else if (p->hangupcause) {
12062             hangupcause = p->hangupcause;
12063          } else {
12064             int respcode;
12065             if (sscanf(msg, "%30d ", &respcode))
12066                hangupcause = hangup_sip2cause(respcode);
12067          }
12068 
12069          if (hangupcause) {
12070             sprintf(buf, "Q.850;cause=%i", hangupcause & 0x7f);
12071             add_header(&resp, "Reason", buf);
12072          }
12073       }
12074 
12075       if (p->owner && ast_channel_hangupcause(p->owner)) {
12076          add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(ast_channel_hangupcause(p->owner)));
12077          snprintf(buf, sizeof(buf), "%d", ast_channel_hangupcause(p->owner));
12078          add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
12079       }
12080    }
12081    return send_response(p, &resp, reliable, seqno);
12082 }
12083 
12084 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)
12085 {
12086    struct sip_request resp;
12087 
12088    if (need_new_etag) {
12089       create_new_sip_etag(esc_entry, 1);
12090    }
12091    respprep(&resp, p, msg, req);
12092    add_header(&resp, "SIP-ETag", esc_entry->entity_tag);
12093 
12094    return send_response(p, &resp, 0, 0);
12095 }
12096 
12097 static int temp_pvt_init(void *data)
12098 {
12099    struct sip_pvt *p = data;
12100 
12101    p->do_history = 0;   /* XXX do we need it ? isn't already all 0 ? */
12102    return ast_string_field_init(p, 512);
12103 }
12104 
12105 static void temp_pvt_cleanup(void *data)
12106 {
12107    struct sip_pvt *p = data;
12108 
12109    ast_string_field_free_memory(p);
12110 
12111    ast_free(data);
12112 }
12113 
12114 /*! \brief Transmit response, no retransmits, using a temporary pvt structure */
12115 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)
12116 {
12117    struct sip_pvt *p = NULL;
12118 
12119    if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
12120       ast_log(LOG_ERROR, "Failed to get temporary pvt\n");
12121       return -1;
12122    }
12123 
12124    /* XXX the structure may be dirty from previous usage.
12125     * Here we should state clearly how we should reinitialize it
12126     * before using it.
12127     * E.g. certainly the threadstorage should be left alone,
12128     * but other thihngs such as flags etc. maybe need cleanup ?
12129     */
12130 
12131    /* Initialize the bare minimum */
12132    p->method = intended_method;
12133 
12134    if (!addr) {
12135       ast_sockaddr_copy(&p->ourip, &internip);
12136    } else {
12137       ast_sockaddr_copy(&p->sa, addr);
12138       ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
12139    }
12140 
12141    p->branch = ast_random();
12142    make_our_tag(p);
12143    p->ocseq = INITIAL_CSEQ;
12144 
12145    if (useglobal_nat && addr) {
12146       ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT_FORCE_RPORT);
12147       ast_copy_flags(&p->flags[2], &global_flags[2], SIP_PAGE3_NAT_AUTO_RPORT);
12148       ast_sockaddr_copy(&p->recv, addr);
12149       check_via(p, req);
12150    }
12151 
12152    ast_string_field_set(p, fromdomain, default_fromdomain);
12153    p->fromdomainport = default_fromdomainport;
12154    build_via(p);
12155    ast_string_field_set(p, callid, callid);
12156 
12157    copy_socket_data(&p->socket, &req->socket);
12158 
12159    /* Use this temporary pvt structure to send the message */
12160    __transmit_response(p, msg, req, XMIT_UNRELIABLE);
12161 
12162    /* Free the string fields, but not the pool space */
12163    ast_string_field_init(p, 0);
12164 
12165    return 0;
12166 }
12167 
12168 /*! \brief Transmit response, no retransmits */
12169 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req)
12170 {
12171    return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
12172 }
12173 
12174 /*! \brief Transmit response, no retransmits */
12175 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported)
12176 {
12177    struct sip_request resp;
12178    respprep(&resp, p, msg, req);
12179    add_date(&resp);
12180    add_header(&resp, "Unsupported", unsupported);
12181    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
12182 }
12183 
12184 /*! \brief Transmit 422 response with Min-SE header (Session-Timers)  */
12185 static int transmit_response_with_minse(struct sip_pvt *p, const char *msg, const struct sip_request *req, int minse_int)
12186 {
12187    struct sip_request resp;
12188    char minse_str[20];
12189 
12190    respprep(&resp, p, msg, req);
12191    add_date(&resp);
12192 
12193    snprintf(minse_str, sizeof(minse_str), "%d", minse_int);
12194    add_header(&resp, "Min-SE", minse_str);
12195    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
12196 }
12197 
12198 
12199 /*! \brief Transmit response, Make sure you get an ACK
12200    This is only used for responses to INVITEs, where we need to make sure we get an ACK
12201 */
12202 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
12203 {
12204    return __transmit_response(p, msg, req, req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL);
12205 }
12206 
12207 /*! \brief Add date header to SIP message */
12208 static void add_date(struct sip_request *req)
12209 {
12210    char tmp[256];
12211    struct tm tm;
12212    time_t t = time(NULL);
12213 
12214    gmtime_r(&t, &tm);
12215    strftime(tmp, sizeof(tmp), "%a, %d %b %Y %T GMT", &tm);
12216    add_header(req, "Date", tmp);
12217 }
12218 
12219 /*! \brief Add Expires header to SIP message */
12220 static void add_expires(struct sip_request *req, int expires)
12221 {
12222    char tmp[32];
12223 
12224    snprintf(tmp, sizeof(tmp), "%d", expires);
12225    add_header(req, "Expires", tmp);
12226 }
12227 
12228 /*! \brief Append Retry-After header field when transmitting response */
12229 static int transmit_response_with_retry_after(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *seconds)
12230 {
12231    struct sip_request resp;
12232    respprep(&resp, p, msg, req);
12233    add_header(&resp, "Retry-After", seconds);
12234    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
12235 }
12236 
12237 /*! \brief Add date before transmitting response */
12238 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
12239 {
12240    struct sip_request resp;
12241    respprep(&resp, p, msg, req);
12242    add_date(&resp);
12243    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
12244 }
12245 
12246 /*! \brief Append Accept header, content length before transmitting response */
12247 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
12248 {
12249    struct sip_request resp;
12250    respprep(&resp, p, msg, req);
12251    add_header(&resp, "Accept", "application/sdp");
12252    return send_response(p, &resp, reliable, 0);
12253 }
12254 
12255 /*! \brief Append Min-Expires header, content length before transmitting response */
12256 static int transmit_response_with_minexpires(struct sip_pvt *p, const char *msg, const struct sip_request *req, int minexpires)
12257 {
12258    struct sip_request resp;
12259    char tmp[32];
12260 
12261    snprintf(tmp, sizeof(tmp), "%d", minexpires);
12262    respprep(&resp, p, msg, req);
12263    add_header(&resp, "Min-Expires", tmp);
12264    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
12265 }
12266 
12267 /*! \brief Respond with authorization request */
12268 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)
12269 {
12270    struct sip_request resp;
12271    char tmp[512];
12272    uint32_t seqno = 0;
12273 
12274    if (reliable && (sscanf(sip_get_header(req, "CSeq"), "%30u ", &seqno) != 1)) {
12275       ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", sip_get_header(req, "CSeq"));
12276       return -1;
12277    }
12278    /* Choose Realm */
12279    get_realm(p, req);
12280 
12281    /* Stale means that they sent us correct authentication, but
12282       based it on an old challenge (nonce) */
12283    snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", p->realm, nonce, stale ? ", stale=true" : "");
12284    respprep(&resp, p, msg, req);
12285    add_header(&resp, header, tmp);
12286    append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
12287    return send_response(p, &resp, reliable, seqno);
12288 }
12289 
12290 /*!
12291  \brief Extract domain from SIP To/From header
12292  \return -1 on error, 1 if domain string is empty, 0 if domain was properly extracted
12293  \note TODO: Such code is all over SIP channel, there is a sense to organize
12294       this patern in one function
12295 */
12296 static int get_domain(const char *str, char *domain, int len)
12297 {
12298    char tmpf[256];
12299    char *a, *from;
12300 
12301    *domain = '\0';
12302    ast_copy_string(tmpf, str, sizeof(tmpf));
12303    from = get_in_brackets(tmpf);
12304    if (!ast_strlen_zero(from)) {
12305       if (strncasecmp(from, "sip:", 4)) {
12306          ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", from);
12307          return -1;
12308       }
12309       from += 4;
12310    } else
12311       from = NULL;
12312 
12313    if (from) {
12314       int bracket = 0;
12315 
12316       /* Strip any params or options from user */
12317       if ((a = strchr(from, ';')))
12318          *a = '\0';
12319       /* Strip port from domain if present */
12320       for (a = from; *a != '\0'; ++a) {
12321          if (*a == ':' && bracket == 0) {
12322             *a = '\0';
12323             break;
12324          } else if (*a == '[') {
12325             ++bracket;
12326          } else if (*a == ']') {
12327             --bracket;
12328          }
12329       }
12330       if ((a = strchr(from, '@'))) {
12331          *a = '\0';
12332          ast_copy_string(domain, a + 1, len);
12333       } else
12334          ast_copy_string(domain, from, len);
12335    }
12336 
12337    return ast_strlen_zero(domain);
12338 }
12339 
12340 /*!
12341   \brief Choose realm based on From header and then To header or use globaly configured realm.
12342   Realm from From/To header should be listed among served domains in config file: domain=...
12343 */
12344 static void get_realm(struct sip_pvt *p, const struct sip_request *req)
12345 {
12346    char domain[MAXHOSTNAMELEN];
12347 
12348    if (!ast_strlen_zero(p->realm))
12349       return;
12350 
12351    if (sip_cfg.domainsasrealm &&
12352        !AST_LIST_EMPTY(&domain_list))
12353    {
12354       /* Check From header first */
12355       if (!get_domain(sip_get_header(req, "From"), domain, sizeof(domain))) {
12356          if (check_sip_domain(domain, NULL, 0)) {
12357             ast_string_field_set(p, realm, domain);
12358             return;
12359          }
12360       }
12361       /* Check To header */
12362       if (!get_domain(sip_get_header(req, "To"), domain, sizeof(domain))) {
12363          if (check_sip_domain(domain, NULL, 0)) {
12364             ast_string_field_set(p, realm, domain);
12365             return;
12366          }
12367       }
12368    }
12369    
12370    /* Use default realm from config file */
12371    ast_string_field_set(p, realm, sip_cfg.realm);
12372 }
12373 
12374 /*!
12375  * \internal
12376  *
12377  * \arg msg Only use a string constant for the msg, here, it is shallow copied
12378  *
12379  * \note assumes the sip_pvt is locked.
12380  */
12381 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp)
12382 {
12383    int res;
12384 
12385    if (!(res = with_sdp ? transmit_response_with_sdp(p, msg, req, XMIT_UNRELIABLE, FALSE, FALSE) : transmit_response(p, msg, req))) {
12386       p->last_provisional = msg;
12387       update_provisional_keepalive(p, with_sdp);
12388    }
12389 
12390    return res;
12391 }
12392 
12393 /*!
12394  * \internal
12395  * \brief Destroy all additional MESSAGE headers.
12396  *
12397  * \param pvt SIP private dialog struct.
12398  *
12399  * \return Nothing
12400  */
12401 static void destroy_msg_headers(struct sip_pvt *pvt)
12402 {
12403    struct sip_msg_hdr *doomed;
12404 
12405    while ((doomed = AST_LIST_REMOVE_HEAD(&pvt->msg_headers, next))) {
12406       ast_free(doomed);
12407    }
12408 }
12409 
12410 /*!
12411  * \internal
12412  * \brief Add a MESSAGE header to the dialog.
12413  *
12414  * \param pvt SIP private dialog struct.
12415  * \param hdr_name Name of header for MESSAGE.
12416  * \param hdr_value Value of header for MESSAGE.
12417  *
12418  * \return Nothing
12419  */
12420 static void add_msg_header(struct sip_pvt *pvt, const char *hdr_name, const char *hdr_value)
12421 {
12422    size_t hdr_len_name;
12423    size_t hdr_len_value;
12424    struct sip_msg_hdr *node;
12425    char *pos;
12426 
12427    hdr_len_name = strlen(hdr_name) + 1;
12428    hdr_len_value = strlen(hdr_value) + 1;
12429 
12430    node = ast_calloc(1, sizeof(*node) + hdr_len_name + hdr_len_value);
12431    if (!node) {
12432       return;
12433    }
12434    pos = node->stuff;
12435    node->name = pos;
12436    strcpy(pos, hdr_name);
12437    pos += hdr_len_name;
12438    node->value = pos;
12439    strcpy(pos, hdr_value);
12440 
12441    AST_LIST_INSERT_TAIL(&pvt->msg_headers, node, next);
12442 }
12443 
12444 /*! \brief Add text body to SIP message */
12445 static int add_text(struct sip_request *req, struct sip_pvt *p)
12446 {
12447    const char *content_type = NULL;
12448    struct sip_msg_hdr *node;
12449 
12450    /* Add any additional MESSAGE headers. */
12451    AST_LIST_TRAVERSE(&p->msg_headers, node, next) {
12452       if (!strcasecmp(node->name, "Content-Type")) {
12453          /* Save content type */
12454          content_type = node->value;
12455       } else {
12456          add_header(req, node->name, node->value);
12457       }
12458    }
12459    if (ast_strlen_zero(content_type)) {
12460       /* "Content-Type" not set - use default value */
12461       content_type = "text/plain;charset=UTF-8";
12462    }
12463    add_header(req, "Content-Type", content_type);
12464 
12465    /* XXX Convert \n's to \r\n's XXX */
12466    add_content(req, p->msg_body);
12467    return 0;
12468 }
12469 
12470 /*! \brief Add DTMF INFO tone to sip message
12471    Mode =   0 for application/dtmf-relay (Cisco)
12472       1 for application/dtmf
12473 */
12474 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode)
12475 {
12476    char tmp[256];
12477    int event;
12478    if (mode) {
12479       /* Application/dtmf short version used by some implementations */
12480       if ('0' <= digit && digit <= '9') {
12481          event = digit - '0';
12482       } else if (digit == '*') {
12483          event = 10;
12484       } else if (digit == '#') {
12485          event = 11;
12486       } else if ('A' <= digit && digit <= 'D') {
12487          event = 12 + digit - 'A';
12488       } else if ('a' <= digit && digit <= 'd') {
12489          event = 12 + digit - 'a';
12490       } else {
12491          /* Unknown digit */
12492          event = 0;
12493       }
12494       snprintf(tmp, sizeof(tmp), "%d\r\n", event);
12495       add_header(req, "Content-Type", "application/dtmf");
12496       add_content(req, tmp);
12497    } else {
12498       /* Application/dtmf-relay as documented by Cisco */
12499       snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
12500       add_header(req, "Content-Type", "application/dtmf-relay");
12501       add_content(req, tmp);
12502    }
12503    return 0;
12504 }
12505 
12506 /*!
12507  * \pre if p->owner exists, it must be locked
12508  * \brief Add Remote-Party-ID header to SIP message
12509  */
12510 static int add_rpid(struct sip_request *req, struct sip_pvt *p)
12511 {
12512    struct ast_str *tmp = ast_str_alloca(256);
12513    char tmp2[256];
12514    char *lid_num;
12515    char *lid_name;
12516    int lid_pres;
12517    const char *fromdomain;
12518    const char *privacy = NULL;
12519    const char *screen = NULL;
12520    struct ast_party_id connected_id;
12521    const char *anonymous_string = "\"Anonymous\" <sip:anonymous@anonymous.invalid>";
12522 
12523    if (!ast_test_flag(&p->flags[0], SIP_SENDRPID)) {
12524       return 0;
12525    }
12526 
12527    if (!p->owner) {
12528       return 0;
12529    }
12530    connected_id = ast_channel_connected_effective_id(p->owner);
12531    lid_num = S_COR(connected_id.number.valid, connected_id.number.str, NULL);
12532    if (!lid_num) {
12533       return 0;
12534    }
12535    lid_name = S_COR(connected_id.name.valid, connected_id.name.str, NULL);
12536    if (!lid_name) {
12537       lid_name = lid_num;
12538    }
12539    lid_pres = ast_party_id_presentation(&connected_id);
12540 
12541    if (((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) &&
12542          (ast_test_flag(&p->flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND) == SIP_PAGE2_TRUST_ID_OUTBOUND_NO)) {
12543       /* If pres is not allowed and we don't trust the peer, we don't apply an RPID header */
12544       return 0;
12545    }
12546 
12547    fromdomain = p->fromdomain;
12548    if (!fromdomain ||
12549          ((ast_test_flag(&p->flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND) == SIP_PAGE2_TRUST_ID_OUTBOUND_YES) &&
12550          !strcmp("anonymous.invalid", fromdomain))) {
12551       /* If the fromdomain is NULL or if it was set to anonymous.invalid due to privacy settings and we trust the peer,
12552        * use the host IP address */
12553       fromdomain = ast_sockaddr_stringify_host_remote(&p->ourip);
12554    }
12555 
12556    lid_num = ast_uri_encode(lid_num, tmp2, sizeof(tmp2), ast_uri_sip_user);
12557 
12558    if (ast_test_flag(&p->flags[0], SIP_SENDRPID_PAI)) {
12559       if (ast_test_flag(&p->flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND) != SIP_PAGE2_TRUST_ID_OUTBOUND_LEGACY) {
12560          /* trust_id_outbound = yes - Always give full information even if it's private, but append a privacy header
12561           * When private data is included */
12562          ast_str_set(&tmp, -1, "\"%s\" <sip:%s@%s>", lid_name, lid_num, fromdomain);
12563          if ((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
12564             add_header(req, "Privacy", "id");
12565          }
12566       } else {
12567          /* trust_id_outbound = legacy - behave in a non RFC-3325 compliant manner and send anonymized data when
12568           * when handling private data. */
12569          if ((lid_pres & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED) {
12570             ast_str_set(&tmp, -1, "\"%s\" <sip:%s@%s>", lid_name, lid_num, fromdomain);
12571          } else {
12572             ast_str_set(&tmp, -1, "%s", anonymous_string);
12573          }
12574       }
12575       add_header(req, "P-Asserted-Identity", ast_str_buffer(tmp));
12576    } else {
12577       ast_str_set(&tmp, -1, "\"%s\" <sip:%s@%s>;party=%s", lid_name, lid_num, fromdomain, p->outgoing_call ? "calling" : "called");
12578 
12579       switch (lid_pres) {
12580       case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
12581       case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
12582          privacy = "off";
12583          screen = "no";
12584          break;
12585       case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
12586       case AST_PRES_ALLOWED_NETWORK_NUMBER:
12587          privacy = "off";
12588          screen = "yes";
12589          break;
12590       case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
12591       case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
12592          privacy = "full";
12593          screen = "no";
12594          break;
12595       case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
12596       case AST_PRES_PROHIB_NETWORK_NUMBER:
12597          privacy = "full";
12598          screen = "yes";
12599          break;
12600       case AST_PRES_NUMBER_NOT_AVAILABLE:
12601          break;
12602       default:
12603          if ((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
12604             privacy = "full";
12605          }
12606          else
12607             privacy = "off";
12608          screen = "no";
12609          break;
12610       }
12611 
12612       if (!ast_strlen_zero(privacy) && !ast_strlen_zero(screen)) {
12613          ast_str_append(&tmp, -1, ";privacy=%s;screen=%s", privacy, screen);
12614       }
12615 
12616       add_header(req, "Remote-Party-ID", ast_str_buffer(tmp));
12617    }
12618    return 0;
12619 }
12620 
12621 /*! \brief add XML encoded media control with update
12622    \note XML: The only way to turn 0 bits of information into a few hundred. (markster) */
12623 static int add_vidupdate(struct sip_request *req)
12624 {
12625    const char *xml_is_a_huge_waste_of_space =
12626       "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
12627       " <media_control>\r\n"
12628       "  <vc_primitive>\r\n"
12629       "   <to_encoder>\r\n"
12630       "    <picture_fast_update>\r\n"
12631       "    </picture_fast_update>\r\n"
12632       "   </to_encoder>\r\n"
12633       "  </vc_primitive>\r\n"
12634       " </media_control>\r\n";
12635    add_header(req, "Content-Type", "application/media_control+xml");
12636    add_content(req, xml_is_a_huge_waste_of_space);
12637    return 0;
12638 }
12639 
12640 /*! \brief Add ICE attributes to SDP */
12641 static void add_ice_to_sdp(struct ast_rtp_instance *instance, struct ast_str **a_buf)
12642 {
12643    struct ast_rtp_engine_ice *ice = ast_rtp_instance_get_ice(instance);
12644    const char *username, *password;
12645    struct ao2_container *candidates;
12646    struct ao2_iterator i;
12647    struct ast_rtp_engine_ice_candidate *candidate;
12648 
12649    /* If no ICE support is present we can't very well add the attributes */
12650    if (!ice || !(candidates = ice->get_local_candidates(instance))) {
12651       return;
12652    }
12653 
12654    if ((username = ice->get_ufrag(instance))) {
12655       ast_str_append(a_buf, 0, "a=ice-ufrag:%s\r\n", username);
12656    }
12657    if ((password = ice->get_password(instance))) {
12658       ast_str_append(a_buf, 0, "a=ice-pwd:%s\r\n", password);
12659    }
12660 
12661    i = ao2_iterator_init(candidates, 0);
12662 
12663    while ((candidate = ao2_iterator_next(&i))) {
12664       ast_str_append(a_buf, 0, "a=candidate:%s %d %s %d ", candidate->foundation, candidate->id, candidate->transport, candidate->priority);
12665       ast_str_append(a_buf, 0, "%s ", ast_sockaddr_stringify_host(&candidate->address));
12666 
12667       if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_SRFLX
12668          && candidate->id == AST_RTP_ICE_COMPONENT_RTCP) {
12669          ast_str_append(a_buf, 0, "%d typ ", ast_sockaddr_port(&candidate->address) + 1);
12670       } else {
12671          ast_str_append(a_buf, 0, "%s typ ", ast_sockaddr_stringify_port(&candidate->address));
12672       }
12673 
12674       if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_HOST) {
12675          ast_str_append(a_buf, 0, "host");
12676       } else if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_SRFLX) {
12677          ast_str_append(a_buf, 0, "srflx");
12678       } else if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_RELAYED) {
12679          ast_str_append(a_buf, 0, "relay");
12680       }
12681 
12682       if (!ast_sockaddr_isnull(&candidate->relay_address)) {
12683          ast_str_append(a_buf, 0, " raddr %s ", ast_sockaddr_stringify_host(&candidate->relay_address));
12684          ast_str_append(a_buf, 0, "rport %s", ast_sockaddr_stringify_port(&candidate->relay_address));
12685       }
12686 
12687       ast_str_append(a_buf, 0, "\r\n");
12688       ao2_ref(candidate, -1);
12689    }
12690 
12691    ao2_iterator_destroy(&i);
12692 
12693    ao2_ref(candidates, -1);
12694 }
12695 
12696 /*! \brief Start ICE negotiation on an RTP instance */
12697 static void start_ice(struct ast_rtp_instance *instance)
12698 {
12699    struct ast_rtp_engine_ice *ice = ast_rtp_instance_get_ice(instance);
12700 
12701    if (!ice) {
12702       return;
12703    }
12704 
12705    ice->start(instance);
12706 }
12707 
12708 /*! \brief Add DTLS attributes to SDP */
12709 static void add_dtls_to_sdp(struct ast_rtp_instance *instance, struct ast_str **a_buf)
12710 {
12711    struct ast_rtp_engine_dtls *dtls;
12712    const char *fingerprint;
12713 
12714    if (!instance || !(dtls = ast_rtp_instance_get_dtls(instance)) || !dtls->active(instance)) {
12715       return;
12716    }
12717 
12718    switch (dtls->get_connection(instance)) {
12719    case AST_RTP_DTLS_CONNECTION_NEW:
12720       ast_str_append(a_buf, 0, "a=connection:new\r\n");
12721       break;
12722    case AST_RTP_DTLS_CONNECTION_EXISTING:
12723       ast_str_append(a_buf, 0, "a=connection:existing\r\n");
12724       break;
12725    default:
12726       break;
12727    }
12728 
12729    switch (dtls->get_setup(instance)) {
12730    case AST_RTP_DTLS_SETUP_ACTIVE:
12731       ast_str_append(a_buf, 0, "a=setup:active\r\n");
12732       break;
12733    case AST_RTP_DTLS_SETUP_PASSIVE:
12734       ast_str_append(a_buf, 0, "a=setup:passive\r\n");
12735       break;
12736    case AST_RTP_DTLS_SETUP_ACTPASS:
12737       ast_str_append(a_buf, 0, "a=setup:actpass\r\n");
12738       break;
12739    case AST_RTP_DTLS_SETUP_HOLDCONN:
12740       ast_str_append(a_buf, 0, "a=setup:holdconn\r\n");
12741       break;
12742    default:
12743       break;
12744    }
12745 
12746    if ((fingerprint = dtls->get_fingerprint(instance, AST_RTP_DTLS_HASH_SHA1))) {
12747       ast_str_append(a_buf, 0, "a=fingerprint:SHA-1 %s\r\n", fingerprint);
12748    }
12749 }
12750 
12751 /*! \brief Add codec offer to SDP offer/answer body in INVITE or 200 OK */
12752 static void add_codec_to_sdp(const struct sip_pvt *p,
12753    struct ast_format *format,
12754    struct ast_str **m_buf,
12755    struct ast_str **a_buf,
12756    int debug,
12757    int *min_packet_size)
12758 {
12759    int rtp_code;
12760    struct ast_format_list fmt;
12761    const char *mime;
12762    unsigned int rate;
12763 
12764    if (debug)
12765       ast_verbose("Adding codec %d (%s) to SDP\n", format->id, ast_getformatname(format));
12766 
12767    if (((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->rtp), 1, format, 0)) == -1) ||
12768        !(mime = ast_rtp_lookup_mime_subtype2(1, format, 0, ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0)) ||
12769        !(rate = ast_rtp_lookup_sample_rate2(1, format, 0))) {
12770       return;
12771    }
12772 
12773    if (p->rtp) {
12774       struct ast_codec_pref *pref = &ast_rtp_instance_get_codecs(p->rtp)->pref;
12775       fmt = ast_codec_pref_getsize(pref, format);
12776    } 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 */
12777       return;
12778    ast_str_append(m_buf, 0, " %d", rtp_code);
12779    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code, mime, rate);
12780 
12781    ast_format_sdp_generate(format, rtp_code, a_buf);
12782 
12783    switch ((int) format->id) {
12784    case AST_FORMAT_G729A:
12785       /* Indicate that we don't support VAD (G.729 annex B) */
12786       ast_str_append(a_buf, 0, "a=fmtp:%d annexb=no\r\n", rtp_code);
12787       break;
12788    case AST_FORMAT_G723_1:
12789       /* Indicate that we don't support VAD (G.723.1 annex A) */
12790       ast_str_append(a_buf, 0, "a=fmtp:%d annexa=no\r\n", rtp_code);
12791       break;
12792    case AST_FORMAT_ILBC:
12793       /* Add information about us using only 20/30 ms packetization */
12794       ast_str_append(a_buf, 0, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
12795       break;
12796    case AST_FORMAT_SIREN7:
12797       /* Indicate that we only expect 32Kbps */
12798       ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=32000\r\n", rtp_code);
12799       break;
12800    case AST_FORMAT_SIREN14:
12801       /* Indicate that we only expect 48Kbps */
12802       ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=48000\r\n", rtp_code);
12803       break;
12804    case AST_FORMAT_G719:
12805       /* Indicate that we only expect 64Kbps */
12806       ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=64000\r\n", rtp_code);
12807       break;
12808    }
12809 
12810    if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
12811       *min_packet_size = fmt.cur_ms;
12812 
12813    /* Our first codec packetization processed cannot be zero */
12814    if ((*min_packet_size)==0 && fmt.cur_ms)
12815       *min_packet_size = fmt.cur_ms;
12816 }
12817 
12818 /*! \brief Add video codec offer to SDP offer/answer body in INVITE or 200 OK */
12819 /* This is different to the audio one now so we can add more caps later */
12820 static void add_vcodec_to_sdp(const struct sip_pvt *p, struct ast_format *format,
12821               struct ast_str **m_buf, struct ast_str **a_buf,
12822               int debug, int *min_packet_size)
12823 {
12824    int rtp_code;
12825    const char *subtype;
12826    unsigned int rate;
12827 
12828    if (!p->vrtp)
12829       return;
12830 
12831    if (debug)
12832       ast_verbose("Adding video codec %d (%s) to SDP\n", format->id, ast_getformatname(format));
12833 
12834    if (((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->vrtp), 1, format, 0)) == -1) ||
12835        !(subtype = ast_rtp_lookup_mime_subtype2(1, format, 0, 0)) ||
12836        !(rate = ast_rtp_lookup_sample_rate2(1, format, 0))) {
12837       return;
12838    }
12839 
12840    ast_str_append(m_buf, 0, " %d", rtp_code);
12841    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code, subtype, rate);
12842 
12843    ast_format_sdp_generate(format, rtp_code, a_buf);
12844 }
12845 
12846 /*! \brief Add text codec offer to SDP offer/answer body in INVITE or 200 OK */
12847 static void add_tcodec_to_sdp(const struct sip_pvt *p, struct ast_format *format,
12848               struct ast_str **m_buf, struct ast_str **a_buf,
12849               int debug, int *min_packet_size)
12850 {
12851    int rtp_code;
12852 
12853    if (!p->trtp)
12854       return;
12855 
12856    if (debug)
12857       ast_verbose("Adding text codec %d (%s) to SDP\n", format->id, ast_getformatname(format));
12858 
12859    if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->trtp), 1, format, 0)) == -1)
12860       return;
12861 
12862    ast_str_append(m_buf, 0, " %d", rtp_code);
12863    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
12864              ast_rtp_lookup_mime_subtype2(1, format, 0, 0),
12865              ast_rtp_lookup_sample_rate2(1, format, 0));
12866    /* Add fmtp code here */
12867 
12868    if (format->id == AST_FORMAT_T140RED) {
12869       struct ast_format tmp_fmt;
12870       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);
12871       ast_str_append(a_buf, 0, "a=fmtp:%d %d/%d/%d\r\n", rtp_code,
12872           t140code,
12873           t140code,
12874           t140code);
12875 
12876    }
12877 }
12878 
12879 
12880 /*! \brief Get Max T.38 Transmission rate from T38 capabilities */
12881 static unsigned int t38_get_rate(enum ast_control_t38_rate rate)
12882 {
12883    switch (rate) {
12884    case AST_T38_RATE_2400:
12885       return 2400;
12886    case AST_T38_RATE_4800:
12887       return 4800;
12888    case AST_T38_RATE_7200:
12889       return 7200;
12890    case AST_T38_RATE_9600:
12891       return 9600;
12892    case AST_T38_RATE_12000:
12893       return 12000;
12894    case AST_T38_RATE_14400:
12895       return 14400;
12896    default:
12897       return 0;
12898    }
12899 }
12900 
12901 /*! \brief Add RFC 2833 DTMF offer to SDP */
12902 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
12903             struct ast_str **m_buf, struct ast_str **a_buf,
12904             int debug)
12905 {
12906    int rtp_code;
12907 
12908    if (debug)
12909       ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype2(0, NULL, format, 0));
12910    if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->rtp), 0, NULL, format)) == -1)
12911       return;
12912 
12913    ast_str_append(m_buf, 0, " %d", rtp_code);
12914    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
12915              ast_rtp_lookup_mime_subtype2(0, NULL, format, 0),
12916              ast_rtp_lookup_sample_rate2(0, NULL, format));
12917    if (format == AST_RTP_DTMF)   /* Indicate we support DTMF and FLASH... */
12918       ast_str_append(a_buf, 0, "a=fmtp:%d 0-16\r\n", rtp_code);
12919 }
12920 
12921 /*! \brief Set all IP media addresses for this call
12922    \note called from add_sdp()
12923 */
12924 static void get_our_media_address(struct sip_pvt *p, int needvideo, int needtext,
12925               struct ast_sockaddr *addr, struct ast_sockaddr *vaddr,
12926               struct ast_sockaddr *taddr, struct ast_sockaddr *dest,
12927               struct ast_sockaddr *vdest, struct ast_sockaddr *tdest)
12928 {
12929    int use_externip = 0;
12930 
12931    /* First, get our address */
12932    ast_rtp_instance_get_local_address(p->rtp, addr);
12933    if (p->vrtp) {
12934       ast_rtp_instance_get_local_address(p->vrtp, vaddr);
12935    }
12936    if (p->trtp) {
12937       ast_rtp_instance_get_local_address(p->trtp, taddr);
12938    }
12939 
12940    /* If our real IP differs from the local address returned by the RTP engine, use it. */
12941    /* The premise is that if we are already using that IP to communicate with the client, */
12942    /* we should be using it for RTP too. */
12943         use_externip = ast_sockaddr_cmp_addr(&p->ourip, addr);
12944 
12945    /* Now, try to figure out where we want them to send data */
12946    /* Is this a re-invite to move the media out, then use the original offer from caller  */
12947    if (!ast_sockaddr_isnull(&p->redirip)) {  /* If we have a redirection IP, use it */
12948       ast_sockaddr_copy(dest, &p->redirip);
12949    } else {
12950       /*
12951        * Audio Destination IP:
12952        *
12953        * 1. Specifically configured media address.
12954        * 2. Local address as specified by the RTP engine.
12955        * 3. The local IP as defined by chan_sip.
12956        *
12957        * Audio Destination Port:
12958        *
12959        * 1. Provided by the RTP engine.
12960        */
12961       ast_sockaddr_copy(dest,
12962               !ast_sockaddr_isnull(&media_address) ? &media_address :
12963               !ast_sockaddr_is_any(addr) && !use_externip ? addr    :
12964               &p->ourip);
12965       ast_sockaddr_set_port(dest, ast_sockaddr_port(addr));
12966    }
12967 
12968    if (needvideo) {
12969       /* Determine video destination */
12970       if (!ast_sockaddr_isnull(&p->vredirip)) {
12971          ast_sockaddr_copy(vdest, &p->vredirip);
12972       } else {
12973          /*
12974           * Video Destination IP:
12975           *
12976           * 1. Specifically configured media address.
12977           * 2. Local address as specified by the RTP engine.
12978           * 3. The local IP as defined by chan_sip.
12979           *
12980           * Video Destination Port:
12981           *
12982           * 1. Provided by the RTP engine.
12983           */
12984          ast_sockaddr_copy(vdest,
12985                  !ast_sockaddr_isnull(&media_address) ? &media_address :
12986                  !ast_sockaddr_is_any(vaddr) && !use_externip ? vaddr  :
12987                  &p->ourip);
12988          ast_sockaddr_set_port(vdest, ast_sockaddr_port(vaddr));
12989       }
12990    }
12991 
12992    if (needtext) {
12993       /* Determine text destination */
12994       if (!ast_sockaddr_isnull(&p->tredirip)) {
12995          ast_sockaddr_copy(tdest, &p->tredirip);
12996       } else {
12997          /*
12998           * Text Destination IP:
12999           *
13000           * 1. Specifically configured media address.
13001           * 2. Local address as specified by the RTP engine.
13002           * 3. The local IP as defined by chan_sip.
13003           *
13004           * Text Destination Port:
13005           *
13006           * 1. Provided by the RTP engine.
13007           */
13008          ast_sockaddr_copy(tdest,
13009                  !ast_sockaddr_isnull(&media_address) ? &media_address  :
13010                  !ast_sockaddr_is_any(taddr) && !use_externip ? taddr   :
13011                  &p->ourip);
13012          ast_sockaddr_set_port(tdest, ast_sockaddr_port(taddr));
13013       }
13014    }
13015 }
13016 
13017 static void get_crypto_attrib(struct sip_pvt *p, struct sip_srtp *srtp, const char **a_crypto)
13018 {
13019    int taglen = 80;
13020 
13021    /* Set encryption properties */
13022    if (srtp) {
13023       if (!srtp->crypto) {
13024          srtp->crypto = sdp_crypto_setup();
13025       }
13026 
13027       if (p->dtls_cfg.enabled) {
13028          /* If DTLS-SRTP is enabled the key details will be pulled from TLS */
13029          return;
13030       }
13031 
13032       /* set the key length based on INVITE or settings */
13033       if (ast_test_flag(srtp, SRTP_CRYPTO_TAG_80)) {
13034          taglen = 80;
13035       } else if (ast_test_flag(&p->flags[2], SIP_PAGE3_SRTP_TAG_32) ||
13036           ast_test_flag(srtp, SRTP_CRYPTO_TAG_32)) {
13037          taglen = 32;
13038       }
13039 
13040       if (srtp->crypto && (sdp_crypto_offer(srtp->crypto, taglen) >= 0)) {
13041          *a_crypto = sdp_crypto_attrib(srtp->crypto);
13042       }
13043 
13044       if (!*a_crypto) {
13045          ast_log(LOG_WARNING, "No SRTP key management enabled\n");
13046       }
13047    }
13048 }
13049 
13050 static char *get_sdp_rtp_profile(const struct sip_pvt *p, unsigned int secure, struct ast_rtp_instance *instance)
13051 {
13052    struct ast_rtp_engine_dtls *dtls;
13053 
13054    if ((dtls = ast_rtp_instance_get_dtls(instance)) && dtls->active(instance)) {
13055       return ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF) ? "UDP/TLS/RTP/SAVPF" : "UDP/TLS/RTP/SAVP";
13056    } else {
13057       if (ast_test_flag(&p->flags[2], SIP_PAGE3_USE_AVPF)) {
13058          return secure ? "RTP/SAVPF" : "RTP/AVPF";
13059       } else {
13060          return secure ? "RTP/SAVP" : "RTP/AVP";
13061       }
13062    }
13063 }
13064 
13065 /*! \brief Add Session Description Protocol message
13066 
13067     If oldsdp is TRUE, then the SDP version number is not incremented. This mechanism
13068     is used in Session-Timers where RE-INVITEs are used for refreshing SIP sessions
13069     without modifying the media session in any way.
13070 */
13071 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38)
13072 {
13073    struct ast_format_cap *alreadysent = ast_format_cap_alloc_nolock();
13074    struct ast_format_cap *tmpcap = ast_format_cap_alloc_nolock();
13075    int res = AST_SUCCESS;
13076    int doing_directmedia = FALSE;
13077    struct ast_sockaddr addr = { {0,} };
13078    struct ast_sockaddr vaddr = { {0,} };
13079    struct ast_sockaddr taddr = { {0,} };
13080    struct ast_sockaddr udptladdr = { {0,} };
13081    struct ast_sockaddr dest = { {0,} };
13082    struct ast_sockaddr vdest = { {0,} };
13083    struct ast_sockaddr tdest = { {0,} };
13084    struct ast_sockaddr udptldest = { {0,} };
13085 
13086    /* SDP fields */
13087    struct offered_media *offer;
13088    char *version =   "v=0\r\n";     /* Protocol version */
13089    char subject[256];            /* Subject of the session */
13090    char owner[256];           /* Session owner/creator */
13091    char connection[256];            /* Connection data */
13092    char *session_time = "t=0 0\r\n";         /* Time the session is active */
13093    char bandwidth[256] = "";        /* Max bitrate */
13094    char *hold = "";
13095    struct ast_str *m_audio = ast_str_alloca(256);  /* Media declaration line for audio */
13096    struct ast_str *m_video = ast_str_alloca(256);  /* Media declaration line for video */
13097    struct ast_str *m_text = ast_str_alloca(256);   /* Media declaration line for text */
13098    struct ast_str *m_modem = ast_str_alloca(256);  /* Media declaration line for modem */
13099    struct ast_str *a_audio = ast_str_create(256); /* Attributes for audio */
13100    struct ast_str *a_video = ast_str_create(256); /* Attributes for video */
13101    struct ast_str *a_text = ast_str_create(256);  /* Attributes for text */
13102    struct ast_str *a_modem = ast_str_alloca(1024); /* Attributes for modem */
13103    const char *a_crypto = NULL;
13104    const char *v_a_crypto = NULL;
13105    const char *t_a_crypto = NULL;
13106 
13107    int x;
13108    struct ast_format tmp_fmt;
13109    int needaudio = FALSE;
13110    int needvideo = FALSE;
13111    int needtext = FALSE;
13112    int debug = sip_debug_test_pvt(p);
13113    int min_audio_packet_size = 0;
13114    int min_video_packet_size = 0;
13115    int min_text_packet_size = 0;
13116 
13117    char codecbuf[SIPBUFSIZE];
13118    char buf[SIPBUFSIZE];
13119 
13120    /* Set the SDP session name */
13121    snprintf(subject, sizeof(subject), "s=%s\r\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
13122 
13123    if (!alreadysent || !tmpcap) {
13124       res = AST_FAILURE;
13125       goto add_sdp_cleanup;
13126    }
13127    if (!p->rtp) {
13128       ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
13129       res = AST_FAILURE;
13130       goto add_sdp_cleanup;
13131 
13132    }
13133    /* XXX We should not change properties in the SIP dialog until
13134       we have acceptance of the offer if this is a re-invite */
13135 
13136    /* Set RTP Session ID and version */
13137    if (!p->sessionid) {
13138       p->sessionid = (int)ast_random();
13139       p->sessionversion = p->sessionid;
13140    } else {
13141       if (oldsdp == FALSE)
13142          p->sessionversion++;
13143    }
13144 
13145    if (add_audio) {
13146       doing_directmedia = (!ast_sockaddr_isnull(&p->redirip) && !(ast_format_cap_is_empty(p->redircaps))) ? TRUE : FALSE;
13147       /* Check if we need video in this call */
13148       if ((ast_format_cap_has_type(p->jointcaps, AST_FORMAT_TYPE_VIDEO)) && !p->novideo) {
13149          ast_format_cap_joint_copy(p->jointcaps, p->redircaps, tmpcap);
13150          if (doing_directmedia && !ast_format_cap_has_type(tmpcap, AST_FORMAT_TYPE_VIDEO)) {
13151             ast_debug(2, "This call needs video offers, but caller probably did not offer it!\n");
13152          } else if (p->vrtp) {
13153             needvideo = TRUE;
13154             ast_debug(2, "This call needs video offers!\n");
13155          } else {
13156             ast_debug(2, "This call needs video offers, but there's no video support enabled!\n");
13157          }
13158       }
13159       /* Check if we need text in this call */
13160       if ((ast_format_cap_has_type(p->jointcaps, AST_FORMAT_TYPE_TEXT)) && !p->notext) {
13161          if (sipdebug_text)
13162             ast_verbose("We think we can do text\n");
13163          if (p->trtp) {
13164             if (sipdebug_text) {
13165                ast_verbose("And we have a text rtp object\n");
13166             }
13167             needtext = TRUE;
13168             ast_debug(2, "This call needs text offers! \n");
13169          } else {
13170             ast_debug(2, "This call needs text offers, but there's no text support enabled ! \n");
13171          }
13172       }
13173    }
13174 
13175    get_our_media_address(p, needvideo, needtext, &addr, &vaddr, &taddr, &dest, &vdest, &tdest);
13176 
13177    snprintf(owner, sizeof(owner), "o=%s %d %d IN %s %s\r\n",
13178        ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner,
13179        p->sessionid, p->sessionversion,
13180        (ast_sockaddr_is_ipv6(&dest) && !ast_sockaddr_is_ipv4_mapped(&dest)) ?
13181          "IP6" : "IP4",
13182        ast_sockaddr_stringify_addr_remote(&dest));
13183 
13184    snprintf(connection, sizeof(connection), "c=IN %s %s\r\n",
13185        (ast_sockaddr_is_ipv6(&dest) && !ast_sockaddr_is_ipv4_mapped(&dest)) ?
13186          "IP6" : "IP4",
13187        ast_sockaddr_stringify_addr_remote(&dest));
13188 
13189    if (add_audio) {
13190       if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR) {
13191          hold = "a=recvonly\r\n";
13192          doing_directmedia = FALSE;
13193       } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE) {
13194          hold = "a=inactive\r\n";
13195          doing_directmedia = FALSE;
13196       } else {
13197          hold = "a=sendrecv\r\n";
13198       }
13199 
13200       ast_format_cap_copy(tmpcap, p->jointcaps);
13201 
13202       /* XXX note, Video and Text are negated - 'true' means 'no' */
13203       ast_debug(1, "** Our capability: %s Video flag: %s Text flag: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), tmpcap),
13204            p->novideo ? "True" : "False", p->notext ? "True" : "False");
13205       ast_debug(1, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcaps));
13206 
13207       if (doing_directmedia) {
13208          ast_format_cap_joint_copy(p->jointcaps, p->redircaps, tmpcap);
13209          ast_debug(1, "** Our native-bridge filtered capablity: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), tmpcap));
13210       }
13211 
13212       /* Check if we need audio */
13213       if (ast_format_cap_has_type(tmpcap, AST_FORMAT_TYPE_AUDIO))
13214          needaudio = TRUE;
13215 
13216       if (debug) {
13217          ast_verbose("Audio is at %s\n", ast_sockaddr_stringify_port(&addr));
13218       }
13219 
13220       /* Ok, we need video. Let's add what we need for video and set codecs.
13221          Video is handled differently than audio since we can not transcode. */
13222       if (needvideo) {
13223          get_crypto_attrib(p, p->vsrtp, &v_a_crypto);
13224          ast_str_append(&m_video, 0, "m=video %d %s", ast_sockaddr_port(&vdest),
13225                    get_sdp_rtp_profile(p, v_a_crypto ? 1 : 0, p->vrtp));
13226 
13227          /* Build max bitrate string */
13228          if (p->maxcallbitrate)
13229             snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
13230          if (debug) {
13231             ast_verbose("Video is at %s\n", ast_sockaddr_stringify(&vdest));
13232          }
13233 
13234          if (!doing_directmedia) {
13235             if (ast_test_flag(&p->flags[2], SIP_PAGE3_ICE_SUPPORT)) {
13236                add_ice_to_sdp(p->vrtp, &a_video);
13237             }
13238 
13239             add_dtls_to_sdp(p->vrtp, &a_video);
13240          }
13241       }
13242 
13243       /* Ok, we need text. Let's add what we need for text and set codecs.
13244          Text is handled differently than audio since we can not transcode. */
13245       if (needtext) {
13246          if (sipdebug_text)
13247             ast_verbose("Lets set up the text sdp\n");
13248          get_crypto_attrib(p, p->tsrtp, &t_a_crypto);
13249          ast_str_append(&m_text, 0, "m=text %d %s", ast_sockaddr_port(&tdest),
13250                    get_sdp_rtp_profile(p, t_a_crypto ? 1 : 0, p->trtp));
13251          if (debug) {  /* XXX should I use tdest below ? */
13252             ast_verbose("Text is at %s\n", ast_sockaddr_stringify(&taddr));
13253          }
13254 
13255          if (!doing_directmedia) {
13256             if (ast_test_flag(&p->flags[2], SIP_PAGE3_ICE_SUPPORT)) {
13257                add_ice_to_sdp(p->trtp, &a_text);
13258             }
13259 
13260             add_dtls_to_sdp(p->trtp, &a_text);
13261          }
13262       }
13263 
13264       /* Start building generic SDP headers */
13265 
13266       /* We break with the "recommendation" and send our IP, in order that our
13267          peer doesn't have to ast_gethostbyname() us */
13268 
13269       get_crypto_attrib(p, p->srtp, &a_crypto);
13270       ast_str_append(&m_audio, 0, "m=audio %d %s", ast_sockaddr_port(&dest),
13271                 get_sdp_rtp_profile(p, a_crypto ? 1 : 0, p->rtp));
13272 
13273       /* Now, start adding audio codecs. These are added in this order:
13274          - First what was requested by the calling channel
13275          - Then preferences in order from sip.conf device config for this peer/user
13276          - Then other codecs in capabilities, including video
13277       */
13278 
13279       /* Prefer the audio codec we were requested to use, first, no matter what
13280          Note that p->prefcodec can include video codecs, so ignore them
13281       */
13282       ast_format_cap_iter_start(p->prefcaps);
13283       while (!(ast_format_cap_iter_next(p->prefcaps, &tmp_fmt))) {
13284          if (AST_FORMAT_GET_TYPE(tmp_fmt.id) != AST_FORMAT_TYPE_AUDIO ||
13285             !ast_format_cap_iscompatible(tmpcap, &tmp_fmt)) {
13286             continue;
13287          }
13288          add_codec_to_sdp(p, &tmp_fmt, &m_audio, &a_audio, debug, &min_audio_packet_size);
13289          ast_format_cap_add(alreadysent, &tmp_fmt);
13290       }
13291       ast_format_cap_iter_end(p->prefcaps);
13292 
13293       /* Start by sending our preferred audio/video codecs */
13294       for (x = 0; x < AST_CODEC_PREF_SIZE; x++) {
13295          struct ast_format pref;
13296 
13297          if (!(ast_codec_pref_index(&p->prefs, x, &pref)))
13298             break;
13299 
13300          if (!ast_format_cap_get_compatible_format(tmpcap, &pref, &tmp_fmt))
13301             continue;
13302 
13303          if (ast_format_cap_iscompatible(alreadysent, &tmp_fmt))
13304             continue;
13305 
13306          if (AST_FORMAT_GET_TYPE(tmp_fmt.id) == AST_FORMAT_TYPE_AUDIO) {
13307             add_codec_to_sdp(p, &tmp_fmt, &m_audio, &a_audio, debug, &min_audio_packet_size);
13308          } else if (needvideo && (AST_FORMAT_GET_TYPE(tmp_fmt.id) == AST_FORMAT_TYPE_VIDEO)) {
13309             add_vcodec_to_sdp(p, &tmp_fmt, &m_video, &a_video, debug, &min_video_packet_size);
13310          } else if (needtext && (AST_FORMAT_GET_TYPE(tmp_fmt.id) == AST_FORMAT_TYPE_TEXT)) {
13311             add_tcodec_to_sdp(p, &tmp_fmt, &m_text, &a_text, debug, &min_text_packet_size);
13312          }
13313 
13314          ast_format_cap_add(alreadysent, &tmp_fmt);
13315       }
13316 
13317       /* Now send any other common audio and video codecs, and non-codec formats: */
13318       ast_format_cap_iter_start(tmpcap);
13319       while (!(ast_format_cap_iter_next(tmpcap, &tmp_fmt))) {
13320          if (ast_format_cap_iscompatible(alreadysent, &tmp_fmt))
13321             continue;
13322 
13323          if (AST_FORMAT_GET_TYPE(tmp_fmt.id) == AST_FORMAT_TYPE_AUDIO) {
13324             add_codec_to_sdp(p, &tmp_fmt, &m_audio, &a_audio, debug, &min_audio_packet_size);
13325          } else if (needvideo && (AST_FORMAT_GET_TYPE(tmp_fmt.id) == AST_FORMAT_TYPE_VIDEO)) {
13326             add_vcodec_to_sdp(p, &tmp_fmt, &m_video, &a_video, debug, &min_video_packet_size);
13327          } else if (needtext && (AST_FORMAT_GET_TYPE(tmp_fmt.id) == AST_FORMAT_TYPE_TEXT)) {
13328             add_tcodec_to_sdp(p, &tmp_fmt, &m_text, &a_text, debug, &min_text_packet_size);
13329          }
13330       }
13331       ast_format_cap_iter_end(tmpcap);
13332 
13333       /* Now add DTMF RFC2833 telephony-event as a codec */
13334       for (x = 1LL; x <= AST_RTP_MAX; x <<= 1) {
13335          if (!(p->jointnoncodeccapability & x))
13336             continue;
13337 
13338          add_noncodec_to_sdp(p, x, &m_audio, &a_audio, debug);
13339       }
13340 
13341       ast_debug(3, "-- Done with adding codecs to SDP\n");
13342 
13343       if (!p->owner || !ast_internal_timing_enabled(p->owner))
13344          ast_str_append(&a_audio, 0, "a=silenceSupp:off - - - -\r\n");
13345 
13346       if (min_audio_packet_size)
13347          ast_str_append(&a_audio, 0, "a=ptime:%d\r\n", min_audio_packet_size);
13348 
13349       /* XXX don't think you can have ptime for video */
13350       if (min_video_packet_size)
13351          ast_str_append(&a_video, 0, "a=ptime:%d\r\n", min_video_packet_size);
13352 
13353       /* XXX don't think you can have ptime for text */
13354       if (min_text_packet_size)
13355          ast_str_append(&a_text, 0, "a=ptime:%d\r\n", min_text_packet_size);
13356 
13357       if (!doing_directmedia) {
13358          if (ast_test_flag(&p->flags[2], SIP_PAGE3_ICE_SUPPORT)) {
13359             add_ice_to_sdp(p->rtp, &a_audio);
13360          }
13361 
13362          add_dtls_to_sdp(p->rtp, &a_audio);
13363       }
13364    }
13365 
13366    if (add_t38) {
13367       /* Our T.38 end is */
13368       ast_udptl_get_us(p->udptl, &udptladdr);
13369 
13370       /* We don't use directmedia for T.38, so keep the destination the same as our IP address. */
13371       ast_sockaddr_copy(&udptldest, &p->ourip);
13372       ast_sockaddr_set_port(&udptldest, ast_sockaddr_port(&udptladdr));
13373 
13374       if (debug) {
13375          ast_debug(1, "T.38 UDPTL is at %s port %d\n", ast_sockaddr_stringify_addr(&p->ourip), ast_sockaddr_port(&udptladdr));
13376       }
13377 
13378       /* We break with the "recommendation" and send our IP, in order that our
13379          peer doesn't have to ast_gethostbyname() us */
13380 
13381       ast_str_append(&m_modem, 0, "m=image %d udptl t38\r\n", ast_sockaddr_port(&udptldest));
13382 
13383       if (ast_sockaddr_cmp(&udptldest, &dest)) {
13384          ast_str_append(&m_modem, 0, "c=IN %s %s\r\n",
13385                (ast_sockaddr_is_ipv6(&udptldest) && !ast_sockaddr_is_ipv4_mapped(&udptldest)) ?
13386                "IP6" : "IP4", ast_sockaddr_stringify_addr_remote(&udptldest));
13387       }
13388 
13389       ast_str_append(&a_modem, 0, "a=T38FaxVersion:%d\r\n", p->t38.our_parms.version);
13390       ast_str_append(&a_modem, 0, "a=T38MaxBitRate:%d\r\n", t38_get_rate(p->t38.our_parms.rate));
13391       if (p->t38.our_parms.fill_bit_removal) {
13392          ast_str_append(&a_modem, 0, "a=T38FaxFillBitRemoval\r\n");
13393       }
13394       if (p->t38.our_parms.transcoding_mmr) {
13395          ast_str_append(&a_modem, 0, "a=T38FaxTranscodingMMR\r\n");
13396       }
13397       if (p->t38.our_parms.transcoding_jbig) {
13398          ast_str_append(&a_modem, 0, "a=T38FaxTranscodingJBIG\r\n");
13399       }
13400       switch (p->t38.our_parms.rate_management) {
13401       case AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF:
13402          ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:transferredTCF\r\n");
13403          break;
13404       case AST_T38_RATE_MANAGEMENT_LOCAL_TCF:
13405          ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:localTCF\r\n");
13406          break;
13407       }
13408       ast_str_append(&a_modem, 0, "a=T38FaxMaxDatagram:%u\r\n", ast_udptl_get_local_max_datagram(p->udptl));
13409       switch (ast_udptl_get_error_correction_scheme(p->udptl)) {
13410       case UDPTL_ERROR_CORRECTION_NONE:
13411          break;
13412       case UDPTL_ERROR_CORRECTION_FEC:
13413          ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPFEC\r\n");
13414          break;
13415       case UDPTL_ERROR_CORRECTION_REDUNDANCY:
13416          ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPRedundancy\r\n");
13417          break;
13418       }
13419    }
13420 
13421    if (needaudio)
13422       ast_str_append(&m_audio, 0, "\r\n");
13423    if (needvideo)
13424       ast_str_append(&m_video, 0, "\r\n");
13425    if (needtext)
13426       ast_str_append(&m_text, 0, "\r\n");
13427 
13428    add_header(resp, "Content-Type", "application/sdp");
13429    add_content(resp, version);
13430    add_content(resp, owner);
13431    add_content(resp, subject);
13432    add_content(resp, connection);
13433    /* only if video response is appropriate */
13434    if (needvideo) {
13435       add_content(resp, bandwidth);
13436    }
13437    add_content(resp, session_time);
13438    /* if this is a response to an invite, order our offers properly */
13439    if (!AST_LIST_EMPTY(&p->offered_media)) {
13440       AST_LIST_TRAVERSE(&p->offered_media, offer, next) {
13441          switch (offer->type) {
13442          case SDP_AUDIO:
13443             if (needaudio) {
13444                add_content(resp, ast_str_buffer(m_audio));
13445                add_content(resp, ast_str_buffer(a_audio));
13446                add_content(resp, hold);
13447                if (a_crypto) {
13448                   add_content(resp, a_crypto);
13449                }
13450             } else {
13451                add_content(resp, offer->decline_m_line);
13452             }
13453             break;
13454          case SDP_VIDEO:
13455             if (needvideo) { /* only if video response is appropriate */
13456                add_content(resp, ast_str_buffer(m_video));
13457                add_content(resp, ast_str_buffer(a_video));
13458                add_content(resp, hold);   /* Repeat hold for the video stream */
13459                if (v_a_crypto) {
13460                   add_content(resp, v_a_crypto);
13461                }
13462             } else {
13463                add_content(resp, offer->decline_m_line);
13464             }
13465             break;
13466          case SDP_TEXT:
13467             if (needtext) { /* only if text response is appropriate */
13468                add_content(resp, ast_str_buffer(m_text));
13469                add_content(resp, ast_str_buffer(a_text));
13470                add_content(resp, hold);   /* Repeat hold for the text stream */
13471                if (t_a_crypto) {
13472                   add_content(resp, t_a_crypto);
13473                }
13474             } else {
13475                add_content(resp, offer->decline_m_line);
13476             }
13477             break;
13478          case SDP_IMAGE:
13479             if (add_t38) {
13480                add_content(resp, ast_str_buffer(m_modem));
13481                add_content(resp, ast_str_buffer(a_modem));
13482             } else {
13483                add_content(resp, offer->decline_m_line);
13484             }
13485             break;
13486          case SDP_UNKNOWN:
13487             add_content(resp, offer->decline_m_line);
13488             break;
13489          }
13490       }
13491    } else {
13492       /* generate new SDP from scratch, no offers */
13493       if (needaudio) {
13494          add_content(resp, ast_str_buffer(m_audio));
13495          add_content(resp, ast_str_buffer(a_audio));
13496          add_content(resp, hold);
13497          if (a_crypto) {
13498             add_content(resp, a_crypto);
13499          }
13500       }
13501       if (needvideo) { /* only if video response is appropriate */
13502          add_content(resp, ast_str_buffer(m_video));
13503          add_content(resp, ast_str_buffer(a_video));
13504          add_content(resp, hold);   /* Repeat hold for the video stream */
13505          if (v_a_crypto) {
13506             add_content(resp, v_a_crypto);
13507          }
13508       }
13509       if (needtext) { /* only if text response is appropriate */
13510          add_content(resp, ast_str_buffer(m_text));
13511          add_content(resp, ast_str_buffer(a_text));
13512          add_content(resp, hold);   /* Repeat hold for the text stream */
13513          if (t_a_crypto) {
13514             add_content(resp, t_a_crypto);
13515          }
13516       }
13517       if (add_t38) {
13518          add_content(resp, ast_str_buffer(m_modem));
13519          add_content(resp, ast_str_buffer(a_modem));
13520       }
13521    }
13522 
13523    /* Update lastrtprx when we send our SDP */
13524    p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
13525 
13526    /*
13527     * We unlink this dialog and link again into the
13528     * dialogs_rtpcheck container so its not in there twice.
13529     */
13530    ao2_lock(dialogs_rtpcheck);
13531    ao2_t_unlink(dialogs_rtpcheck, p, "unlink pvt into dialogs_rtpcheck container");
13532    ao2_t_link(dialogs_rtpcheck, p, "link pvt into dialogs_rtpcheck container");
13533    ao2_unlock(dialogs_rtpcheck);
13534 
13535    ast_debug(3, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, tmpcap));
13536 
13537 add_sdp_cleanup:
13538    ast_free(a_text);
13539    ast_free(a_video);
13540    ast_free(a_audio);
13541    alreadysent = ast_format_cap_destroy(alreadysent);
13542    tmpcap = ast_format_cap_destroy(tmpcap);
13543 
13544    return res;
13545 }
13546 
13547 /*! \brief Used for 200 OK and 183 early media */
13548 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
13549 {
13550    struct sip_request resp;
13551    uint32_t seqno;
13552 
13553    if (sscanf(sip_get_header(req, "CSeq"), "%30u ", &seqno) != 1) {
13554       ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", sip_get_header(req, "CSeq"));
13555       return -1;
13556    }
13557    respprep(&resp, p, msg, req);
13558    if (p->udptl) {
13559       add_sdp(&resp, p, 0, 0, 1);
13560    } else
13561       ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
13562    if (retrans && !p->pendinginvite)
13563       p->pendinginvite = seqno;     /* Buggy clients sends ACK on RINGING too */
13564    return send_response(p, &resp, retrans, seqno);
13565 }
13566 
13567 /*! \brief copy SIP request (mostly used to save request for responses) */
13568 static void copy_request(struct sip_request *dst, const struct sip_request *src)
13569 {
13570    /* XXX this function can encounter memory allocation errors, perhaps it
13571     * should return a value */
13572 
13573    struct ast_str *duplicate = dst->data;
13574    struct ast_str *duplicate_content = dst->content;
13575 
13576    /* copy the entire request then restore the original data and content
13577     * members from the dst request */
13578    *dst = *src;
13579    dst->data = duplicate;
13580    dst->content = duplicate_content;
13581 
13582    /* copy the data into the dst request */
13583    if (!dst->data && !(dst->data = ast_str_create(ast_str_strlen(src->data) + 1))) {
13584       return;
13585    }
13586    ast_str_copy_string(&dst->data, src->data);
13587 
13588    /* copy the content into the dst request (if it exists) */
13589    if (src->content) {
13590       if (!dst->content && !(dst->content = ast_str_create(ast_str_strlen(src->content) + 1))) {
13591          return;
13592       }
13593       ast_str_copy_string(&dst->content, src->content);
13594    }
13595 }
13596 
13597 static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp)
13598 {
13599    char uri[SIPBUFSIZE];
13600    struct ast_str *header = ast_str_alloca(SIPBUFSIZE);
13601    struct ast_cc_agent *agent = find_sip_cc_agent_by_original_callid(p);
13602    struct sip_cc_agent_pvt *agent_pvt;
13603 
13604    if (!agent) {
13605       /* Um, what? How could the SIP_OFFER_CC flag be set but there not be an
13606        * agent? Oh well, we'll just warn and return without adding the header.
13607        */
13608       ast_log(LOG_WARNING, "Can't find SIP CC agent for call '%s' even though OFFER_CC flag was set?\n", p->callid);
13609       return;
13610    }
13611 
13612    agent_pvt = agent->private_data;
13613 
13614    if (!ast_strlen_zero(agent_pvt->subscribe_uri)) {
13615       ast_copy_string(uri, agent_pvt->subscribe_uri, sizeof(uri));
13616    } else {
13617       generate_uri(p, uri, sizeof(uri));
13618       ast_copy_string(agent_pvt->subscribe_uri, uri, sizeof(agent_pvt->subscribe_uri));
13619    }
13620    /* XXX Hardcode "NR" as the m reason for now. This should perhaps be changed
13621     * to be more accurate. This parameter has no bearing on the actual operation
13622     * of the feature; it's just there for informational purposes.
13623     */
13624    ast_str_set(&header, 0, "<%s>;purpose=call-completion;m=%s", uri, "NR");
13625    add_header(resp, "Call-Info", ast_str_buffer(header));
13626    ao2_ref(agent, -1);
13627 }
13628 
13629 /*! \brief Used for 200 OK and 183 early media
13630    \return Will return XMIT_ERROR for network errors.
13631 */
13632 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)
13633 {
13634    struct sip_request resp;
13635    uint32_t seqno;
13636    if (sscanf(sip_get_header(req, "CSeq"), "%30u ", &seqno) != 1) {
13637       ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", sip_get_header(req, "CSeq"));
13638       return -1;
13639    }
13640    respprep(&resp, p, msg, req);
13641    if (rpid == TRUE) {
13642       add_rpid(&resp, p);
13643    }
13644    if (ast_test_flag(&p->flags[0], SIP_OFFER_CC)) {
13645       add_cc_call_info_to_response(p, &resp);
13646    }
13647    if (p->rtp) {
13648       if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
13649          ast_debug(1, "Setting framing from config on incoming call\n");
13650          ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &p->prefs);
13651       }
13652       ast_rtp_instance_activate(p->rtp);
13653       try_suggested_sip_codec(p);
13654       if (p->t38.state == T38_ENABLED) {
13655          add_sdp(&resp, p, oldsdp, TRUE, TRUE);
13656       } else {
13657          add_sdp(&resp, p, oldsdp, TRUE, FALSE);
13658       }
13659    } else
13660       ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
13661    if (reliable && !p->pendinginvite)
13662       p->pendinginvite = seqno;     /* Buggy clients sends ACK on RINGING too */
13663    add_required_respheader(&resp);
13664    return send_response(p, &resp, reliable, seqno);
13665 }
13666 
13667 /*! \brief Parse first line of incoming SIP request */
13668 static int determine_firstline_parts(struct sip_request *req)
13669 {
13670    char *e = ast_skip_blanks(req->data->str);   /* there shouldn't be any */
13671    char *local_rlpart1;
13672 
13673    if (!*e)
13674       return -1;
13675    req->rlpart1 = e - req->data->str;  /* method or protocol */
13676    local_rlpart1 = e;
13677    e = ast_skip_nonblanks(e);
13678    if (*e)
13679       *e++ = '\0';
13680    /* Get URI or status code */
13681    e = ast_skip_blanks(e);
13682    if ( !*e )
13683       return -1;
13684    ast_trim_blanks(e);
13685 
13686    if (!strcasecmp(local_rlpart1, "SIP/2.0") ) { /* We have a response */
13687       if (strlen(e) < 3)   /* status code is 3 digits */
13688          return -1;
13689       req->rlpart2 = e - req->data->str;
13690    } else { /* We have a request */
13691       if ( *e == '<' ) { /* XXX the spec says it must not be in <> ! */
13692          ast_debug(3, "Oops. Bogus uri in <> %s\n", e);
13693          e++;
13694          if (!*e)
13695             return -1;
13696       }
13697       req->rlpart2 = e - req->data->str;  /* URI */
13698       e = ast_skip_nonblanks(e);
13699       if (*e)
13700          *e++ = '\0';
13701       e = ast_skip_blanks(e);
13702       if (strcasecmp(e, "SIP/2.0") ) {
13703          ast_debug(3, "Skipping packet - Bad request protocol %s\n", e);
13704          return -1;
13705       }
13706    }
13707    return 1;
13708 }
13709 
13710 /*! \brief Transmit reinvite with SDP
13711 \note    A re-invite is basically a new INVITE with the same CALL-ID and TAG as the
13712    INVITE that opened the SIP dialogue
13713    We reinvite so that the audio stream (RTP) go directly between
13714    the SIP UAs. SIP Signalling stays with * in the path.
13715    
13716    If t38version is TRUE, we send T38 SDP for re-invite from audio/video to
13717    T38 UDPTL transmission on the channel
13718 
13719     If oldsdp is TRUE then the SDP version number is not incremented. This
13720     is needed for Session-Timers so we can send a re-invite to refresh the
13721     SIP session without modifying the media session.
13722 */
13723 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp)
13724 {
13725    struct sip_request req;
13726    
13727    reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ?  SIP_UPDATE : SIP_INVITE, 0, 1);
13728 
13729    add_header(&req, "Allow", ALLOWED_METHODS);
13730    add_supported(p, &req);
13731    if (sipdebug) {
13732       if (oldsdp == TRUE)
13733          add_header(&req, "X-asterisk-Info", "SIP re-invite (Session-Timers)");
13734       else
13735          add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
13736    }
13737 
13738    if (ast_test_flag(&p->flags[0], SIP_SENDRPID))
13739       add_rpid(&req, p);
13740 
13741    if (p->do_history) {
13742       append_history(p, "ReInv", "Re-invite sent");
13743    }
13744 
13745    offered_media_list_destroy(p);
13746 
13747    try_suggested_sip_codec(p);
13748    if (t38version) {
13749       add_sdp(&req, p, oldsdp, FALSE, TRUE);
13750    } else {
13751       add_sdp(&req, p, oldsdp, TRUE, FALSE);
13752    }
13753 
13754    /* Use this as the basis */
13755    initialize_initreq(p, &req);
13756    p->lastinvite = p->ocseq;
13757    ast_set_flag(&p->flags[0], SIP_OUTGOING);       /* Change direction of this dialog */
13758    p->ongoing_reinvite = 1;
13759    return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
13760 }
13761 
13762 /* \brief Remove URI parameters at end of URI, not in username part though */
13763 static char *remove_uri_parameters(char *uri)
13764 {
13765    char *atsign;
13766    atsign = strchr(uri, '@'); /* First, locate the at sign */
13767    if (!atsign) {
13768       atsign = uri;  /* Ok hostname only, let's stick with the rest */
13769    }
13770    atsign = strchr(atsign, ';'); /* Locate semi colon */
13771    if (atsign)
13772       *atsign = '\0';   /* Kill at the semi colon */
13773    return uri;
13774 }
13775 
13776 /*! \brief Check Contact: URI of SIP message */
13777 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
13778 {
13779    char stripped[SIPBUFSIZE];
13780    char *c;
13781 
13782    ast_copy_string(stripped, sip_get_header(req, "Contact"), sizeof(stripped));
13783    c = get_in_brackets(stripped);
13784    /* Cut the URI at the at sign after the @, not in the username part */
13785    c = remove_uri_parameters(c);
13786    if (!ast_strlen_zero(c)) {
13787       ast_string_field_set(p, uri, c);
13788    }
13789 
13790 }
13791 
13792 /*! \brief Build contact header - the contact header we send out */
13793 static void build_contact(struct sip_pvt *p)
13794 {
13795    char tmp[SIPBUFSIZE];
13796    char *user = ast_uri_encode(p->exten, tmp, sizeof(tmp), ast_uri_sip_user);
13797 
13798    if (p->socket.type == SIP_TRANSPORT_UDP) {
13799       ast_string_field_build(p, our_contact, "<sip:%s%s%s>", user,
13800          ast_strlen_zero(user) ? "" : "@", ast_sockaddr_stringify_remote(&p->ourip));
13801    } else {
13802       ast_string_field_build(p, our_contact, "<sip:%s%s%s;transport=%s>", user,
13803          ast_strlen_zero(user) ? "" : "@", ast_sockaddr_stringify_remote(&p->ourip),
13804          sip_get_transport(p->socket.type));
13805    }
13806 }
13807 
13808 /*! \brief Initiate new SIP request to peer/user */
13809 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri)
13810 {
13811    struct ast_str *invite = ast_str_alloca(256);
13812    char from[256];
13813    char to[256];
13814    char tmp_n[SIPBUFSIZE/2];  /* build a local copy of 'n' if needed */
13815    char tmp_l[SIPBUFSIZE/2];  /* build a local copy of 'l' if needed */
13816    const char *l = NULL;   /* XXX what is this, exactly ? */
13817    const char *n = NULL;   /* XXX what is this, exactly ? */
13818    const char *d = NULL;   /* domain in from header */
13819    const char *urioptions = "";
13820    int ourport;
13821    int cid_has_name = 1;
13822    int cid_has_num = 1;
13823    struct ast_party_id connected_id;
13824 
13825    if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
13826       const char *s = p->username;  /* being a string field, cannot be NULL */
13827 
13828       /* Test p->username against allowed characters in AST_DIGIT_ANY
13829          If it matches the allowed characters list, then sipuser = ";user=phone"
13830          If not, then sipuser = ""
13831       */
13832       /* + is allowed in first position in a tel: uri */
13833       if (*s == '+')
13834          s++;
13835       for (; *s; s++) {
13836          if (!strchr(AST_DIGIT_ANYNUM, *s) )
13837             break;
13838       }
13839       /* If we have only digits, add ;user=phone to the uri */
13840       if (!*s)
13841          urioptions = ";user=phone";
13842    }
13843 
13844 
13845    snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
13846 
13847    if (ast_strlen_zero(p->fromdomain)) {
13848       d = ast_sockaddr_stringify_host_remote(&p->ourip);
13849    }
13850    if (p->owner) {
13851       connected_id = ast_channel_connected_effective_id(p->owner);
13852 
13853       if ((ast_party_id_presentation(&connected_id) & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED) {
13854          if (connected_id.number.valid) {
13855             l = connected_id.number.str;
13856          }
13857          if (connected_id.name.valid) {
13858             n = connected_id.name.str;
13859          }
13860       } else {
13861          /* Even if we are using RPID, we shouldn't leak information in the From if the user wants
13862           * their callerid restricted */
13863          l = "anonymous";
13864          n = CALLERID_UNKNOWN;
13865          d = FROMDOMAIN_INVALID;
13866       }
13867    }
13868 
13869    /* Hey, it's a NOTIFY! See if they've configured a mwi_from.
13870     * XXX Right now, this logic works because the only place that mwi_from
13871     * is set on the sip_pvt is in sip_send_mwi_to_peer. If things changed, then
13872     * we might end up putting the mwi_from setting into other types of NOTIFY
13873     * messages as well.
13874     */
13875    if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->mwi_from)) {
13876       l = p->mwi_from;
13877    }
13878 
13879    if (ast_strlen_zero(l)) {
13880       cid_has_num = 0;
13881       l = default_callerid;
13882    }
13883    if (ast_strlen_zero(n)) {
13884       cid_has_name = 0;
13885       n = l;
13886    }
13887 
13888    /* Allow user to be overridden */
13889    if (!ast_strlen_zero(p->fromuser))
13890       l = p->fromuser;
13891    else /* Save for any further attempts */
13892       ast_string_field_set(p, fromuser, l);
13893 
13894    /* Allow user to be overridden */
13895    if (!ast_strlen_zero(p->fromname))
13896       n = p->fromname;
13897    else /* Save for any further attempts */
13898       ast_string_field_set(p, fromname, n);
13899 
13900    /* Allow domain to be overridden */
13901    if (!ast_strlen_zero(p->fromdomain))
13902       d = p->fromdomain;
13903    else /* Save for any further attempts */
13904       ast_string_field_set(p, fromdomain, d);
13905 
13906    ast_copy_string(tmp_l, l, sizeof(tmp_l));
13907    if (sip_cfg.pedanticsipchecking) {
13908       ast_escape_quoted(n, tmp_n, sizeof(tmp_n));
13909       n = tmp_n;
13910       ast_uri_encode(l, tmp_l, sizeof(tmp_l), ast_uri_sip_user);
13911    }
13912 
13913    ourport = (p->fromdomainport) ? p->fromdomainport : ast_sockaddr_port(&p->ourip);
13914 
13915    /* If a caller id name was specified, add a display name. */
13916    if (cid_has_name || !cid_has_num) {
13917       snprintf(from, sizeof(from), "\"%s\" ", n);
13918    } else {
13919       from[0] = '\0';
13920    }
13921 
13922    if (!sip_standard_port(p->socket.type, ourport)) {
13923       size_t offset = strlen(from);
13924       snprintf(&from[offset], sizeof(from) - offset, "<sip:%s@%s:%d>;tag=%s", tmp_l, d, ourport, p->tag);
13925    } else {
13926       size_t offset = strlen(from);
13927       snprintf(&from[offset], sizeof(from) - offset, "<sip:%s@%s>;tag=%s", tmp_l, d, p->tag);
13928    }
13929 
13930    if (!ast_strlen_zero(explicit_uri)) {
13931       ast_str_set(&invite, 0, "%s", explicit_uri);
13932    } else {
13933       /* If we're calling a registered SIP peer, use the fullcontact to dial to the peer */
13934       if (!ast_strlen_zero(p->fullcontact)) {
13935          /* If we have full contact, trust it */
13936          ast_str_append(&invite, 0, "%s", p->fullcontact);
13937       } else {
13938          /* Otherwise, use the username while waiting for registration */
13939          ast_str_append(&invite, 0, "sip:");
13940          if (!ast_strlen_zero(p->username)) {
13941             n = p->username;
13942             if (sip_cfg.pedanticsipchecking) {
13943                ast_uri_encode(n, tmp_n, sizeof(tmp_n), ast_uri_sip_user);
13944                n = tmp_n;
13945             }
13946             ast_str_append(&invite, 0, "%s@", n);
13947          }
13948          ast_str_append(&invite, 0, "%s", p->tohost);
13949          if (p->portinuri) {
13950             ast_str_append(&invite, 0, ":%d", ast_sockaddr_port(&p->sa));
13951          }
13952          ast_str_append(&invite, 0, "%s", urioptions);
13953       }
13954    }
13955 
13956    /* If custom URI options have been provided, append them */
13957    if (p->options && !ast_strlen_zero(p->options->uri_options))
13958       ast_str_append(&invite, 0, ";%s", p->options->uri_options);
13959    
13960    /* This is the request URI, which is the next hop of the call
13961       which may or may not be the destination of the call
13962    */
13963    ast_string_field_set(p, uri, ast_str_buffer(invite));
13964 
13965    if (!ast_strlen_zero(p->todnid)) {
13966       /*! \todo Need to add back the VXML URL here at some point, possibly use build_string for all this junk */
13967       if (!strchr(p->todnid, '@')) {
13968          /* We have no domain in the dnid */
13969          snprintf(to, sizeof(to), "<sip:%s@%s>%s%s", p->todnid, p->tohost, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
13970       } else {
13971          snprintf(to, sizeof(to), "<sip:%s>%s%s", p->todnid, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
13972       }
13973    } else {
13974       if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) {
13975          /* If this is a NOTIFY, use the From: tag in the subscribe (RFC 3265) */
13976          snprintf(to, sizeof(to), "<%s%s>;tag=%s", (strncasecmp(p->uri, "sip:", 4) ? "sip:" : ""), p->uri, p->theirtag);
13977       } else if (p->options && p->options->vxml_url) {
13978          /* If there is a VXML URL append it to the SIP URL */
13979          snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
13980       } else {
13981          snprintf(to, sizeof(to), "<%s>", p->uri);
13982       }
13983    }
13984 
13985    init_req(req, sipmethod, p->uri);
13986    /* now tmp_n is available so reuse it to build the CSeq */
13987    snprintf(tmp_n, sizeof(tmp_n), "%u %s", ++p->ocseq, sip_methods[sipmethod].text);
13988 
13989    add_header(req, "Via", p->via);
13990    add_max_forwards(p, req);
13991    /* This will be a no-op most of the time. However, under certain circumstances,
13992     * NOTIFY messages will use this function for preparing the request and should
13993     * have Route headers present.
13994     */
13995    add_route(req, p->route);
13996 
13997    add_header(req, "From", from);
13998    add_header(req, "To", to);
13999    ast_string_field_set(p, exten, l);
14000    build_contact(p);
14001    add_header(req, "Contact", p->our_contact);
14002    add_header(req, "Call-ID", p->callid);
14003    add_header(req, "CSeq", tmp_n);
14004    if (!ast_strlen_zero(global_useragent)) {
14005       add_header(req, "User-Agent", global_useragent);
14006    }
14007 }
14008 
14009 /*! \brief Add "Diversion" header to outgoing message
14010  *
14011  * We need to add a Diversion header if the owner channel of
14012  * this dialog has redirecting information associated with it.
14013  *
14014  * \param req The request/response to which we will add the header
14015  * \param pvt The sip_pvt which represents the call-leg
14016  */
14017 static void add_diversion(struct sip_request *req, struct sip_pvt *pvt)
14018 {
14019    struct ast_party_id diverting_from;
14020    const char *reason;
14021    char header_text[256];
14022 
14023    /* We skip this entirely if the configuration doesn't allow diversion headers */
14024    if (!sip_cfg.send_diversion) {
14025       return;
14026    }
14027 
14028    if (!pvt->owner) {
14029       return;
14030    }
14031 
14032    diverting_from = ast_channel_redirecting_effective_from(pvt->owner);
14033    if (!diverting_from.number.valid
14034       || ast_strlen_zero(diverting_from.number.str)) {
14035       return;
14036    }
14037 
14038    reason = sip_reason_code_to_str(ast_channel_redirecting(pvt->owner)->reason);
14039 
14040    /* We at least have a number to place in the Diversion header, which is enough */
14041    if (!diverting_from.name.valid
14042       || ast_strlen_zero(diverting_from.name.str)) {
14043       snprintf(header_text, sizeof(header_text), "<sip:%s@%s>;reason=%s", diverting_from.number.str,
14044             ast_sockaddr_stringify_host_remote(&pvt->ourip), reason);
14045    } else {
14046       snprintf(header_text, sizeof(header_text), "\"%s\" <sip:%s@%s>;reason=%s",
14047             diverting_from.name.str, diverting_from.number.str,
14048             ast_sockaddr_stringify_host_remote(&pvt->ourip), reason);
14049    }
14050 
14051    add_header(req, "Diversion", header_text);
14052 }
14053 
14054 static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri)
14055 {
14056    struct sip_pvt *pvt;
14057    int expires;
14058 
14059    epa_entry->publish_type = publish_type;
14060 
14061    if (!(pvt = sip_alloc(NULL, NULL, 0, SIP_PUBLISH, NULL, NULL))) {
14062       return -1;
14063    }
14064 
14065    sip_pvt_lock(pvt);
14066 
14067    if (create_addr(pvt, epa_entry->destination, NULL, TRUE)) {
14068       sip_pvt_unlock(pvt);
14069       dialog_unlink_all(pvt);
14070       dialog_unref(pvt, "create_addr failed in transmit_publish. Unref dialog");
14071       return -1;
14072    }
14073    ast_sip_ouraddrfor(&pvt->sa, &pvt->ourip, pvt);
14074    ast_set_flag(&pvt->flags[0], SIP_OUTGOING);
14075    expires = (publish_type == SIP_PUBLISH_REMOVE) ? 0 : DEFAULT_PUBLISH_EXPIRES;
14076    pvt->expiry = expires;
14077 
14078    /* Bump refcount for sip_pvt's reference */
14079    ao2_ref(epa_entry, +1);
14080    pvt->epa_entry = epa_entry;
14081 
14082    transmit_invite(pvt, SIP_PUBLISH, FALSE, 2, explicit_uri);
14083    sip_pvt_unlock(pvt);
14084    sip_scheddestroy(pvt, DEFAULT_TRANS_TIMEOUT);
14085    dialog_unref(pvt, "Done with the sip_pvt allocated for transmitting PUBLISH");
14086    return 0;
14087 }
14088 
14089 /*! 
14090  * \brief Build REFER/INVITE/OPTIONS/SUBSCRIBE message and transmit it
14091  * \param p sip_pvt structure
14092  * \param sipmethod
14093  * \param sdp unknown
14094  * \param init 0 = Prepare request within dialog, 1= prepare request, new branch,
14095  *  2= prepare new request and new dialog. do_proxy_auth calls this with init!=2
14096  * \param explicit_uri
14097 */
14098 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri)
14099 {
14100    struct sip_request req;
14101    struct ast_variable *var;
14102 
14103    if (init) {/* Bump branch even on initial requests */
14104       p->branch ^= ast_random();
14105       p->invite_branch = p->branch;
14106       build_via(p);
14107    }
14108    if (init > 1) {
14109       initreqprep(&req, p, sipmethod, explicit_uri);
14110    } else {
14111       /* If init=1, we should not generate a new branch. If it's 0, we need a new branch. */
14112       reqprep(&req, p, sipmethod, 0, init ? 0 : 1);
14113    }
14114 
14115    if (p->options && p->options->auth) {
14116       add_header(&req, p->options->authheader, p->options->auth);
14117    }
14118    add_date(&req);
14119    if (sipmethod == SIP_REFER && p->refer) { /* Call transfer */
14120       if (!ast_strlen_zero(p->refer->refer_to)) {
14121          add_header(&req, "Refer-To", p->refer->refer_to);
14122       }
14123       if (!ast_strlen_zero(p->refer->referred_by)) {
14124          add_header(&req, "Referred-By", p->refer->referred_by);
14125       }
14126    } else if (sipmethod == SIP_SUBSCRIBE) {
14127       if (p->subscribed == MWI_NOTIFICATION) {
14128          add_header(&req, "Event", "message-summary");
14129          add_header(&req, "Accept", "application/simple-message-summary");
14130       } else if (p->subscribed == CALL_COMPLETION) {
14131          add_header(&req, "Event", "call-completion");
14132          add_header(&req, "Accept", "application/call-completion");
14133       }
14134       add_expires(&req, p->expiry);
14135    }
14136 
14137    /* This new INVITE is part of an attended transfer. Make sure that the
14138    other end knows and replace the current call with this new call */
14139    if (p->options && !ast_strlen_zero(p->options->replaces)) {
14140       add_header(&req, "Replaces", p->options->replaces);
14141       add_header(&req, "Require", "replaces");
14142    }
14143 
14144    /* Add Session-Timers related headers */
14145    if (st_get_mode(p, 0) == SESSION_TIMER_MODE_ORIGINATE
14146       || (st_get_mode(p, 0) == SESSION_TIMER_MODE_ACCEPT
14147          && st_get_se(p, FALSE) != DEFAULT_MIN_SE)) {
14148       char i2astr[10];
14149 
14150       if (!p->stimer->st_interval) {
14151          p->stimer->st_interval = st_get_se(p, TRUE);
14152       }
14153 
14154       p->stimer->st_active = TRUE;
14155       if (st_get_mode(p, 0) == SESSION_TIMER_MODE_ORIGINATE) { 
14156          snprintf(i2astr, sizeof(i2astr), "%d", p->stimer->st_interval);
14157          add_header(&req, "Session-Expires", i2astr);
14158       }
14159 
14160       snprintf(i2astr, sizeof(i2astr), "%d", st_get_se(p, FALSE));
14161       add_header(&req, "Min-SE", i2astr);
14162    }
14163 
14164    add_header(&req, "Allow", ALLOWED_METHODS);
14165    add_supported(p, &req);
14166 
14167    if (p->owner && ((p->options && p->options->addsipheaders)
14168               || (p->refer && global_refer_addheaders))) {
14169       struct ast_channel *chan = p->owner; /* The owner channel */
14170       struct varshead *headp;
14171    
14172       ast_channel_lock(chan);
14173 
14174       headp = ast_channel_varshead(chan);
14175 
14176       if (!headp) {
14177          ast_log(LOG_WARNING, "No Headp for the channel...ooops!\n");
14178       } else {
14179          const struct ast_var_t *current;
14180          AST_LIST_TRAVERSE(headp, current, entries) {
14181             /* SIPADDHEADER: Add SIP header to outgoing call */
14182             if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
14183                char *content, *end;
14184                const char *header = ast_var_value(current);
14185                char *headdup = ast_strdupa(header);
14186 
14187                /* Strip of the starting " (if it's there) */
14188                if (*headdup == '"') {
14189                   headdup++;
14190                }
14191                if ((content = strchr(headdup, ':'))) {
14192                   *content++ = '\0';
14193                   content = ast_skip_blanks(content); /* Skip white space */
14194                   /* Strip the ending " (if it's there) */
14195                   end = content + strlen(content) -1;
14196                   if (*end == '"') {
14197                      *end = '\0';
14198                   }
14199 
14200                   add_header(&req, headdup, content);
14201                   if (sipdebug) {
14202                      ast_debug(1, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
14203                   }
14204                }
14205             }
14206          }
14207       }
14208 
14209       ast_channel_unlock(chan);
14210    }
14211    if ((sipmethod == SIP_INVITE || sipmethod == SIP_UPDATE) && ast_test_flag(&p->flags[0], SIP_SENDRPID))
14212       add_rpid(&req, p);
14213    if (sipmethod == SIP_INVITE) {
14214       add_diversion(&req, p);
14215    }
14216    if (sdp) {
14217       offered_media_list_destroy(p);
14218       if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
14219          ast_debug(1, "T38 is in state %d on channel %s\n", p->t38.state, p->owner ? ast_channel_name(p->owner) : "<none>");
14220          add_sdp(&req, p, FALSE, FALSE, TRUE);
14221       } else if (p->rtp) {
14222          try_suggested_sip_codec(p);
14223          add_sdp(&req, p, FALSE, TRUE, FALSE);
14224       }
14225    } else if (sipmethod == SIP_NOTIFY && p->notify) {
14226       for (var = p->notify->headers; var; var = var->next) {
14227          add_header(&req, var->name, var->value);
14228       }
14229       if (ast_str_strlen(p->notify->content)) {
14230          add_content(&req, ast_str_buffer(p->notify->content));
14231       }
14232    } else if (sipmethod == SIP_PUBLISH) {
14233       switch (p->epa_entry->static_data->event) {
14234       case CALL_COMPLETION:
14235          add_header(&req, "Event", "call-completion");
14236          add_expires(&req, p->expiry);
14237          if (p->epa_entry->publish_type != SIP_PUBLISH_INITIAL) {
14238             add_header(&req, "SIP-If-Match", p->epa_entry->entity_tag);
14239          }
14240 
14241          if (!ast_strlen_zero(p->epa_entry->body)) {
14242             add_header(&req, "Content-Type", "application/pidf+xml");
14243             add_content(&req, p->epa_entry->body);
14244          }
14245       default:
14246          break;
14247       }
14248    }
14249 
14250    if (!p->initreq.headers || init > 2) {
14251       initialize_initreq(p, &req);
14252    }
14253    if (sipmethod == SIP_INVITE || sipmethod == SIP_SUBSCRIBE) {
14254       p->lastinvite = p->ocseq;
14255    }
14256    return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
14257 }
14258 
14259 /*! \brief Send a subscription or resubscription for MWI */
14260 static int sip_subscribe_mwi_do(const void *data)
14261 {
14262    struct sip_subscription_mwi *mwi = (struct sip_subscription_mwi*)data;
14263    
14264    if (!mwi) {
14265       return -1;
14266    }
14267    
14268    mwi->resub = -1;
14269    __sip_subscribe_mwi_do(mwi);
14270    ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
14271    
14272    return 0;
14273 }
14274 
14275 static void on_dns_update_registry(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
14276 {
14277    struct sip_registry *reg = data;
14278    const char *old_str;
14279 
14280    /* This shouldn't happen, but just in case */
14281    if (ast_sockaddr_isnull(new)) {
14282       ast_debug(1, "Empty sockaddr change...ignoring!\n");
14283       return;
14284    }
14285 
14286    if (!ast_sockaddr_port(new)) {
14287       ast_sockaddr_set_port(new, reg->portno);
14288    }
14289 
14290    old_str = ast_strdupa(ast_sockaddr_stringify(old));
14291 
14292    ast_debug(1, "Changing registry %s from %s to %s\n", S_OR(reg->peername, reg->hostname), old_str, ast_sockaddr_stringify(new));
14293    ast_sockaddr_copy(&reg->us, new);
14294 }
14295 
14296 static void on_dns_update_peer(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
14297 {
14298    struct sip_peer *peer = data;
14299    const char *old_str;
14300 
14301    /* This shouldn't happen, but just in case */
14302    if (ast_sockaddr_isnull(new)) {
14303       ast_debug(1, "Empty sockaddr change...ignoring!\n");
14304       return;
14305    }
14306 
14307    if (!ast_sockaddr_isnull(&peer->addr)) {
14308       ao2_unlink(peers_by_ip, peer);
14309    }
14310 
14311    if (!ast_sockaddr_port(new)) {
14312       ast_sockaddr_set_port(new, default_sip_port(peer->socket.type));
14313    }
14314 
14315    old_str = ast_strdupa(ast_sockaddr_stringify(old));
14316    ast_debug(1, "Changing peer %s address from %s to %s\n", peer->name, old_str, ast_sockaddr_stringify(new));
14317 
14318    ao2_lock(peer);
14319    ast_sockaddr_copy(&peer->addr, new);
14320    ao2_unlock(peer);
14321 
14322    ao2_link(peers_by_ip, peer);
14323 }
14324 
14325 static void on_dns_update_mwi(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
14326 {
14327    struct sip_subscription_mwi *mwi = data;
14328    const char *old_str;
14329 
14330    /* This shouldn't happen, but just in case */
14331    if (ast_sockaddr_isnull(new)) {
14332       ast_debug(1, "Empty sockaddr change...ignoring!\n");
14333       return;
14334    }
14335 
14336    old_str = ast_strdupa(ast_sockaddr_stringify(old));
14337    ast_debug(1, "Changing mwi %s from %s to %s\n", mwi->hostname, old_str, ast_sockaddr_stringify(new));
14338    ast_sockaddr_copy(&mwi->us, new);
14339 }
14340 
14341 /*! \brief Actually setup an MWI subscription or resubscribe */
14342 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi)
14343 {
14344    /* If we have no DNS manager let's do a lookup */
14345    if (!mwi->dnsmgr) {
14346       char transport[MAXHOSTNAMELEN];
14347       struct sip_subscription_mwi *saved;
14348       snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(mwi->transport), get_srv_protocol(mwi->transport));
14349 
14350       mwi->us.ss.ss_family = get_address_family_filter(mwi->transport); /* Filter address family */
14351       saved = ASTOBJ_REF(mwi);
14352       ast_dnsmgr_lookup_cb(mwi->hostname, &mwi->us, &mwi->dnsmgr, sip_cfg.srvlookup ? transport : NULL, on_dns_update_mwi, saved);
14353       if (!mwi->dnsmgr) {
14354          ASTOBJ_UNREF(saved, sip_subscribe_mwi_destroy); /* dnsmgr disabled, remove reference */
14355       }
14356    }
14357 
14358    /* If we already have a subscription up simply send a resubscription */
14359    if (mwi->call) {
14360       transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 0, NULL);
14361       return 0;
14362    }
14363    
14364    /* Create a dialog that we will use for the subscription */
14365    if (!(mwi->call = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL, NULL))) {
14366       return -1;
14367    }
14368 
14369    ref_proxy(mwi->call, obproxy_get(mwi->call, NULL));
14370 
14371    if (!ast_sockaddr_port(&mwi->us) && mwi->portno) {
14372       ast_sockaddr_set_port(&mwi->us, mwi->portno);
14373    }
14374    
14375    /* Setup the destination of our subscription */
14376    if (create_addr(mwi->call, mwi->hostname, &mwi->us, 0)) {
14377       dialog_unlink_all(mwi->call);
14378       mwi->call = dialog_unref(mwi->call, "unref dialog after unlink_all");
14379       return 0;
14380    }
14381 
14382    mwi->call->expiry = mwi_expiry;
14383    
14384    if (!mwi->dnsmgr && mwi->portno) {
14385       ast_sockaddr_set_port(&mwi->call->sa, mwi->portno);
14386       ast_sockaddr_set_port(&mwi->call->recv, mwi->portno);
14387    } else {
14388       mwi->portno = ast_sockaddr_port(&mwi->call->sa);
14389    }
14390    
14391    /* Set various other information */
14392    if (!ast_strlen_zero(mwi->authuser)) {
14393       ast_string_field_set(mwi->call, peername, mwi->authuser);
14394       ast_string_field_set(mwi->call, authname, mwi->authuser);
14395       ast_string_field_set(mwi->call, fromuser, mwi->authuser);
14396    } else {
14397       ast_string_field_set(mwi->call, peername, mwi->username);
14398       ast_string_field_set(mwi->call, authname, mwi->username);
14399       ast_string_field_set(mwi->call, fromuser, mwi->username);
14400    }
14401    ast_string_field_set(mwi->call, username, mwi->username);
14402    if (!ast_strlen_zero(mwi->secret)) {
14403       ast_string_field_set(mwi->call, peersecret, mwi->secret);
14404    }
14405    set_socket_transport(&mwi->call->socket, mwi->transport);
14406    mwi->call->socket.port = htons(mwi->portno);
14407    ast_sip_ouraddrfor(&mwi->call->sa, &mwi->call->ourip, mwi->call);
14408    build_contact(mwi->call);
14409    build_via(mwi->call);
14410 
14411    /* Change the dialog callid. */
14412    change_callid_pvt(mwi->call, NULL);
14413 
14414    ast_set_flag(&mwi->call->flags[0], SIP_OUTGOING);
14415    
14416    /* Associate the call with us */
14417    mwi->call->mwi = ASTOBJ_REF(mwi);
14418 
14419    mwi->call->subscribed = MWI_NOTIFICATION;
14420 
14421    /* Actually send the packet */
14422    transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 2, NULL);
14423 
14424    return 0;
14425 }
14426 
14427 /*! \internal \brief Find the channel that is causing the RINGING update, ref'd */
14428 static struct ast_channel *find_ringing_channel(struct ao2_container *device_state_info, struct sip_pvt *p)
14429 {
14430    struct ao2_iterator citer;
14431    struct ast_device_state_info *device_state;
14432    struct ast_channel *c = NULL;
14433    struct timeval tv = {0,};
14434 
14435    /* iterate ringing devices and get the oldest of all causing channels */
14436    citer = ao2_iterator_init(device_state_info, 0);
14437    for (; (device_state = ao2_iterator_next(&citer)); ao2_ref(device_state, -1)) {
14438       if (!device_state->causing_channel || (device_state->device_state != AST_DEVICE_RINGING &&
14439           device_state->device_state != AST_DEVICE_RINGINUSE)) {
14440          continue;
14441       }
14442       ast_channel_lock(device_state->causing_channel);
14443       if (ast_tvzero(tv) || ast_tvcmp(ast_channel_creationtime(device_state->causing_channel), tv) < 0) {
14444          c = device_state->causing_channel;
14445          tv = ast_channel_creationtime(c);
14446       }
14447       ast_channel_unlock(device_state->causing_channel);
14448    }
14449    ao2_iterator_destroy(&citer);
14450    return c ? ast_channel_ref(c) : NULL;
14451 }
14452 
14453 /* XXX Candidate for moving into its own file */
14454 static int allow_notify_user_presence(struct sip_pvt *p)
14455 {
14456    return (strstr(p->useragent, "Digium")) ? 1 : 0;
14457 }
14458 
14459 /*! \brief Builds XML portion of NOTIFY messages for presence or dialog updates */
14460 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)
14461 {
14462    enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
14463    const char *statestring = "terminated";
14464    const char *pidfstate = "--";
14465    const char *pidfnote ="Ready";
14466    char hint[AST_MAX_EXTENSION];
14467 
14468    switch (data->state) {
14469    case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
14470       statestring = (sip_cfg.notifyringing) ? "early" : "confirmed";
14471       local_state = NOTIFY_INUSE;
14472       pidfstate = "busy";
14473       pidfnote = "Ringing";
14474       break;
14475    case AST_EXTENSION_RINGING:
14476       statestring = "early";
14477       local_state = NOTIFY_INUSE;
14478       pidfstate = "busy";
14479       pidfnote = "Ringing";
14480       break;
14481    case AST_EXTENSION_INUSE:
14482       statestring = "confirmed";
14483       local_state = NOTIFY_INUSE;
14484       pidfstate = "busy";
14485       pidfnote = "On the phone";
14486       break;
14487    case AST_EXTENSION_BUSY:
14488       statestring = "confirmed";
14489       local_state = NOTIFY_CLOSED;
14490       pidfstate = "busy";
14491       pidfnote = "On the phone";
14492       break;
14493    case AST_EXTENSION_UNAVAILABLE:
14494       statestring = "terminated";
14495       local_state = NOTIFY_CLOSED;
14496       pidfstate = "away";
14497       pidfnote = "Unavailable";
14498       break;
14499    case AST_EXTENSION_ONHOLD:
14500       statestring = "confirmed";
14501       local_state = NOTIFY_CLOSED;
14502       pidfstate = "busy";
14503       pidfnote = "On hold";
14504       break;
14505    case AST_EXTENSION_NOT_INUSE:
14506    default:
14507       /* Default setting */
14508       break;
14509    }
14510 
14511    /* Check which device/devices we are watching  and if they are registered */
14512    if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, context, exten)) {
14513       char *hint2;
14514       char *individual_hint = NULL;
14515       int hint_count = 0, unavailable_count = 0;
14516 
14517       /* strip off any possible PRESENCE providers from hint */
14518       if ((hint2 = strrchr(hint, ','))) {
14519          *hint2 = '\0';
14520       }
14521       hint2 = hint;
14522 
14523       while ((individual_hint = strsep(&hint2, "&"))) {
14524          hint_count++;
14525 
14526          if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
14527             unavailable_count++;
14528       }
14529 
14530       /* If none of the hinted devices are registered, we will
14531        * override notification and show no availability.
14532        */
14533       if (hint_count > 0 && hint_count == unavailable_count) {
14534          local_state = NOTIFY_CLOSED;
14535          pidfstate = "away";
14536          pidfnote = "Not online";
14537       }
14538    }
14539 
14540    switch (subscribed) {
14541    case XPIDF_XML:
14542    case CPIM_PIDF_XML:
14543       ast_str_append(tmp, 0,
14544          "<?xml version=\"1.0\"?>\n"
14545          "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n"
14546          "<presence>\n");
14547       ast_str_append(tmp, 0, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
14548       ast_str_append(tmp, 0, "<atom id=\"%s\">\n", exten);
14549       ast_str_append(tmp, 0, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
14550       ast_str_append(tmp, 0, "<status status=\"%s\" />\n", (local_state ==  NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
14551       ast_str_append(tmp, 0, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
14552       ast_str_append(tmp, 0, "</address>\n</atom>\n</presence>\n");
14553       break;
14554    case PIDF_XML: /* Eyebeam supports this format */
14555       ast_str_append(tmp, 0,
14556          "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
14557          "<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);
14558       ast_str_append(tmp, 0, "<pp:person><status>\n");
14559       if (pidfstate[0] != '-') {
14560          ast_str_append(tmp, 0, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
14561       }
14562       ast_str_append(tmp, 0, "</status></pp:person>\n");
14563       ast_str_append(tmp, 0, "<note>%s</note>\n", pidfnote); /* Note */
14564       ast_str_append(tmp, 0, "<tuple id=\"%s\">\n", exten); /* Tuple start */
14565       ast_str_append(tmp, 0, "<contact priority=\"1\">%s</contact>\n", mto);
14566       if (pidfstate[0] == 'b') /* Busy? Still open ... */
14567          ast_str_append(tmp, 0, "<status><basic>open</basic></status>\n");
14568       else
14569          ast_str_append(tmp, 0, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
14570 
14571       if (allow_notify_user_presence(p) && (data->presence_state != AST_PRESENCE_INVALID)
14572             && (data->presence_state != AST_PRESENCE_NOT_SET)) {
14573          ast_str_append(tmp, 0, "</tuple>\n");
14574          ast_str_append(tmp, 0, "<tuple id=\"digium-presence\">\n");
14575          ast_str_append(tmp, 0, "<status>\n");
14576          ast_str_append(tmp, 0, "<digium_presence type=\"%s\" subtype=\"%s\">%s</digium_presence>\n",
14577             ast_presence_state2str(data->presence_state),
14578             S_OR(data->presence_subtype, ""),
14579             S_OR(data->presence_message, ""));
14580          ast_str_append(tmp, 0, "</status>\n");
14581          ast_test_suite_event_notify("DIGIUM_PRESENCE_SENT",
14582                "PresenceState: %s\r\n"
14583                "Subtype: %s\r\n"
14584                "Message: %s",
14585                ast_presence_state2str(data->presence_state),
14586                S_OR(data->presence_subtype, ""),
14587                S_OR(data->presence_message, ""));
14588       }
14589       ast_str_append(tmp, 0, "</tuple>\n</presence>\n");
14590       break;
14591    case DIALOG_INFO_XML: /* SNOM subscribes in this format */
14592       ast_str_append(tmp, 0, "<?xml version=\"1.0\"?>\n");
14593       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);
14594       if (data->state > 0 && (data->state & AST_EXTENSION_RINGING) && sip_cfg.notifyringing) {
14595          /* Twice the extension length should be enough for XML encoding */
14596          char local_display[AST_MAX_EXTENSION * 2];
14597          char remote_display[AST_MAX_EXTENSION * 2];
14598          char *local_target = ast_strdupa(mto);
14599          /* It may seem odd to base the remote_target on the To header here,
14600           * but testing by reporters on issue ASTERISK-16735 found that basing
14601           * on the From header would cause ringing state hints to not work
14602           * properly on certain SNOM devices. If you are using notifycid properly
14603           * (i.e. in the same extension and context as the dialed call) then this
14604           * should not be an issue since the data will be overwritten shortly
14605           * with channel caller ID
14606           */
14607          char *remote_target = ast_strdupa(mto);
14608 
14609          ast_xml_escape(exten, local_display, sizeof(local_display));
14610          ast_xml_escape(exten, remote_display, sizeof(remote_display));
14611 
14612          /* There are some limitations to how this works.  The primary one is that the
14613             callee must be dialing the same extension that is being monitored.  Simply dialing
14614             the hint'd device is not sufficient. */
14615          if (sip_cfg.notifycid) {
14616             struct ast_channel *callee;
14617 
14618             callee = find_ringing_channel(data->device_state_info, p);
14619             if (callee) {
14620                static char *anonymous = "anonymous";
14621                static char *invalid = "anonymous.invalid";
14622                char *cid_num;
14623                char *connected_num;
14624                int need;
14625                int cid_num_restricted, connected_num_restricted;
14626 
14627                ast_channel_lock(callee);
14628 
14629                cid_num_restricted = (ast_channel_caller(callee)->id.number.presentation &
14630                            AST_PRES_RESTRICTION) == AST_PRES_RESTRICTED;
14631                cid_num = S_COR(ast_channel_caller(callee)->id.number.valid,
14632                      S_COR(cid_num_restricted, anonymous,
14633                            ast_channel_caller(callee)->id.number.str), "");
14634 
14635                need = strlen(cid_num) + (cid_num_restricted ? strlen(invalid) :
14636                           strlen(p->fromdomain)) + sizeof("sip:@");
14637                local_target = ast_alloca(need);
14638 
14639                snprintf(local_target, need, "sip:%s@%s", cid_num,
14640                    cid_num_restricted ? invalid : p->fromdomain);
14641 
14642                ast_xml_escape(S_COR(ast_channel_caller(callee)->id.name.valid,
14643                           S_COR((ast_channel_caller(callee)->id.name.presentation &
14644                              AST_PRES_RESTRICTION) == AST_PRES_RESTRICTED, anonymous,
14645                            ast_channel_caller(callee)->id.name.str), ""),
14646                          local_display, sizeof(local_display));
14647 
14648                connected_num_restricted = (ast_channel_connected(callee)->id.number.presentation &
14649                             AST_PRES_RESTRICTION) == AST_PRES_RESTRICTED;
14650                connected_num = S_COR(ast_channel_connected(callee)->id.number.valid,
14651                            S_COR(connected_num_restricted, anonymous,
14652                             ast_channel_connected(callee)->id.number.str), "");
14653 
14654                need = strlen(connected_num) + (connected_num_restricted ? strlen(invalid) :
14655                            strlen(p->fromdomain)) + sizeof("sip:@");
14656                remote_target = ast_alloca(need);
14657 
14658                snprintf(remote_target, need, "sip:%s@%s", connected_num,
14659                    connected_num_restricted ? invalid : p->fromdomain);
14660 
14661                ast_xml_escape(S_COR(ast_channel_connected(callee)->id.name.valid,
14662                           S_COR((ast_channel_connected(callee)->id.name.presentation &
14663                              AST_PRES_RESTRICTION) == AST_PRES_RESTRICTED, anonymous,
14664                             ast_channel_connected(callee)->id.name.str), ""),
14665                          remote_display, sizeof(remote_display));
14666 
14667                ast_channel_unlock(callee);
14668                callee = ast_channel_unref(callee);
14669             }
14670 
14671             /* We create a fake call-id which the phone will send back in an INVITE
14672                Replaces header which we can grab and do some magic with. */
14673             if (sip_cfg.pedanticsipchecking) {
14674                ast_str_append(tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" local-tag=\"%s\" remote-tag=\"%s\" direction=\"recipient\">\n",
14675                   exten, p->callid, p->theirtag, p->tag);
14676             } else {
14677                ast_str_append(tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" direction=\"recipient\">\n",
14678                   exten, p->callid);
14679             }
14680             ast_str_append(tmp, 0,
14681                   "<remote>\n"
14682                   /* See the limitations of this above.  Luckily the phone seems to still be
14683                      happy when these values are not correct. */
14684                   "<identity display=\"%s\">%s</identity>\n"
14685                   "<target uri=\"%s\"/>\n"
14686                   "</remote>\n"
14687                   "<local>\n"
14688                   "<identity display=\"%s\">%s</identity>\n"
14689                   "<target uri=\"%s\"/>\n"
14690                   "</local>\n",
14691                   remote_display, remote_target, remote_target, local_display, local_target, local_target);
14692          } else {
14693             ast_str_append(tmp, 0, "<dialog id=\"%s\" direction=\"recipient\">\n", exten);
14694          }
14695 
14696       } else {
14697          ast_str_append(tmp, 0, "<dialog id=\"%s\">\n", exten);
14698       }
14699       ast_str_append(tmp, 0, "<state>%s</state>\n", statestring);
14700       if (data->state == AST_EXTENSION_ONHOLD) {
14701             ast_str_append(tmp, 0, "<local>\n<target uri=\"%s\">\n"
14702                                              "<param pname=\"+sip.rendering\" pvalue=\"no\"/>\n"
14703                                              "</target>\n</local>\n", mto);
14704       }
14705       ast_str_append(tmp, 0, "</dialog>\n</dialog-info>\n");
14706       break;
14707    case NONE:
14708    default:
14709       break;
14710    }
14711 }
14712 
14713 static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state)
14714 {
14715    struct sip_request req;
14716    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
14717    char uri[SIPBUFSIZE];
14718    char state_str[64];
14719    char subscription_state_hdr[64];
14720 
14721    if (state < CC_QUEUED || state > CC_READY) {
14722       ast_log(LOG_WARNING, "Invalid state provided for transmit_cc_notify (%d)\n", state);
14723       return -1;
14724    }
14725 
14726    reqprep(&req, subscription, SIP_NOTIFY, 0, TRUE);
14727    snprintf(state_str, sizeof(state_str), "%s\r\n", sip_cc_notify_state_map[state].state_string);
14728    add_header(&req, "Event", "call-completion");
14729    add_header(&req, "Content-Type", "application/call-completion");
14730    snprintf(subscription_state_hdr, sizeof(subscription_state_hdr), "active;expires=%d", subscription->expiry);
14731    add_header(&req, "Subscription-State", subscription_state_hdr);
14732    if (state == CC_READY) {
14733       generate_uri(subscription, agent_pvt->notify_uri, sizeof(agent_pvt->notify_uri));
14734       snprintf(uri, sizeof(uri) - 1, "cc-URI: %s\r\n", agent_pvt->notify_uri);
14735    }
14736    add_content(&req, state_str);
14737    if (state == CC_READY) {
14738       add_content(&req, uri);
14739    }
14740    return send_request(subscription, &req, XMIT_RELIABLE, subscription->ocseq);
14741 }
14742 
14743 /*! \brief Used in the SUBSCRIBE notification subsystem (RFC3265) */
14744 static int transmit_state_notify(struct sip_pvt *p, struct state_notify_data *data, int full, int timeout)
14745 {
14746    struct ast_str *tmp = ast_str_alloca(4000);
14747    char from[256], to[256];
14748    char *c, *mfrom, *mto;
14749    struct sip_request req;
14750    const struct cfsubscription_types *subscriptiontype;
14751 
14752    /* If the subscription has not yet been accepted do not send a NOTIFY */
14753    if (!ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
14754       return 0;
14755    }
14756 
14757    memset(from, 0, sizeof(from));
14758    memset(to, 0, sizeof(to));
14759 
14760    subscriptiontype = find_subscription_type(p->subscribed);
14761 
14762    ast_copy_string(from, sip_get_header(&p->initreq, "From"), sizeof(from));
14763    c = get_in_brackets(from);
14764    if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
14765       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
14766       return -1;
14767    }
14768 
14769    mfrom = remove_uri_parameters(c);
14770 
14771    ast_copy_string(to, sip_get_header(&p->initreq, "To"), sizeof(to));
14772    c = get_in_brackets(to);
14773    if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
14774       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
14775       return -1;
14776    }
14777    mto = remove_uri_parameters(c);
14778 
14779    reqprep(&req, p, SIP_NOTIFY, 0, 1);
14780 
14781    switch(data->state) {
14782    case AST_EXTENSION_DEACTIVATED:
14783       if (timeout)
14784          add_header(&req, "Subscription-State", "terminated;reason=timeout");
14785       else {
14786          add_header(&req, "Subscription-State", "terminated;reason=probation");
14787          add_header(&req, "Retry-After", "60");
14788       }
14789       break;
14790    case AST_EXTENSION_REMOVED:
14791       add_header(&req, "Subscription-State", "terminated;reason=noresource");
14792       break;
14793    default:
14794       if (p->expiry)
14795          add_header(&req, "Subscription-State", "active");
14796       else  /* Expired */
14797          add_header(&req, "Subscription-State", "terminated;reason=timeout");
14798    }
14799 
14800    switch (p->subscribed) {
14801    case XPIDF_XML:
14802    case CPIM_PIDF_XML:
14803       add_header(&req, "Event", subscriptiontype->event);
14804       state_notify_build_xml(data, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
14805       add_header(&req, "Content-Type", subscriptiontype->mediatype);
14806       p->dialogver++;
14807       break;
14808    case PIDF_XML: /* Eyebeam supports this format */
14809       add_header(&req, "Event", subscriptiontype->event);
14810       state_notify_build_xml(data, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
14811       add_header(&req, "Content-Type", subscriptiontype->mediatype);
14812       p->dialogver++;
14813       break;
14814    case DIALOG_INFO_XML: /* SNOM subscribes in this format */
14815       add_header(&req, "Event", subscriptiontype->event);
14816       state_notify_build_xml(data, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
14817       add_header(&req, "Content-Type", subscriptiontype->mediatype);
14818       p->dialogver++;
14819       break;
14820    case NONE:
14821    default:
14822       break;
14823    }
14824 
14825    add_content(&req, ast_str_buffer(tmp));
14826 
14827    p->pendinginvite = p->ocseq;  /* Remember that we have a pending NOTIFY in order not to confuse the NOTIFY subsystem */
14828 
14829    /* Send as XMIT_CRITICAL as we may never receive a 200 OK Response which clears p->pendinginvite.
14830     *
14831     * extensionstate_update() uses p->pendinginvite for queuing control.
14832     * Updates stall if pendinginvite <> 0.
14833     *
14834     * The most appropriate solution is to remove the subscription when the NOTIFY transaction fails.
14835     * The client will re-subscribe after restarting or maxexpiry timeout.
14836     */
14837 
14838    /* RFC6665 4.2.2.  Sending State Information to Subscribers
14839     * If the NOTIFY request fails due to expiration of SIP Timer F (transaction timeout),
14840     * the notifier SHOULD remove the subscription.
14841     */
14842    return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
14843 }
14844 
14845 /*! \brief Notify user of messages waiting in voicemail (RFC3842)
14846 \note - Notification only works for registered peers with mailbox= definitions
14847    in sip.conf
14848    - We use the SIP Event package message-summary
14849     MIME type defaults to  "application/simple-message-summary";
14850  */
14851 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten)
14852 {
14853    struct sip_request req;
14854    struct ast_str *out = ast_str_alloca(500);
14855    int ourport = (p->fromdomainport) ? p->fromdomainport : ast_sockaddr_port(&p->ourip);
14856    const char *domain;
14857    const char *exten = S_OR(vmexten, default_vmexten);
14858 
14859    initreqprep(&req, p, SIP_NOTIFY, NULL);
14860    add_header(&req, "Event", "message-summary");
14861    add_header(&req, "Content-Type", default_notifymime);
14862    ast_str_append(&out, 0, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
14863 
14864    /* domain initialization occurs here because initreqprep changes ast_sockaddr_stringify string. */
14865    domain = S_OR(p->fromdomain, ast_sockaddr_stringify_host_remote(&p->ourip));
14866 
14867    if (!sip_standard_port(p->socket.type, ourport)) {
14868       if (p->socket.type == SIP_TRANSPORT_UDP) {
14869          ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d\r\n", exten, domain, ourport);
14870       } else {
14871          ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d;transport=%s\r\n", exten, domain, ourport, sip_get_transport(p->socket.type));
14872       }
14873    } else {
14874       if (p->socket.type == SIP_TRANSPORT_UDP) {
14875          ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, domain);
14876       } else {
14877          ast_str_append(&out, 0, "Message-Account: sip:%s@%s;transport=%s\r\n", exten, domain, sip_get_transport(p->socket.type));
14878       }
14879    }
14880    /* Cisco has a bug in the SIP stack where it can't accept the
14881       (0/0) notification. This can temporarily be disabled in
14882       sip.conf with the "buggymwi" option */
14883    ast_str_append(&out, 0, "Voice-Message: %d/%d%s\r\n",
14884       newmsgs, oldmsgs, (ast_test_flag(&p->flags[1], SIP_PAGE2_BUGGY_MWI) ? "" : " (0/0)"));
14885 
14886    if (p->subscribed) {
14887       if (p->expiry) {
14888          add_header(&req, "Subscription-State", "active");
14889       } else { /* Expired */
14890          add_header(&req, "Subscription-State", "terminated;reason=timeout");
14891       }
14892    }
14893 
14894    add_content(&req, ast_str_buffer(out));
14895 
14896    if (!p->initreq.headers) {
14897       initialize_initreq(p, &req);
14898    }
14899    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
14900 }
14901 
14902 /*! \brief Notify a transferring party of the status of transfer (RFC3515) */
14903 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
14904 {
14905    struct sip_request req;
14906    char tmp[SIPBUFSIZE/2];
14907    
14908    reqprep(&req, p, SIP_NOTIFY, 0, 1);
14909    snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
14910    add_header(&req, "Event", tmp);
14911    add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
14912    add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
14913    add_header(&req, "Allow", ALLOWED_METHODS);
14914    add_supported(p, &req);
14915 
14916    snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
14917    add_content(&req, tmp);
14918 
14919    if (!p->initreq.headers) {
14920       initialize_initreq(p, &req);
14921    }
14922 
14923    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
14924 }
14925 
14926 static int manager_sipnotify(struct mansession *s, const struct message *m)
14927 {
14928    const char *channame = astman_get_header(m, "Channel");
14929    struct ast_variable *vars = astman_get_variables(m);
14930    struct sip_pvt *p;
14931    struct ast_variable *header, *var;
14932 
14933    if (ast_strlen_zero(channame)) {
14934       astman_send_error(s, m, "SIPNotify requires a channel name");
14935       return 0;
14936    }
14937 
14938    if (!strncasecmp(channame, "sip/", 4)) {
14939       channame += 4;
14940    }
14941 
14942    if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL, NULL))) {
14943       astman_send_error(s, m, "Unable to build sip pvt data for notify (memory/socket error)");
14944       return 0;
14945    }
14946 
14947    if (create_addr(p, channame, NULL, 0)) {
14948       /* Maybe they're not registered, etc. */
14949       dialog_unlink_all(p);
14950       dialog_unref(p, "unref dialog inside for loop" );
14951       /* sip_destroy(p); */
14952       astman_send_error(s, m, "Could not create address");
14953       return 0;
14954    }
14955 
14956    /* Notify is outgoing call */
14957    ast_set_flag(&p->flags[0], SIP_OUTGOING);
14958    sip_notify_alloc(p);
14959 
14960    p->notify->headers = header = ast_variable_new("Subscription-State", "terminated", "");
14961 
14962    for (var = vars; var; var = var->next) {
14963       if (!strcasecmp(var->name, "Content")) {
14964          if (ast_str_strlen(p->notify->content))
14965             ast_str_append(&p->notify->content, 0, "\r\n");
14966          ast_str_append(&p->notify->content, 0, "%s", var->value);
14967       } else if (!strcasecmp(var->name, "Content-Length")) {
14968          ast_log(LOG_WARNING, "it is not necessary to specify Content-Length, ignoring\n");
14969       } else {
14970          header->next = ast_variable_new(var->name, var->value, "");
14971          header = header->next;
14972       }
14973    }
14974 
14975    sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
14976    transmit_invite(p, SIP_NOTIFY, 0, 2, NULL);
14977    dialog_unref(p, "bump down the count of p since we're done with it.");
14978 
14979    astman_send_ack(s, m, "Notify Sent");
14980    ast_variables_destroy(vars);
14981    return 0;
14982 }
14983 
14984 /*! \brief Send a provisional response indicating that a call was redirected
14985  */
14986 static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen)
14987 {
14988    struct sip_request resp;
14989 
14990    if (ast_channel_state(p->owner) == AST_STATE_UP || ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
14991       return;
14992    }
14993 
14994    respprep(&resp, p, "181 Call is being forwarded", &p->initreq);
14995    add_diversion(&resp, p);
14996    send_response(p, &resp, XMIT_UNRELIABLE, 0);
14997 }
14998 
14999 /*! \brief Notify peer that the connected line has changed */
15000 static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen)
15001 {
15002    struct ast_party_id connected_id = ast_channel_connected_effective_id(p->owner);
15003 
15004    if (!ast_test_flag(&p->flags[0], SIP_SENDRPID)) {
15005       return;
15006    }
15007    if (!connected_id.number.valid
15008       || ast_strlen_zero(connected_id.number.str)) {
15009       return;
15010    }
15011 
15012    append_history(p, "ConnectedLine", "%s party is now %s <%s>",
15013       ast_test_flag(&p->flags[0], SIP_OUTGOING) ? "Calling" : "Called",
15014       S_COR(connected_id.name.valid, connected_id.name.str, ""),
15015       S_COR(connected_id.number.valid, connected_id.number.str, ""));
15016 
15017    if (ast_channel_state(p->owner) == AST_STATE_UP || ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
15018       struct sip_request req;
15019 
15020       if (!p->pendinginvite && (p->invitestate == INV_CONFIRMED || p->invitestate == INV_TERMINATED)) {
15021          reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
15022 
15023          add_header(&req, "Allow", ALLOWED_METHODS);
15024          add_supported(p, &req);
15025          add_rpid(&req, p);
15026          add_sdp(&req, p, FALSE, TRUE, FALSE);
15027 
15028          initialize_initreq(p, &req);
15029          p->lastinvite = p->ocseq;
15030          ast_set_flag(&p->flags[0], SIP_OUTGOING);
15031          p->invitestate = INV_CALLING;
15032          send_request(p, &req, XMIT_CRITICAL, p->ocseq);
15033       } else if ((is_method_allowed(&p->allowed_methods, SIP_UPDATE)) && (!ast_strlen_zero(p->okcontacturi))) { 
15034          reqprep(&req, p, SIP_UPDATE, 0, 1);
15035          add_rpid(&req, p);
15036          add_header(&req, "X-Asterisk-rpid-update", "Yes");
15037          send_request(p, &req, XMIT_CRITICAL, p->ocseq);
15038       } else {
15039          /* We cannot send the update yet, so we have to wait until we can */
15040          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
15041       }
15042    } else {
15043       ast_set_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
15044       if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPID_IMMEDIATE)) {
15045          struct sip_request resp;
15046 
15047          if ((ast_channel_state(p->owner) == AST_STATE_RING) && !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT)) {
15048             ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
15049             respprep(&resp, p, "180 Ringing", &p->initreq);
15050             add_rpid(&resp, p);
15051             send_response(p, &resp, XMIT_UNRELIABLE, 0);
15052             ast_set_flag(&p->flags[0], SIP_RINGING);
15053          } else if (ast_channel_state(p->owner) == AST_STATE_RINGING) {
15054             ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
15055             respprep(&resp, p, "183 Session Progress", &p->initreq);
15056             add_rpid(&resp, p);
15057             send_response(p, &resp, XMIT_UNRELIABLE, 0);
15058             ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
15059          } else {
15060             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)));
15061          }
15062       }
15063    }
15064 }
15065 
15066 static const struct _map_x_s regstatestrings[] = {
15067    { REG_STATE_FAILED,     "Failed" },
15068    { REG_STATE_UNREGISTERED, "Unregistered"},
15069    { REG_STATE_REGSENT, "Request Sent"},
15070    { REG_STATE_AUTHSENT, "Auth. Sent"},
15071    { REG_STATE_REGISTERED, "Registered"},
15072    { REG_STATE_REJECTED, "Rejected"},
15073    { REG_STATE_TIMEOUT, "Timeout"},
15074    { REG_STATE_NOAUTH, "No Authentication"},
15075    { -1, NULL } /* terminator */
15076 };
15077 
15078 /*! \brief Convert registration state status to string */
15079 static const char *regstate2str(enum sipregistrystate regstate)
15080 {
15081    return map_x_s(regstatestrings, regstate, "Unknown");
15082 }
15083 
15084 /*! \brief Update registration with SIP Proxy.
15085  * Called from the scheduler when the previous registration expires,
15086  * so we don't have to cancel the pending event.
15087  * We assume the reference so the sip_registry is valid, since it
15088  * is stored in the scheduled event anyways.
15089  */
15090 static int sip_reregister(const void *data)
15091 {
15092    /* if we are here, we know that we need to reregister. */
15093    struct sip_registry *r = (struct sip_registry *) data;
15094 
15095    /* if we couldn't get a reference to the registry object, punt */
15096    if (!r) {
15097       return 0;
15098    }
15099 
15100    if (r->call && r->call->do_history) {
15101       append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
15102    }
15103    /* Since registry's are only added/removed by the the monitor thread, this
15104       may be overkill to reference/dereference at all here */
15105    if (sipdebug) {
15106       ast_log(LOG_NOTICE, "   -- Re-registration for  %s@%s\n", r->username, r->hostname);
15107    }
15108 
15109    r->expire = -1;
15110    r->expiry = r->configured_expiry;
15111    __sip_do_register(r);
15112    registry_unref(r, "unref the re-register scheduled event");
15113    return 0;
15114 }
15115 
15116 /*! \brief Register with SIP proxy 
15117    \return see \ref __sip_xmit 
15118 */
15119 static int __sip_do_register(struct sip_registry *r)
15120 {
15121    int res;
15122 
15123    res = transmit_register(r, SIP_REGISTER, NULL, NULL);
15124    return res;
15125 }
15126 
15127 /*! \brief Registration timeout, register again
15128  * Registered as a timeout handler during transmit_register(),
15129  * to retransmit the packet if a reply does not come back.
15130  * This is called by the scheduler so the event is not pending anymore when
15131  * we are called.
15132  */
15133 static int sip_reg_timeout(const void *data)
15134 {
15135 
15136    /* if we are here, our registration timed out, so we'll just do it over */
15137    struct sip_registry *r = (struct sip_registry *)data; /* the ref count should have been bumped when the sched item was added */
15138    struct sip_pvt *p;
15139 
15140    /* if we couldn't get a reference to the registry object, punt */
15141    if (!r) {
15142       return 0;
15143    }
15144 
15145    if (r->dnsmgr) {
15146       /* If the registration has timed out, maybe the IP changed.  Force a refresh. */
15147       ast_dnsmgr_refresh(r->dnsmgr);
15148    }
15149 
15150    /* If the initial tranmission failed, we may not have an existing dialog,
15151     * so it is possible that r->call == NULL.
15152     * Otherwise destroy it, as we have a timeout so we don't want it.
15153     */
15154    if (r->call) {
15155       /* Unlink us, destroy old call.  Locking is not relevant here because all this happens
15156          in the single SIP manager thread. */
15157       p = r->call;
15158       sip_pvt_lock(p);
15159       pvt_set_needdestroy(p, "registration timeout");
15160       /* Pretend to ACK anything just in case */
15161       __sip_pretend_ack(p);
15162       sip_pvt_unlock(p);
15163 
15164       /* decouple the two objects */
15165       /* p->registry == r, so r has 2 refs, and the unref won't take the object away */
15166       if (p->registry) {
15167          p->registry = registry_unref(p->registry, "p->registry unreffed");
15168       }
15169       r->call = dialog_unref(r->call, "unrefing r->call");
15170    }
15171    /* If we have a limit, stop registration and give up */
15172    r->timeout = -1;
15173    if (global_regattempts_max && r->regattempts >= global_regattempts_max) {
15174       /* Ok, enough is enough. Don't try any more */
15175       /* We could add an external notification here...
15176          steal it from app_voicemail :-) */
15177       ast_log(LOG_NOTICE, "   -- Last Registration Attempt #%d failed, Giving up forever trying to register '%s@%s'\n", r->regattempts, r->username, r->hostname);
15178       r->regstate = REG_STATE_FAILED;
15179    } else {
15180       r->regstate = REG_STATE_UNREGISTERED;
15181       transmit_register(r, SIP_REGISTER, NULL, NULL);
15182       ast_log(LOG_NOTICE, "   -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts);
15183    }
15184    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));
15185    registry_unref(r, "unreffing registry_unref r");
15186    return 0;
15187 }
15188 
15189 static const char *sip_sanitized_host(const char *host)
15190 {
15191    struct ast_sockaddr addr = { { 0, 0, }, };
15192 
15193    /* peer/sip_pvt->tohost and sip_registry->hostname should never have a port
15194     * in them, so we use PARSE_PORT_FORBID here. If this lookup fails, we return
15195     * the original host which is most likely a host name and not an IP. */
15196    if (!ast_sockaddr_parse(&addr, host, PARSE_PORT_FORBID)) {
15197       return host;
15198    }
15199    return ast_sockaddr_stringify_host_remote(&addr);
15200 }
15201 
15202 /*! \brief Transmit register to SIP proxy or UA
15203  * auth = NULL on the initial registration (from sip_reregister())
15204  */
15205 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
15206 {
15207    struct sip_request req;
15208    char from[256];
15209    char to[256];
15210    char tmp[80];
15211    char addr[80];
15212    struct sip_pvt *p;
15213    struct sip_peer *peer = NULL;
15214    int res;
15215    int portno = 0;
15216 
15217    /* exit if we are already in process with this registrar ?*/
15218    if (r == NULL || ((auth == NULL) && (r->regstate == REG_STATE_REGSENT || r->regstate == REG_STATE_AUTHSENT))) {
15219       if (r) {
15220          ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
15221       }
15222       return 0;
15223    }
15224 
15225    if (r->dnsmgr == NULL) {
15226       char transport[MAXHOSTNAMELEN];
15227       peer = sip_find_peer(r->hostname, NULL, TRUE, FINDPEERS, FALSE, 0);
15228       snprintf(transport, sizeof(transport), "_%s._%s",get_srv_service(r->transport), get_srv_protocol(r->transport)); /* have to use static sip_get_transport function */
15229       r->us.ss.ss_family = get_address_family_filter(r->transport); /* Filter address family */
15230 
15231       /* No point in doing a DNS lookup of the register hostname if we're just going to
15232        * end up using an outbound proxy. obproxy_get is safe to call with either of r->call
15233        * or peer NULL. Since we're only concerned with its existence, we're not going to
15234        * bother getting a ref to the proxy*/
15235       if (!obproxy_get(r->call, peer)) {
15236          registry_addref(r, "add reg ref for dnsmgr");
15237          ast_dnsmgr_lookup_cb(peer ? peer->tohost : r->hostname, &r->us, &r->dnsmgr, sip_cfg.srvlookup ? transport : NULL, on_dns_update_registry, r);
15238          if (!r->dnsmgr) {
15239             /*dnsmgr refresh disabled, no reference added! */
15240             registry_unref(r, "remove reg ref, dnsmgr disabled");
15241          }
15242       }
15243       if (peer) {
15244          peer = sip_unref_peer(peer, "removing peer ref for dnsmgr_lookup");
15245       }
15246    }
15247 
15248    if (r->call) { /* We have a registration */
15249       if (!auth) {
15250          ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
15251          return 0;
15252       } else {
15253          p = dialog_ref(r->call, "getting a copy of the r->call dialog in transmit_register");
15254          ast_string_field_set(p, theirtag, NULL);  /* forget their old tag, so we don't match tags when getting response */
15255       }
15256    } else {
15257       /* Build callid for registration if we haven't registered before */
15258       if (!r->callid_valid) {
15259          build_callid_registry(r, &internip, default_fromdomain);
15260          build_localtag_registry(r);
15261          r->callid_valid = TRUE;
15262       }
15263       /* Allocate SIP dialog for registration */
15264       if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER, NULL, NULL))) {
15265          ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
15266          return 0;
15267       }
15268 
15269       /* reset tag to consistent value from registry */
15270       ast_string_field_set(p, tag, r->localtag);
15271 
15272       if (p->do_history) {
15273          append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
15274       }
15275 
15276       p->socket.type = r->transport;
15277 
15278       /* Use port number specified if no SRV record was found */
15279       if (!ast_sockaddr_isnull(&r->us)) {
15280          if (!ast_sockaddr_port(&r->us) && r->portno) {
15281             ast_sockaddr_set_port(&r->us, r->portno);
15282          }
15283 
15284          /* It is possible that DNS was unavailable at the time the peer was created.
15285           * Here, if we've updated the address in the registry via manually calling
15286           * ast_dnsmgr_lookup_cb() above, then we call the same function that dnsmgr would
15287           * call if it was updating a peer's address */
15288          if ((peer = sip_find_peer(S_OR(r->peername, r->hostname), NULL, TRUE, FINDPEERS, FALSE, 0))) {
15289             if (ast_sockaddr_cmp(&peer->addr, &r->us)) {
15290                on_dns_update_peer(&peer->addr, &r->us, peer);
15291             }
15292             peer = sip_unref_peer(peer, "unref after sip_find_peer");
15293          }
15294       }
15295 
15296       /* Find address to hostname */
15297       if (create_addr(p, S_OR(r->peername, r->hostname), &r->us, 0)) {
15298          /* we have what we hope is a temporary network error,
15299           * probably DNS.  We need to reschedule a registration try */
15300          dialog_unlink_all(p);
15301          p = dialog_unref(p, "unref dialog after unlink_all");
15302          if (r->timeout > -1) {
15303             AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
15304                               registry_unref(_data, "del for REPLACE of registry ptr"),
15305                               registry_unref(r, "object ptr dec when SCHED_REPLACE add failed"),
15306                               registry_addref(r,"add for REPLACE registry ptr"));
15307             ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
15308          } else {
15309             r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, registry_addref(r, "add for REPLACE registry ptr"));
15310             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);
15311          }
15312          r->regattempts++;
15313          return 0;
15314       }
15315 
15316       /* Copy back Call-ID in case create_addr changed it */
15317       ast_string_field_set(r, callid, p->callid);
15318 
15319       if (!r->dnsmgr && r->portno) {
15320          ast_sockaddr_set_port(&p->sa, r->portno);
15321          ast_sockaddr_set_port(&p->recv, r->portno);
15322       }
15323       if (!ast_strlen_zero(p->fromdomain)) {
15324          portno = (p->fromdomainport) ? p->fromdomainport : STANDARD_SIP_PORT;
15325       } else if (!ast_strlen_zero(r->regdomain)) {
15326          portno = (r->regdomainport) ? r->regdomainport : STANDARD_SIP_PORT;
15327       } else {
15328          portno = ast_sockaddr_port(&p->sa);
15329       }
15330 
15331       ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Registration is outgoing call */
15332       r->call = dialog_ref(p, "copying dialog into registry r->call");     /* Save pointer to SIP dialog */
15333       p->registry = registry_addref(r, "transmit_register: addref to p->registry in transmit_register"); /* Add pointer to registry in packet */
15334       if (!ast_strlen_zero(r->secret)) {  /* Secret (password) */
15335          ast_string_field_set(p, peersecret, r->secret);
15336       }
15337       if (!ast_strlen_zero(r->md5secret))
15338          ast_string_field_set(p, peermd5secret, r->md5secret);
15339       /* User name in this realm
15340       - if authuser is set, use that, otherwise use username */
15341       if (!ast_strlen_zero(r->authuser)) {
15342          ast_string_field_set(p, peername, r->authuser);
15343          ast_string_field_set(p, authname, r->authuser);
15344       } else if (!ast_strlen_zero(r->username)) {
15345          ast_string_field_set(p, peername, r->username);
15346          ast_string_field_set(p, authname, r->username);
15347          ast_string_field_set(p, fromuser, r->username);
15348       }
15349       if (!ast_strlen_zero(r->username)) {
15350          ast_string_field_set(p, username, r->username);
15351       }
15352       /* Save extension in packet */
15353       if (!ast_strlen_zero(r->callback)) {
15354          ast_string_field_set(p, exten, r->callback);
15355       }
15356 
15357       /* Set transport and port so the correct contact is built */
15358       set_socket_transport(&p->socket, r->transport);
15359       if (r->transport == SIP_TRANSPORT_TLS || r->transport == SIP_TRANSPORT_TCP) {
15360          p->socket.port =
15361              htons(ast_sockaddr_port(&sip_tcp_desc.local_address));
15362       }
15363 
15364       /*
15365         check which address we should use in our contact header
15366         based on whether the remote host is on the external or
15367         internal network so we can register through nat
15368        */
15369       ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
15370       build_contact(p);
15371    }
15372 
15373    /* set up a timeout */
15374    if (auth == NULL)  {
15375       if (r->timeout > -1) {
15376          ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
15377       }
15378       AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
15379                         registry_unref(_data,"reg ptr unrefed from del in SCHED_REPLACE"),
15380                         registry_unref(r,"reg ptr unrefed from add failure in SCHED_REPLACE"),
15381                         registry_addref(r,"reg ptr reffed from add in SCHED_REPLACE"));
15382       ast_debug(1, "Scheduled a registration timeout for %s id  #%d \n", r->hostname, r->timeout);
15383    }
15384 
15385    snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)), p->tag);
15386    if (!ast_strlen_zero(p->theirtag)) {
15387       snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)), p->theirtag);
15388    } else {
15389       snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)));
15390    }
15391 
15392    /* Fromdomain is what we are registering to, regardless of actual
15393       host name from SRV */
15394    if (portno && portno != STANDARD_SIP_PORT) {
15395       snprintf(addr, sizeof(addr), "sip:%s:%d", S_OR(p->fromdomain,S_OR(r->regdomain, sip_sanitized_host(r->hostname))), portno);
15396    } else {
15397       snprintf(addr, sizeof(addr), "sip:%s", S_OR(p->fromdomain,S_OR(r->regdomain, sip_sanitized_host(r->hostname))));
15398    }
15399 
15400    ast_string_field_set(p, uri, addr);
15401 
15402    p->branch ^= ast_random();
15403 
15404    init_req(&req, sipmethod, addr);
15405 
15406    /* Add to CSEQ */
15407    snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
15408    p->ocseq = r->ocseq;
15409 
15410    build_via(p);
15411    add_header(&req, "Via", p->via);
15412    add_max_forwards(p, &req);
15413    add_header(&req, "From", from);
15414    add_header(&req, "To", to);
15415    add_header(&req, "Call-ID", p->callid);
15416    add_header(&req, "CSeq", tmp);
15417    if (!ast_strlen_zero(global_useragent))
15418       add_header(&req, "User-Agent", global_useragent);
15419 
15420    if (auth) { /* Add auth header */
15421       add_header(&req, authheader, auth);
15422    } else if (!ast_strlen_zero(r->nonce)) {
15423       char digest[1024];
15424 
15425       /* We have auth data to reuse, build a digest header.
15426        * Note, this is not always useful because some parties do not
15427        * like nonces to be reused (for good reasons!) so they will
15428        * challenge us anyways.
15429        */
15430       if (sipdebug) {
15431          ast_debug(1, "   >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
15432       }
15433       ast_string_field_set(p, realm, r->realm);
15434       ast_string_field_set(p, nonce, r->nonce);
15435       ast_string_field_set(p, domain, r->authdomain);
15436       ast_string_field_set(p, opaque, r->opaque);
15437       ast_string_field_set(p, qop, r->qop);
15438       p->noncecount = ++r->noncecount;
15439 
15440       memset(digest, 0, sizeof(digest));
15441       if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
15442          add_header(&req, "Authorization", digest);
15443       } else {
15444          ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
15445       }
15446    }
15447 
15448    add_expires(&req, r->expiry);
15449    add_header(&req, "Contact", p->our_contact);
15450 
15451    initialize_initreq(p, &req);
15452    if (sip_debug_test_pvt(p)) {
15453       ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
15454    }
15455    r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
15456    r->regattempts++; /* Another attempt */
15457    ast_debug(4, "REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
15458    res = send_request(p, &req, XMIT_CRITICAL, p->ocseq);
15459    dialog_unref(p, "p is finished here at the end of transmit_register");
15460    return res;
15461 }
15462 
15463 /*!
15464  * \brief Transmit with SIP MESSAGE method
15465  * \note The p->msg_headers and p->msg_body are already setup.
15466  */
15467 static int transmit_message(struct sip_pvt *p, int init, int auth)
15468 {
15469    struct sip_request req;
15470 
15471    if (init) {
15472       initreqprep(&req, p, SIP_MESSAGE, NULL);
15473       initialize_initreq(p, &req);
15474    } else {
15475       reqprep(&req, p, SIP_MESSAGE, 0, 1);
15476    }
15477    if (auth) {
15478       return transmit_request_with_auth(p, SIP_MESSAGE, p->ocseq, XMIT_RELIABLE, 0);
15479    } else {
15480       add_text(&req, p);
15481       return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
15482    }
15483 }
15484 
15485 /*! \brief Allocate SIP refer structure */
15486 static int sip_refer_alloc(struct sip_pvt *p)
15487 {
15488    p->refer = ast_calloc_with_stringfields(1, struct sip_refer, 512);
15489    return p->refer ? 1 : 0;
15490 }
15491 
15492 /*! \brief Allocate SIP refer structure */
15493 static int sip_notify_alloc(struct sip_pvt *p)
15494 {
15495    p->notify = ast_calloc(1, sizeof(struct sip_notify));
15496    if (p->notify) {
15497       p->notify->content = ast_str_create(128);
15498    }
15499    return p->notify ? 1 : 0;
15500 }
15501 
15502 /*! \brief Transmit SIP REFER message (initiated by the transfer() dialplan application
15503    \note this is currently broken as we have no way of telling the dialplan
15504    engine whether a transfer succeeds or fails.
15505    \todo Fix the transfer() dialplan function so that a transfer may fail
15506 */
15507 static int transmit_refer(struct sip_pvt *p, const char *dest)
15508 {
15509    char from[256];
15510    const char *of;
15511    char *c;
15512    char referto[256];
15513    int   use_tls=FALSE;
15514 
15515    if (sipdebug) {
15516       ast_debug(1, "SIP transfer of %s to %s\n", p->callid, dest);
15517    }
15518 
15519    /* Are we transfering an inbound or outbound call ? */
15520    if (ast_test_flag(&p->flags[0], SIP_OUTGOING))  {
15521       of = sip_get_header(&p->initreq, "To");
15522    } else {
15523       of = sip_get_header(&p->initreq, "From");
15524    }
15525 
15526    ast_copy_string(from, of, sizeof(from));
15527    of = get_in_brackets(from);
15528    ast_string_field_set(p, from, of);
15529    if (!strncasecmp(of, "sip:", 4)) {
15530       of += 4;
15531    } else if (!strncasecmp(of, "sips:", 5)) {
15532       of += 5;
15533       use_tls = TRUE;
15534    } else {
15535       ast_log(LOG_NOTICE, "From address missing 'sip(s):', assuming sip:\n");
15536    }
15537    /* Get just the username part */
15538    if (strchr(dest, '@')) {
15539       c = NULL;
15540    } else if ((c = strchr(of, '@'))) {
15541       *c++ = '\0';
15542    }
15543    if (c) {
15544       snprintf(referto, sizeof(referto), "<sip%s:%s@%s>", use_tls ? "s" : "", dest, c);
15545    } else {
15546       snprintf(referto, sizeof(referto), "<sip%s:%s>", use_tls ? "s" : "", dest);
15547    }
15548 
15549    /* save in case we get 407 challenge */
15550    sip_refer_alloc(p);
15551    ast_string_field_set(p->refer, refer_to, referto);
15552    ast_string_field_set(p->refer, referred_by, p->our_contact);
15553    p->refer->status = REFER_SENT;   /* Set refer status */
15554 
15555    return transmit_invite(p, SIP_REFER, FALSE, 0, NULL);
15556    /* We should propably wait for a NOTIFY here until we ack the transfer */
15557    /* Maybe fork a new thread and wait for a STATUS of REFER_200OK on the refer status before returning to app_transfer */
15558 
15559    /*! \todo In theory, we should hang around and wait for a reply, before
15560    returning to the dial plan here. Don't know really how that would
15561    affect the transfer() app or the pbx, but, well, to make this
15562    useful we should have a STATUS code on transfer().
15563    */
15564 }
15565 
15566 /*! \brief Send SIP INFO advice of charge message */
15567 static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded)
15568 {
15569    struct sip_request req;
15570    struct ast_str *str = ast_str_alloca(512);
15571    const struct ast_aoc_unit_entry *unit_entry = ast_aoc_get_unit_info(decoded, 0);
15572    enum ast_aoc_charge_type charging = ast_aoc_get_charge_type(decoded);
15573 
15574    reqprep(&req, p, SIP_INFO, 0, 1);
15575 
15576    if (ast_aoc_get_msg_type(decoded) == AST_AOC_D) {
15577       ast_str_append(&str, 0, "type=active;");
15578    } else if (ast_aoc_get_msg_type(decoded) == AST_AOC_E) {
15579       ast_str_append(&str, 0, "type=terminated;");
15580    } else {
15581       /* unsupported message type */
15582       return -1;
15583    }
15584 
15585    switch (charging) {
15586    case AST_AOC_CHARGE_FREE:
15587       ast_str_append(&str, 0, "free-of-charge;");
15588       break;
15589    case AST_AOC_CHARGE_CURRENCY:
15590       ast_str_append(&str, 0, "charging;");
15591       ast_str_append(&str, 0, "charging-info=currency;");
15592       ast_str_append(&str, 0, "amount=%u;", ast_aoc_get_currency_amount(decoded));
15593       ast_str_append(&str, 0, "multiplier=%s;", ast_aoc_get_currency_multiplier_decimal(decoded));
15594       if (!ast_strlen_zero(ast_aoc_get_currency_name(decoded))) {
15595          ast_str_append(&str, 0, "currency=%s;", ast_aoc_get_currency_name(decoded));
15596       }
15597       break;
15598    case AST_AOC_CHARGE_UNIT:
15599       ast_str_append(&str, 0, "charging;");
15600       ast_str_append(&str, 0, "charging-info=pulse;");
15601       if (unit_entry) {
15602          ast_str_append(&str, 0, "recorded-units=%u;", unit_entry->amount);
15603       }
15604       break;
15605    default:
15606       ast_str_append(&str, 0, "not-available;");
15607    };
15608 
15609    add_header(&req, "AOC", ast_str_buffer(str));
15610 
15611    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
15612 }
15613 
15614 /*! \brief Send SIP INFO dtmf message, see Cisco documentation on cisco.com */
15615 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
15616 {
15617    struct sip_request req;
15618    
15619    reqprep(&req, p, SIP_INFO, 0, 1);
15620    add_digit(&req, digit, duration, (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO));
15621    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
15622 }
15623 
15624 /*! \brief Send SIP INFO with video update request */
15625 static int transmit_info_with_vidupdate(struct sip_pvt *p)
15626 {
15627    struct sip_request req;
15628    
15629    reqprep(&req, p, SIP_INFO, 0, 1);
15630    add_vidupdate(&req);
15631    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
15632 }
15633 
15634 /*! \brief Transmit generic SIP request
15635    returns XMIT_ERROR if transmit failed with a critical error (don't retry)
15636 */
15637 static int transmit_request(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch)
15638 {
15639    struct sip_request resp;
15640    
15641    reqprep(&resp, p, sipmethod, seqno, newbranch);
15642    if (sipmethod == SIP_CANCEL && p->answered_elsewhere) {
15643       add_header(&resp, "Reason", "SIP;cause=200;text=\"Call completed elsewhere\"");
15644    }
15645 
15646    if (sipmethod == SIP_ACK) {
15647       p->invitestate = INV_CONFIRMED;
15648    }
15649 
15650    return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
15651 }
15652 
15653 /*! \brief return the request and response header for a 401 or 407 code */
15654 void sip_auth_headers(enum sip_auth_type code, char **header, char **respheader)
15655 {
15656    if (code == WWW_AUTH) {       /* 401 */
15657       *header = "WWW-Authenticate";
15658       *respheader = "Authorization";
15659    } else if (code == PROXY_AUTH) { /* 407 */
15660       *header = "Proxy-Authenticate";
15661       *respheader = "Proxy-Authorization";
15662    } else {
15663       ast_verbose("-- wrong response code %d\n", code);
15664       *header = *respheader = "Invalid";
15665    }
15666 }
15667 
15668 /*! \brief Transmit SIP request, auth added */
15669 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch)
15670 {
15671    struct sip_request resp;
15672    
15673    reqprep(&resp, p, sipmethod, seqno, newbranch);
15674    if (!ast_strlen_zero(p->realm)) {
15675       char digest[1024];
15676 
15677       memset(digest, 0, sizeof(digest));
15678       if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
15679          char *dummy, *response;
15680          enum sip_auth_type code = p->options ? p->options->auth_type : PROXY_AUTH; /* XXX force 407 if unknown */
15681          sip_auth_headers(code, &dummy, &response);
15682          add_header(&resp, response, digest);
15683       } else {
15684          ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
15685       }
15686    }
15687 
15688    switch (sipmethod) {
15689    case SIP_BYE:
15690    {
15691       char buf[20];
15692 
15693       /*
15694        * We are hanging up.  If we know a cause for that, send it in
15695        * clear text to make debugging easier.
15696        */
15697       if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON) && p->hangupcause) {
15698          snprintf(buf, sizeof(buf), "Q.850;cause=%d", p->hangupcause & 0x7f);
15699          add_header(&resp, "Reason", buf);
15700       }
15701 
15702       add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->hangupcause));
15703       snprintf(buf, sizeof(buf), "%d", p->hangupcause);
15704       add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
15705       break;
15706    }
15707    case SIP_MESSAGE:
15708       add_text(&resp, p);
15709       break;
15710    default:
15711       break;
15712    }
15713 
15714    return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);   
15715 }
15716 
15717 /*! \brief Remove registration data from realtime database or AST/DB when registration expires */
15718 static void destroy_association(struct sip_peer *peer)
15719 {
15720    int realtimeregs = ast_check_realtime("sipregs");
15721    char *tablename = (realtimeregs) ? "sipregs" : "sippeers";
15722 
15723    if (!sip_cfg.ignore_regexpire) {
15724       if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
15725          ast_update_realtime(tablename, "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", "regserver", "", "useragent", "", "lastms", "0", SENTINEL);
15726       } else {
15727          ast_db_del("SIP/Registry", peer->name);
15728          ast_db_del("SIP/PeerMethods", peer->name);
15729       }
15730    }
15731 }
15732 
15733 static void set_socket_transport(struct sip_socket *socket, int transport)
15734 {
15735    /* if the transport type changes, clear all socket data */
15736    if (socket->type != transport) {
15737       socket->fd = -1;
15738       socket->type = transport;
15739       if (socket->tcptls_session) {
15740          ao2_ref(socket->tcptls_session, -1);
15741          socket->tcptls_session = NULL;
15742       } else if (socket->ws_session) {
15743          ast_websocket_unref(socket->ws_session);
15744          socket->ws_session = NULL;
15745       }
15746    }
15747 }
15748 
15749 /*! \brief Expire registration of SIP peer */
15750 static int expire_register(const void *data)
15751 {
15752    struct sip_peer *peer = (struct sip_peer *)data;
15753 
15754    if (!peer) {      /* Hmmm. We have no peer. Weird. */
15755       return 0;
15756    }
15757 
15758    peer->expire = -1;
15759    peer->portinuri = 0;
15760 
15761    destroy_association(peer); /* remove registration data from storage */
15762    set_socket_transport(&peer->socket, peer->default_outbound_transport);
15763 
15764    if (peer->socket.tcptls_session) {
15765       ao2_ref(peer->socket.tcptls_session, -1);
15766       peer->socket.tcptls_session = NULL;
15767    } else if (peer->socket.ws_session) {
15768       ast_websocket_unref(peer->socket.ws_session);
15769       peer->socket.ws_session = NULL;
15770    }
15771 
15772    manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
15773    register_peer_exten(peer, FALSE);   /* Remove regexten */
15774    ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", peer->name);
15775 
15776    /* Do we need to release this peer from memory?
15777       Only for realtime peers and autocreated peers
15778    */
15779    if (peer->is_realtime) {
15780       ast_debug(3, "-REALTIME- peer expired registration. Name: %s. Realtime peer objects now %d\n", peer->name, rpeerobjs);
15781    }
15782 
15783    if (peer->selfdestruct ||
15784        ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
15785       unlink_peer_from_tables(peer);
15786    } else if (!ast_sockaddr_isnull(&peer->addr)) {
15787       /* If we aren't self-destructing a temp_peer, we still need to unlink the peer
15788        * from the peers_by_ip table, otherwise we end up with multiple copies hanging
15789        * around each time a registration expires and the peer re-registers. */
15790       ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
15791    }
15792 
15793    /* Only clear the addr after we check for destruction.  The addr must remain
15794     * in order to unlink from the peers_by_ip container correctly */
15795    memset(&peer->addr, 0, sizeof(peer->addr));
15796 
15797    sip_unref_peer(peer, "removing peer ref for expire_register");
15798 
15799    return 0;
15800 }
15801 
15802 /*! \brief Poke peer (send qualify to check if peer is alive and well) */
15803 static int sip_poke_peer_s(const void *data)
15804 {
15805    struct sip_peer *peer = (struct sip_peer *)data;
15806    struct sip_peer *foundpeer;
15807 
15808    peer->pokeexpire = -1;
15809 
15810    foundpeer = ao2_find(peers, peer, OBJ_POINTER);
15811    if (!foundpeer) {
15812       sip_unref_peer(peer, "removing poke peer ref");
15813       return 0;
15814    } else if (foundpeer->name != peer->name) {
15815       sip_unref_peer(foundpeer, "removing above peer ref");
15816       sip_unref_peer(peer, "removing poke peer ref");
15817       return 0;
15818    }
15819 
15820    sip_unref_peer(foundpeer, "removing above peer ref");
15821    sip_poke_peer(peer, 0);
15822    sip_unref_peer(peer, "removing poke peer ref");
15823 
15824    return 0;
15825 }
15826 
15827 /*! \brief Get registration details from Asterisk DB */
15828 static void reg_source_db(struct sip_peer *peer)
15829 {
15830    char data[256];
15831    struct ast_sockaddr sa;
15832    int expire;
15833    char full_addr[128];
15834    AST_DECLARE_APP_ARGS(args,
15835       AST_APP_ARG(addr);
15836       AST_APP_ARG(port);
15837       AST_APP_ARG(expiry_str);
15838       AST_APP_ARG(username);
15839       AST_APP_ARG(contact);
15840    );
15841 
15842    /* If read-only RT backend, then refresh from local DB cache */
15843    if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
15844       return;
15845    }
15846    if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data))) {
15847       return;
15848    }
15849 
15850    AST_NONSTANDARD_RAW_ARGS(args, data, ':');
15851 
15852    snprintf(full_addr, sizeof(full_addr), "%s:%s", args.addr, args.port);
15853 
15854    if (!ast_sockaddr_parse(&sa, full_addr, 0)) {
15855       return;
15856    }
15857 
15858    if (args.expiry_str) {
15859       expire = atoi(args.expiry_str);
15860    } else {
15861       return;
15862    }
15863 
15864    if (args.username) {
15865       ast_string_field_set(peer, username, args.username);
15866    }
15867    if (args.contact) {
15868       ast_string_field_set(peer, fullcontact, args.contact);
15869    }
15870 
15871    ast_debug(2, "SIP Seeding peer from astdb: '%s' at %s@%s for %d\n",
15872        peer->name, peer->username, ast_sockaddr_stringify_host(&sa), expire);
15873 
15874    ast_sockaddr_copy(&peer->addr, &sa);
15875    if (peer->maxms) {
15876       /* Don't poke peer immediately, just schedule it within qualifyfreq */
15877       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
15878             ast_random() % ((peer->qualifyfreq) ? peer->qualifyfreq : global_qualifyfreq) + 1,
15879             sip_poke_peer_s, peer,
15880             sip_unref_peer(_data, "removing poke peer ref"),
15881             sip_unref_peer(peer, "removing poke peer ref"),
15882             sip_ref_peer(peer, "adding poke peer ref"));
15883    }
15884    AST_SCHED_REPLACE_UNREF(peer->expire, sched, (expire + 10) * 1000, expire_register, peer,
15885          sip_unref_peer(_data, "remove registration ref"),
15886          sip_unref_peer(peer, "remove registration ref"),
15887          sip_ref_peer(peer, "add registration ref"));
15888    register_peer_exten(peer, TRUE);
15889 }
15890 
15891 /*! \brief Save contact header for 200 OK on INVITE */
15892 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
15893 {
15894    char contact[SIPBUFSIZE];
15895    char *c;
15896 
15897    /* Look for brackets */
15898    ast_copy_string(contact, sip_get_header(req, "Contact"), sizeof(contact));
15899    c = get_in_brackets(contact);
15900 
15901    /* Save full contact to call pvt for later bye or re-invite */
15902    ast_string_field_set(pvt, fullcontact, c);
15903 
15904    /* Save URI for later ACKs, BYE or RE-invites */
15905    ast_string_field_set(pvt, okcontacturi, c);
15906 
15907    /* We should return false for URI:s we can't handle,
15908       like tel:, mailto:,ldap: etc */
15909    return TRUE;      
15910 }
15911 
15912 /*! \brief parse uri in a way that allows semicolon stripping if legacy mode is enabled
15913  *
15914  * \note This calls parse_uri which has the unexpected property that passing more
15915  *       arguments results in more splitting. Most common is to leave out the pass
15916  *       argument, causing user to contain user:pass if available.
15917  */
15918 static int parse_uri_legacy_check(char *uri, const char *scheme, char **user, char **pass, char **hostport, char **transport)
15919 {
15920    int ret = parse_uri(uri, scheme, user, pass, hostport, transport);
15921    if (sip_cfg.legacy_useroption_parsing) { /* if legacy mode is active, strip semis from the user field */
15922       char *p;
15923       if ((p = strchr(uri, (int)';'))) {
15924          *p = '\0';
15925       }
15926    }
15927    return ret;
15928 }
15929 
15930 static int __set_address_from_contact(const char *fullcontact, struct ast_sockaddr *addr, int tcp)
15931 {
15932    char *hostport, *transport;
15933    char contact_buf[256];
15934    char *contact;
15935 
15936    /* Work on a copy */
15937    ast_copy_string(contact_buf, fullcontact, sizeof(contact_buf));
15938    contact = contact_buf;
15939 
15940    /* 
15941     * We have only the part in <brackets> here so we just need to parse a SIP URI.
15942     *
15943     * Note: The outbound proxy could be using UDP between the proxy and Asterisk.
15944     * We still need to be able to send to the remote agent through the proxy.
15945     */
15946 
15947    if (parse_uri_legacy_check(contact, "sip:,sips:", &contact, NULL, &hostport,
15948             &transport)) {
15949       ast_log(LOG_WARNING, "Invalid contact uri %s (missing sip: or sips:), attempting to use anyway\n", fullcontact);
15950    }
15951 
15952    /* XXX This could block for a long time XXX */
15953    /* We should only do this if it's a name, not an IP */
15954    /* \todo - if there's no PORT number in contact - we are required to check NAPTR/SRV records
15955       to find transport, port address and hostname. If there's a port number, we have to
15956       assume that the hostport part is a host name and only look for an A/AAAA record in DNS.
15957    */
15958 
15959    /* If we took in an invalid URI, hostport may not have been initialized */
15960    /* ast_sockaddr_resolve requires an initialized hostport string. */
15961    if (ast_strlen_zero(hostport)) {
15962       ast_log(LOG_WARNING, "Invalid URI: parse_uri failed to acquire hostport\n");
15963       return -1;
15964    }
15965 
15966    if (ast_sockaddr_resolve_first_transport(addr, hostport, 0, get_transport_str2enum(transport))) {
15967       ast_log(LOG_WARNING, "Invalid host name in Contact: (can't "
15968          "resolve in DNS) : '%s'\n", hostport);
15969       return -1;
15970    }
15971 
15972    /* set port */
15973    if (!ast_sockaddr_port(addr)) {
15974       ast_sockaddr_set_port(addr,
15975                   (get_transport_str2enum(transport) ==
15976                    SIP_TRANSPORT_TLS ||
15977                    !strncasecmp(fullcontact, "sips", 4)) ?
15978                   STANDARD_TLS_PORT : STANDARD_SIP_PORT);
15979    }
15980 
15981    return 0;
15982 }
15983 
15984 /*! \brief Change the other partys IP address based on given contact */
15985 static int set_address_from_contact(struct sip_pvt *pvt)
15986 {
15987    if (ast_test_flag(&pvt->flags[0], SIP_NAT_FORCE_RPORT)) {
15988       /* NAT: Don't trust the contact field.  Just use what they came to us
15989          with. */
15990       /*! \todo We need to save the TRANSPORT here too */
15991       pvt->sa = pvt->recv;
15992       return 0;
15993    }
15994 
15995    return __set_address_from_contact(pvt->fullcontact, &pvt->sa, pvt->socket.type == SIP_TRANSPORT_TLS ? 1 : 0);
15996 }
15997 
15998 /*! \brief Parse contact header and save registration (peer registration) */
15999 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
16000 {
16001    char contact[SIPBUFSIZE];
16002    char data[SIPBUFSIZE];
16003    const char *expires = sip_get_header(req, "Expires");
16004    int expire = atoi(expires);
16005    char *curi = NULL, *hostport = NULL, *transport = NULL;
16006    int transport_type;
16007    const char *useragent;
16008    struct ast_sockaddr oldsin, testsa;
16009    char *firstcuri = NULL;
16010    int start = 0;
16011    int wildcard_found = 0;
16012    int single_binding_found = 0;
16013 
16014    ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
16015 
16016    if (ast_strlen_zero(expires)) {  /* No expires header, try look in Contact: */
16017       char *s = strcasestr(contact, ";expires=");
16018       if (s) {
16019          expires = strsep(&s, ";"); /* trim ; and beyond */
16020          if (sscanf(expires + 9, "%30d", &expire) != 1) {
16021             expire = default_expiry;
16022          }
16023       } else {
16024          /* Nothing has been specified */
16025          expire = default_expiry;
16026       }
16027    }
16028 
16029    if (expire > max_expiry) {
16030       expire = max_expiry;
16031    }
16032    if (expire < min_expiry && expire != 0) {
16033       expire = min_expiry;
16034    }
16035    pvt->expiry = expire;
16036 
16037    copy_socket_data(&pvt->socket, &req->socket);
16038 
16039    do {
16040       /* Look for brackets */
16041       curi = contact;
16042       if (strchr(contact, '<') == NULL)   /* No <, check for ; and strip it */
16043          strsep(&curi, ";");  /* This is Header options, not URI options */
16044       curi = get_in_brackets(contact);
16045       if (!firstcuri) {
16046          firstcuri = ast_strdupa(curi);
16047       }
16048 
16049       if (!strcasecmp(curi, "*")) {
16050          wildcard_found = 1;
16051       } else {
16052          single_binding_found = 1;
16053       }
16054 
16055       if (wildcard_found && (ast_strlen_zero(expires) || expire != 0 || single_binding_found)) {
16056          /* Contact header parameter "*" detected, so punt if: Expires header is missing,
16057           * Expires value is not zero, or another Contact header is present. */
16058          return PARSE_REGISTER_FAILED;
16059       }
16060 
16061       ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
16062    } while (!ast_strlen_zero(contact));
16063    curi = firstcuri;
16064 
16065    /* if they did not specify Contact: or Expires:, they are querying
16066       what we currently have stored as their contact address, so return
16067       it
16068    */
16069    if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
16070       /* If we have an active registration, tell them when the registration is going to expire */
16071       if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact)) {
16072          pvt->expiry = ast_sched_when(sched, peer->expire);
16073       }
16074       return PARSE_REGISTER_QUERY;
16075    } else if (!strcasecmp(curi, "*") || !expire) { /* Unregister this peer */
16076       /* This means remove all registrations and return OK */
16077       AST_SCHED_DEL_UNREF(sched, peer->expire,
16078             sip_unref_peer(peer, "remove register expire ref"));
16079       ast_verb(3, "Unregistered SIP '%s'\n", peer->name);
16080       expire_register(sip_ref_peer(peer,"add ref for explicit expire_register"));
16081       return PARSE_REGISTER_UPDATE;
16082    }
16083 
16084    /* Store whatever we got as a contact from the client */
16085    ast_string_field_set(peer, fullcontact, curi);
16086 
16087    /* For the 200 OK, we should use the received contact */
16088    ast_string_field_build(pvt, our_contact, "<%s>", curi);
16089 
16090    /* Make sure it's a SIP URL */
16091    if (ast_strlen_zero(curi) || parse_uri_legacy_check(curi, "sip:,sips:", &curi, NULL, &hostport, &transport)) {
16092       ast_log(LOG_NOTICE, "Not a valid SIP contact (missing sip:/sips:) trying to use anyway\n");
16093    }
16094 
16095    /* handle the transport type specified in Contact header. */
16096    if (!(transport_type = get_transport_str2enum(transport))) {
16097       transport_type = pvt->socket.type;
16098    }
16099 
16100    /* if the peer's socket type is different than the Registration
16101     * transport type, change it.  If it got this far, it is a
16102     * supported type, but check just in case */
16103    if ((peer->socket.type != transport_type) && (peer->transports & transport_type)) {
16104       set_socket_transport(&peer->socket, transport_type);
16105    }
16106 
16107    oldsin = peer->addr;
16108 
16109    /* If we were already linked into the peers_by_ip container unlink ourselves so nobody can find us */
16110    if (!ast_sockaddr_isnull(&peer->addr) && (!peer->is_realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS))) {
16111       ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
16112    }
16113 
16114    if ((transport_type != SIP_TRANSPORT_WS) && (transport_type != SIP_TRANSPORT_WSS) &&
16115        (!ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) && !ast_test_flag(&peer->flags[0], SIP_NAT_RPORT_PRESENT))) {
16116       /* use the data provided in the Contact header for call routing */
16117       ast_debug(1, "Store REGISTER's Contact header for call routing.\n");
16118       /* XXX This could block for a long time XXX */
16119       /*! \todo Check NAPTR/SRV if we have not got a port in the URI */
16120       if (ast_sockaddr_resolve_first_transport(&testsa, hostport, 0, peer->socket.type)) {
16121          ast_log(LOG_WARNING, "Invalid hostport '%s'\n", hostport);
16122          ast_string_field_set(peer, fullcontact, "");
16123          ast_string_field_set(pvt, our_contact, "");
16124          return PARSE_REGISTER_FAILED;
16125       }
16126 
16127       /* If we have a port number in the given URI, make sure we do remember to not check for NAPTR/SRV records.
16128          The hostport part is actually a host. */
16129       peer->portinuri = ast_sockaddr_port(&testsa) ? TRUE : FALSE;
16130 
16131       if (!ast_sockaddr_port(&testsa)) {
16132          ast_sockaddr_set_port(&testsa, default_sip_port(transport_type));
16133       }
16134 
16135       ast_sockaddr_copy(&peer->addr, &testsa);
16136    } else {
16137       /* Don't trust the contact field.  Just use what they came to us
16138          with */
16139       ast_debug(1, "Store REGISTER's src-IP:port for call routing.\n");
16140       peer->addr = pvt->recv;
16141    }
16142 
16143    /* Check that they're allowed to register at this IP */
16144    if (ast_apply_acl(sip_cfg.contact_acl, &peer->addr, "SIP contact ACL: ") != AST_SENSE_ALLOW ||
16145          ast_apply_acl(peer->contactacl, &peer->addr, "SIP contact ACL: ") != AST_SENSE_ALLOW) {
16146       ast_log(LOG_WARNING, "Domain '%s' disallowed by contact ACL (violating IP %s)\n", hostport,
16147             ast_sockaddr_stringify_addr(&peer->addr));
16148       ast_string_field_set(peer, fullcontact, "");
16149       ast_string_field_set(pvt, our_contact, "");
16150       return PARSE_REGISTER_DENIED;
16151    }
16152 
16153    /* if the Contact header information copied into peer->addr matches the
16154     * received address, and the transport types are the same, then copy socket
16155     * data into the peer struct */
16156    if ((peer->socket.type == pvt->socket.type) &&
16157       !ast_sockaddr_cmp(&peer->addr, &pvt->recv)) {
16158       copy_socket_data(&peer->socket, &pvt->socket);
16159    }
16160 
16161    /* Now that our address has been updated put ourselves back into the container for lookups */
16162    if (!peer->is_realtime || ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
16163       ao2_t_link(peers_by_ip, peer, "ao2_link into peers_by_ip table");
16164    }
16165 
16166    /* Save SIP options profile */
16167    peer->sipoptions = pvt->sipoptions;
16168 
16169    if (!ast_strlen_zero(curi) && ast_strlen_zero(peer->username)) {
16170       ast_string_field_set(peer, username, curi);
16171    }
16172 
16173    AST_SCHED_DEL_UNREF(sched, peer->expire,
16174          sip_unref_peer(peer, "remove register expire ref"));
16175 
16176    if (peer->is_realtime && !ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
16177       peer->expire = -1;
16178    } else {
16179       peer->expire = ast_sched_add(sched, (expire + 10) * 1000, expire_register,
16180             sip_ref_peer(peer, "add registration ref"));
16181       if (peer->expire == -1) {
16182          sip_unref_peer(peer, "remote registration ref");
16183       }
16184    }
16185    snprintf(data, sizeof(data), "%s:%d:%s:%s", ast_sockaddr_stringify(&peer->addr),
16186        expire, peer->username, peer->fullcontact);
16187    /* We might not immediately be able to reconnect via TCP, but try caching it anyhow */
16188    if (!peer->rt_fromcontact || !sip_cfg.peer_rtupdate)
16189       ast_db_put("SIP/Registry", peer->name, data);
16190    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));
16191 
16192    /* Is this a new IP address for us? */
16193    if (ast_sockaddr_cmp(&peer->addr, &oldsin)) {
16194       ast_verb(3, "Registered SIP '%s' at %s\n", peer->name,
16195          ast_sockaddr_stringify(&peer->addr));
16196    }
16197    sip_pvt_unlock(pvt);
16198    sip_poke_peer(peer, 0);
16199    sip_pvt_lock(pvt);
16200    register_peer_exten(peer, 1);
16201 
16202    /* Save User agent */
16203    useragent = sip_get_header(req, "User-Agent");
16204    if (strcasecmp(useragent, peer->useragent)) {
16205       ast_string_field_set(peer, useragent, useragent);
16206       ast_verb(4, "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
16207    }
16208    return PARSE_REGISTER_UPDATE;
16209 }
16210 
16211 /*! \brief Remove route from route list */
16212 static void free_old_route(struct sip_route *route)
16213 {
16214    struct sip_route *next;
16215 
16216    while (route) {
16217       next = route->next;
16218       ast_free(route);
16219       route = next;
16220    }
16221 }
16222 
16223 /*! \brief List all routes - mostly for debugging */
16224 static void list_route(struct sip_route *route)
16225 {
16226    if (!route) {
16227       ast_verbose("list_route: no route\n");
16228    } else {
16229       for (;route; route = route->next)
16230          ast_verbose("list_route: hop: <%s>\n", route->hop);
16231    }
16232 }
16233 
16234 /*! \brief Build route list from Record-Route header 
16235     \param resp the SIP response code or 0 for a request */
16236 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards, int resp)
16237 {
16238    struct sip_route *thishop, *head, *tail;
16239    int start = 0;
16240    int len;
16241    const char *rr, *c;
16242 
16243    /* Once a persistent route is set, don't fool with it */
16244    if (p->route && p->route_persistent) {
16245       ast_debug(1, "build_route: Retaining previous route: <%s>\n", p->route->hop);
16246       return;
16247    }
16248 
16249    if (p->route) {
16250       free_old_route(p->route);
16251       p->route = NULL;
16252    }
16253 
16254    /* We only want to create the route set the first time this is called except
16255       it is called from a provisional response.*/
16256    if ((resp < 100) || (resp > 199)) {
16257       p->route_persistent = 1;
16258    }
16259 
16260    /* Build a tailq, then assign it to p->route when done.
16261     * If backwards, we add entries from the head so they end up
16262     * in reverse order. However, we do need to maintain a correct
16263     * tail pointer because the contact is always at the end.
16264     */
16265    head = NULL;
16266    tail = head;
16267    /* 1st we pass through all the hops in any Record-Route headers */
16268    for (;;) {
16269       /* Each Record-Route header */
16270       int len = 0;
16271       const char *uri;
16272       rr = __get_header(req, "Record-Route", &start);
16273       if (*rr == '\0') {
16274          break;
16275       }
16276       while (!get_in_brackets_const(rr, &uri, &len)) {
16277          len++;
16278          rr = strchr(rr, ',');
16279          if(rr >= uri && rr < (uri + len)) {
16280             /* comma inside brackets*/
16281             const char *next_br = strchr(rr, '<');
16282             if (next_br && next_br < (uri + len)) {
16283                rr++;
16284                continue;
16285             }
16286             continue;
16287          }
16288          if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
16289             ast_copy_string(thishop->hop, uri, len);
16290             ast_debug(2, "build_route: Record-Route hop: <%s>\n", thishop->hop);
16291             /* Link in */
16292             if (backwards) {
16293                /* Link in at head so they end up in reverse order */
16294                thishop->next = head;
16295                head = thishop;
16296                /* If this was the first then it'll be the tail */
16297                if (!tail) {
16298                   tail = thishop;
16299                }
16300             } else {
16301                thishop->next = NULL;
16302                /* Link in at the end */
16303                if (tail) {
16304                   tail->next = thishop;
16305                } else {
16306                   head = thishop;
16307                }
16308                tail = thishop;
16309             }
16310          }
16311          rr = strchr(uri + len, ',');
16312          if (rr == NULL) {
16313             /* No more field-values, we're done with this header */
16314             break;
16315          }
16316          /* Advance past comma */
16317          rr++;
16318       }
16319    }
16320 
16321    /* Only append the contact if we are dealing with a strict router */
16322    if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop, ";lr") == NULL) ) {
16323       /* 2nd append the Contact: if there is one */
16324       /* Can be multiple Contact headers, comma separated values - we just take the first */
16325       char *contact = ast_strdupa(sip_get_header(req, "Contact"));
16326       if (!ast_strlen_zero(contact)) {
16327          ast_debug(2, "build_route: Contact hop: %s\n", contact);
16328          /* Look for <: delimited address */
16329          c = get_in_brackets(contact);
16330          len = strlen(c) + 1;
16331          if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
16332             /* ast_calloc is not needed because all fields are initialized in this block */
16333             ast_copy_string(thishop->hop, c, len);
16334             thishop->next = NULL;
16335             /* Goes at the end */
16336             if (tail) {
16337                tail->next = thishop;
16338             } else {
16339                head = thishop;
16340             }
16341          }
16342       }
16343    }
16344 
16345    /* Store as new route */
16346    p->route = head;
16347 
16348    /* For debugging dump what we ended up with */
16349    if (sip_debug_test_pvt(p)) {
16350       list_route(p->route);
16351    }
16352 }
16353 
16354 /*! \brief builds the sip_pvt's nonce field which is used for the authentication 
16355  *  challenge.  When forceupdate is not set, the nonce is only updated if
16356  *  the current one is stale.  In this case, a stalenonce is one which
16357  *  has already received a response, if a nonce has not received a response
16358  *  it is not always necessary or beneficial to create a new one. */
16359 
16360 static void build_nonce(struct sip_pvt *p, int forceupdate)
16361 {
16362    if (p->stalenonce || forceupdate || ast_strlen_zero(p->nonce)) {
16363       ast_string_field_build(p, nonce, "%08lx", ast_random()); /* Create nonce for challenge */
16364       p->stalenonce = 0;
16365    }
16366 }
16367 
16368 /*! \brief Takes the digest response and parses it */
16369 void sip_digest_parser(char *c, struct digestkeys *keys)
16370 {
16371         struct digestkeys *i = i;
16372 
16373         while(c && *(c = ast_skip_blanks(c)) ) { /* lookup for keys */
16374                 for (i = keys; i->key != NULL; i++) {
16375                         const char *separator = ",";    /* default */
16376 
16377                         if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
16378                                 continue;
16379                         }
16380                         /* Found. Skip keyword, take text in quotes or up to the separator. */
16381                         c += strlen(i->key);
16382                         if (*c == '"') { /* in quotes. Skip first and look for last */
16383                                 c++;
16384                                 separator = "\"";
16385                         }
16386                         i->s = c;
16387                         strsep(&c, separator);
16388                         break;
16389                 }
16390                 if (i->key == NULL) { /* not found, jump after space or comma */
16391          strsep(&c, " ,");
16392       }
16393         }
16394 }
16395 
16396 /*! \brief  Check user authorization from peer definition
16397    Some actions, like REGISTER and INVITEs from peers require
16398    authentication (if peer have secret set)
16399     \return 0 on success, non-zero on error
16400 */
16401 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
16402                 const char *secret, const char *md5secret, int sipmethod,
16403                 const char *uri, enum xmittype reliable)
16404 {
16405    const char *response;
16406    char *reqheader, *respheader;
16407    const char *authtoken;
16408    char a1_hash[256];
16409    char resp_hash[256]="";
16410    char *c;
16411    int is_bogus_peer = 0;
16412    int  wrongnonce = FALSE;
16413    int  good_response;
16414    const char *usednonce = p->nonce;
16415    struct ast_str *buf;
16416    int res;
16417 
16418    /* table of recognised keywords, and their value in the digest */
16419    struct digestkeys keys[] = {
16420       [K_RESP] = { "response=", "" },
16421       [K_URI] = { "uri=", "" },
16422       [K_USER] = { "username=", "" },
16423       [K_NONCE] = { "nonce=", "" },
16424       [K_LAST] = { NULL, NULL}
16425    };
16426 
16427    /* Always OK if no secret */
16428    if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret)) {
16429       return AUTH_SUCCESSFUL;
16430    }
16431 
16432    /* Always auth with WWW-auth since we're NOT a proxy */
16433    /* Using proxy-auth in a B2BUA may block proxy authorization in the same transaction */
16434    response = "401 Unauthorized";
16435 
16436    /*
16437     * Note the apparent swap of arguments below, compared to other
16438     * usages of sip_auth_headers().
16439     */
16440    sip_auth_headers(WWW_AUTH, &respheader, &reqheader);
16441 
16442    authtoken = sip_get_header(req, reqheader);
16443    if (req->ignore && !ast_strlen_zero(p->nonce) && ast_strlen_zero(authtoken)) {
16444       /* This is a retransmitted invite/register/etc, don't reconstruct authentication
16445          information */
16446       if (!reliable) {
16447          /* Resend message if this was NOT a reliable delivery.   Otherwise the
16448             retransmission should get it */
16449          transmit_response_with_auth(p, response, req, p->nonce, reliable, respheader, 0);
16450          /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
16451          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16452       }
16453       return AUTH_CHALLENGE_SENT;
16454    } else if (ast_strlen_zero(p->nonce) || ast_strlen_zero(authtoken)) {
16455       /* We have no auth, so issue challenge and request authentication */
16456       build_nonce(p, 1); /* Create nonce for challenge */
16457       transmit_response_with_auth(p, response, req, p->nonce, reliable, respheader, 0);
16458       /* Schedule auto destroy in 32 seconds */
16459       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16460       return AUTH_CHALLENGE_SENT;
16461    }
16462 
16463    /* --- We have auth, so check it */
16464 
16465    /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
16466       an example in the spec of just what it is you're doing a hash on. */
16467 
16468    if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
16469       return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
16470    }
16471 
16472    /* Make a copy of the response and parse it */
16473    res = ast_str_set(&buf, 0, "%s", authtoken);
16474 
16475    if (res == AST_DYNSTR_BUILD_FAILED) {
16476       return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
16477    }
16478 
16479    c = buf->str;
16480 
16481    sip_digest_parser(c, keys);
16482 
16483    /* We cannot rely on the bogus_peer having a bad md5 value. Someone could
16484     * use it to construct valid auth. */
16485    if (md5secret && strcmp(md5secret, BOGUS_PEER_MD5SECRET) == 0) {
16486       is_bogus_peer = 1;
16487    }
16488 
16489    /* Verify that digest username matches  the username we auth as */
16490    if (strcmp(username, keys[K_USER].s) && !is_bogus_peer) {
16491       ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
16492          username, keys[K_USER].s);
16493       /* Oops, we're trying something here */
16494       return AUTH_USERNAME_MISMATCH;
16495    }
16496 
16497    /* Verify nonce from request matches our nonce, and the nonce has not already been responded to.
16498     * If this check fails, send 401 with new nonce */
16499    if (strcasecmp(p->nonce, keys[K_NONCE].s) || p->stalenonce) { /* XXX it was 'n'casecmp ? */
16500       wrongnonce = TRUE;
16501       usednonce = keys[K_NONCE].s;
16502    } else {
16503       p->stalenonce = 1; /* now, since the nonce has a response, mark it as stale so it can't be sent or responded to again */
16504    }
16505 
16506    if (!ast_strlen_zero(md5secret)) {
16507       ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
16508    } else {
16509       char a1[256];
16510 
16511       snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
16512       ast_md5_hash(a1_hash, a1);
16513    }
16514 
16515    /* compute the expected response to compare with what we received */
16516    {
16517       char a2[256];
16518       char a2_hash[256];
16519       char resp[256];
16520 
16521       snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
16522             S_OR(keys[K_URI].s, uri));
16523       ast_md5_hash(a2_hash, a2);
16524       snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
16525       ast_md5_hash(resp_hash, resp);
16526    }
16527 
16528    good_response = keys[K_RESP].s &&
16529          !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash)) &&
16530          !is_bogus_peer; /* lastly, check that the peer isn't the fake peer */
16531    if (wrongnonce) {
16532       if (good_response) {
16533          if (sipdebug)
16534             ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", sip_get_header(req, "From"));
16535          /* We got working auth token, based on stale nonce . */
16536          build_nonce(p, 0);
16537          transmit_response_with_auth(p, response, req, p->nonce, reliable, respheader, TRUE);
16538       } else {
16539          /* Everything was wrong, so give the device one more try with a new challenge */
16540          if (!req->ignore) {
16541             if (sipdebug) {
16542                ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", sip_get_header(req, "To"));
16543             }
16544             build_nonce(p, 1);
16545          } else {
16546             if (sipdebug) {
16547                ast_log(LOG_NOTICE, "Duplicate authentication received from '%s'\n", sip_get_header(req, "To"));
16548             }
16549          }
16550          transmit_response_with_auth(p, response, req, p->nonce, reliable, respheader, FALSE);
16551       }
16552 
16553       /* Schedule auto destroy in 32 seconds */
16554       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16555       return AUTH_CHALLENGE_SENT;
16556    }
16557    if (good_response) {
16558       append_history(p, "AuthOK", "Auth challenge successful for %s", username);
16559       return AUTH_SUCCESSFUL;
16560    }
16561 
16562    /* Ok, we have a bad username/secret pair */
16563    /* Tell the UAS not to re-send this authentication data, because
16564       it will continue to fail
16565    */
16566 
16567    return AUTH_SECRET_FAILED;
16568 }
16569 
16570 /*! \brief Change onhold state of a peer using a pvt structure */
16571 static void sip_peer_hold(struct sip_pvt *p, int hold)
16572 {
16573    if (!p->relatedpeer) {
16574       return;
16575    }
16576 
16577    /* If they put someone on hold, increment the value... otherwise decrement it */
16578    ast_atomic_fetchadd_int(&p->relatedpeer->onhold, (hold ? +1 : -1));
16579 
16580    /* Request device state update */
16581    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),
16582               "SIP/%s", p->relatedpeer->name);
16583 
16584    return;
16585 }
16586 
16587 /*! \brief Receive MWI events that we have subscribed to */
16588 static void mwi_event_cb(const struct ast_event *event, void *userdata)
16589 {
16590    struct sip_peer *peer = userdata;
16591 
16592    sip_send_mwi_to_peer(peer, 0);
16593 }
16594 
16595 static void network_change_event_subscribe(void)
16596 {
16597    if (!network_change_event_subscription) {
16598       network_change_event_subscription = ast_event_subscribe(AST_EVENT_NETWORK_CHANGE,
16599          network_change_event_cb, "SIP Network Change", NULL, AST_EVENT_IE_END);
16600    }
16601 }
16602 
16603 static void network_change_event_unsubscribe(void)
16604 {
16605    if (network_change_event_subscription) {
16606       network_change_event_subscription = ast_event_unsubscribe(network_change_event_subscription);
16607    }
16608 }
16609 
16610 static void acl_change_event_subscribe(void)
16611 {
16612    if (!acl_change_event_subscription) {
16613       acl_change_event_subscription = ast_event_subscribe(AST_EVENT_ACL_CHANGE,
16614       acl_change_event_cb, "Manager must react to Named ACL changes", NULL, AST_EVENT_IE_END);
16615    }
16616 
16617 }
16618 
16619 static void acl_change_event_unsubscribe(void)
16620 {
16621    if (acl_change_event_subscription) {
16622       acl_change_event_subscription = ast_event_unsubscribe(acl_change_event_subscription);
16623    }
16624 }
16625 
16626 static int network_change_event_sched_cb(const void *data)
16627 {
16628    network_change_event_sched_id = -1;
16629    sip_send_all_registers();
16630    sip_send_all_mwi_subscriptions();
16631    return 0;
16632 }
16633 
16634 static void network_change_event_cb(const struct ast_event *event, void *userdata)
16635 {
16636    ast_debug(1, "SIP, got a network change event, renewing all SIP registrations.\n");
16637    if (network_change_event_sched_id == -1) {
16638       network_change_event_sched_id = ast_sched_add(sched, 1000, network_change_event_sched_cb, NULL);
16639    }
16640 }
16641 
16642 static void cb_extensionstate_destroy(int id, void *data)
16643 {
16644    struct sip_pvt *p = data;
16645 
16646    dialog_unref(p, "the extensionstate containing this dialog ptr was destroyed");
16647 }
16648 
16649 /*! \brief Callback for the devicestate notification (SUBSCRIBE) support subsystem
16650 \note If you add an "hint" priority to the extension in the dial plan,
16651    you will get notifications on device state changes */
16652 static int extensionstate_update(const char *context, const char *exten, struct state_notify_data *data, struct sip_pvt *p, int force)
16653 {
16654    sip_pvt_lock(p);
16655 
16656    switch (data->state) {
16657    case AST_EXTENSION_DEACTIVATED:  /* Retry after a while */
16658    case AST_EXTENSION_REMOVED:   /* Extension is gone */
16659       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);  /* Delete subscription in 32 secs */
16660       ast_verb(2, "Extension state: Watcher for hint %s %s. Notify User %s\n", exten, data->state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", p->username);
16661       p->subscribed = NONE;
16662       append_history(p, "Subscribestatus", "%s", data->state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
16663       break;
16664    default: /* Tell user */
16665       if (force) {
16666          /* we must skip the next two checks for a queued state change or resubscribe */
16667       } else if ((p->laststate == data->state && (~data->state & AST_EXTENSION_RINGING)) &&
16668             (p->last_presence_state == data->presence_state &&
16669                !strcmp(p->last_presence_subtype, data->presence_subtype) &&
16670                !strcmp(p->last_presence_message, data->presence_message))) {
16671          /* don't notify unchanged state or unchanged early-state causing parties again */
16672          sip_pvt_unlock(p);
16673          return 0;
16674       } else if (data->state & AST_EXTENSION_RINGING) {
16675          /* check if another channel than last time is ringing now to be notified */
16676          struct ast_channel *ringing = find_ringing_channel(data->device_state_info, p);
16677          if (ringing) {
16678             if (!ast_tvcmp(ast_channel_creationtime(ringing), p->last_ringing_channel_time)) {
16679                /* we assume here that no two channels have the exact same creation time */
16680                ao2_ref(ringing, -1);
16681                sip_pvt_unlock(p);
16682                return 0;
16683             } else {
16684                p->last_ringing_channel_time = ast_channel_creationtime(ringing);
16685                ao2_ref(ringing, -1);
16686             }
16687          }
16688          /* If no ringing channel was found, it doesn't necessarily indicate anything bad.
16689           * Likely, a device state change occurred for a custom device state, which does not
16690           * correspond to any channel. In such a case, just go ahead and pass the notification
16691           * along.
16692           */
16693       }
16694       /* ref before unref because the new could be the same as the old one. Don't risk destruction! */
16695       if (data->device_state_info) {
16696          ao2_ref(data->device_state_info, 1);
16697       }
16698       ao2_cleanup(p->last_device_state_info);
16699       p->last_device_state_info = data->device_state_info;
16700       p->laststate = data->state;
16701       p->last_presence_state = data->presence_state;
16702       ast_string_field_set(p, last_presence_subtype, S_OR(data->presence_subtype, ""));
16703       ast_string_field_set(p, last_presence_message, S_OR(data->presence_message, ""));
16704       break;
16705    }
16706    if (p->subscribed != NONE) {  /* Only send state NOTIFY if we know the format */
16707       if (!p->pendinginvite) {
16708          transmit_state_notify(p, data, 1, FALSE);
16709          if (p->last_device_state_info) {
16710             /* We don't need the saved ref anymore, don't keep channels ref'd. */
16711             ao2_ref(p->last_device_state_info, -1);
16712             p->last_device_state_info = NULL;
16713          }
16714       } else {
16715          /* We already have a NOTIFY sent that is not answered. Queue the state up.
16716             if many state changes happen meanwhile, we will only send a notification of the last one */
16717          ast_set_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
16718       }
16719    }
16720 
16721    if (!force) {
16722       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,
16723             ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE) ? "(queued)" : "");
16724    }
16725 
16726    sip_pvt_unlock(p);
16727 
16728    return 0;
16729 }
16730 
16731 /*! \brief Callback for the devicestate notification (SUBSCRIBE) support subsystem
16732 \note If you add an "hint" priority to the extension in the dial plan,
16733    you will get notifications on device state changes */
16734 static int cb_extensionstate(char *context, char *exten, struct ast_state_cb_info *info, void *data)
16735 {
16736    struct sip_pvt *p = data;
16737    struct state_notify_data notify_data = {
16738       .state = info->exten_state,
16739       .device_state_info = info->device_state_info,
16740       .presence_state = info->presence_state,
16741       .presence_subtype = info->presence_subtype,
16742       .presence_message = info->presence_message,
16743    };
16744 
16745    if ((info->reason == AST_HINT_UPDATE_PRESENCE) && !(allow_notify_user_presence(p))) {
16746       /* ignore a presence triggered update if we know the useragent doesn't care */
16747       return 0;
16748    }
16749 
16750    return extensionstate_update(context, exten, &notify_data, p, FALSE);
16751 }
16752 
16753 /*! \brief Send a fake 401 Unauthorized response when the administrator
16754   wants to hide the names of local devices  from fishers
16755  */
16756 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable)
16757 {
16758    /* We have to emulate EXACTLY what we'd get with a good peer
16759     * and a bad password, or else we leak information. */
16760    const char *response = "401 Unauthorized";
16761    const char *reqheader = "Authorization";
16762    const char *respheader = "WWW-Authenticate";
16763    const char *authtoken;
16764    struct ast_str *buf;
16765    char *c;
16766 
16767    /* table of recognised keywords, and their value in the digest */
16768    enum keys { K_NONCE, K_LAST };
16769    struct x {
16770       const char *key;
16771       const char *s;
16772    } *i, keys[] = {
16773       [K_NONCE] = { "nonce=", "" },
16774       [K_LAST] = { NULL, NULL}
16775    };
16776 
16777    authtoken = sip_get_header(req, reqheader);
16778    if (req->ignore && !ast_strlen_zero(p->nonce) && ast_strlen_zero(authtoken)) {
16779       /* This is a retransmitted invite/register/etc, don't reconstruct authentication
16780        * information */
16781       transmit_response_with_auth(p, response, req, p->nonce, reliable, respheader, 0);
16782       /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
16783       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16784       return;
16785    } else if (ast_strlen_zero(p->nonce) || ast_strlen_zero(authtoken)) {
16786       /* We have no auth, so issue challenge and request authentication */
16787       build_nonce(p, 1);
16788       transmit_response_with_auth(p, response, req, p->nonce, reliable, respheader, 0);
16789       /* Schedule auto destroy in 32 seconds */
16790       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16791       return;
16792    }
16793 
16794    if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
16795       __transmit_response(p, "403 Forbidden", &p->initreq, reliable);
16796       return;
16797    }
16798 
16799    /* Make a copy of the response and parse it */
16800    if (ast_str_set(&buf, 0, "%s", authtoken) == AST_DYNSTR_BUILD_FAILED) {
16801       __transmit_response(p, "403 Forbidden", &p->initreq, reliable);
16802       return;
16803    }
16804 
16805    c = buf->str;
16806 
16807    while (c && *(c = ast_skip_blanks(c))) { /* lookup for keys */
16808       for (i = keys; i->key != NULL; i++) {
16809          const char *separator = ",";  /* default */
16810 
16811          if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
16812             continue;
16813          }
16814          /* Found. Skip keyword, take text in quotes or up to the separator. */
16815          c += strlen(i->key);
16816          if (*c == '"') { /* in quotes. Skip first and look for last */
16817             c++;
16818             separator = "\"";
16819          }
16820          i->s = c;
16821          strsep(&c, separator);
16822          break;
16823       }
16824       if (i->key == NULL) { /* not found, jump after space or comma */
16825          strsep(&c, " ,");
16826       }
16827    }
16828 
16829    /* Verify nonce from request matches our nonce.  If not, send 401 with new nonce */
16830    if (strcasecmp(p->nonce, keys[K_NONCE].s)) {
16831       if (!req->ignore) {
16832          build_nonce(p, 1);
16833       }
16834       transmit_response_with_auth(p, response, req, p->nonce, reliable, respheader, FALSE);
16835 
16836       /* Schedule auto destroy in 32 seconds */
16837       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16838    } else {
16839       __transmit_response(p, "403 Forbidden", &p->initreq, reliable);
16840    }
16841 }
16842 
16843 /*!
16844  * Terminate the uri at the first ';' or space.
16845  * Technically we should ignore escaped space per RFC3261 (19.1.1 etc)
16846  * but don't do it for the time being. Remember the uri format is:
16847  * (User-parameters was added after RFC 3261)
16848  *\verbatim
16849  *
16850  * sip:user:password;user-parameters@host:port;uri-parameters?headers
16851  * sips:user:password;user-parameters@host:port;uri-parameters?headers
16852  *
16853  *\endverbatim
16854  * \todo As this function does not support user-parameters, it's considered broken
16855  * and needs fixing.
16856  */
16857 static char *terminate_uri(char *uri)
16858 {
16859    char *t = uri;
16860    while (*t && *t > ' ' && *t != ';') {
16861       t++;
16862    }
16863    *t = '\0';
16864    return uri;
16865 }
16866 
16867 /*! \brief Terminate a host:port at the ':'
16868  * \param hostport The address of the hostport string
16869  *
16870  * \note In the case of a bracket-enclosed IPv6 address, the hostport variable
16871  * will contain the non-bracketed host as a result of calling this function.
16872  */
16873 static void extract_host_from_hostport(char **hostport)
16874 {
16875    char *dont_care;
16876    ast_sockaddr_split_hostport(*hostport, hostport, &dont_care, PARSE_PORT_IGNORE);
16877 }
16878 
16879 /*! \internal \brief Helper function to update a peer's lastmsgssent value
16880  */
16881 static void update_peer_lastmsgssent(struct sip_peer *peer, int value, int locked)
16882 {
16883    if (!locked) {
16884       ao2_lock(peer);
16885    }
16886    peer->lastmsgssent = value;
16887    if (!locked) {
16888       ao2_unlock(peer);
16889    }
16890 }
16891 
16892 
16893 /*! \brief Verify registration of user
16894    - Registration is done in several steps, first a REGISTER without auth
16895      to get a challenge (nonce) then a second one with auth
16896    - Registration requests are only matched with peers that are marked as "dynamic"
16897  */
16898 static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
16899                      struct sip_request *req, const char *uri)
16900 {
16901    enum check_auth_result res = AUTH_NOT_FOUND;
16902    struct sip_peer *peer;
16903    char tmp[256];
16904    char *c, *name, *unused_password, *domain;
16905    char *uri2 = ast_strdupa(uri);
16906    int send_mwi = 0;
16907 
16908    terminate_uri(uri2);
16909 
16910    ast_copy_string(tmp, sip_get_header(req, "To"), sizeof(tmp));
16911 
16912    c = get_in_brackets(tmp);
16913    c = remove_uri_parameters(c);
16914 
16915    if (parse_uri_legacy_check(c, "sip:,sips:", &name, &unused_password, &domain, NULL)) {
16916       ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_sockaddr_stringify_addr(addr));
16917       return -1;
16918    }
16919 
16920    SIP_PEDANTIC_DECODE(name);
16921    SIP_PEDANTIC_DECODE(domain);
16922 
16923    extract_host_from_hostport(&domain);
16924 
16925    if (ast_strlen_zero(domain)) {
16926       /* <sip:name@[EMPTY]>, never good */
16927       transmit_response(p, "404 Not found", &p->initreq);
16928       return AUTH_UNKNOWN_DOMAIN;
16929    }
16930 
16931    if (ast_strlen_zero(name)) {
16932       /* <sip:[EMPTY][@]hostport>, unsure whether valid for
16933        * registration. RFC 3261, 10.2 states:
16934        * "The To header field and the Request-URI field typically
16935        * differ, as the former contains a user name."
16936        * But, Asterisk has always treated the domain-only uri as a
16937        * username: we allow admins to create accounts described by
16938        * domain name. */
16939       name = domain;
16940    }
16941 
16942    /* This here differs from 1.4 and 1.6: the domain matching ACLs were
16943     * skipped if it was a domain-only URI (used as username). Here we treat
16944     * <sip:hostport> as <sip:host@hostport> and won't forget to test the
16945     * domain ACLs against host. */
16946    if (!AST_LIST_EMPTY(&domain_list)) {
16947       if (!check_sip_domain(domain, NULL, 0)) {
16948          if (sip_cfg.alwaysauthreject) {
16949             transmit_fake_auth_response(p, &p->initreq, XMIT_UNRELIABLE);
16950          } else {
16951             transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
16952          }
16953          return AUTH_UNKNOWN_DOMAIN;
16954       }
16955    }
16956 
16957    ast_string_field_set(p, exten, name);
16958    build_contact(p);
16959    if (req->ignore) {
16960       /* Expires is a special case, where we only want to load the peer if this isn't a deregistration attempt */
16961       const char *expires = sip_get_header(req, "Expires");
16962       int expire = atoi(expires);
16963 
16964       if (ast_strlen_zero(expires)) { /* No expires header; look in Contact */
16965          if ((expires = strcasestr(sip_get_header(req, "Contact"), ";expires="))) {
16966             expire = atoi(expires + 9);
16967          }
16968       }
16969       if (!ast_strlen_zero(expires) && expire == 0) {
16970          transmit_response_with_date(p, "200 OK", req);
16971          return 0;
16972       }
16973    }
16974    peer = sip_find_peer(name, NULL, TRUE, FINDPEERS, FALSE, 0);
16975 
16976    /* If we don't want username disclosure, use the bogus_peer when a user
16977     * is not found. */
16978    if (!peer && sip_cfg.alwaysauthreject && sip_cfg.autocreatepeer == AUTOPEERS_DISABLED) {
16979       peer = bogus_peer;
16980       sip_ref_peer(peer, "register_verify: ref the bogus_peer");
16981    }
16982 
16983    if (!(peer && ast_apply_acl(peer->acl, addr, "SIP Peer ACL: "))) {
16984       /* Peer fails ACL check */
16985       if (peer) {
16986          sip_unref_peer(peer, "register_verify: sip_unref_peer: from sip_find_peer operation");
16987          peer = NULL;
16988          res = AUTH_ACL_FAILED;
16989       } else {
16990          res = AUTH_NOT_FOUND;
16991       }
16992    }
16993 
16994    if (peer) {
16995       ao2_lock(peer);
16996       if (!peer->host_dynamic) {
16997          ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
16998          res = AUTH_PEER_NOT_DYNAMIC;
16999       } else {
17000 
17001          set_peer_nat(p, peer);
17002 
17003          ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT_FORCE_RPORT);
17004 
17005          if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri2, XMIT_UNRELIABLE))) {
17006             if (sip_cancel_destroy(p))
17007                ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
17008 
17009             if (check_request_transport(peer, req)) {
17010                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
17011                transmit_response_with_date(p, "403 Forbidden", req);
17012                res = AUTH_BAD_TRANSPORT;
17013             } else {
17014 
17015                /* We have a successful registration attempt with proper authentication,
17016                now, update the peer */
17017                switch (parse_register_contact(p, peer, req)) {
17018                case PARSE_REGISTER_DENIED:
17019                   ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
17020                   transmit_response_with_date(p, "603 Denied", req);
17021                   res = 0;
17022                   break;
17023                case PARSE_REGISTER_FAILED:
17024                   ast_log(LOG_WARNING, "Failed to parse contact info\n");
17025                   transmit_response_with_date(p, "400 Bad Request", req);
17026                   res = 0;
17027                   break;
17028                case PARSE_REGISTER_QUERY:
17029                   ast_string_field_set(p, fullcontact, peer->fullcontact);
17030                   transmit_response_with_date(p, "200 OK", req);
17031                   res = 0;
17032                   send_mwi = 1;
17033                   break;
17034                case PARSE_REGISTER_UPDATE:
17035                   ast_string_field_set(p, fullcontact, peer->fullcontact);
17036                   /* If expiry is 0, peer has been unregistered already */
17037                   if (p->expiry != 0) {
17038                      update_peer(peer, p->expiry);
17039                   }
17040                   /* Say OK and ask subsystem to retransmit msg counter */
17041                   transmit_response_with_date(p, "200 OK", req);
17042                   send_mwi = 1;
17043                   res = 0;
17044                   break;
17045                }
17046             }
17047 
17048          }
17049       }
17050       ao2_unlock(peer);
17051    }
17052    if (!peer && sip_cfg.autocreatepeer != AUTOPEERS_DISABLED) {
17053       /* Create peer if we have autocreate mode enabled */
17054       peer = temp_peer(name);
17055       if (peer) {
17056          ao2_t_link(peers, peer, "link peer into peer table");
17057          if (!ast_sockaddr_isnull(&peer->addr)) {
17058             ao2_t_link(peers_by_ip, peer, "link peer into peers-by-ip table");
17059          }
17060          ao2_lock(peer);
17061          if (sip_cancel_destroy(p))
17062             ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
17063          switch (parse_register_contact(p, peer, req)) {
17064          case PARSE_REGISTER_DENIED:
17065             ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
17066             transmit_response_with_date(p, "403 Forbidden", req);
17067             res = 0;
17068             break;
17069          case PARSE_REGISTER_FAILED:
17070             ast_log(LOG_WARNING, "Failed to parse contact info\n");
17071             transmit_response_with_date(p, "400 Bad Request", req);
17072             res = 0;
17073             break;
17074          case PARSE_REGISTER_QUERY:
17075             ast_string_field_set(p, fullcontact, peer->fullcontact);
17076             transmit_response_with_date(p, "200 OK", req);
17077             send_mwi = 1;
17078             res = 0;
17079             break;
17080          case PARSE_REGISTER_UPDATE:
17081             ast_string_field_set(p, fullcontact, peer->fullcontact);
17082             /* Say OK and ask subsystem to retransmit msg counter */
17083             transmit_response_with_date(p, "200 OK", req);
17084             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));
17085             send_mwi = 1;
17086             res = 0;
17087             break;
17088          }
17089          ao2_unlock(peer);
17090       }
17091    }
17092    if (!res) {
17093       if (send_mwi) {
17094          sip_pvt_unlock(p);
17095          sip_send_mwi_to_peer(peer, 0);
17096          sip_pvt_lock(p);
17097       } else {
17098          update_peer_lastmsgssent(peer, -1, 0);
17099       }
17100       ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", peer->name);
17101    }
17102    if (res < 0) {
17103       switch (res) {
17104       case AUTH_SECRET_FAILED:
17105          /* Wrong password in authentication. Go away, don't try again until you fixed it */
17106          transmit_response(p, "403 Forbidden", &p->initreq);
17107          if (global_authfailureevents) {
17108             const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
17109             const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
17110             manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
17111                      "ChannelType: SIP\r\n"
17112                      "Peer: SIP/%s\r\n"
17113                      "PeerStatus: Rejected\r\n"
17114                      "Cause: AUTH_SECRET_FAILED\r\n"
17115                      "Address: %s\r\n"
17116                      "Port: %s\r\n",
17117                      name, peer_addr, peer_port);
17118          }
17119          break;
17120       case AUTH_USERNAME_MISMATCH:
17121          /* Username and digest username does not match.
17122             Asterisk uses the From: username for authentication. We need the
17123             devices to use the same authentication user name until we support
17124             proper authentication by digest auth name */
17125       case AUTH_NOT_FOUND:
17126       case AUTH_PEER_NOT_DYNAMIC:
17127       case AUTH_ACL_FAILED:
17128          if (sip_cfg.alwaysauthreject) {
17129             transmit_fake_auth_response(p, &p->initreq, XMIT_UNRELIABLE);
17130             if (global_authfailureevents) {
17131                const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
17132                const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
17133                manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
17134                         "ChannelType: SIP\r\n"
17135                         "Peer: SIP/%s\r\n"
17136                         "PeerStatus: Rejected\r\n"
17137                         "Cause: %s\r\n"
17138                         "Address: %s\r\n"
17139                         "Port: %s\r\n",
17140                         name,
17141                         res == AUTH_PEER_NOT_DYNAMIC ? "AUTH_PEER_NOT_DYNAMIC" : "URI_NOT_FOUND",
17142                         peer_addr, peer_port);
17143             }
17144          } else {
17145             /* URI not found */
17146             if (res == AUTH_PEER_NOT_DYNAMIC) {
17147                transmit_response(p, "403 Forbidden", &p->initreq);
17148                if (global_authfailureevents) {
17149                   const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
17150                   const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
17151                   manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
17152                      "ChannelType: SIP\r\n"
17153                      "Peer: SIP/%s\r\n"
17154                      "PeerStatus: Rejected\r\n"
17155                      "Cause: AUTH_PEER_NOT_DYNAMIC\r\n"
17156                      "Address: %s\r\n"
17157                      "Port: %s\r\n",
17158                      name, peer_addr, peer_port);
17159                }
17160             } else {
17161                transmit_response(p, "404 Not found", &p->initreq);
17162                if (global_authfailureevents) {
17163                   const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
17164                   const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
17165                   manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
17166                      "ChannelType: SIP\r\n"
17167                      "Peer: SIP/%s\r\n"
17168                      "PeerStatus: Rejected\r\n"
17169                      "Cause: %s\r\n"
17170                      "Address: %s\r\n"
17171                      "Port: %s\r\n",
17172                      name,
17173                      (res == AUTH_USERNAME_MISMATCH) ? "AUTH_USERNAME_MISMATCH" : "URI_NOT_FOUND",
17174                      peer_addr, peer_port);
17175                }
17176             }
17177          }
17178          break;
17179       case AUTH_BAD_TRANSPORT:
17180       default:
17181          break;
17182       }
17183    }
17184    if (peer) {
17185       sip_unref_peer(peer, "register_verify: sip_unref_peer: tossing stack peer pointer at end of func");
17186    }
17187 
17188    return res;
17189 }
17190 
17191 /*! \brief Translate referring cause */
17192 static void sip_set_redirstr(struct sip_pvt *p, char *reason) {
17193 
17194    if (!strcmp(reason, "unknown")) {
17195       ast_string_field_set(p, redircause, "UNKNOWN");
17196    } else if (!strcmp(reason, "user-busy")) {
17197       ast_string_field_set(p, redircause, "BUSY");
17198    } else if (!strcmp(reason, "no-answer")) {
17199       ast_string_field_set(p, redircause, "NOANSWER");
17200    } else if (!strcmp(reason, "unavailable")) {
17201       ast_string_field_set(p, redircause, "UNREACHABLE");
17202    } else if (!strcmp(reason, "unconditional")) {
17203       ast_string_field_set(p, redircause, "UNCONDITIONAL");
17204    } else if (!strcmp(reason, "time-of-day")) {
17205       ast_string_field_set(p, redircause, "UNKNOWN");
17206    } else if (!strcmp(reason, "do-not-disturb")) {
17207       ast_string_field_set(p, redircause, "UNKNOWN");
17208    } else if (!strcmp(reason, "deflection")) {
17209       ast_string_field_set(p, redircause, "UNKNOWN");
17210    } else if (!strcmp(reason, "follow-me")) {
17211       ast_string_field_set(p, redircause, "UNKNOWN");
17212    } else if (!strcmp(reason, "out-of-service")) {
17213       ast_string_field_set(p, redircause, "UNREACHABLE");
17214    } else if (!strcmp(reason, "away")) {
17215       ast_string_field_set(p, redircause, "UNREACHABLE");
17216    } else {
17217       ast_string_field_set(p, redircause, "UNKNOWN");
17218    }
17219 }
17220 
17221 /*! \brief Parse the parts of the P-Asserted-Identity header
17222  * on an incoming packet. Returns 1 if a valid header is found
17223  * and it is different from the current caller id.
17224  */
17225 static int get_pai(struct sip_pvt *p, struct sip_request *req)
17226 {
17227    char pai[256];
17228    char privacy[64];
17229    char *cid_num = NULL;
17230    char *cid_name = NULL;
17231    char emptyname[1] = "";
17232    int callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
17233    char *uri = NULL;
17234    int is_anonymous = 0, do_update = 1, no_name = 0;
17235 
17236    ast_copy_string(pai, sip_get_header(req, "P-Asserted-Identity"), sizeof(pai));
17237 
17238    if (ast_strlen_zero(pai)) {
17239       return 0;
17240    }
17241 
17242    /* use the reqresp_parser function get_name_and_number*/
17243    if (get_name_and_number(pai, &cid_name, &cid_num)) {
17244       return 0;
17245    }
17246 
17247    if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(cid_num)) {
17248       ast_shrink_phone_number(cid_num);
17249    }
17250 
17251    uri = get_in_brackets(pai);
17252    if (!strncasecmp(uri, "sip:anonymous@anonymous.invalid", 31)) {
17253       callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
17254       /*XXX Assume no change in cid_num. Perhaps it should be
17255        * blanked?
17256        */
17257       ast_free(cid_num);
17258       is_anonymous = 1;
17259       cid_num = (char *)p->cid_num;
17260    }
17261 
17262    ast_copy_string(privacy, sip_get_header(req, "Privacy"), sizeof(privacy));
17263    if (!ast_strlen_zero(privacy) && !strncmp(privacy, "id", 2)) {
17264       callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
17265    }
17266    if (!cid_name) {
17267       no_name = 1;
17268       cid_name = (char *)emptyname;
17269    }  
17270    /* Only return true if the supplied caller id is different */
17271    if (!strcasecmp(p->cid_num, cid_num) && !strcasecmp(p->cid_name, cid_name) && p->callingpres == callingpres) {
17272       do_update = 0;
17273    } else {
17274 
17275       ast_string_field_set(p, cid_num, cid_num);
17276       ast_string_field_set(p, cid_name, cid_name);
17277       p->callingpres = callingpres;
17278 
17279       if (p->owner) {
17280          ast_set_callerid(p->owner, cid_num, cid_name, NULL);
17281          ast_channel_caller(p->owner)->id.name.presentation = callingpres;
17282          ast_channel_caller(p->owner)->id.number.presentation = callingpres;
17283       }
17284    }
17285 
17286    /* get_name_and_number allocates memory for cid_num and cid_name so we have to free it */
17287    if (!is_anonymous) {
17288       ast_free(cid_num);
17289    }
17290    if (!no_name) {
17291       ast_free(cid_name);
17292    }
17293 
17294    return do_update;
17295 }
17296 
17297 /*! \brief Get name, number and presentation from remote party id header,
17298  *  returns true if a valid header was found and it was different from the
17299  *  current caller id.
17300  */
17301 static int get_rpid(struct sip_pvt *p, struct sip_request *oreq)
17302 {
17303    char tmp[256];
17304    struct sip_request *req;
17305    char *cid_num = "";
17306    char *cid_name = "";
17307    int callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
17308    char *privacy = "";
17309    char *screen = "";
17310    char *start, *end;
17311 
17312    if (!ast_test_flag(&p->flags[0], SIP_TRUSTRPID))
17313       return 0;
17314    req = oreq;
17315    if (!req)
17316       req = &p->initreq;
17317    ast_copy_string(tmp, sip_get_header(req, "Remote-Party-ID"), sizeof(tmp));
17318    if (ast_strlen_zero(tmp)) {
17319       return get_pai(p, req);
17320    }
17321 
17322    /*
17323     * RPID is not:
17324     *   rpid = (name-addr / addr-spec) *(SEMI rpi-token)
17325     * But it is:
17326     *   rpid = [display-name] LAQUOT addr-spec RAQUOT *(SEMI rpi-token)
17327     * Ergo, calling parse_name_andor_addr() on it wouldn't be
17328     * correct because that would allow addr-spec style too.
17329     */
17330    start = tmp;
17331    /* Quoted (note that we're not dealing with escapes properly) */
17332    if (*start == '"') {
17333       *start++ = '\0';
17334       end = strchr(start, '"');
17335       if (!end)
17336          return 0;
17337       *end++ = '\0';
17338       cid_name = start;
17339       start = ast_skip_blanks(end);
17340    /* Unquoted */
17341    } else {
17342       cid_name = start;
17343       start = end = strchr(start, '<');
17344       if (!start) {
17345          return 0;
17346       }
17347       /* trim blanks if there are any. the mandatory NUL is done below */
17348       while (--end >= cid_name && *end < 33) {
17349          *end = '\0';
17350       }
17351    }
17352 
17353    if (*start != '<')
17354       return 0;
17355    *start++ = '\0';
17356    end = strchr(start, '@');
17357    if (!end)
17358       return 0;
17359    *end++ = '\0';
17360    if (strncasecmp(start, "sip:", 4))
17361       return 0;
17362    cid_num = start + 4;
17363    if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(cid_num))
17364       ast_shrink_phone_number(cid_num);
17365    start = end;
17366 
17367    end = strchr(start, '>');
17368    if (!end)
17369       return 0;
17370    *end++ = '\0';
17371    if (*end) {
17372       start = end;
17373       if (*start != ';')
17374          return 0;
17375       *start++ = '\0';
17376       while (!ast_strlen_zero(start)) {
17377          end = strchr(start, ';');
17378          if (end)
17379             *end++ = '\0';
17380          if (!strncasecmp(start, "privacy=", 8))
17381             privacy = start + 8;
17382          else if (!strncasecmp(start, "screen=", 7))
17383             screen = start + 7;
17384          start = end;
17385       }
17386 
17387       if (!strcasecmp(privacy, "full")) {
17388          if (!strcasecmp(screen, "yes"))
17389             callingpres = AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN;
17390          else if (!strcasecmp(screen, "no"))
17391             callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
17392       } else {
17393          if (!strcasecmp(screen, "yes"))
17394             callingpres = AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
17395          else if (!strcasecmp(screen, "no"))
17396             callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
17397       }
17398    }
17399 
17400    /* Only return true if the supplied caller id is different */
17401    if (!strcasecmp(p->cid_num, cid_num) && !strcasecmp(p->cid_name, cid_name) && p->callingpres == callingpres)
17402       return 0;
17403 
17404    ast_string_field_set(p, cid_num, cid_num);
17405    ast_string_field_set(p, cid_name, cid_name);
17406    p->callingpres = callingpres;
17407 
17408    if (p->owner) {
17409       ast_set_callerid(p->owner, cid_num, cid_name, NULL);
17410       ast_channel_caller(p->owner)->id.name.presentation = callingpres;
17411       ast_channel_caller(p->owner)->id.number.presentation = callingpres;
17412    }
17413 
17414    return 1;
17415 }
17416 
17417 /*! \brief Get referring dnis */
17418 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason)
17419 {
17420    char tmp[256], *exten, *rexten, *rdomain, *rname = NULL;
17421    char *params, *reason_param = NULL;
17422    struct sip_request *req;
17423 
17424    req = oreq ? oreq : &p->initreq;
17425 
17426    ast_copy_string(tmp, sip_get_header(req, "Diversion"), sizeof(tmp));
17427    if (ast_strlen_zero(tmp))
17428       return -1;
17429 
17430    if ((params = strchr(tmp, '>'))) {
17431       params = strchr(params, ';');
17432    }
17433 
17434    exten = get_in_brackets(tmp);
17435    if (!strncasecmp(exten, "sip:", 4)) {
17436       exten += 4;
17437    } else if (!strncasecmp(exten, "sips:", 5)) {
17438       exten += 5;
17439    } else {
17440       ast_log(LOG_WARNING, "Huh?  Not an RDNIS SIP header (%s)?\n", exten);
17441       return -1;
17442    }
17443 
17444    /* Get diversion-reason param if present */
17445    if (params) {
17446       *params = '\0';   /* Cut off parameters  */
17447       params++;
17448       while (*params == ';' || *params == ' ')
17449          params++;
17450       /* Check if we have a reason parameter */
17451       if ((reason_param = strcasestr(params, "reason="))) {
17452          char *end;
17453          reason_param+=7;
17454          if ((end = strchr(reason_param, ';'))) {
17455             *end = '\0';
17456          }
17457          /* Remove enclosing double-quotes */
17458          if (*reason_param == '"')
17459             reason_param = ast_strip_quoted(reason_param, "\"", "\"");
17460          if (!ast_strlen_zero(reason_param)) {
17461             sip_set_redirstr(p, reason_param);
17462             if (p->owner) {
17463                pbx_builtin_setvar_helper(p->owner, "__PRIREDIRECTREASON", p->redircause);
17464                pbx_builtin_setvar_helper(p->owner, "__SIPREDIRECTREASON", reason_param);
17465             }
17466          }
17467       }
17468    }
17469 
17470    rdomain = exten;
17471    rexten = strsep(&rdomain, "@");  /* trim anything after @ */
17472    if (p->owner)
17473       pbx_builtin_setvar_helper(p->owner, "__SIPRDNISDOMAIN", rdomain);
17474 
17475    if (sip_debug_test_pvt(p))
17476       ast_verbose("RDNIS for this call is %s (reason %s)\n", exten, S_OR(reason_param, ""));
17477 
17478    /*ast_string_field_set(p, rdnis, rexten);*/
17479 
17480    if (*tmp == '\"') {
17481       char *end_quote;
17482       rname = tmp + 1;
17483       end_quote = strchr(rname, '\"');
17484       if (end_quote) {
17485          *end_quote = '\0';
17486       }
17487    }
17488 
17489    if (number) {
17490       *number = ast_strdup(rexten);
17491    }
17492 
17493    if (name && rname) {
17494       *name = ast_strdup(rname);
17495    }
17496 
17497    if (reason && !ast_strlen_zero(reason_param)) {
17498       *reason = sip_reason_str_to_code(reason_param);
17499    }
17500 
17501    return 0;
17502 }
17503 
17504 /*!
17505  * \brief Find out who the call is for.
17506  *
17507  * \details
17508  * We use the request uri as a destination.
17509  * This code assumes authentication has been done, so that the
17510  * device (peer/user) context is already set.
17511  *
17512  * \return 0 on success (found a matching extension), non-zero on failure
17513  *
17514  * \note If the incoming uri is a SIPS: uri, we are required to carry this across
17515  * the dialplan, so that the outbound call also is a sips: call or encrypted
17516  * IAX2 call. If that's not available, the call should FAIL.
17517  */
17518 static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id)
17519 {
17520    char tmp[256] = "", *uri, *unused_password, *domain;
17521    char tmpf[256] = "", *from = NULL;
17522    struct sip_request *req;
17523    char *decoded_uri;
17524 
17525    req = oreq;
17526    if (!req) {
17527       req = &p->initreq;
17528    }
17529 
17530    /* Find the request URI */
17531    if (req->rlpart2) {
17532       ast_copy_string(tmp, REQ_OFFSET_TO_STR(req, rlpart2), sizeof(tmp));
17533    }
17534 
17535    uri = ast_strdupa(get_in_brackets(tmp));
17536 
17537    if (parse_uri_legacy_check(uri, "sip:,sips:", &uri, &unused_password, &domain, NULL)) {
17538       ast_log(LOG_WARNING, "Not a SIP header (%s)?\n", uri);
17539       return SIP_GET_DEST_INVALID_URI;
17540    }
17541 
17542    SIP_PEDANTIC_DECODE(domain);
17543    SIP_PEDANTIC_DECODE(uri);
17544 
17545    extract_host_from_hostport(&domain);
17546 
17547    if (ast_strlen_zero(uri)) {
17548       /*
17549        * Either there really was no extension found or the request
17550        * URI had encoded nulls that made the string "empty".  Use "s"
17551        * as the extension.
17552        */
17553       uri = "s";
17554    }
17555 
17556    ast_string_field_set(p, domain, domain);
17557 
17558    /* Now find the From: caller ID and name */
17559    /* XXX Why is this done in get_destination? Isn't it already done?
17560       Needs to be checked
17561         */
17562    ast_copy_string(tmpf, sip_get_header(req, "From"), sizeof(tmpf));
17563    if (!ast_strlen_zero(tmpf)) {
17564       from = get_in_brackets(tmpf);
17565       if (parse_uri_legacy_check(from, "sip:,sips:", &from, NULL, &domain, NULL)) {
17566          ast_log(LOG_WARNING, "Not a SIP header (%s)?\n", from);
17567          return SIP_GET_DEST_INVALID_URI;
17568       }
17569 
17570       SIP_PEDANTIC_DECODE(from);
17571       SIP_PEDANTIC_DECODE(domain);
17572 
17573       extract_host_from_hostport(&domain);
17574 
17575       ast_string_field_set(p, fromdomain, domain);
17576    }
17577 
17578    if (!AST_LIST_EMPTY(&domain_list)) {
17579       char domain_context[AST_MAX_EXTENSION];
17580 
17581       domain_context[0] = '\0';
17582       if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
17583          if (!sip_cfg.allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
17584             ast_debug(1, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
17585             return SIP_GET_DEST_REFUSED;
17586          }
17587       }
17588       /* If we don't have a peer (i.e. we're a guest call),
17589        * overwrite the original context */
17590       if (!ast_test_flag(&p->flags[1], SIP_PAGE2_HAVEPEERCONTEXT) && !ast_strlen_zero(domain_context)) {
17591          ast_string_field_set(p, context, domain_context);
17592       }
17593    }
17594 
17595    /* If the request coming in is a subscription and subscribecontext has been specified use it */
17596    if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext)) {
17597       ast_string_field_set(p, context, p->subscribecontext);
17598    }
17599 
17600    if (sip_debug_test_pvt(p)) {
17601       ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
17602    }
17603 
17604    /* Since extensions.conf can have unescaped characters, try matching a
17605     * decoded uri in addition to the non-decoded uri. */
17606    decoded_uri = ast_strdupa(uri);
17607    ast_uri_decode(decoded_uri, ast_uri_sip_user);
17608 
17609    /* If this is a subscription we actually just need to see if a hint exists for the extension */
17610    if (req->method == SIP_SUBSCRIBE) {
17611       char hint[AST_MAX_EXTENSION];
17612       int which = 0;
17613       if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, uri) ||
17614           (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, decoded_uri) && (which = 1))) {
17615          if (!oreq) {
17616             ast_string_field_set(p, exten, which ? decoded_uri : uri);
17617          }
17618          return SIP_GET_DEST_EXTEN_FOUND;
17619       } else {
17620          return SIP_GET_DEST_EXTEN_NOT_FOUND;
17621       }
17622    } else {
17623       struct ast_cc_agent *agent;
17624       /* Check the dialplan for the username part of the request URI,
17625          the domain will be stored in the SIPDOMAIN variable
17626          Return 0 if we have a matching extension */
17627       if (ast_exists_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from))) {
17628          if (!oreq) {
17629             ast_string_field_set(p, exten, uri);
17630          }
17631          return SIP_GET_DEST_EXTEN_FOUND;
17632       }
17633       if (ast_exists_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))
17634          || !strcmp(decoded_uri, ast_pickup_ext())) {
17635          if (!oreq) {
17636             ast_string_field_set(p, exten, decoded_uri);
17637          }
17638          return SIP_GET_DEST_EXTEN_FOUND;
17639       }
17640       if ((agent = find_sip_cc_agent_by_notify_uri(tmp))) {
17641          struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
17642          /* This is a CC recall. We can set p's extension to the exten from
17643           * the original INVITE
17644           */
17645          ast_string_field_set(p, exten, agent_pvt->original_exten);
17646          /* And we need to let the CC core know that the caller is attempting
17647           * his recall
17648           */
17649          ast_cc_agent_recalling(agent->core_id, "SIP caller %s is attempting recall",
17650                agent->device_name);
17651          if (cc_recall_core_id) {
17652             *cc_recall_core_id = agent->core_id;
17653          }
17654          ao2_ref(agent, -1);
17655          return SIP_GET_DEST_EXTEN_FOUND;
17656       }
17657    }
17658 
17659    if (ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)
17660       && (ast_canmatch_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from))
17661          || ast_canmatch_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))
17662          || !strncmp(decoded_uri, ast_pickup_ext(), strlen(decoded_uri)))) {
17663       /* Overlap dialing is enabled and we need more digits to match an extension. */
17664       return SIP_GET_DEST_EXTEN_MATCHMORE;
17665    }
17666 
17667    return SIP_GET_DEST_EXTEN_NOT_FOUND;
17668 }
17669 
17670 /*! \brief Lock dialog lock and find matching pvt lock
17671    \return a reference, remember to release it when done
17672 */
17673 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag)
17674 {
17675    struct sip_pvt *sip_pvt_ptr;
17676    struct sip_pvt tmp_dialog = {
17677       .callid = callid,
17678    };
17679 
17680    if (totag) {
17681       ast_debug(4, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
17682    }
17683 
17684    /* Search dialogs and find the match */
17685 
17686    sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find of dialog in dialogs table");
17687    if (sip_pvt_ptr) {
17688       /* Go ahead and lock it (and its owner) before returning */
17689       sip_pvt_lock(sip_pvt_ptr);
17690       if (sip_cfg.pedanticsipchecking) {
17691          unsigned char frommismatch = 0, tomismatch = 0;
17692 
17693          if (ast_strlen_zero(fromtag)) {
17694             sip_pvt_unlock(sip_pvt_ptr);
17695             ast_debug(4, "Matched %s call for callid=%s - no from tag specified, pedantic check fails\n",
17696                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
17697             return NULL;
17698          }
17699 
17700          if (ast_strlen_zero(totag)) {
17701             sip_pvt_unlock(sip_pvt_ptr);
17702             ast_debug(4, "Matched %s call for callid=%s - no to tag specified, pedantic check fails\n",
17703                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
17704             return NULL;
17705          }
17706          /* RFC 3891
17707           * > 3.  User Agent Server Behavior: Receiving a Replaces Header
17708           * > The Replaces header contains information used to match an existing
17709           * > SIP dialog (call-id, to-tag, and from-tag).  Upon receiving an INVITE
17710           * > with a Replaces header, the User Agent (UA) attempts to match this
17711           * > information with a confirmed or early dialog.  The User Agent Server
17712           * > (UAS) matches the to-tag and from-tag parameters as if they were tags
17713           * > present in an incoming request.  In other words, the to-tag parameter
17714           * > is compared to the local tag, and the from-tag parameter is compared
17715           * > to the remote tag.
17716           *
17717           * Thus, the totag is always compared to the local tag, regardless if
17718           * this our call is an incoming or outgoing call.
17719           */
17720          frommismatch = !!strcmp(fromtag, sip_pvt_ptr->theirtag);
17721          tomismatch = !!strcmp(totag, sip_pvt_ptr->tag);
17722 
17723                         /* Don't check from if the dialog is not established, due to multi forking the from
17724                          * can change when the call is not answered yet.
17725                          */
17726          if ((frommismatch && ast_test_flag(&sip_pvt_ptr->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) || tomismatch) {
17727             sip_pvt_unlock(sip_pvt_ptr);
17728             if (frommismatch) {
17729                ast_debug(4, "Matched %s call for callid=%s - pedantic from tag check fails; their tag is %s our tag is %s\n",
17730                     sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
17731                     fromtag, sip_pvt_ptr->theirtag);
17732             }
17733             if (tomismatch) {
17734                ast_debug(4, "Matched %s call for callid=%s - pedantic to tag check fails; their tag is %s our tag is %s\n",
17735                     sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
17736                     totag, sip_pvt_ptr->tag);
17737             }
17738             return NULL;
17739          }
17740       }
17741 
17742       if (totag)
17743          ast_debug(4, "Matched %s call - their tag is %s Our tag is %s\n",
17744                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING",
17745                  sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
17746 
17747       /* deadlock avoidance... */
17748       while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
17749          sip_pvt_unlock(sip_pvt_ptr);
17750          usleep(1);
17751          sip_pvt_lock(sip_pvt_ptr);
17752       }
17753    }
17754    
17755    return sip_pvt_ptr;
17756 }
17757 
17758 /*! \brief Call transfer support (the REFER method)
17759  *    Extracts Refer headers into pvt dialog structure
17760  *
17761  * \note If we get a SIPS uri in the refer-to header, we're required to set up a secure signalling path
17762  * to that extension. As a minimum, this needs to be added to a channel variable, if not a channel
17763  * flag.
17764  */
17765 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
17766 {
17767    const char *p_referred_by = NULL;
17768    char *h_refer_to = NULL;
17769    char *h_referred_by = NULL;
17770    char *refer_to;
17771    const char *p_refer_to;
17772    char *referred_by_uri = NULL;
17773    char *ptr;
17774    struct sip_request *req = NULL;
17775    const char *transfer_context = NULL;
17776    struct sip_refer *refer;
17777 
17778    req = outgoing_req;
17779    refer = transferer->refer;
17780 
17781    if (!req) {
17782       req = &transferer->initreq;
17783    }
17784 
17785    p_refer_to = sip_get_header(req, "Refer-To");
17786    if (ast_strlen_zero(p_refer_to)) {
17787       ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
17788       return -2;  /* Syntax error */
17789    }
17790    h_refer_to = ast_strdupa(p_refer_to);
17791    refer_to = get_in_brackets(h_refer_to);
17792    if (!strncasecmp(refer_to, "sip:", 4)) {
17793       refer_to += 4;       /* Skip sip: */
17794    } else if (!strncasecmp(refer_to, "sips:", 5)) {
17795       refer_to += 5;
17796    } else {
17797       ast_log(LOG_WARNING, "Can't transfer to non-sip: URI.  (Refer-to: %s)?\n", refer_to);
17798       return -3;
17799    }
17800 
17801    /* Get referred by header if it exists */
17802    p_referred_by = sip_get_header(req, "Referred-By");
17803 
17804    /* Give useful transfer information to the dialplan */
17805    if (transferer->owner) {
17806       struct ast_channel *peer = ast_bridged_channel(transferer->owner);
17807       if (peer) {
17808          pbx_builtin_setvar_helper(peer, "SIPREFERRINGCONTEXT", transferer->context);
17809          pbx_builtin_setvar_helper(peer, "SIPREFERREDBYHDR", p_referred_by);
17810       }
17811    }
17812 
17813    if (!ast_strlen_zero(p_referred_by)) {
17814       h_referred_by = ast_strdupa(p_referred_by);
17815 
17816       referred_by_uri = get_in_brackets(h_referred_by);
17817 
17818       if (!strncasecmp(referred_by_uri, "sip:", 4)) {
17819          referred_by_uri += 4;      /* Skip sip: */
17820       } else if (!strncasecmp(referred_by_uri, "sips:", 5)) {
17821          referred_by_uri += 5;      /* Skip sips: */
17822       } else {
17823          ast_log(LOG_WARNING, "Huh?  Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
17824          referred_by_uri = NULL;
17825       }
17826    }
17827 
17828    /* Check for arguments in the refer_to header */
17829    if ((ptr = strcasestr(refer_to, "replaces="))) {
17830       char *to = NULL, *from = NULL, *callid;
17831 
17832       /* This is an attended transfer */
17833       refer->attendedtransfer = 1;
17834 
17835       callid = ast_strdupa(ptr + 9);
17836       ast_uri_decode(callid, ast_uri_sip_user);
17837       if ((ptr = strchr(callid, ';'))) { /* Find options */
17838          *ptr++ = '\0';
17839       }
17840       ast_string_field_set(refer, replaces_callid, callid);
17841 
17842       if (ptr) {
17843          /* Find the different tags before we destroy the string */
17844          to = strcasestr(ptr, "to-tag=");
17845          from = strcasestr(ptr, "from-tag=");
17846       }
17847       
17848       /* Grab the to header */
17849       if (to) {
17850          ptr = to + 7;
17851          if ((to = strchr(ptr, '&'))) {
17852             *to = '\0';
17853          }
17854          if ((to = strchr(ptr, ';'))) {
17855             *to = '\0';
17856          }
17857          ast_string_field_set(refer, replaces_callid_totag, ptr);
17858       }
17859 
17860       if (from) {
17861          ptr = from + 9;
17862          if ((from = strchr(ptr, '&'))) {
17863             *from = '\0';
17864          }
17865          if ((from = strchr(ptr, ';'))) {
17866             *from = '\0';
17867          }
17868          ast_string_field_set(refer, replaces_callid_fromtag, ptr);
17869       }
17870 
17871       if (!strcmp(refer->replaces_callid, transferer->callid) &&
17872          (!sip_cfg.pedanticsipchecking ||
17873          (!strcmp(refer->replaces_callid_fromtag, transferer->theirtag) &&
17874          !strcmp(refer->replaces_callid_totag, transferer->tag)))) {
17875             ast_log(LOG_WARNING, "Got an attempt to replace own Call-ID on %s\n", transferer->callid);
17876             return -4;
17877       }
17878 
17879       if (!sip_cfg.pedanticsipchecking) {
17880          ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", refer->replaces_callid);
17881       } else {
17882          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>");
17883       }
17884    }
17885 
17886    if ((ptr = strchr(refer_to, '@'))) {   /* Separate domain */
17887       char *urioption = NULL, *domain;
17888       int bracket = 0;
17889       *ptr++ = '\0';
17890 
17891       if ((urioption = strchr(ptr, ';'))) { /* Separate urioptions */
17892          *urioption++ = '\0';
17893       }
17894 
17895       domain = ptr;
17896 
17897       /* Remove :port */
17898       for (; *ptr != '\0'; ++ptr) {
17899          if (*ptr == ':' && bracket == 0) {
17900             *ptr = '\0';
17901             break;
17902          } else if (*ptr == '[') {
17903             ++bracket;
17904          } else if (*ptr == ']') {
17905             --bracket;
17906          }
17907       }
17908 
17909       SIP_PEDANTIC_DECODE(domain);
17910       SIP_PEDANTIC_DECODE(urioption);
17911 
17912       /* Save the domain for the dial plan */
17913       ast_string_field_set(refer, refer_to_domain, domain);
17914       if (urioption) {
17915          ast_string_field_set(refer, refer_to_urioption, urioption);
17916       }
17917    }
17918 
17919    if ((ptr = strchr(refer_to, ';'))) /* Remove options */
17920       *ptr = '\0';
17921 
17922    SIP_PEDANTIC_DECODE(refer_to);
17923    ast_string_field_set(refer, refer_to, refer_to);
17924 
17925    if (referred_by_uri) {
17926       if ((ptr = strchr(referred_by_uri, ';'))) /* Remove options */
17927          *ptr = '\0';
17928       SIP_PEDANTIC_DECODE(referred_by_uri);
17929       ast_string_field_build(refer, referred_by, "<sip:%s>", referred_by_uri);
17930    } else {
17931       ast_string_field_set(refer, referred_by, "");
17932    }
17933 
17934    /* Determine transfer context */
17935    if (transferer->owner) {
17936       /* By default, use the context in the channel sending the REFER */
17937       transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
17938       if (ast_strlen_zero(transfer_context)) {
17939          transfer_context = ast_channel_macrocontext(transferer->owner);
17940       }
17941    }
17942    if (ast_strlen_zero(transfer_context)) {
17943       transfer_context = S_OR(transferer->context, sip_cfg.default_context);
17944    }
17945 
17946    ast_string_field_set(refer, refer_to_context, transfer_context);
17947 
17948    /* Either an existing extension or the parking extension */
17949    if (refer->attendedtransfer || ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL)) {
17950       if (sip_debug_test_pvt(transferer)) {
17951          ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
17952       }
17953       /* We are ready to transfer to the extension */
17954       return 0;
17955    }
17956    if (sip_debug_test_pvt(transferer))
17957       ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
17958 
17959    /* Failure, we can't find this extension */
17960    return -1;
17961 }
17962 
17963 
17964 /*! \brief Call transfer support (old way, deprecated by the IETF)
17965  * \note does not account for SIPS: uri requirements, nor check transport
17966  */
17967 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
17968 {
17969    char tmp[256] = "", *c, *a;
17970    struct sip_request *req = oreq ? oreq : &p->initreq;
17971    struct sip_refer *refer = NULL;
17972    const char *transfer_context = NULL;
17973 
17974    if (!p->refer && !sip_refer_alloc(p))
17975       return -1;
17976 
17977    refer = p->refer;
17978 
17979    ast_copy_string(tmp, sip_get_header(req, "Also"), sizeof(tmp));
17980    c = get_in_brackets(tmp);
17981 
17982    if (parse_uri_legacy_check(c, "sip:,sips:", &c, NULL, &a, NULL)) {
17983       ast_log(LOG_WARNING, "Huh?  Not a SIP header in Also: transfer (%s)?\n", c);
17984       return -1;
17985    }
17986 
17987    SIP_PEDANTIC_DECODE(c);
17988    SIP_PEDANTIC_DECODE(a);
17989 
17990    if (!ast_strlen_zero(a)) {
17991       ast_string_field_set(refer, refer_to_domain, a);
17992    }
17993 
17994    if (sip_debug_test_pvt(p))
17995       ast_verbose("Looking for %s in %s\n", c, p->context);
17996 
17997    /* Determine transfer context */
17998    if (p->owner) {
17999       /* By default, use the context in the channel sending the REFER */
18000       transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
18001       if (ast_strlen_zero(transfer_context)) {
18002          transfer_context = ast_channel_macrocontext(p->owner);
18003       }
18004    }
18005    if (ast_strlen_zero(transfer_context)) {
18006       transfer_context = S_OR(p->context, sip_cfg.default_context);
18007    }
18008 
18009    if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
18010       /* This is a blind transfer */
18011       ast_debug(1, "SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
18012       ast_string_field_set(refer, refer_to, c);
18013       ast_string_field_set(refer, referred_by, "");
18014       ast_string_field_set(refer, refer_contact, "");
18015       /* Set new context */
18016       ast_string_field_set(p, context, transfer_context);
18017       return 0;
18018    } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
18019       return 1;
18020    }
18021 
18022    return -1;
18023 }
18024 
18025 /*! \brief Set the peers nat flags if they are using auto_* settings */
18026 static void set_peer_nat(const struct sip_pvt *p, struct sip_peer *peer)
18027 {
18028 
18029    if (!p || !peer) {
18030       return;
18031    }
18032 
18033    if (ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_RPORT)) {
18034       if (p->natdetected) {
18035          ast_set_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT);
18036       } else {
18037          ast_clear_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT);
18038       }
18039    }
18040 
18041    if (ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_COMEDIA)) {
18042       if (p->natdetected) {
18043          ast_set_flag(&peer->flags[1], SIP_PAGE2_SYMMETRICRTP);
18044       } else {
18045          ast_clear_flag(&peer->flags[1], SIP_PAGE2_SYMMETRICRTP);
18046       }
18047    }
18048 }
18049 
18050 /*! \brief Check and see if the requesting UA is likely to be behind a NAT.
18051  *
18052  * If the requesting NAT is behind NAT, set the * natdetected flag so that
18053  * later, peers with nat=auto_* can use the value. Also, set the flags so
18054  * that Asterisk responds identically whether or not a peer exists so as
18055  * not to leak peer name information.
18056  */
18057 static void check_for_nat(const struct ast_sockaddr *addr, struct sip_pvt *p)
18058 {
18059 
18060    if (!addr || !p) {
18061       return;
18062    }
18063 
18064    if (ast_sockaddr_cmp_addr(addr, &p->recv)) {
18065       char *tmp_str = ast_strdupa(ast_sockaddr_stringify_addr(addr));
18066       ast_debug(3, "NAT detected for %s / %s\n", tmp_str, ast_sockaddr_stringify_addr(&p->recv));
18067       p->natdetected = 1;
18068       if (ast_test_flag(&p->flags[2], SIP_PAGE3_NAT_AUTO_RPORT)) {
18069          ast_set_flag(&p->flags[0], SIP_NAT_FORCE_RPORT);
18070       }
18071       if (ast_test_flag(&p->flags[2], SIP_PAGE3_NAT_AUTO_COMEDIA)) {
18072          ast_set_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
18073       }
18074    } else {
18075       p->natdetected = 0;
18076       if (ast_test_flag(&p->flags[2], SIP_PAGE3_NAT_AUTO_RPORT)) {
18077          ast_clear_flag(&p->flags[0], SIP_NAT_FORCE_RPORT);
18078       }
18079       if (ast_test_flag(&p->flags[2], SIP_PAGE3_NAT_AUTO_COMEDIA)) {
18080          ast_clear_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
18081       }
18082    }
18083 
18084 }
18085 
18086 /*! \brief check Via: header for hostname, port and rport request/answer */
18087 static void check_via(struct sip_pvt *p, const struct sip_request *req)
18088 {
18089    char via[512];
18090    char *c, *maddr;
18091    struct ast_sockaddr tmp = { { 0, } };
18092    uint16_t port;
18093 
18094    ast_copy_string(via, sip_get_header(req, "Via"), sizeof(via));
18095 
18096    /* If this is via WebSocket we don't use the Via header contents at all */
18097    if (!strncasecmp(via, "SIP/2.0/WS", 10)) {
18098       return;
18099    }
18100 
18101    /* Work on the leftmost value of the topmost Via header */
18102    c = strchr(via, ',');
18103    if (c)
18104       *c = '\0';
18105 
18106    /* Check for rport */
18107    c = strstr(via, ";rport");
18108    if (c && (c[6] != '=')) { /* rport query, not answer */
18109       ast_set_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT);
18110       ast_set_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT);
18111    }
18112 
18113    /* Check for maddr */
18114    maddr = strstr(via, "maddr=");
18115    if (maddr) {
18116       maddr += 6;
18117       c = maddr + strspn(maddr, "abcdefghijklmnopqrstuvwxyz"
18118                       "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-.:[]");
18119       *c = '\0';
18120    }
18121 
18122    c = strchr(via, ';');
18123    if (c)
18124       *c = '\0';
18125 
18126    c = strchr(via, ' ');
18127    if (c) {
18128       *c = '\0';
18129       c = ast_skip_blanks(c+1);
18130       if (strcasecmp(via, "SIP/2.0/UDP") && strcasecmp(via, "SIP/2.0/TCP") && strcasecmp(via, "SIP/2.0/TLS")) {
18131          ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
18132          return;
18133       }
18134 
18135       if (maddr && ast_sockaddr_resolve_first(&p->sa, maddr, 0)) {
18136          p->sa = p->recv;
18137       }
18138 
18139       if (ast_sockaddr_resolve_first(&tmp, c, 0)) {
18140          ast_log(LOG_WARNING, "Could not resolve socket address for '%s'\n", c);
18141          port = STANDARD_SIP_PORT;
18142       } else if (!(port = ast_sockaddr_port(&tmp))) {
18143          port = STANDARD_SIP_PORT;
18144          ast_sockaddr_set_port(&tmp, port);
18145       }
18146 
18147       ast_sockaddr_set_port(&p->sa, port);
18148 
18149       check_for_nat(&tmp, p);
18150 
18151       if (sip_debug_test_pvt(p)) {
18152          ast_verbose("Sending to %s (%s)\n",
18153                 ast_sockaddr_stringify(sip_real_dst(p)),
18154                 sip_nat_mode(p));
18155       }
18156    }
18157 }
18158 
18159 /*! \brief Validate device authentication */
18160 static enum check_auth_result check_peer_ok(struct sip_pvt *p, char *of,
18161    struct sip_request *req, int sipmethod, struct ast_sockaddr *addr,
18162    struct sip_peer **authpeer,
18163    enum xmittype reliable, char *calleridname, char *uri2)
18164 {
18165    enum check_auth_result res;
18166    int debug = sip_debug_test_addr(addr);
18167    struct sip_peer *peer;
18168 
18169    if (sipmethod == SIP_SUBSCRIBE) {
18170       /* For subscribes, match on device name only; for other methods,
18171       * match on IP address-port of the incoming request.
18172       */
18173       peer = sip_find_peer(of, NULL, TRUE, FINDALLDEVICES, FALSE, 0);
18174    } else {
18175       /* First find devices based on username (avoid all type=peer's) */
18176       peer = sip_find_peer(of, NULL, TRUE, FINDUSERS, FALSE, 0);
18177 
18178       /* Then find devices based on IP */
18179       if (!peer) {
18180          char *uri_tmp, *callback = NULL, *dummy;
18181          uri_tmp = ast_strdupa(uri2);
18182          parse_uri(uri_tmp, "sip:,sips:", &callback, &dummy, &dummy, &dummy);
18183          if (!ast_strlen_zero(callback) && (peer = sip_find_peer_by_ip_and_exten(&p->recv, callback, p->socket.type))) {
18184             ; /* found, fall through */
18185          } else {
18186             peer = sip_find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
18187          }
18188       }
18189    }
18190 
18191    if (!peer) {
18192       if (debug) {
18193          ast_verbose("No matching peer for '%s' from '%s'\n",
18194             of, ast_sockaddr_stringify(&p->recv));
18195       }
18196 
18197       /* If you don't mind, we can return 404s for devices that do
18198        * not exist: username disclosure. If we allow guests, there
18199        * is no way around that. */
18200       if (sip_cfg.allowguest || !sip_cfg.alwaysauthreject) {
18201          return AUTH_DONT_KNOW;
18202       }
18203 
18204       /* If you do mind, we use a peer that will never authenticate.
18205        * This ensures that we follow the same code path as regular
18206        * auth: less chance for username disclosure. */
18207       peer = bogus_peer;
18208       sip_ref_peer(peer, "sip_ref_peer: check_peer_ok: must ref bogus_peer so unreffing it does not fail");
18209    }
18210 
18211    /*  build_peer, called through sip_find_peer, is not able to check the
18212     *  sip_pvt->natdetected flag in order to determine if the peer is behind
18213     *  NAT or not when SIP_PAGE3_NAT_AUTO_RPORT or SIP_PAGE3_NAT_AUTO_COMEDIA
18214     *  are set on the peer.  So we check for that here and set the peer's
18215     *  address accordingly.
18216     */
18217    set_peer_nat(p, peer);
18218 
18219    if (p->natdetected && ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_RPORT)) {
18220       ast_sockaddr_copy(&peer->addr, &p->recv);
18221    }
18222 
18223    if (!ast_apply_acl(peer->acl, addr, "SIP Peer ACL: ")) {
18224       ast_debug(2, "Found peer '%s' for '%s', but fails host access\n", peer->name, of);
18225       sip_unref_peer(peer, "sip_unref_peer: check_peer_ok: from sip_find_peer call, early return of AUTH_ACL_FAILED");
18226       return AUTH_ACL_FAILED;
18227    }
18228    if (debug && peer != bogus_peer) {
18229       ast_verbose("Found peer '%s' for '%s' from %s\n",
18230          peer->name, of, ast_sockaddr_stringify(&p->recv));
18231    }
18232 
18233    /* XXX what about p->prefs = peer->prefs; ? */
18234    /* Set Frame packetization */
18235    if (p->rtp) {
18236       ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &peer->prefs);
18237       p->autoframing = peer->autoframing;
18238    }
18239 
18240    /* Take the peer */
18241    ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
18242    ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
18243    ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
18244 
18245    if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && p->udptl) {
18246       p->t38_maxdatagram = peer->t38_maxdatagram;
18247       set_t38_capabilities(p);
18248    }
18249 
18250    ast_rtp_dtls_cfg_copy(&peer->dtls_cfg, &p->dtls_cfg);
18251 
18252    /* Copy SIP extensions profile to peer */
18253    /* XXX is this correct before a successful auth ? */
18254    if (p->sipoptions)
18255       peer->sipoptions = p->sipoptions;
18256 
18257    do_setnat(p);
18258 
18259    ast_string_field_set(p, peersecret, peer->secret);
18260    ast_string_field_set(p, peermd5secret, peer->md5secret);
18261    ast_string_field_set(p, subscribecontext, peer->subscribecontext);
18262    ast_string_field_set(p, mohinterpret, peer->mohinterpret);
18263    ast_string_field_set(p, mohsuggest, peer->mohsuggest);
18264    if (!ast_strlen_zero(peer->parkinglot)) {
18265       ast_string_field_set(p, parkinglot, peer->parkinglot);
18266    }
18267    ast_string_field_set(p, engine, peer->engine);
18268    p->disallowed_methods = peer->disallowed_methods;
18269    set_pvt_allowed_methods(p, req);
18270    ast_cc_copy_config_params(p->cc_params, peer->cc_params);
18271    if (peer->callingpres)  /* Peer calling pres setting will override RPID */
18272       p->callingpres = peer->callingpres;
18273    if (peer->maxms && peer->lastms)
18274       p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
18275    else
18276       p->timer_t1 = peer->timer_t1;
18277 
18278    /* Set timer B to control transaction timeouts */
18279    if (peer->timer_b)
18280       p->timer_b = peer->timer_b;
18281    else
18282       p->timer_b = 64 * p->timer_t1;
18283 
18284    p->allowtransfer = peer->allowtransfer;
18285 
18286    if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
18287       /* Pretend there is no required authentication */
18288       ast_string_field_set(p, peersecret, NULL);
18289       ast_string_field_set(p, peermd5secret, NULL);
18290    }
18291    if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable))) {
18292       /* If we have a call limit, set flag */
18293       if (peer->call_limit)
18294          ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
18295       ast_string_field_set(p, peername, peer->name);
18296       ast_string_field_set(p, authname, peer->name);
18297 
18298       ast_rtp_dtls_cfg_copy(&peer->dtls_cfg, &p->dtls_cfg);
18299 
18300       if (sipmethod == SIP_INVITE) {
18301          /* destroy old channel vars and copy in new ones. */
18302          ast_variables_destroy(p->chanvars);
18303          p->chanvars = copy_vars(peer->chanvars);
18304       }
18305 
18306       if (authpeer) {
18307          ao2_t_ref(peer, 1, "copy pointer into (*authpeer)");
18308          (*authpeer) = peer;  /* Add a ref to the object here, to keep it in memory a bit longer if it is realtime */
18309       }
18310 
18311       if (!ast_strlen_zero(peer->username)) {
18312          ast_string_field_set(p, username, peer->username);
18313          /* Use the default username for authentication on outbound calls */
18314          /* XXX this takes the name from the caller... can we override ? */
18315          ast_string_field_set(p, authname, peer->username);
18316       }
18317       if (!get_rpid(p, req)) {
18318          if (!ast_strlen_zero(peer->cid_num)) {
18319             char *tmp = ast_strdupa(peer->cid_num);
18320             if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
18321                ast_shrink_phone_number(tmp);
18322             ast_string_field_set(p, cid_num, tmp);
18323          }
18324          if (!ast_strlen_zero(peer->cid_name))
18325             ast_string_field_set(p, cid_name, peer->cid_name);
18326          if (peer->callingpres)
18327             p->callingpres = peer->callingpres;
18328       }
18329       if (!ast_strlen_zero(peer->cid_tag)) {
18330          ast_string_field_set(p, cid_tag, peer->cid_tag);
18331       }
18332       ast_string_field_set(p, fullcontact, peer->fullcontact);
18333       if (!ast_strlen_zero(peer->context)) {
18334          ast_string_field_set(p, context, peer->context);
18335       }
18336       if (!ast_strlen_zero(peer->messagecontext)) {
18337          ast_string_field_set(p, messagecontext, peer->messagecontext);
18338       }
18339       if (!ast_strlen_zero(peer->mwi_from)) {
18340          ast_string_field_set(p, mwi_from, peer->mwi_from);
18341       }
18342       ast_string_field_set(p, peersecret, peer->secret);
18343       ast_string_field_set(p, peermd5secret, peer->md5secret);
18344       ast_string_field_set(p, language, peer->language);
18345       ast_string_field_set(p, accountcode, peer->accountcode);
18346       p->amaflags = peer->amaflags;
18347       p->callgroup = peer->callgroup;
18348       p->pickupgroup = peer->pickupgroup;
18349       ast_unref_namedgroups(p->named_callgroups);
18350       p->named_callgroups = ast_ref_namedgroups(peer->named_callgroups);
18351       ast_unref_namedgroups(p->named_pickupgroups);
18352       p->named_pickupgroups = ast_ref_namedgroups(peer->named_pickupgroups);
18353       ast_format_cap_copy(p->caps, peer->caps);
18354       ast_format_cap_copy(p->jointcaps, peer->caps);
18355       p->prefs = peer->prefs;
18356       ast_copy_string(p->zone, peer->zone, sizeof(p->zone));
18357       if (peer->maxforwards > 0) {
18358          p->maxforwards = peer->maxforwards;
18359       }
18360       if (!(ast_format_cap_is_empty(p->peercaps))) {
18361          struct ast_format_cap *tmp = ast_format_cap_joint(p->jointcaps, p->peercaps);
18362          struct ast_format_cap *tmp2;
18363          if (tmp) {
18364             tmp2 = p->jointcaps;
18365             p->jointcaps = tmp;
18366             ast_format_cap_destroy(tmp2);
18367          }
18368       }
18369       p->maxcallbitrate = peer->maxcallbitrate;
18370       if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
18371           (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
18372          p->noncodeccapability |= AST_RTP_DTMF;
18373       else
18374          p->noncodeccapability &= ~AST_RTP_DTMF;
18375       p->jointnoncodeccapability = p->noncodeccapability;
18376       p->rtptimeout = peer->rtptimeout;
18377       p->rtpholdtimeout = peer->rtpholdtimeout;
18378       p->rtpkeepalive = peer->rtpkeepalive;
18379       if (!dialog_initialize_rtp(p)) {
18380          if (p->rtp) {
18381             ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &peer->prefs);
18382             p->autoframing = peer->autoframing;
18383          }
18384       } else {
18385          res = AUTH_RTP_FAILED;
18386       }
18387    }
18388    sip_unref_peer(peer, "check_peer_ok: sip_unref_peer: tossing temp ptr to peer from sip_find_peer");
18389    return res;
18390 }
18391 
18392 
18393 /*! \brief  Check if matching user or peer is defined
18394    Match user on From: user name and peer on IP/port
18395    This is used on first invite (not re-invites) and subscribe requests
18396     \return 0 on success, non-zero on failure
18397 */
18398 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
18399                      int sipmethod, const char *uri, enum xmittype reliable,
18400                      struct ast_sockaddr *addr, struct sip_peer **authpeer)
18401 {
18402    char from[256], *of, *name, *unused_password, *domain;
18403    enum check_auth_result res = AUTH_DONT_KNOW;
18404    char calleridname[256];
18405    char *uri2 = ast_strdupa(uri);
18406 
18407    terminate_uri(uri2); /* trim extra stuff */
18408 
18409    ast_copy_string(from, sip_get_header(req, "From"), sizeof(from));
18410    /* XXX here tries to map the username for invite things */
18411 
18412    /* strip the display-name portion off the beginning of the FROM header. */
18413    if (!(of = (char *) get_calleridname(from, calleridname, sizeof(calleridname)))) {
18414       ast_log(LOG_ERROR, "FROM header can not be parsed \n");
18415       return res;
18416    }
18417 
18418    if (calleridname[0]) {
18419       ast_string_field_set(p, cid_name, calleridname);
18420    }
18421 
18422    if (ast_strlen_zero(p->exten)) {
18423       char *t = uri2;
18424       if (!strncasecmp(t, "sip:", 4))
18425          t+= 4;
18426       else if (!strncasecmp(t, "sips:", 5))
18427          t += 5;
18428       ast_string_field_set(p, exten, t);
18429       t = strchr(p->exten, '@');
18430       if (t)
18431          *t = '\0';
18432 
18433       if (ast_strlen_zero(p->our_contact))
18434          build_contact(p);
18435    }
18436 
18437    of = get_in_brackets(of);
18438 
18439    /* save the URI part of the From header */
18440    ast_string_field_set(p, from, of);
18441 
18442    if (parse_uri_legacy_check(of, "sip:,sips:", &name, &unused_password, &domain, NULL)) {
18443       ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
18444    }
18445 
18446    SIP_PEDANTIC_DECODE(name);
18447    SIP_PEDANTIC_DECODE(domain);
18448 
18449    extract_host_from_hostport(&domain);
18450 
18451    if (ast_strlen_zero(domain)) {
18452       /* <sip:name@[EMPTY]>, never good */
18453       ast_log(LOG_ERROR, "Empty domain name in FROM header\n");
18454       return res;
18455    }
18456 
18457    if (ast_strlen_zero(name)) {
18458       /* <sip:[EMPTY][@]hostport>. Asterisk 1.4 and 1.6 have always
18459        * treated that as a username, so we continue the tradition:
18460        * uri is now <sip:host@hostport>. */
18461       name = domain;
18462    } else {
18463       /* Non-empty name, try to get caller id from it */
18464       char *tmp = ast_strdupa(name);
18465       /* We need to be able to handle from-headers looking like
18466          <sip:8164444422;phone-context=+1@1.2.3.4:5060;user=phone;tag=SDadkoa01-gK0c3bdb43>
18467       */
18468       tmp = strsep(&tmp, ";");
18469       if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp)) {
18470          ast_shrink_phone_number(tmp);
18471       }
18472       ast_string_field_set(p, cid_num, tmp);
18473    }
18474 
18475    if (global_match_auth_username) {
18476       /*
18477        * XXX This is experimental code to grab the search key from the
18478        * Auth header's username instead of the 'From' name, if available.
18479        * Do not enable this block unless you understand the side effects (if any!)
18480        * Note, the search for "username" should be done in a more robust way.
18481        * Note2, at the moment we check both fields, though maybe we should
18482        * pick one or another depending on the request ? XXX
18483        */
18484       const char *hdr = sip_get_header(req, "Authorization");
18485       if (ast_strlen_zero(hdr)) {
18486          hdr = sip_get_header(req, "Proxy-Authorization");
18487       }
18488 
18489       if (!ast_strlen_zero(hdr) && (hdr = strstr(hdr, "username=\""))) {
18490          ast_copy_string(from, hdr + strlen("username=\""), sizeof(from));
18491          name = from;
18492          name = strsep(&name, "\"");
18493       }
18494    }
18495 
18496    res = check_peer_ok(p, name, req, sipmethod, addr,
18497          authpeer, reliable, calleridname, uri2);
18498    if (res != AUTH_DONT_KNOW) {
18499       return res;
18500    }
18501 
18502    /* Finally, apply the guest policy */
18503    if (sip_cfg.allowguest) {
18504       /* Ignore check_return warning from Coverity for get_rpid below. */
18505       get_rpid(p, req);
18506       p->rtptimeout = global_rtptimeout;
18507       p->rtpholdtimeout = global_rtpholdtimeout;
18508       p->rtpkeepalive = global_rtpkeepalive;
18509       if (!dialog_initialize_rtp(p)) {
18510          res = AUTH_SUCCESSFUL;
18511       } else {
18512          res = AUTH_RTP_FAILED;
18513       }
18514    } else {
18515       res = AUTH_SECRET_FAILED; /* we don't want any guests, authentication will fail */
18516    }
18517 
18518    if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT)) {
18519       ast_set_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT);
18520    }
18521 
18522    return res;
18523 }
18524 
18525 /*! \brief  Find user
18526    If we get a match, this will add a reference pointer to the user object in ASTOBJ, that needs to be unreferenced
18527 */
18528 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr)
18529 {
18530    return check_user_full(p, req, sipmethod, uri, reliable, addr, NULL);
18531 }
18532 
18533 static int set_message_vars_from_req(struct ast_msg *msg, struct sip_request *req)
18534 {
18535    size_t x;
18536    char name_buf[1024];
18537    char val_buf[1024];
18538    const char *name;
18539    char *c;
18540    int res = 0;
18541 
18542    for (x = 0; x < req->headers; x++) {
18543       const char *header = REQ_OFFSET_TO_STR(req, header[x]);
18544 
18545       if ((c = strchr(header, ':'))) {
18546          ast_copy_string(name_buf, header, MIN((c - header + 1), sizeof(name_buf)));
18547          ast_copy_string(val_buf, ast_skip_blanks(c + 1), sizeof(val_buf));
18548          ast_trim_blanks(name_buf);
18549 
18550          /* Convert header name to full name alias. */
18551          name = find_full_alias(name_buf, name_buf);
18552 
18553          res = ast_msg_set_var(msg, name, val_buf);
18554          if (res) {
18555             break;
18556          }
18557       }
18558    }
18559    return res;
18560 }
18561 
18562 /*! \brief  Receive SIP MESSAGE method messages
18563 \note We only handle messages within current calls currently
18564    Reference: RFC 3428 */
18565 static void receive_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e)
18566 {
18567    char *buf;
18568    size_t len;
18569    struct ast_frame f;
18570    const char *content_type = sip_get_header(req, "Content-Type");
18571    struct ast_msg *msg;
18572    int res;
18573    char *from;
18574    char *to;
18575    char from_name[50];
18576    char stripped[SIPBUFSIZE];
18577 
18578    if (strncmp(content_type, "text/plain", strlen("text/plain"))) { /* No text/plain attachment */
18579       transmit_response(p, "415 Unsupported Media Type", req); /* Good enough, or? */
18580       if (!p->owner) {
18581          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18582       }
18583       return;
18584    }
18585 
18586    if (!(buf = get_content(req))) {
18587       ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
18588       transmit_response(p, "500 Internal Server Error", req);
18589       if (!p->owner) {
18590          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18591       }
18592       return;
18593    }
18594 
18595    /* Strip trailing line feeds from message body. (get_content may add
18596     * a trailing linefeed and we don't need any at the end) */
18597    len = strlen(buf);
18598    while (len > 0) {
18599       if (buf[--len] != '\n') {
18600          ++len;
18601          break;
18602       }
18603    }
18604    buf[len] = '\0';
18605 
18606    if (p->owner) {
18607       if (sip_debug_test_pvt(p)) {
18608          ast_verbose("SIP Text message received: '%s'\n", buf);
18609       }
18610       memset(&f, 0, sizeof(f));
18611       f.frametype = AST_FRAME_TEXT;
18612       f.subclass.integer = 0;
18613       f.offset = 0;
18614       f.data.ptr = buf;
18615       f.datalen = strlen(buf) + 1;
18616       ast_queue_frame(p->owner, &f);
18617       transmit_response(p, "202 Accepted", req); /* We respond 202 accepted, since we relay the message */
18618       return;
18619    }
18620 
18621    /*
18622     * At this point MESSAGE is outside of a call.
18623     *
18624     * NOTE: p->owner is NULL so no additional check is needed after
18625     * this point.
18626     */
18627 
18628    if (!sip_cfg.accept_outofcall_message) {
18629       /* Message outside of a call, we do not support that */
18630       ast_debug(1, "MESSAGE outside of a call administratively disabled.\n");
18631       transmit_response(p, "405 Method Not Allowed", req);
18632       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18633       return;
18634    }
18635 
18636    copy_request(&p->initreq, req);
18637 
18638    if (sip_cfg.auth_message_requests) {
18639       int res;
18640 
18641       set_pvt_allowed_methods(p, req);
18642       res = check_user(p, req, SIP_MESSAGE, e, XMIT_UNRELIABLE, addr);
18643       if (res == AUTH_CHALLENGE_SENT) {
18644          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18645          return;
18646       }
18647       if (res < 0) { /* Something failed in authentication */
18648          ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", sip_get_header(req, "From"));
18649          transmit_response(p, "403 Forbidden", req);
18650          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18651          return;
18652       }
18653       /* Auth was successful.  Proceed. */
18654    } else {
18655       struct sip_peer *peer;
18656 
18657       /*
18658        * MESSAGE outside of a call, not authenticating it.
18659        * Check to see if we match a peer anyway so that we can direct
18660        * it to the right context.
18661        */
18662 
18663       peer = sip_find_peer(NULL, &p->recv, TRUE, FINDPEERS, 0, p->socket.type);
18664       if (peer) {
18665          /* Only if no auth is required. */
18666          if (ast_strlen_zero(peer->secret) && ast_strlen_zero(peer->md5secret)) {
18667             ast_string_field_set(p, context, peer->context);
18668          }
18669          if (!ast_strlen_zero(peer->messagecontext)) {
18670             ast_string_field_set(p, messagecontext, peer->messagecontext);
18671          }
18672          ast_string_field_set(p, peername, peer->name);
18673          peer = sip_unref_peer(peer, "from sip_find_peer() in receive_message");
18674       }
18675    }
18676 
18677    /* Override the context with the message context _BEFORE_
18678     * getting the destination.  This way we can guarantee the correct
18679     * extension is used in the message context when it is present. */
18680    if (!ast_strlen_zero(p->messagecontext)) {
18681       ast_string_field_set(p, context, p->messagecontext);
18682    } else if (!ast_strlen_zero(sip_cfg.messagecontext)) {
18683       ast_string_field_set(p, context, sip_cfg.messagecontext);
18684    }
18685 
18686    switch (get_destination(p, NULL, NULL)) {
18687    case SIP_GET_DEST_REFUSED:
18688       /* Okay to send 403 since this is after auth processing */
18689       transmit_response(p, "403 Forbidden", req);
18690       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18691       return;
18692    case SIP_GET_DEST_INVALID_URI:
18693       transmit_response(p, "416 Unsupported URI Scheme", req);
18694       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18695       return;
18696    case SIP_GET_DEST_EXTEN_NOT_FOUND:
18697    case SIP_GET_DEST_EXTEN_MATCHMORE:
18698       transmit_response(p, "404 Not Found", req);
18699       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18700       return;
18701    case SIP_GET_DEST_EXTEN_FOUND:
18702       break;
18703    }
18704 
18705    if (!(msg = ast_msg_alloc())) {
18706       transmit_response(p, "500 Internal Server Error", req);
18707       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18708       return;
18709    }
18710 
18711    to = ast_strdupa(REQ_OFFSET_TO_STR(req, rlpart2));
18712    from = ast_strdupa(sip_get_header(req, "From"));
18713 
18714    res = ast_msg_set_to(msg, "%s", to);
18715 
18716    /* Build "display" <uri> for from string. */
18717    from = (char *) get_calleridname(from, from_name, sizeof(from_name));
18718    from = get_in_brackets(from);
18719    if (from_name[0]) {
18720       res |= ast_msg_set_from(msg, "\"%s\" <%s>", from_name, from);
18721    } else {
18722       res |= ast_msg_set_from(msg, "<%s>", from);
18723    }
18724 
18725    res |= ast_msg_set_body(msg, "%s", buf);
18726    res |= ast_msg_set_context(msg, "%s", p->context);
18727 
18728    res |= ast_msg_set_var(msg, "SIP_RECVADDR", ast_sockaddr_stringify(&p->recv));
18729    if (!ast_strlen_zero(p->peername)) {
18730       res |= ast_msg_set_var(msg, "SIP_PEERNAME", p->peername);
18731    }
18732 
18733    ast_copy_string(stripped, sip_get_header(req, "Contact"), sizeof(stripped));
18734    res |= ast_msg_set_var(msg, "SIP_FULLCONTACT", get_in_brackets(stripped));
18735 
18736    res |= ast_msg_set_exten(msg, "%s", p->exten);
18737    res |= set_message_vars_from_req(msg, req);
18738 
18739    if (res) {
18740       ast_msg_destroy(msg);
18741       transmit_response(p, "500 Internal Server Error", req);
18742    } else {
18743       ast_msg_queue(msg);
18744       transmit_response(p, "202 Accepted", req);
18745    }
18746 
18747    sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18748 }
18749 
18750 /*! \brief  CLI Command to show calls within limits set by call_limit */
18751 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18752 {
18753 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
18754 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
18755    char ilimits[40];
18756    char iused[40];
18757    int showall = FALSE;
18758    struct ao2_iterator i;
18759    struct sip_peer *peer;
18760    
18761    switch (cmd) {
18762    case CLI_INIT:
18763       e->command = "sip show inuse";
18764       e->usage =
18765          "Usage: sip show inuse [all]\n"
18766          "       List all SIP devices usage counters and limits.\n"
18767          "       Add option \"all\" to show all devices, not only those with a limit.\n";
18768       return NULL;
18769    case CLI_GENERATE:
18770       return NULL;
18771    }
18772 
18773    if (a->argc < 3)
18774       return CLI_SHOWUSAGE;
18775 
18776    if (a->argc == 4 && !strcmp(a->argv[3], "all"))
18777       showall = TRUE;
18778    
18779    ast_cli(a->fd, FORMAT, "* Peer name", "In use", "Limit");
18780 
18781    i = ao2_iterator_init(peers, 0);
18782    while ((peer = ao2_t_iterator_next(&i, "iterate thru peer table"))) {
18783       ao2_lock(peer);
18784       if (peer->call_limit)
18785          snprintf(ilimits, sizeof(ilimits), "%d", peer->call_limit);
18786       else
18787          ast_copy_string(ilimits, "N/A", sizeof(ilimits));
18788       snprintf(iused, sizeof(iused), "%d/%d/%d", peer->inuse, peer->ringing, peer->onhold);
18789       if (showall || peer->call_limit)
18790          ast_cli(a->fd, FORMAT2, peer->name, iused, ilimits);
18791       ao2_unlock(peer);
18792       sip_unref_peer(peer, "toss iterator pointer");
18793    }
18794    ao2_iterator_destroy(&i);
18795 
18796    return CLI_SUCCESS;
18797 #undef FORMAT
18798 #undef FORMAT2
18799 }
18800 
18801 
18802 /*! \brief Convert transfer mode to text string */
18803 static char *transfermode2str(enum transfermodes mode)
18804 {
18805    if (mode == TRANSFER_OPENFORALL)
18806       return "open";
18807    else if (mode == TRANSFER_CLOSED)
18808       return "closed";
18809    return "strict";
18810 }
18811 
18812 /*! \brief  Report Peer status in character string
18813  *  \return 0 if peer is unreachable, 1 if peer is online, -1 if unmonitored
18814  */
18815 
18816 
18817 /* Session-Timer Modes */
18818 static const struct _map_x_s stmodes[] = {
18819         { SESSION_TIMER_MODE_ACCEPT,    "Accept"},
18820         { SESSION_TIMER_MODE_ORIGINATE, "Originate"},
18821         { SESSION_TIMER_MODE_REFUSE,    "Refuse"},
18822         { -1,                           NULL},
18823 };
18824 
18825 static const char *stmode2str(enum st_mode m)
18826 {
18827    return map_x_s(stmodes, m, "Unknown");
18828 }
18829 
18830 static enum st_mode str2stmode(const char *s)
18831 {
18832    return map_s_x(stmodes, s, -1);
18833 }
18834 
18835 /* Session-Timer Refreshers */
18836 static const struct _map_x_s strefresher_params[] = {
18837         { SESSION_TIMER_REFRESHER_PARAM_UNKNOWN, "unknown" },
18838         { SESSION_TIMER_REFRESHER_PARAM_UAC,     "uac"     },
18839         { SESSION_TIMER_REFRESHER_PARAM_UAS,     "uas"     },
18840         { -1,                                NULL  },
18841 };
18842 
18843 static const struct _map_x_s strefreshers[] = {
18844         { SESSION_TIMER_REFRESHER_AUTO, "auto" },
18845         { SESSION_TIMER_REFRESHER_US,   "us"   },
18846         { SESSION_TIMER_REFRESHER_THEM, "them" },
18847         { -1,                           NULL   },
18848 };
18849 
18850 static const char *strefresherparam2str(enum st_refresher r)
18851 {
18852    return map_x_s(strefresher_params, r, "Unknown");
18853 }
18854 
18855 static enum st_refresher str2strefresherparam(const char *s)
18856 {
18857    return map_s_x(strefresher_params, s, -1);
18858 }
18859 
18860 /* Autocreatepeer modes */
18861 static struct _map_x_s autopeermodes[] = {
18862         { AUTOPEERS_DISABLED, "Off"},
18863         { AUTOPEERS_VOLATILE, "Volatile"},
18864         { AUTOPEERS_PERSIST,  "Persisted"},
18865         { -1, NULL},
18866 };
18867 
18868 static const char *strefresher2str(enum st_refresher r)
18869 {
18870    return map_x_s(strefreshers, r, "Unknown");
18871 }
18872 
18873 static const char *autocreatepeer2str(enum autocreatepeer_mode r)
18874 {
18875    return map_x_s(autopeermodes, r, "Unknown");
18876 }
18877 
18878 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
18879 {
18880    int res = 0;
18881    if (peer->maxms) {
18882       if (peer->lastms < 0) {
18883          ast_copy_string(status, "UNREACHABLE", statuslen);
18884       } else if (peer->lastms > peer->maxms) {
18885          snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
18886          res = 1;
18887       } else if (peer->lastms) {
18888          snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
18889          res = 1;
18890       } else {
18891          ast_copy_string(status, "UNKNOWN", statuslen);
18892       }
18893    } else {
18894       ast_copy_string(status, "Unmonitored", statuslen);
18895       /* Checking if port is 0 */
18896       res = -1;
18897    }
18898    return res;
18899 }
18900 
18901 /*! \brief  Show active TCP connections */
18902 static char *sip_show_tcp(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18903 {
18904    struct sip_threadinfo *th;
18905    struct ao2_iterator i;
18906 
18907 #define FORMAT2 "%-47.47s %9.9s %6.6s\n"
18908 #define FORMAT  "%-47.47s %-9.9s %-6.6s\n"
18909 
18910    switch (cmd) {
18911    case CLI_INIT:
18912       e->command = "sip show tcp";
18913       e->usage =
18914          "Usage: sip show tcp\n"
18915          "       Lists all active TCP/TLS sessions.\n";
18916       return NULL;
18917    case CLI_GENERATE:
18918       return NULL;
18919    }
18920 
18921    if (a->argc != 3)
18922       return CLI_SHOWUSAGE;
18923 
18924    ast_cli(a->fd, FORMAT2, "Address", "Transport", "Type");
18925 
18926    i = ao2_iterator_init(threadt, 0);
18927    while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
18928       ast_cli(a->fd, FORMAT,
18929          ast_sockaddr_stringify(&th->tcptls_session->remote_address),
18930          sip_get_transport(th->type),
18931          (th->tcptls_session->client ? "Client" : "Server"));
18932       ao2_t_ref(th, -1, "decrement ref from iterator");
18933    }
18934    ao2_iterator_destroy(&i);
18935 
18936    return CLI_SUCCESS;
18937 #undef FORMAT
18938 #undef FORMAT2
18939 }
18940 
18941 /*! \brief  CLI Command 'SIP Show Users' */
18942 static char *sip_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18943 {
18944    regex_t regexbuf;
18945    int havepattern = FALSE;
18946    struct ao2_iterator user_iter;
18947    struct sip_peer *user;
18948 
18949 #define FORMAT  "%-25.25s  %-15.15s  %-15.15s  %-15.15s  %-5.5s%-10.10s\n"
18950 
18951    switch (cmd) {
18952    case CLI_INIT:
18953       e->command = "sip show users";
18954       e->usage =
18955          "Usage: sip show users [like <pattern>]\n"
18956          "       Lists all known SIP users.\n"
18957          "       Optional regular expression pattern is used to filter the user list.\n";
18958       return NULL;
18959    case CLI_GENERATE:
18960       return NULL;
18961    }
18962 
18963    switch (a->argc) {
18964    case 5:
18965       if (!strcasecmp(a->argv[3], "like")) {
18966          if (regcomp(&regexbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
18967             return CLI_SHOWUSAGE;
18968          havepattern = TRUE;
18969       } else
18970          return CLI_SHOWUSAGE;
18971    case 3:
18972       break;
18973    default:
18974       return CLI_SHOWUSAGE;
18975    }
18976 
18977    ast_cli(a->fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "Forcerport");
18978 
18979    user_iter = ao2_iterator_init(peers, 0);
18980    while ((user = ao2_t_iterator_next(&user_iter, "iterate thru peers table"))) {
18981       ao2_lock(user);
18982       if (!(user->type & SIP_TYPE_USER)) {
18983          ao2_unlock(user);
18984          sip_unref_peer(user, "sip show users");
18985          continue;
18986       }
18987 
18988       if (havepattern && regexec(&regexbuf, user->name, 0, NULL, 0)) {
18989          ao2_unlock(user);
18990          sip_unref_peer(user, "sip show users");
18991          continue;
18992       }
18993 
18994       ast_cli(a->fd, FORMAT, user->name,
18995          user->secret,
18996          user->accountcode,
18997          user->context,
18998          AST_CLI_YESNO(ast_acl_list_is_empty(user->acl) == 0),
18999          AST_CLI_YESNO(ast_test_flag(&user->flags[0], SIP_NAT_FORCE_RPORT)));
19000       ao2_unlock(user);
19001       sip_unref_peer(user, "sip show users");
19002    }
19003    ao2_iterator_destroy(&user_iter);
19004 
19005    if (havepattern)
19006       regfree(&regexbuf);
19007 
19008    return CLI_SUCCESS;
19009 #undef FORMAT
19010 }
19011 
19012 /*! \brief Show SIP registrations in the manager API */
19013 static int manager_show_registry(struct mansession *s, const struct message *m)
19014 {
19015    const char *id = astman_get_header(m, "ActionID");
19016    char idtext[256] = "";
19017    int total = 0;
19018 
19019    if (!ast_strlen_zero(id))
19020       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
19021 
19022    astman_send_listack(s, m, "Registrations will follow", "start");
19023 
19024    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
19025       ASTOBJ_RDLOCK(iterator);
19026       astman_append(s,
19027          "Event: RegistryEntry\r\n"
19028          "%s"
19029          "Host: %s\r\n"
19030          "Port: %d\r\n"
19031          "Username: %s\r\n"
19032          "Domain: %s\r\n"
19033          "DomainPort: %d\r\n"
19034          "Refresh: %d\r\n"
19035          "State: %s\r\n"
19036          "RegistrationTime: %ld\r\n"
19037          "\r\n",
19038          idtext,
19039          iterator->hostname,
19040          iterator->portno ? iterator->portno : STANDARD_SIP_PORT,
19041          iterator->username,
19042          S_OR(iterator->regdomain,iterator->hostname),
19043          iterator->regdomainport ? iterator->regdomainport : STANDARD_SIP_PORT,
19044          iterator->refresh,
19045          regstate2str(iterator->regstate),
19046          (long) iterator->regtime.tv_sec);
19047       ASTOBJ_UNLOCK(iterator);
19048       total++;
19049    } while(0));
19050 
19051    astman_append(s,
19052       "Event: RegistrationsComplete\r\n"
19053       "EventList: Complete\r\n"
19054       "ListItems: %d\r\n"
19055       "%s"
19056       "\r\n", total, idtext);
19057    
19058    return 0;
19059 }
19060 
19061 /*! \brief  Show SIP peers in the manager API */
19062 /*    Inspired from chan_iax2 */
19063 static int manager_sip_show_peers(struct mansession *s, const struct message *m)
19064 {
19065    const char *id = astman_get_header(m, "ActionID");
19066    const char *a[] = {"sip", "show", "peers"};
19067    char idtext[256] = "";
19068    int total = 0;
19069 
19070    if (!ast_strlen_zero(id))
19071       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
19072 
19073    astman_send_listack(s, m, "Peer status list will follow", "start");
19074    /* List the peers in separate manager events */
19075    _sip_show_peers(-1, &total, s, m, 3, a);
19076    /* Send final confirmation */
19077    astman_append(s,
19078    "Event: PeerlistComplete\r\n"
19079    "EventList: Complete\r\n"
19080    "ListItems: %d\r\n"
19081    "%s"
19082    "\r\n", total, idtext);
19083    return 0;
19084 }
19085 
19086 /*! \brief  CLI Show Peers command */
19087 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19088 {
19089    switch (cmd) {
19090    case CLI_INIT:
19091       e->command = "sip show peers";
19092       e->usage =
19093          "Usage: sip show peers [like <pattern>]\n"
19094          "       Lists all known SIP peers.\n"
19095          "       Optional regular expression pattern is used to filter the peer list.\n";
19096       return NULL;
19097    case CLI_GENERATE:
19098       return NULL;
19099    }
19100 
19101    return _sip_show_peers(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
19102 }
19103 
19104 int peercomparefunc(const void *a, const void *b);
19105 
19106 int peercomparefunc(const void *a, const void *b)
19107 {
19108    struct sip_peer **ap = (struct sip_peer **)a;
19109    struct sip_peer **bp = (struct sip_peer **)b;
19110    return strcmp((*ap)->name, (*bp)->name);
19111 }
19112 
19113 /* the last argument is left-aligned, so we don't need a size anyways */
19114 #define PEERS_FORMAT2 "%-25.25s %-39.39s %-3.3s %-10.10s %-10.10s %-3.3s %-8s %-11s %-32.32s %s\n"
19115 
19116 /*! \brief Used in the sip_show_peers functions to pass parameters */
19117 struct show_peers_context {
19118    regex_t regexbuf;
19119    int havepattern;
19120    char idtext[256];
19121    int realtimepeers;
19122    int peers_mon_online;
19123    int peers_mon_offline;
19124    int peers_unmon_offline;
19125    int peers_unmon_online;
19126 };
19127 
19128 /*! \brief Execute sip show peers command */
19129 static char *_sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
19130 {
19131    struct show_peers_context cont = {
19132       .havepattern = FALSE,
19133       .idtext = "",
19134 
19135       .peers_mon_online = 0,
19136       .peers_mon_offline = 0,
19137       .peers_unmon_online = 0,
19138       .peers_unmon_offline = 0,
19139    };
19140 
19141    struct sip_peer *peer;
19142    struct ao2_iterator* it_peers;
19143 
19144    int total_peers = 0;
19145    const char *id;
19146    struct sip_peer **peerarray;
19147    int k;
19148 
19149    cont.realtimepeers = ast_check_realtime("sippeers");
19150 
19151    if (s) { /* Manager - get ActionID */
19152       id = astman_get_header(m, "ActionID");
19153       if (!ast_strlen_zero(id)) {
19154          snprintf(cont.idtext, sizeof(cont.idtext), "ActionID: %s\r\n", id);
19155       }
19156    }
19157 
19158    switch (argc) {
19159    case 5:
19160       if (!strcasecmp(argv[3], "like")) {
19161          if (regcomp(&cont.regexbuf, argv[4], REG_EXTENDED | REG_NOSUB)) {
19162             return CLI_SHOWUSAGE;
19163          }
19164          cont.havepattern = TRUE;
19165       } else {
19166          return CLI_SHOWUSAGE;
19167       }
19168    case 3:
19169       break;
19170    default:
19171       return CLI_SHOWUSAGE;
19172    }
19173 
19174    if (!s) {
19175       /* Normal list */
19176       ast_cli(fd, PEERS_FORMAT2, "Name/username", "Host", "Dyn", "Forcerport", "Comedia", "ACL", "Port", "Status", "Description", (cont.realtimepeers ? "Realtime" : ""));
19177    }
19178 
19179    ao2_lock(peers);
19180    if (!(it_peers = ao2_callback(peers, OBJ_MULTIPLE, NULL, NULL))) {
19181       ast_log(AST_LOG_ERROR, "Unable to create iterator for peers container for sip show peers\n");
19182       ao2_unlock(peers);
19183       return CLI_FAILURE;
19184    }
19185    if (!(peerarray = ast_calloc(sizeof(struct sip_peer *), ao2_container_count(peers)))) {
19186       ast_log(AST_LOG_ERROR, "Unable to allocate peer array for sip show peers\n");
19187       ao2_iterator_destroy(it_peers);
19188       ao2_unlock(peers);
19189       return CLI_FAILURE;
19190    }
19191    ao2_unlock(peers);
19192 
19193    while ((peer = ao2_t_iterator_next(it_peers, "iterate thru peers table"))) {
19194       ao2_lock(peer);
19195 
19196       if (!(peer->type & SIP_TYPE_PEER)) {
19197          ao2_unlock(peer);
19198          sip_unref_peer(peer, "unref peer because it's actually a user");
19199          continue;
19200       }
19201 
19202       if (cont.havepattern && regexec(&cont.regexbuf, peer->name, 0, NULL, 0)) {
19203          ao2_unlock(peer);
19204          sip_unref_peer(peer, "toss iterator peer ptr before continue");
19205          continue;
19206       }
19207 
19208       peerarray[total_peers++] = peer;
19209       ao2_unlock(peer);
19210    }
19211    ao2_iterator_destroy(it_peers);
19212 
19213    qsort(peerarray, total_peers, sizeof(struct sip_peer *), peercomparefunc);
19214 
19215    for(k = 0; k < total_peers; k++) {
19216       peerarray[k] = _sip_show_peers_one(fd, s, &cont, peerarray[k]);
19217    }
19218 
19219    if (!s) {
19220       ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
19221               total_peers, cont.peers_mon_online, cont.peers_mon_offline, cont.peers_unmon_online, cont.peers_unmon_offline);
19222    }
19223 
19224    if (cont.havepattern) {
19225       regfree(&cont.regexbuf);
19226    }
19227 
19228    if (total) {
19229       *total = total_peers;
19230    }
19231 
19232    ast_free(peerarray);
19233 
19234    return CLI_SUCCESS;
19235 }
19236 
19237 /*! \brief Emit informations for one peer during sip show peers command */
19238 static struct sip_peer *_sip_show_peers_one(int fd, struct mansession *s, struct show_peers_context *cont, struct sip_peer *peer)
19239 {
19240    /* _sip_show_peers_one() is separated from _sip_show_peers() to properly free the ast_strdupa
19241     * (this is executed in a loop in _sip_show_peers() )
19242     */
19243 
19244    char name[256];
19245    char status[20] = "";
19246    char pstatus;
19247 
19248    /*
19249     * tmp_port and tmp_host store copies of ast_sockaddr_stringify strings since the
19250     * string pointers for that function aren't valid between subsequent calls to
19251     * ast_sockaddr_stringify functions
19252     */
19253    char *tmp_port;
19254    char *tmp_host;
19255 
19256    tmp_port = ast_sockaddr_isnull(&peer->addr) ?
19257       "0" : ast_strdupa(ast_sockaddr_stringify_port(&peer->addr));
19258 
19259    tmp_host = ast_sockaddr_isnull(&peer->addr) ?
19260       "(Unspecified)" : ast_strdupa(ast_sockaddr_stringify_addr(&peer->addr));
19261 
19262    ao2_lock(peer);
19263    if (cont->havepattern && regexec(&cont->regexbuf, peer->name, 0, NULL, 0)) {
19264       ao2_unlock(peer);
19265       return sip_unref_peer(peer, "toss iterator peer ptr no match");
19266    }
19267 
19268    if (!ast_strlen_zero(peer->username) && !s) {
19269       snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
19270    } else {
19271       ast_copy_string(name, peer->name, sizeof(name));
19272    }
19273 
19274    pstatus = peer_status(peer, status, sizeof(status));
19275    if (pstatus == 1) {
19276       cont->peers_mon_online++;
19277    } else if (pstatus == 0) {
19278       cont->peers_mon_offline++;
19279    } else {
19280       if (ast_sockaddr_isnull(&peer->addr) ||
19281           !ast_sockaddr_port(&peer->addr)) {
19282          cont->peers_unmon_offline++;
19283       } else {
19284          cont->peers_unmon_online++;
19285       }
19286    }
19287 
19288    if (!s) { /* Normal CLI list */
19289       ast_cli(fd, PEERS_FORMAT2, name,
19290       tmp_host,
19291       peer->host_dynamic ? " D " : "   ", /* Dynamic or not? */
19292       force_rport_string(peer->flags),
19293       comedia_string(peer->flags),
19294       (!ast_acl_list_is_empty(peer->acl)) ? " A " : "   ",       /* permit/deny */
19295       tmp_port, status,
19296       peer->description ? peer->description : "",
19297       cont->realtimepeers ? (peer->is_realtime ? "Cached RT" : "") : "");
19298    } else { /* Manager format */
19299       /* The names here need to be the same as other channels */
19300       astman_append(s,
19301       "Event: PeerEntry\r\n%s"
19302       "Channeltype: SIP\r\n"
19303       "ObjectName: %s\r\n"
19304       "ChanObjectType: peer\r\n" /* "peer" or "user" */
19305       "IPaddress: %s\r\n"
19306       "IPport: %s\r\n"
19307       "Dynamic: %s\r\n"
19308       "AutoForcerport: %s\r\n"
19309       "Forcerport: %s\r\n"
19310       "AutoComedia: %s\r\n"
19311       "Comedia: %s\r\n"
19312       "VideoSupport: %s\r\n"
19313       "TextSupport: %s\r\n"
19314       "ACL: %s\r\n"
19315       "Status: %s\r\n"
19316       "RealtimeDevice: %s\r\n"
19317       "Description: %s\r\n\r\n",
19318       cont->idtext,
19319       peer->name,
19320       ast_sockaddr_isnull(&peer->addr) ? "-none-" : tmp_host,
19321       ast_sockaddr_isnull(&peer->addr) ? "0" : tmp_port,
19322       peer->host_dynamic ? "yes" : "no",  /* Dynamic or not? */
19323       ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_RPORT) ? "yes" : "no",
19324       ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? "yes" : "no",
19325       ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_COMEDIA) ? "yes" : "no",
19326       ast_test_flag(&peer->flags[1], SIP_PAGE2_SYMMETRICRTP) ? "yes" : "no",
19327       ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no",  /* VIDEOSUPPORT=yes? */
19328       ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "yes" : "no",   /* TEXTSUPPORT=yes? */
19329       ast_acl_list_is_empty(peer->acl) ? "no" : "yes",       /* permit/deny/acl */
19330       status,
19331       cont->realtimepeers ? (peer->is_realtime ? "yes" : "no") : "no",
19332       peer->description);
19333    }
19334    ao2_unlock(peer);
19335 
19336    return sip_unref_peer(peer, "toss iterator peer ptr");
19337 }
19338 #undef PEERS_FORMAT2
19339 
19340 static int peer_dump_func(void *userobj, void *arg, int flags)
19341 {
19342    struct sip_peer *peer = userobj;
19343    int refc = ao2_t_ref(userobj, 0, "");
19344    struct ast_cli_args *a = (struct ast_cli_args *) arg;
19345    
19346    ast_cli(a->fd, "name: %s\ntype: peer\nobjflags: %d\nrefcount: %d\n\n",
19347       peer->name, 0, refc);
19348    return 0;
19349 }
19350 
19351 static int dialog_dump_func(void *userobj, void *arg, int flags)
19352 {
19353    struct sip_pvt *pvt = userobj;
19354    int refc = ao2_t_ref(userobj, 0, "");
19355    struct ast_cli_args *a = (struct ast_cli_args *) arg;
19356    
19357    ast_cli(a->fd, "name: %s\ntype: dialog\nobjflags: %d\nrefcount: %d\n\n",
19358       pvt->callid, 0, refc);
19359    return 0;
19360 }
19361 
19362 
19363 /*! \brief List all allocated SIP Objects (realtime or static) */
19364 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19365 {
19366    char tmp[256];
19367    
19368    switch (cmd) {
19369    case CLI_INIT:
19370       e->command = "sip show objects";
19371       e->usage =
19372          "Usage: sip show objects\n"
19373          "       Lists status of known SIP objects\n";
19374       return NULL;
19375    case CLI_GENERATE:
19376       return NULL;
19377    }  
19378 
19379    if (a->argc != 3)
19380       return CLI_SHOWUSAGE;
19381    ast_cli(a->fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
19382    ao2_t_callback(peers, OBJ_NODATA, peer_dump_func, a, "initiate ao2_callback to dump peers");
19383    ast_cli(a->fd, "-= Peer objects by IP =-\n\n"); 
19384    ao2_t_callback(peers_by_ip, OBJ_NODATA, peer_dump_func, a, "initiate ao2_callback to dump peers_by_ip");
19385    ast_cli(a->fd, "-= Registry objects: %d =-\n\n", regobjs);
19386    ASTOBJ_CONTAINER_DUMP(a->fd, tmp, sizeof(tmp), &regl);
19387    ast_cli(a->fd, "-= Dialog objects:\n\n");
19388    ao2_t_callback(dialogs, OBJ_NODATA, dialog_dump_func, a, "initiate ao2_callback to dump dialogs");
19389    return CLI_SUCCESS;
19390 }
19391 /*! \brief Print call group and pickup group */
19392 static void print_group(int fd, ast_group_t group, int crlf)
19393 {
19394    char buf[256];
19395    ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
19396 }
19397 
19398 /*! \brief Print named call groups and pickup groups */
19399 static void print_named_groups(int fd, struct ast_namedgroups *group, int crlf)
19400 {
19401    struct ast_str *buf = ast_str_create(1024);
19402    if (buf) {
19403       ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_namedgroups(&buf, group) );
19404       ast_free(buf);
19405    }
19406 }
19407 
19408 /*! \brief mapping between dtmf flags and strings */
19409 static const struct _map_x_s dtmfstr[] = {
19410    { SIP_DTMF_RFC2833,     "rfc2833" },
19411    { SIP_DTMF_INFO,        "info" },
19412    { SIP_DTMF_SHORTINFO,   "shortinfo" },
19413    { SIP_DTMF_INBAND,      "inband" },
19414    { SIP_DTMF_AUTO,        "auto" },
19415    { -1,                   NULL }, /* terminator */
19416 };
19417 
19418 /*! \brief Convert DTMF mode to printable string */
19419 static const char *dtmfmode2str(int mode)
19420 {
19421    return map_x_s(dtmfstr, mode, "<error>");
19422 }
19423 
19424 /*! \brief maps a string to dtmfmode, returns -1 on error */
19425 static int str2dtmfmode(const char *str)
19426 {
19427    return map_s_x(dtmfstr, str, -1);
19428 }
19429 
19430 static const struct _map_x_s insecurestr[] = {
19431    { SIP_INSECURE_PORT,    "port" },
19432    { SIP_INSECURE_INVITE,  "invite" },
19433    { SIP_INSECURE_PORT | SIP_INSECURE_INVITE, "port,invite" },
19434    { 0,                    "no" },
19435    { -1,                   NULL }, /* terminator */
19436 };
19437 
19438 /*! \brief Convert Insecure setting to printable string */
19439 static const char *insecure2str(int mode)
19440 {
19441    return map_x_s(insecurestr, mode, "<error>");
19442 }
19443 
19444 static const struct _map_x_s allowoverlapstr[] = {
19445    { SIP_PAGE2_ALLOWOVERLAP_YES,   "Yes" },
19446    { SIP_PAGE2_ALLOWOVERLAP_DTMF,  "DTMF" },
19447    { SIP_PAGE2_ALLOWOVERLAP_NO,    "No" },
19448    { -1,                           NULL }, /* terminator */
19449 };
19450 
19451 /*! \brief Convert AllowOverlap setting to printable string */
19452 static const char *allowoverlap2str(int mode)
19453 {
19454    return map_x_s(allowoverlapstr, mode, "<error>");
19455 }
19456 
19457 static const struct _map_x_s trust_id_outboundstr[] = {
19458    { SIP_PAGE2_TRUST_ID_OUTBOUND_LEGACY,  "Legacy" },
19459    { SIP_PAGE2_TRUST_ID_OUTBOUND_NO,      "No" },
19460    { SIP_PAGE2_TRUST_ID_OUTBOUND_YES,     "Yes" },
19461    { -1,                                  NULL }, /* terminator */
19462 };
19463 
19464 static const char *trust_id_outbound2str(int mode)
19465 {
19466    return map_x_s(trust_id_outboundstr, mode, "<error>");
19467 }
19468 
19469 /*! \brief Destroy disused contexts between reloads
19470    Only used in reload_config so the code for regcontext doesn't get ugly
19471 */
19472 static void cleanup_stale_contexts(char *new, char *old)
19473 {
19474    char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
19475 
19476    while ((oldcontext = strsep(&old, "&"))) {
19477       stalecontext = '\0';
19478       ast_copy_string(newlist, new, sizeof(newlist));
19479       stringp = newlist;
19480       while ((newcontext = strsep(&stringp, "&"))) {
19481          if (!strcmp(newcontext, oldcontext)) {
19482             /* This is not the context you're looking for */
19483             stalecontext = '\0';
19484             break;
19485          } else if (strcmp(newcontext, oldcontext)) {
19486             stalecontext = oldcontext;
19487          }
19488          
19489       }
19490       if (stalecontext)
19491          ast_context_destroy(ast_context_find(stalecontext), "SIP");
19492    }
19493 }
19494 
19495 /*!
19496  * \brief Check RTP Timeout on dialogs
19497  *
19498  * \details This is used with ao2_callback to check rtptimeout
19499  * rtponholdtimeout and send rtpkeepalive packets.
19500  *
19501  * \return CMP_MATCH for items to be unlinked from dialogs_rtpcheck.
19502  */
19503 static int dialog_checkrtp_cb(void *dialogobj, void *arg, int flags)
19504 {
19505    struct sip_pvt *dialog = dialogobj;
19506    time_t *t = arg;
19507    int match_status;
19508 
19509    if (sip_pvt_trylock(dialog)) {
19510       return 0;
19511    }
19512 
19513    if (dialog->rtp || dialog->vrtp) {
19514       match_status = check_rtp_timeout(dialog, *t);
19515    } else {
19516       /* Dialog has no active RTP or VRTP. unlink it from dialogs_rtpcheck. */
19517       match_status = CMP_MATCH;
19518    }
19519    sip_pvt_unlock(dialog);
19520 
19521    return match_status;
19522 }
19523 
19524 /*!
19525  * \brief Match dialogs that need to be destroyed
19526  *
19527  * \details This is used with ao2_callback to unlink/delete all dialogs that
19528  * are marked needdestroy.
19529  *
19530  * \todo Re-work this to improve efficiency.  Currently, this function is called
19531  * on _every_ dialog after processing _every_ incoming SIP/UDP packet, or
19532  * potentially even more often when the scheduler has entries to run.
19533  */
19534 static int dialog_needdestroy(void *dialogobj, void *arg, int flags)
19535 {
19536    struct sip_pvt *dialog = dialogobj;
19537 
19538    if (sip_pvt_trylock(dialog)) {
19539       /* Don't block the monitor thread.  This function is called often enough
19540        * that we can wait for the next time around. */
19541       return 0;
19542    }
19543 
19544    /* If we have sessions that needs to be destroyed, do it now */
19545    /* Check if we have outstanding requests not responsed to or an active call
19546       - if that's the case, wait with destruction */
19547    if (dialog->needdestroy && !dialog->packets && !dialog->owner) {
19548       /* We absolutely cannot destroy the rtp struct while a bridge is active or we WILL crash */
19549       if (dialog->rtp && ast_rtp_instance_get_bridged(dialog->rtp)) {
19550          ast_debug(2, "Bridge still active.  Delaying destruction of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
19551          sip_pvt_unlock(dialog);
19552          return 0;
19553       }
19554 
19555       if (dialog->vrtp && ast_rtp_instance_get_bridged(dialog->vrtp)) {
19556          ast_debug(2, "Bridge still active.  Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
19557          sip_pvt_unlock(dialog);
19558          return 0;
19559       }
19560 
19561       sip_pvt_unlock(dialog);
19562       /* no, the unlink should handle this: dialog_unref(dialog, "needdestroy: one more refcount decrement to allow dialog to be destroyed"); */
19563       /* the CMP_MATCH will unlink this dialog from the dialog hash table */
19564       dialog_unlink_all(dialog);
19565       return 0; /* the unlink_all should unlink this from the table, so.... no need to return a match */
19566    }
19567 
19568    sip_pvt_unlock(dialog);
19569 
19570    return 0;
19571 }
19572 
19573 /*! \brief Remove temporary realtime objects from memory (CLI) */
19574 /*! \todo XXXX Propably needs an overhaul after removal of the devices */
19575 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19576 {
19577    struct sip_peer *peer, *pi;
19578    int prunepeer = FALSE;
19579    int multi = FALSE;
19580    const char *name = NULL;
19581    regex_t regexbuf;
19582    int havepattern = 0;
19583    struct ao2_iterator i;
19584    static const char * const choices[] = { "all", "like", NULL };
19585    char *cmplt;
19586    
19587    if (cmd == CLI_INIT) {
19588       e->command = "sip prune realtime [peer|all]";
19589       e->usage =
19590          "Usage: sip prune realtime [peer [<name>|all|like <pattern>]|all]\n"
19591          "       Prunes object(s) from the cache.\n"
19592          "       Optional regular expression pattern is used to filter the objects.\n";
19593       return NULL;
19594    } else if (cmd == CLI_GENERATE) {
19595       if (a->pos == 4 && !strcasecmp(a->argv[3], "peer")) {
19596          cmplt = ast_cli_complete(a->word, choices, a->n);
19597          if (!cmplt)
19598             cmplt = complete_sip_peer(a->word, a->n - sizeof(choices), SIP_PAGE2_RTCACHEFRIENDS);
19599          return cmplt;
19600       }
19601       if (a->pos == 5 && !strcasecmp(a->argv[4], "like"))
19602          return complete_sip_peer(a->word, a->n, SIP_PAGE2_RTCACHEFRIENDS);
19603       return NULL;
19604    }
19605    switch (a->argc) {
19606    case 4:
19607       name = a->argv[3];
19608       /* we accept a name in position 3, but keywords are not good. */
19609       if (!strcasecmp(name, "peer") || !strcasecmp(name, "like"))
19610          return CLI_SHOWUSAGE;
19611       prunepeer = TRUE;
19612       if (!strcasecmp(name, "all")) {
19613          multi = TRUE;
19614          name = NULL;
19615       }
19616       /* else a single name, already set */
19617       break;
19618    case 5:
19619       /* sip prune realtime {peer|like} name */
19620       name = a->argv[4];
19621       if (!strcasecmp(a->argv[3], "peer"))
19622          prunepeer = TRUE;
19623       else if (!strcasecmp(a->argv[3], "like")) {
19624          prunepeer = TRUE;
19625          multi = TRUE;
19626       } else
19627          return CLI_SHOWUSAGE;
19628       if (!strcasecmp(name, "like"))
19629          return CLI_SHOWUSAGE;
19630       if (!multi && !strcasecmp(name, "all")) {
19631          multi = TRUE;
19632          name = NULL;
19633       }
19634       break;
19635    case 6:
19636       name = a->argv[5];
19637       multi = TRUE;
19638       /* sip prune realtime {peer} like name */
19639       if (strcasecmp(a->argv[4], "like"))
19640          return CLI_SHOWUSAGE;
19641       if (!strcasecmp(a->argv[3], "peer")) {
19642          prunepeer = TRUE;
19643       } else
19644          return CLI_SHOWUSAGE;
19645       break;
19646    default:
19647       return CLI_SHOWUSAGE;
19648    }
19649 
19650    if (multi && name) {
19651       if (regcomp(&regexbuf, name, REG_EXTENDED | REG_NOSUB)) {
19652          return CLI_SHOWUSAGE;
19653       }
19654       havepattern = 1;
19655    }
19656 
19657    if (multi) {
19658       if (prunepeer) {
19659          int pruned = 0;
19660          
19661          i = ao2_iterator_init(peers, 0);
19662          while ((pi = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
19663             ao2_lock(pi);
19664             if (name && regexec(&regexbuf, pi->name, 0, NULL, 0)) {
19665                ao2_unlock(pi);
19666                sip_unref_peer(pi, "toss iterator peer ptr before continue");
19667                continue;
19668             };
19669             if (ast_test_flag(&pi->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
19670                pi->the_mark = 1;
19671                pruned++;
19672             }
19673             ao2_unlock(pi);
19674             sip_unref_peer(pi, "toss iterator peer ptr");
19675          }
19676          ao2_iterator_destroy(&i);
19677          if (pruned) {
19678             unlink_marked_peers_from_tables();
19679             ast_cli(a->fd, "%d peers pruned.\n", pruned);
19680          } else
19681             ast_cli(a->fd, "No peers found to prune.\n");
19682       }
19683    } else {
19684       if (prunepeer) {
19685          struct sip_peer tmp;
19686          ast_copy_string(tmp.name, name, sizeof(tmp.name));
19687          if ((peer = ao2_t_find(peers, &tmp, OBJ_POINTER | OBJ_UNLINK, "finding to unlink from peers"))) {
19688             if (!ast_sockaddr_isnull(&peer->addr)) {
19689                ao2_t_unlink(peers_by_ip, peer, "unlinking peer from peers_by_ip also");
19690             }
19691             if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
19692                ast_cli(a->fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
19693                /* put it back! */
19694                ao2_t_link(peers, peer, "link peer into peer table");
19695                if (!ast_sockaddr_isnull(&peer->addr)) {
19696                   ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
19697                }
19698             } else
19699                ast_cli(a->fd, "Peer '%s' pruned.\n", name);
19700             sip_unref_peer(peer, "sip_prune_realtime: sip_unref_peer: tossing temp peer ptr");
19701          } else
19702             ast_cli(a->fd, "Peer '%s' not found.\n", name);
19703       }
19704    }
19705 
19706    if (havepattern) {
19707       regfree(&regexbuf);
19708    }
19709 
19710    return CLI_SUCCESS;
19711 }
19712 
19713 /*! \brief Print codec list from preference to CLI/manager */
19714 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
19715 {
19716    int x;
19717    struct ast_format codec;
19718 
19719    for(x = 0; x < AST_CODEC_PREF_SIZE; x++) {
19720       if (!(ast_codec_pref_index(pref, x, &codec))) {
19721          break;
19722       }
19723       ast_cli(fd, "%s", ast_getformatname(&codec));
19724       ast_cli(fd, ":%d", pref->framing[x]);
19725       if (x < 31 && ast_codec_pref_index(pref, x + 1, &codec))
19726          ast_cli(fd, ",");
19727    }
19728    if (!x)
19729       ast_cli(fd, "none");
19730 }
19731 
19732 /*! \brief Print domain mode to cli */
19733 static const char *domain_mode_to_text(const enum domain_mode mode)
19734 {
19735    switch (mode) {
19736    case SIP_DOMAIN_AUTO:
19737       return "[Automatic]";
19738    case SIP_DOMAIN_CONFIG:
19739       return "[Configured]";
19740    }
19741 
19742    return "";
19743 }
19744 
19745 /*! \brief CLI command to list local domains */
19746 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19747 {
19748    struct domain *d;
19749 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
19750 
19751    switch (cmd) {
19752    case CLI_INIT:
19753       e->command = "sip show domains";
19754       e->usage =
19755          "Usage: sip show domains\n"
19756          "       Lists all configured SIP local domains.\n"
19757          "       Asterisk only responds to SIP messages to local domains.\n";
19758       return NULL;
19759    case CLI_GENERATE:
19760       return NULL;
19761    }
19762 
19763    if (AST_LIST_EMPTY(&domain_list)) {
19764       ast_cli(a->fd, "SIP Domain support not enabled.\n\n");
19765       return CLI_SUCCESS;
19766    } else {
19767       ast_cli(a->fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
19768       AST_LIST_LOCK(&domain_list);
19769       AST_LIST_TRAVERSE(&domain_list, d, list)
19770          ast_cli(a->fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
19771             domain_mode_to_text(d->mode));
19772       AST_LIST_UNLOCK(&domain_list);
19773       ast_cli(a->fd, "\n");
19774       return CLI_SUCCESS;
19775    }
19776 }
19777 #undef FORMAT
19778 
19779 /*! \brief Show SIP peers in the manager API  */
19780 static int manager_sip_show_peer(struct mansession *s, const struct message *m)
19781 {
19782    const char *a[4];
19783    const char *peer;
19784 
19785    peer = astman_get_header(m, "Peer");
19786    if (ast_strlen_zero(peer)) {
19787       astman_send_error(s, m, "Peer: <name> missing.");
19788       return 0;
19789    }
19790    a[0] = "sip";
19791    a[1] = "show";
19792    a[2] = "peer";
19793    a[3] = peer;
19794 
19795    _sip_show_peer(1, -1, s, m, 4, a);
19796    astman_append(s, "\r\n" );
19797    return 0;
19798 }
19799 
19800 /*! \brief Show one peer in detail */
19801 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19802 {
19803    switch (cmd) {
19804    case CLI_INIT:
19805       e->command = "sip show peer";
19806       e->usage =
19807          "Usage: sip show peer <name> [load]\n"
19808          "       Shows all details on one SIP peer and the current status.\n"
19809          "       Option \"load\" forces lookup of peer in realtime storage.\n";
19810       return NULL;
19811    case CLI_GENERATE:
19812       return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
19813    }
19814    return _sip_show_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
19815 }
19816 
19817 static void send_manager_peer_status(struct mansession *s, struct sip_peer *peer, const char *idText)
19818 {
19819    char time[128] = "";
19820    char status[128] = "";
19821    if (peer->maxms) {
19822       if (peer->lastms < 0) {
19823          snprintf(status, sizeof(status), "PeerStatus: Unreachable\r\n");
19824       } else if (peer->lastms > peer->maxms) {
19825          snprintf(status, sizeof(status), "PeerStatus: Lagged\r\n");
19826          snprintf(time, sizeof(time), "Time: %d\r\n", peer->lastms);
19827       } else if (peer->lastms) {
19828          snprintf(status, sizeof(status), "PeerStatus: Reachable\r\n");
19829          snprintf(time, sizeof(time), "Time: %d\r\n", peer->lastms);
19830       } else {
19831          snprintf(status, sizeof(status), "PeerStatus: Unknown\r\n");
19832       }
19833    } else {
19834       snprintf(status, sizeof(status), "PeerStatus: Unmonitored\r\n");
19835    }
19836 
19837    astman_append(s,
19838    "Event: PeerStatus\r\n"
19839    "Privilege: System\r\n"
19840    "ChannelType: SIP\r\n"
19841    "Peer: SIP/%s\r\n"
19842    "%s"
19843    "%s"
19844    "%s"
19845    "\r\n",
19846    peer->name, status, time, idText);
19847 }
19848 
19849 /*! \brief Show SIP peers in the manager API  */
19850 static int manager_sip_peer_status(struct mansession *s, const struct message *m)
19851 {
19852    const char *id = astman_get_header(m,"ActionID");
19853    const char *peer_name = astman_get_header(m,"Peer");
19854    char idText[256] = "";
19855    struct sip_peer *peer = NULL;
19856 
19857    if (!ast_strlen_zero(id)) {
19858       snprintf(idText, sizeof(idText), "ActionID: %s\r\n", id);
19859    }
19860 
19861    if (!ast_strlen_zero(peer_name)) {
19862       /* strip SIP/ from the begining of the peer name */
19863       if (strlen(peer_name) >= 4 && !strncasecmp("SIP/", peer_name, 4)) {
19864          peer_name += 4;
19865       }
19866 
19867       peer = sip_find_peer(peer_name, NULL, TRUE, FINDPEERS, FALSE, 0);
19868       if (!peer) {
19869          astman_send_error(s, m, "No such peer");
19870          return 0;
19871       }
19872    }
19873 
19874    astman_send_ack(s, m, "Peer status will follow");
19875 
19876    if (!peer) {
19877       struct ao2_iterator i = ao2_iterator_init(peers, 0);
19878       while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table for SIPpeerstatus"))) {
19879          ao2_lock(peer);
19880          send_manager_peer_status(s, peer, idText);
19881          ao2_unlock(peer);
19882          sip_unref_peer(peer, "unref peer for SIPpeerstatus");
19883       }
19884       ao2_iterator_destroy(&i);
19885    } else {
19886       ao2_lock(peer);
19887       send_manager_peer_status(s, peer, idText);
19888       ao2_unlock(peer);
19889       sip_unref_peer(peer, "unref peer for SIPpeerstatus");
19890    }
19891 
19892 
19893    astman_append(s,
19894    "Event: SIPpeerstatusComplete\r\n"
19895    "%s"
19896    "\r\n",
19897    idText);
19898 
19899    return 0;
19900 }
19901 
19902 
19903 /*! \brief Send qualify message to peer from cli or manager. Mostly for debugging. */
19904 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
19905 {
19906    struct sip_peer *peer;
19907    int load_realtime;
19908 
19909    if (argc < 4)
19910       return CLI_SHOWUSAGE;
19911 
19912    load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
19913    if ((peer = sip_find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0))) {
19914       sip_poke_peer(peer, 1);
19915       sip_unref_peer(peer, "qualify: done with peer");
19916    } else if (type == 0) {
19917       ast_cli(fd, "Peer '%s' not found\n", argv[3]);
19918    } else {
19919       astman_send_error(s, m, "Peer not found");
19920    }
19921    return CLI_SUCCESS;
19922 }
19923 
19924 /*! \brief Qualify SIP peers in the manager API  */
19925 static int manager_sip_qualify_peer(struct mansession *s, const struct message *m)
19926 {
19927    const char *a[4];
19928    const char *peer;
19929 
19930    peer = astman_get_header(m, "Peer");
19931    if (ast_strlen_zero(peer)) {
19932       astman_send_error(s, m, "Peer: <name> missing.");
19933       return 0;
19934    }
19935    a[0] = "sip";
19936    a[1] = "qualify";
19937    a[2] = "peer";
19938    a[3] = peer;
19939 
19940    _sip_qualify_peer(1, -1, s, m, 4, a);
19941    astman_append(s, "\r\n\r\n" );
19942    return 0;
19943 }
19944 
19945 /*! \brief Send an OPTIONS packet to a SIP peer */
19946 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19947 {
19948    switch (cmd) {
19949    case CLI_INIT:
19950       e->command = "sip qualify peer";
19951       e->usage =
19952          "Usage: sip qualify peer <name> [load]\n"
19953          "       Requests a response from one SIP peer and the current status.\n"
19954          "       Option \"load\" forces lookup of peer in realtime storage.\n";
19955       return NULL;
19956    case CLI_GENERATE:
19957       return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
19958    }
19959    return _sip_qualify_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
19960 }
19961 
19962 /*! \brief list peer mailboxes to CLI */
19963 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer)
19964 {
19965    struct sip_mailbox *mailbox;
19966 
19967    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
19968       ast_str_append(mailbox_str, 0, "%s%s%s%s",
19969          mailbox->mailbox,
19970          ast_strlen_zero(mailbox->context) ? "" : "@",
19971          S_OR(mailbox->context, ""),
19972          AST_LIST_NEXT(mailbox, entry) ? "," : "");
19973    }
19974 }
19975 
19976 static struct _map_x_s faxecmodes[] = {
19977    { SIP_PAGE2_T38SUPPORT_UDPTL,       "None"},
19978    { SIP_PAGE2_T38SUPPORT_UDPTL_FEC,      "FEC"},
19979    { SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY,  "Redundancy"},
19980    { -1,                NULL},
19981 };
19982 
19983 static const char *faxec2str(int faxec)
19984 {
19985    return map_x_s(faxecmodes, faxec, "Unknown");
19986 }
19987 
19988 /*! \brief Show one peer in detail (main function) */
19989 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
19990 {
19991    char status[30] = "";
19992    char cbuf[256];
19993    struct sip_peer *peer;
19994    char codec_buf[512];
19995    struct ast_codec_pref *pref;
19996    struct ast_variable *v;
19997    int x = 0, load_realtime;
19998    struct ast_format codec;
19999    int realtimepeers;
20000 
20001    realtimepeers = ast_check_realtime("sippeers");
20002 
20003    if (argc < 4)
20004       return CLI_SHOWUSAGE;
20005 
20006    load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
20007    peer = sip_find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0);
20008 
20009    if (s) {    /* Manager */
20010       if (peer) {
20011          const char *id = astman_get_header(m, "ActionID");
20012 
20013          astman_append(s, "Response: Success\r\n");
20014          if (!ast_strlen_zero(id))
20015             astman_append(s, "ActionID: %s\r\n", id);
20016       } else {
20017          snprintf (cbuf, sizeof(cbuf), "Peer %s not found.", argv[3]);
20018          astman_send_error(s, m, cbuf);
20019          return CLI_SUCCESS;
20020       }
20021    }
20022    if (peer && type==0 ) { /* Normal listing */
20023       struct ast_str *mailbox_str = ast_str_alloca(512);
20024       struct sip_auth_container *credentials;
20025 
20026       ao2_lock(peer);
20027       credentials = peer->auth;
20028       if (credentials) {
20029          ao2_t_ref(credentials, +1, "Ref peer auth for show");
20030       }
20031       ao2_unlock(peer);
20032 
20033       ast_cli(fd, "\n\n");
20034       ast_cli(fd, "  * Name       : %s\n", peer->name);
20035       ast_cli(fd, "  Description  : %s\n", peer->description);
20036       if (realtimepeers) { /* Realtime is enabled */
20037          ast_cli(fd, "  Realtime peer: %s\n", peer->is_realtime ? "Yes, cached" : "No");
20038       }
20039       ast_cli(fd, "  Secret       : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
20040       ast_cli(fd, "  MD5Secret    : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
20041       ast_cli(fd, "  Remote Secret: %s\n", ast_strlen_zero(peer->remotesecret)?"<Not set>":"<Set>");
20042       if (credentials) {
20043          struct sip_auth *auth;
20044 
20045          AST_LIST_TRAVERSE(&credentials->list, auth, node) {
20046             ast_cli(fd, "  Realm-auth   : Realm %-15.15s User %-10.20s %s\n",
20047                auth->realm,
20048                auth->username,
20049                !ast_strlen_zero(auth->secret)
20050                   ? "<Secret set>"
20051                   : (!ast_strlen_zero(auth->md5secret)
20052                      ? "<MD5secret set>" : "<Not set>"));
20053          }
20054          ao2_t_ref(credentials, -1, "Unref peer auth for show");
20055       }
20056       ast_cli(fd, "  Context      : %s\n", peer->context);
20057       ast_cli(fd, "  Record On feature : %s\n", peer->record_on_feature);
20058       ast_cli(fd, "  Record Off feature : %s\n", peer->record_off_feature);
20059       ast_cli(fd, "  Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
20060       ast_cli(fd, "  Language     : %s\n", peer->language);
20061       ast_cli(fd, "  Tonezone     : %s\n", peer->zone[0] != '\0' ? peer->zone : "<Not set>");
20062       if (!ast_strlen_zero(peer->accountcode))
20063          ast_cli(fd, "  Accountcode  : %s\n", peer->accountcode);
20064       ast_cli(fd, "  AMA flags    : %s\n", ast_cdr_flags2str(peer->amaflags));
20065       ast_cli(fd, "  Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
20066       ast_cli(fd, "  CallingPres  : %s\n", ast_describe_caller_presentation(peer->callingpres));
20067       if (!ast_strlen_zero(peer->fromuser))
20068          ast_cli(fd, "  FromUser     : %s\n", peer->fromuser);
20069       if (!ast_strlen_zero(peer->fromdomain))
20070          ast_cli(fd, "  FromDomain   : %s Port %d\n", peer->fromdomain, (peer->fromdomainport) ? peer->fromdomainport : STANDARD_SIP_PORT);
20071       ast_cli(fd, "  Callgroup    : ");
20072       print_group(fd, peer->callgroup, 0);
20073       ast_cli(fd, "  Pickupgroup  : ");
20074       print_group(fd, peer->pickupgroup, 0);
20075       ast_cli(fd, "  Named Callgr : ");
20076       print_named_groups(fd, peer->named_callgroups, 0);
20077       ast_cli(fd, "  Nam. Pickupgr: ");
20078       print_named_groups(fd, peer->named_pickupgroups, 0);
20079       peer_mailboxes_to_str(&mailbox_str, peer);
20080       ast_cli(fd, "  MOH Suggest  : %s\n", peer->mohsuggest);
20081       ast_cli(fd, "  Mailbox      : %s\n", ast_str_buffer(mailbox_str));
20082       ast_cli(fd, "  VM Extension : %s\n", peer->vmexten);
20083       ast_cli(fd, "  LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
20084       ast_cli(fd, "  Call limit   : %d\n", peer->call_limit);
20085       ast_cli(fd, "  Max forwards : %d\n", peer->maxforwards);
20086       if (peer->busy_level)
20087          ast_cli(fd, "  Busy level   : %d\n", peer->busy_level);
20088       ast_cli(fd, "  Dynamic      : %s\n", AST_CLI_YESNO(peer->host_dynamic));
20089       ast_cli(fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
20090       ast_cli(fd, "  MaxCallBR    : %d kbps\n", peer->maxcallbitrate);
20091       ast_cli(fd, "  Expire       : %ld\n", ast_sched_when(sched, peer->expire));
20092       ast_cli(fd, "  Insecure     : %s\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
20093       ast_cli(fd, "  Force rport  : %s\n", force_rport_string(peer->flags));
20094       ast_cli(fd, "  Symmetric RTP: %s\n", comedia_string(peer->flags));
20095       ast_cli(fd, "  ACL          : %s\n", AST_CLI_YESNO(ast_acl_list_is_empty(peer->acl) == 0));
20096       ast_cli(fd, "  DirectMedACL : %s\n", AST_CLI_YESNO(ast_acl_list_is_empty(peer->directmediaacl) == 0));
20097       ast_cli(fd, "  T.38 support : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
20098       ast_cli(fd, "  T.38 EC mode : %s\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
20099       ast_cli(fd, "  T.38 MaxDtgrm: %d\n", peer->t38_maxdatagram);
20100       ast_cli(fd, "  DirectMedia  : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)));
20101       ast_cli(fd, "  PromiscRedir : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)));
20102       ast_cli(fd, "  User=Phone   : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)));
20103       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)));
20104       ast_cli(fd, "  Text Support : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)));
20105       ast_cli(fd, "  Ign SDP ver  : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_IGNORESDPVERSION)));
20106       ast_cli(fd, "  Trust RPID   : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_TRUSTRPID)));
20107       ast_cli(fd, "  Send RPID    : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_SENDRPID)));
20108       ast_cli(fd, "  TrustIDOutbnd: %s\n", trust_id_outbound2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND)));
20109       ast_cli(fd, "  Subscriptions: %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
20110       ast_cli(fd, "  Overlap dial : %s\n", allowoverlap2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP)));
20111       if (peer->outboundproxy)
20112          ast_cli(fd, "  Outb. proxy  : %s %s\n", ast_strlen_zero(peer->outboundproxy->name) ? "<not set>" : peer->outboundproxy->name,
20113                      peer->outboundproxy->force ? "(forced)" : "");
20114 
20115       /* - is enumerated */
20116       ast_cli(fd, "  DTMFmode     : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
20117       ast_cli(fd, "  Timer T1     : %d\n", peer->timer_t1);
20118       ast_cli(fd, "  Timer B      : %d\n", peer->timer_b);
20119       ast_cli(fd, "  ToHost       : %s\n", peer->tohost);
20120       ast_cli(fd, "  Addr->IP     : %s\n", ast_sockaddr_stringify(&peer->addr));
20121       ast_cli(fd, "  Defaddr->IP  : %s\n", ast_sockaddr_stringify(&peer->defaddr));
20122       ast_cli(fd, "  Prim.Transp. : %s\n", sip_get_transport(peer->socket.type));
20123       ast_cli(fd, "  Allowed.Trsp : %s\n", get_transport_list(peer->transports));
20124       if (!ast_strlen_zero(sip_cfg.regcontext))
20125          ast_cli(fd, "  Reg. exten   : %s\n", peer->regexten);
20126       ast_cli(fd, "  Def. Username: %s\n", peer->username);
20127       ast_cli(fd, "  SIP Options  : ");
20128       if (peer->sipoptions) {
20129          int lastoption = -1;
20130          for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
20131             if (sip_options[x].id != lastoption) {
20132                if (peer->sipoptions & sip_options[x].id)
20133                   ast_cli(fd, "%s ", sip_options[x].text);
20134                lastoption = x;
20135             }
20136          }
20137       } else
20138          ast_cli(fd, "(none)");
20139 
20140       ast_cli(fd, "\n");
20141       ast_cli(fd, "  Codecs       : ");
20142       ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->caps);
20143       ast_cli(fd, "%s\n", codec_buf);
20144       ast_cli(fd, "  Codec Order  : (");
20145       print_codec_to_cli(fd, &peer->prefs);
20146       ast_cli(fd, ")\n");
20147 
20148       ast_cli(fd, "  Auto-Framing : %s\n", AST_CLI_YESNO(peer->autoframing));
20149       ast_cli(fd, "  Status       : ");
20150       peer_status(peer, status, sizeof(status));
20151       ast_cli(fd, "%s\n", status);
20152       ast_cli(fd, "  Useragent    : %s\n", peer->useragent);
20153       ast_cli(fd, "  Reg. Contact : %s\n", peer->fullcontact);
20154       ast_cli(fd, "  Qualify Freq : %d ms\n", peer->qualifyfreq);
20155       ast_cli(fd, "  Keepalive    : %d ms\n", peer->keepalive * 1000);
20156       if (peer->chanvars) {
20157          ast_cli(fd, "  Variables    :\n");
20158          for (v = peer->chanvars ; v ; v = v->next)
20159             ast_cli(fd, "                 %s = %s\n", v->name, v->value);
20160       }
20161 
20162       ast_cli(fd, "  Sess-Timers  : %s\n", stmode2str(peer->stimer.st_mode_oper));
20163       ast_cli(fd, "  Sess-Refresh : %s\n", strefresherparam2str(peer->stimer.st_ref));
20164       ast_cli(fd, "  Sess-Expires : %d secs\n", peer->stimer.st_max_se);
20165       ast_cli(fd, "  Min-Sess     : %d secs\n", peer->stimer.st_min_se);
20166       ast_cli(fd, "  RTP Engine   : %s\n", peer->engine);
20167       ast_cli(fd, "  Parkinglot   : %s\n", peer->parkinglot);
20168       ast_cli(fd, "  Use Reason   : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_Q850_REASON)));
20169       ast_cli(fd, "  Encryption   : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP)));
20170       ast_cli(fd, "\n");
20171       peer = sip_unref_peer(peer, "sip_show_peer: sip_unref_peer: done with peer ptr");
20172    } else  if (peer && type == 1) { /* manager listing */
20173       char buffer[256];
20174       struct ast_str *tmp_str = ast_str_alloca(512);
20175       astman_append(s, "Channeltype: SIP\r\n");
20176       astman_append(s, "ObjectName: %s\r\n", peer->name);
20177       astman_append(s, "ChanObjectType: peer\r\n");
20178       astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
20179       astman_append(s, "RemoteSecretExist: %s\r\n", ast_strlen_zero(peer->remotesecret)?"N":"Y");
20180       astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
20181       astman_append(s, "Context: %s\r\n", peer->context);
20182       astman_append(s, "Language: %s\r\n", peer->language);
20183       astman_append(s, "ToneZone: %s\r\n", peer->zone[0] != '\0' ? peer->zone : "<Not set>");
20184       if (!ast_strlen_zero(peer->accountcode))
20185          astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
20186       astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
20187       astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
20188       if (!ast_strlen_zero(peer->fromuser))
20189          astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
20190       if (!ast_strlen_zero(peer->fromdomain))
20191          astman_append(s, "SIP-FromDomain: %s\r\nSip-FromDomain-Port: %d\r\n", peer->fromdomain, (peer->fromdomainport) ? peer->fromdomainport : STANDARD_SIP_PORT);
20192       astman_append(s, "Callgroup: ");
20193       astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->callgroup));
20194       astman_append(s, "Pickupgroup: ");
20195       astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->pickupgroup));
20196       astman_append(s, "Named Callgroup: ");
20197       astman_append(s, "%s\r\n", ast_print_namedgroups(&tmp_str, peer->named_callgroups));
20198       ast_str_reset(tmp_str);
20199       astman_append(s, "Named Pickupgroup: ");
20200       astman_append(s, "%s\r\n", ast_print_namedgroups(&tmp_str, peer->named_pickupgroups));
20201       ast_str_reset(tmp_str);
20202       astman_append(s, "MOHSuggest: %s\r\n", peer->mohsuggest);
20203       peer_mailboxes_to_str(&tmp_str, peer);
20204       astman_append(s, "VoiceMailbox: %s\r\n", ast_str_buffer(tmp_str));
20205       astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
20206       astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
20207       astman_append(s, "Maxforwards: %d\r\n", peer->maxforwards);
20208       astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
20209       astman_append(s, "Busy-level: %d\r\n", peer->busy_level);
20210       astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
20211       astman_append(s, "Dynamic: %s\r\n", peer->host_dynamic?"Y":"N");
20212       astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
20213       astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched, peer->expire));
20214       astman_append(s, "SIP-AuthInsecure: %s\r\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
20215       astman_append(s, "SIP-Forcerport: %s\r\n", ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_RPORT) ?
20216             (ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? "A" : "a") :
20217             (ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? "Y" : "N"));
20218       astman_append(s, "SIP-Comedia: %s\r\n", ast_test_flag(&peer->flags[2], SIP_PAGE3_NAT_AUTO_COMEDIA) ?
20219             (ast_test_flag(&peer->flags[1], SIP_PAGE2_SYMMETRICRTP) ? "A" : "a") :
20220             (ast_test_flag(&peer->flags[1], SIP_PAGE2_SYMMETRICRTP) ? "Y" : "N"));
20221       astman_append(s, "ACL: %s\r\n", (ast_acl_list_is_empty(peer->acl) ? "N" : "Y"));
20222       astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
20223       astman_append(s, "SIP-DirectMedia: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
20224       astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
20225       astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
20226       astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
20227       astman_append(s, "SIP-TextSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)?"Y":"N"));
20228       astman_append(s, "SIP-T.38Support: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)?"Y":"N"));
20229       astman_append(s, "SIP-T.38EC: %s\r\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
20230       astman_append(s, "SIP-T.38MaxDtgrm: %d\r\n", peer->t38_maxdatagram);
20231       astman_append(s, "SIP-Sess-Timers: %s\r\n", stmode2str(peer->stimer.st_mode_oper));
20232       astman_append(s, "SIP-Sess-Refresh: %s\r\n", strefresherparam2str(peer->stimer.st_ref));
20233       astman_append(s, "SIP-Sess-Expires: %d\r\n", peer->stimer.st_max_se);
20234       astman_append(s, "SIP-Sess-Min: %d\r\n", peer->stimer.st_min_se);
20235       astman_append(s, "SIP-RTP-Engine: %s\r\n", peer->engine);
20236       astman_append(s, "SIP-Encryption: %s\r\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP) ? "Y" : "N");
20237 
20238       /* - is enumerated */
20239       astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
20240       astman_append(s, "ToHost: %s\r\n", peer->tohost);
20241       astman_append(s, "Address-IP: %s\r\nAddress-Port: %d\r\n", ast_sockaddr_stringify_addr(&peer->addr), ast_sockaddr_port(&peer->addr));
20242       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));
20243       astman_append(s, "Default-Username: %s\r\n", peer->username);
20244       if (!ast_strlen_zero(sip_cfg.regcontext))
20245          astman_append(s, "RegExtension: %s\r\n", peer->regexten);
20246       astman_append(s, "Codecs: ");
20247       ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->caps);
20248       astman_append(s, "%s\r\n", codec_buf);
20249       astman_append(s, "CodecOrder: ");
20250       pref = &peer->prefs;
20251       for(x = 0; x < AST_CODEC_PREF_SIZE ; x++) {
20252          if (!(ast_codec_pref_index(pref, x, &codec))) {
20253             break;
20254          }
20255          astman_append(s, "%s", ast_getformatname(&codec));
20256          if ((x < (AST_CODEC_PREF_SIZE - 1)) && ast_codec_pref_index(pref, x+1, &codec))
20257             astman_append(s, ",");
20258       }
20259 
20260       astman_append(s, "\r\n");
20261       astman_append(s, "Status: ");
20262       peer_status(peer, status, sizeof(status));
20263       astman_append(s, "%s\r\n", status);
20264       astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
20265       astman_append(s, "Reg-Contact: %s\r\n", peer->fullcontact);
20266       astman_append(s, "QualifyFreq: %d ms\r\n", peer->qualifyfreq);
20267       astman_append(s, "Parkinglot: %s\r\n", peer->parkinglot);
20268       if (peer->chanvars) {
20269          for (v = peer->chanvars ; v ; v = v->next) {
20270             astman_append(s, "ChanVariable: %s=%s\r\n", v->name, v->value);
20271          }
20272       }
20273       astman_append(s, "SIP-Use-Reason-Header: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_Q850_REASON)) ? "Y" : "N");
20274       astman_append(s, "Description: %s\r\n", peer->description);
20275 
20276       peer = sip_unref_peer(peer, "sip_show_peer: sip_unref_peer: done with peer");
20277 
20278    } else {
20279       ast_cli(fd, "Peer %s not found.\n", argv[3]);
20280       ast_cli(fd, "\n");
20281    }
20282 
20283    return CLI_SUCCESS;
20284 }
20285 
20286 /*! \brief Do completion on user name */
20287 static char *complete_sip_user(const char *word, int state)
20288 {
20289    char *result = NULL;
20290    int wordlen = strlen(word);
20291    int which = 0;
20292    struct ao2_iterator user_iter;
20293    struct sip_peer *user;
20294 
20295    user_iter = ao2_iterator_init(peers, 0);
20296    while ((user = ao2_t_iterator_next(&user_iter, "iterate thru peers table"))) {
20297       ao2_lock(user);
20298       if (!(user->type & SIP_TYPE_USER)) {
20299          ao2_unlock(user);
20300          sip_unref_peer(user, "complete sip user");
20301          continue;
20302       }
20303       /* locking of the object is not required because only the name and flags are being compared */
20304       if (!strncasecmp(word, user->name, wordlen) && ++which > state) {
20305          result = ast_strdup(user->name);
20306       }
20307       ao2_unlock(user);
20308       sip_unref_peer(user, "complete sip user");
20309       if (result) {
20310          break;
20311       }
20312    }
20313    ao2_iterator_destroy(&user_iter);
20314    return result;
20315 }
20316 /*! \brief Support routine for 'sip show user' CLI */
20317 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
20318 {
20319    if (pos == 3)
20320       return complete_sip_user(word, state);
20321 
20322    return NULL;
20323 }
20324 
20325 /*! \brief Show one user in detail */
20326 static char *sip_show_user(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
20327 {
20328    char cbuf[256];
20329    struct sip_peer *user;
20330    struct ast_variable *v;
20331    int load_realtime;
20332 
20333    switch (cmd) {
20334    case CLI_INIT:
20335       e->command = "sip show user";
20336       e->usage =
20337          "Usage: sip show user <name> [load]\n"
20338          "       Shows all details on one SIP user and the current status.\n"
20339          "       Option \"load\" forces lookup of peer in realtime storage.\n";
20340       return NULL;
20341    case CLI_GENERATE:
20342       return complete_sip_show_user(a->line, a->word, a->pos, a->n);
20343    }
20344 
20345    if (a->argc < 4)
20346       return CLI_SHOWUSAGE;
20347 
20348    /* Load from realtime storage? */
20349    load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? TRUE : FALSE;
20350 
20351    if ((user = sip_find_peer(a->argv[3], NULL, load_realtime, FINDUSERS, FALSE, 0))) {
20352       ao2_lock(user);
20353       ast_cli(a->fd, "\n\n");
20354       ast_cli(a->fd, "  * Name       : %s\n", user->name);
20355       ast_cli(a->fd, "  Secret       : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
20356       ast_cli(a->fd, "  MD5Secret    : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
20357       ast_cli(a->fd, "  Context      : %s\n", user->context);
20358       ast_cli(a->fd, "  Language     : %s\n", user->language);
20359       if (!ast_strlen_zero(user->accountcode))
20360          ast_cli(a->fd, "  Accountcode  : %s\n", user->accountcode);
20361       ast_cli(a->fd, "  AMA flags    : %s\n", ast_cdr_flags2str(user->amaflags));
20362       ast_cli(a->fd, "  Tonezone     : %s\n", user->zone[0] != '\0' ? user->zone : "<Not set>");
20363       ast_cli(a->fd, "  Transfer mode: %s\n", transfermode2str(user->allowtransfer));
20364       ast_cli(a->fd, "  MaxCallBR    : %d kbps\n", user->maxcallbitrate);
20365       ast_cli(a->fd, "  CallingPres  : %s\n", ast_describe_caller_presentation(user->callingpres));
20366       ast_cli(a->fd, "  Call limit   : %d\n", user->call_limit);
20367       ast_cli(a->fd, "  Callgroup    : ");
20368       print_group(a->fd, user->callgroup, 0);
20369       ast_cli(a->fd, "  Pickupgroup  : ");
20370       print_group(a->fd, user->pickupgroup, 0);
20371       ast_cli(a->fd, "  Named Callgr : ");
20372       print_named_groups(a->fd, user->named_callgroups, 0);
20373       ast_cli(a->fd, "  Nam. Pickupgr: ");
20374       print_named_groups(a->fd, user->named_pickupgroups, 0);
20375       ast_cli(a->fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
20376       ast_cli(a->fd, "  ACL          : %s\n", AST_CLI_YESNO(ast_acl_list_is_empty(user->acl) == 0));
20377       ast_cli(a->fd, "  Sess-Timers  : %s\n", stmode2str(user->stimer.st_mode_oper));
20378       ast_cli(a->fd, "  Sess-Refresh : %s\n", strefresherparam2str(user->stimer.st_ref));
20379       ast_cli(a->fd, "  Sess-Expires : %d secs\n", user->stimer.st_max_se);
20380       ast_cli(a->fd, "  Sess-Min-SE  : %d secs\n", user->stimer.st_min_se);
20381       ast_cli(a->fd, "  RTP Engine   : %s\n", user->engine);
20382 
20383       ast_cli(a->fd, "  Codec Order  : (");
20384       print_codec_to_cli(a->fd, &user->prefs);
20385       ast_cli(a->fd, ")\n");
20386 
20387       ast_cli(a->fd, "  Auto-Framing:  %s \n", AST_CLI_YESNO(user->autoframing));
20388       if (user->chanvars) {
20389          ast_cli(a->fd, "  Variables    :\n");
20390          for (v = user->chanvars ; v ; v = v->next)
20391             ast_cli(a->fd, "                 %s = %s\n", v->name, v->value);
20392       }
20393 
20394       ast_cli(a->fd, "\n");
20395 
20396       ao2_unlock(user);
20397       sip_unref_peer(user, "sip show user");
20398    } else {
20399       ast_cli(a->fd, "User %s not found.\n", a->argv[3]);
20400       ast_cli(a->fd, "\n");
20401    }
20402 
20403    return CLI_SUCCESS;
20404 }
20405 
20406 
20407 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
20408 {
20409    struct ast_str *cbuf;
20410    struct ast_cb_names cbnames = {9, { "retrans_pkt",
20411                                         "__sip_autodestruct",
20412                                         "expire_register",
20413                                         "auto_congest",
20414                                         "sip_reg_timeout",
20415                                         "sip_poke_peer_s",
20416                                         "sip_poke_noanswer",
20417                                         "sip_reregister",
20418                                         "sip_reinvite_retry"},
20419                            { retrans_pkt,
20420                                      __sip_autodestruct,
20421                                      expire_register,
20422                                      auto_congest,
20423                                      sip_reg_timeout,
20424                                      sip_poke_peer_s,
20425                                      sip_poke_noanswer,
20426                                      sip_reregister,
20427                                      sip_reinvite_retry}};
20428    
20429    switch (cmd) {
20430    case CLI_INIT:
20431       e->command = "sip show sched";
20432       e->usage =
20433          "Usage: sip show sched\n"
20434          "       Shows stats on what's in the sched queue at the moment\n";
20435       return NULL;
20436    case CLI_GENERATE:
20437       return NULL;
20438    }
20439 
20440    cbuf = ast_str_alloca(2048);
20441 
20442    ast_cli(a->fd, "\n");
20443    ast_sched_report(sched, &cbuf, &cbnames);
20444    ast_cli(a->fd, "%s", ast_str_buffer(cbuf));
20445 
20446    return CLI_SUCCESS;
20447 }
20448 
20449 /*! \brief  Show SIP Registry (registrations with other SIP proxies */
20450 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
20451 {
20452 #define FORMAT2 "%-39.39s %-6.6s %-12.12s  %8.8s %-20.20s %-25.25s\n"
20453 #define FORMAT  "%-39.39s %-6.6s %-12.12s  %8d %-20.20s %-25.25s\n"
20454    char host[80];
20455    char user[80];
20456    char tmpdat[256];
20457    struct ast_tm tm;
20458    int counter = 0;
20459 
20460    switch (cmd) {
20461    case CLI_INIT:
20462       e->command = "sip show registry";
20463       e->usage =
20464          "Usage: sip show registry\n"
20465          "       Lists all registration requests and status.\n";
20466       return NULL;
20467    case CLI_GENERATE:
20468       return NULL;
20469    }
20470 
20471    if (a->argc != 3)
20472       return CLI_SHOWUSAGE;
20473    ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Refresh", "State", "Reg.Time");
20474    
20475    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
20476       ASTOBJ_RDLOCK(iterator);
20477       snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
20478       snprintf(user, sizeof(user), "%s", iterator->username);
20479       if (!ast_strlen_zero(iterator->regdomain)) {
20480          snprintf(tmpdat, sizeof(tmpdat), "%s", user);
20481          snprintf(user, sizeof(user), "%s@%s", tmpdat, iterator->regdomain);}
20482       if (iterator->regdomainport) {
20483          snprintf(tmpdat, sizeof(tmpdat), "%s", user);
20484          snprintf(user, sizeof(user), "%s:%d", tmpdat, iterator->regdomainport);}
20485       if (iterator->regtime.tv_sec) {
20486          ast_localtime(&iterator->regtime, &tm, NULL);
20487          ast_strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
20488       } else
20489          tmpdat[0] = '\0';
20490       ast_cli(a->fd, FORMAT, host, (iterator->dnsmgr) ? "Y" : "N", user, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
20491       ASTOBJ_UNLOCK(iterator);
20492       counter++;
20493    } while(0));
20494    ast_cli(a->fd, "%d SIP registrations.\n", counter);
20495    return CLI_SUCCESS;
20496 #undef FORMAT
20497 #undef FORMAT2
20498 }
20499 
20500 /*! \brief Unregister (force expiration) a SIP peer in the registry via CLI
20501    \note This function does not tell the SIP device what's going on,
20502    so use it with great care.
20503 */
20504 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
20505 {
20506    struct sip_peer *peer;
20507    int load_realtime = 0;
20508 
20509    switch (cmd) {
20510    case CLI_INIT:
20511       e->command = "sip unregister";
20512       e->usage =
20513          "Usage: sip unregister <peer>\n"
20514          "       Unregister (force expiration) a SIP peer from the registry\n";
20515       return NULL;
20516    case CLI_GENERATE:
20517       return complete_sip_unregister(a->line, a->word, a->pos, a->n);
20518    }
20519    
20520    if (a->argc != 3)
20521       return CLI_SHOWUSAGE;
20522    
20523    if ((peer = sip_find_peer(a->argv[2], NULL, load_realtime, FINDPEERS, TRUE, 0))) {
20524       if (peer->expire > 0) {
20525          AST_SCHED_DEL_UNREF(sched, peer->expire,
20526             sip_unref_peer(peer, "remove register expire ref"));
20527          expire_register(sip_ref_peer(peer, "ref for expire_register"));
20528          ast_cli(a->fd, "Unregistered peer \'%s\'\n\n", a->argv[2]);
20529       } else {
20530          ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
20531       }
20532       sip_unref_peer(peer, "sip_unregister: sip_unref_peer via sip_unregister: done with peer from sip_find_peer call");
20533    } else {
20534       ast_cli(a->fd, "Peer unknown: \'%s\'. Not unregistered.\n", a->argv[2]);
20535    }
20536    
20537    return CLI_SUCCESS;
20538 }
20539 
20540 /*! \brief Callback for show_chanstats */
20541 static int show_chanstats_cb(void *__cur, void *__arg, int flags)
20542 {
20543 #define FORMAT2 "%-15.15s  %-11.11s  %-8.8s %-10.10s  %-10.10s (     %%) %-6.6s %-10.10s  %-10.10s (     %%) %-6.6s\n"
20544 #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"
20545    struct sip_pvt *cur = __cur;
20546    struct ast_rtp_instance_stats stats;
20547    char durbuf[10];
20548    int duration;
20549    int durh, durm, durs;
20550    struct ast_channel *c;
20551    struct __show_chan_arg *arg = __arg;
20552    int fd = arg->fd;
20553 
20554    sip_pvt_lock(cur);
20555    c = cur->owner;
20556 
20557    if (cur->subscribed != NONE) {
20558       /* Subscriptions */
20559       sip_pvt_unlock(cur);
20560       return 0;   /* don't care, we scan all channels */
20561    }
20562 
20563    if (!cur->rtp) {
20564       if (sipdebug) {
20565          ast_cli(fd, "%-15.15s  %-11.11s (inv state: %s) -- %s\n",
20566             ast_sockaddr_stringify_addr(&cur->sa), cur->callid,
20567             invitestate2string[cur->invitestate].desc,
20568             "-- No RTP active");
20569       }
20570       sip_pvt_unlock(cur);
20571       return 0;   /* don't care, we scan all channels */
20572    }
20573 
20574    if (ast_rtp_instance_get_stats(cur->rtp, &stats, AST_RTP_INSTANCE_STAT_ALL)) {
20575       sip_pvt_unlock(cur);
20576       ast_log(LOG_WARNING, "Could not get RTP stats.\n");
20577       return 0;
20578    }
20579 
20580    if (c && ast_channel_cdr(c) && !ast_tvzero(ast_channel_cdr(c)->start)) {
20581       duration = (int)(ast_tvdiff_ms(ast_tvnow(), ast_channel_cdr(c)->start) / 1000);
20582       durh = duration / 3600;
20583       durm = (duration % 3600) / 60;
20584       durs = duration % 60;
20585       snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
20586    } else {
20587       durbuf[0] = '\0';
20588    }
20589 
20590    ast_cli(fd, FORMAT,
20591       ast_sockaddr_stringify_addr(&cur->sa),
20592       cur->callid,
20593       durbuf,
20594       stats.rxcount > (unsigned int) 100000 ? (unsigned int) (stats.rxcount)/(unsigned int) 1000 : stats.rxcount,
20595       stats.rxcount > (unsigned int) 100000 ? "K":" ",
20596       stats.rxploss,
20597       (stats.rxcount + stats.rxploss) > 0 ? (double) stats.rxploss / (stats.rxcount + stats.rxploss) * 100 : 0,
20598       stats.rxjitter,
20599       stats.txcount > (unsigned int) 100000 ? (unsigned int) (stats.txcount)/(unsigned int) 1000 : stats.txcount,
20600       stats.txcount > (unsigned int) 100000 ? "K":" ",
20601       stats.txploss,
20602       stats.txcount > 0 ? (double) stats.txploss / stats.txcount * 100 : 0,
20603       stats.txjitter
20604    );
20605    arg->numchans++;
20606    sip_pvt_unlock(cur);
20607 
20608    return 0;   /* don't care, we scan all channels */
20609 }
20610 
20611 /*! \brief SIP show channelstats CLI (main function) */
20612 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
20613 {
20614    struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
20615 
20616    switch (cmd) {
20617    case CLI_INIT:
20618       e->command = "sip show channelstats";
20619       e->usage =
20620          "Usage: sip show channelstats\n"
20621          "       Lists all currently active SIP channel's RTCP statistics.\n"
20622          "       Note that calls in the much optimized RTP P2P bridge mode will not show any packets here.";
20623       return NULL;
20624    case CLI_GENERATE:
20625       return NULL;
20626    }
20627 
20628    if (a->argc != 3)
20629       return CLI_SHOWUSAGE;
20630 
20631    ast_cli(a->fd, FORMAT2, "Peer", "Call ID", "Duration", "Recv: Pack", "Lost", "Jitter", "Send: Pack", "Lost", "Jitter");
20632    /* iterate on the container and invoke the callback on each item */
20633    ao2_t_callback(dialogs, OBJ_NODATA, show_chanstats_cb, &arg, "callback to sip show chanstats");
20634    ast_cli(a->fd, "%d active SIP channel%s\n", arg.numchans, (arg.numchans != 1) ? "s" : "");
20635    return CLI_SUCCESS;
20636 }
20637 #undef FORMAT
20638 #undef FORMAT2
20639 
20640 /*! \brief List global settings for the SIP channel */
20641 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
20642 {
20643    int realtimepeers;
20644    int realtimeregs;
20645    char codec_buf[SIPBUFSIZE];
20646    const char *msg;  /* temporary msg pointer */
20647    struct sip_auth_container *credentials;
20648 
20649    switch (cmd) {
20650    case CLI_INIT:
20651       e->command = "sip show settings";
20652       e->usage =
20653          "Usage: sip show settings\n"
20654          "       Provides detailed list of the configuration of the SIP channel.\n";
20655       return NULL;
20656    case CLI_GENERATE:
20657       return NULL;
20658    }
20659 
20660    if (a->argc != 3)
20661       return CLI_SHOWUSAGE;
20662 
20663    realtimepeers = ast_check_realtime("sippeers");
20664    realtimeregs = ast_check_realtime("sipregs");
20665 
20666    ast_mutex_lock(&authl_lock);
20667    credentials = authl;
20668    if (credentials) {
20669       ao2_t_ref(credentials, +1, "Ref global auth for show");
20670    }
20671    ast_mutex_unlock(&authl_lock);
20672 
20673    ast_cli(a->fd, "\n\nGlobal Settings:\n");
20674    ast_cli(a->fd, "----------------\n");
20675    ast_cli(a->fd, "  UDP Bindaddress:        %s\n", ast_sockaddr_stringify(&bindaddr));
20676    if (ast_sockaddr_is_ipv6(&bindaddr) && ast_sockaddr_is_any(&bindaddr)) {
20677       ast_cli(a->fd, "  ** Additional Info:\n");
20678       ast_cli(a->fd, "     [::] may include IPv4 in addition to IPv6, if such a feature is enabled in the OS.\n");
20679    }
20680    ast_cli(a->fd, "  TCP SIP Bindaddress:    %s\n",
20681       sip_cfg.tcp_enabled != FALSE ?
20682             ast_sockaddr_stringify(&sip_tcp_desc.local_address) :
20683             "Disabled");
20684    ast_cli(a->fd, "  TLS SIP Bindaddress:    %s\n",
20685       default_tls_cfg.enabled != FALSE ?
20686             ast_sockaddr_stringify(&sip_tls_desc.local_address) :
20687             "Disabled");
20688    ast_cli(a->fd, "  Videosupport:           %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT)));
20689    ast_cli(a->fd, "  Textsupport:            %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT)));
20690    ast_cli(a->fd, "  Ignore SDP sess. ver.:  %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION)));
20691    ast_cli(a->fd, "  AutoCreate Peer:        %s\n", autocreatepeer2str(sip_cfg.autocreatepeer));
20692    ast_cli(a->fd, "  Match Auth Username:    %s\n", AST_CLI_YESNO(global_match_auth_username));
20693    ast_cli(a->fd, "  Allow unknown access:   %s\n", AST_CLI_YESNO(sip_cfg.allowguest));
20694    ast_cli(a->fd, "  Allow subscriptions:    %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
20695    ast_cli(a->fd, "  Allow overlap dialing:  %s\n", allowoverlap2str(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)));
20696    ast_cli(a->fd, "  Allow promisc. redir:   %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_PROMISCREDIR)));
20697    ast_cli(a->fd, "  Enable call counters:   %s\n", AST_CLI_YESNO(global_callcounter));
20698    ast_cli(a->fd, "  SIP domain support:     %s\n", AST_CLI_YESNO(!AST_LIST_EMPTY(&domain_list)));
20699    ast_cli(a->fd, "  Realm. auth:            %s\n", AST_CLI_YESNO(credentials != NULL));
20700    if (credentials) {
20701       struct sip_auth *auth;
20702 
20703       AST_LIST_TRAVERSE(&credentials->list, auth, node) {
20704          ast_cli(a->fd, "  Realm. auth entry:      Realm %-15.15s User %-10.20s %s\n",
20705             auth->realm,
20706             auth->username,
20707             !ast_strlen_zero(auth->secret)
20708                ? "<Secret set>"
20709                : (!ast_strlen_zero(auth->md5secret)
20710                   ? "<MD5secret set>" : "<Not set>"));
20711       }
20712       ao2_t_ref(credentials, -1, "Unref global auth for show");
20713    }
20714    ast_cli(a->fd, "  Our auth realm          %s\n", sip_cfg.realm);
20715    ast_cli(a->fd, "  Use domains as realms:  %s\n", AST_CLI_YESNO(sip_cfg.domainsasrealm));
20716    ast_cli(a->fd, "  Call to non-local dom.: %s\n", AST_CLI_YESNO(sip_cfg.allow_external_domains));
20717    ast_cli(a->fd, "  URI user is phone no:   %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_USEREQPHONE)));
20718    ast_cli(a->fd, "  Always auth rejects:    %s\n", AST_CLI_YESNO(sip_cfg.alwaysauthreject));
20719    ast_cli(a->fd, "  Direct RTP setup:       %s\n", AST_CLI_YESNO(sip_cfg.directrtpsetup));
20720    ast_cli(a->fd, "  User Agent:             %s\n", global_useragent);
20721    ast_cli(a->fd, "  SDP Session Name:       %s\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
20722    ast_cli(a->fd, "  SDP Owner Name:         %s\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner);
20723    ast_cli(a->fd, "  Reg. context:           %s\n", S_OR(sip_cfg.regcontext, "(not set)"));
20724    ast_cli(a->fd, "  Regexten on Qualify:    %s\n", AST_CLI_YESNO(sip_cfg.regextenonqualify));
20725    ast_cli(a->fd, "  Trust RPID:             %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_TRUSTRPID)));
20726    ast_cli(a->fd, "  Send RPID:              %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_SENDRPID)));
20727    ast_cli(a->fd, "  Legacy userfield parse: %s\n", AST_CLI_YESNO(sip_cfg.legacy_useroption_parsing));
20728    ast_cli(a->fd, "  Send Diversion:         %s\n", AST_CLI_YESNO(sip_cfg.send_diversion));
20729    ast_cli(a->fd, "  Caller ID:              %s\n", default_callerid);
20730    if ((default_fromdomainport) && (default_fromdomainport != STANDARD_SIP_PORT)) {
20731       ast_cli(a->fd, "  From: Domain:           %s:%d\n", default_fromdomain, default_fromdomainport);
20732    } else {
20733       ast_cli(a->fd, "  From: Domain:           %s\n", default_fromdomain);
20734    }
20735    ast_cli(a->fd, "  Record SIP history:     %s\n", AST_CLI_ONOFF(recordhistory));
20736    ast_cli(a->fd, "  Call Events:            %s\n", AST_CLI_ONOFF(sip_cfg.callevents));
20737    ast_cli(a->fd, "  Auth. Failure Events:   %s\n", AST_CLI_ONOFF(global_authfailureevents));
20738 
20739    ast_cli(a->fd, "  T.38 support:           %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
20740    ast_cli(a->fd, "  T.38 EC mode:           %s\n", faxec2str(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
20741    ast_cli(a->fd, "  T.38 MaxDtgrm:          %d\n", global_t38_maxdatagram);
20742    if (!realtimepeers && !realtimeregs)
20743       ast_cli(a->fd, "  SIP realtime:           Disabled\n" );
20744    else
20745       ast_cli(a->fd, "  SIP realtime:           Enabled\n" );
20746    ast_cli(a->fd, "  Qualify Freq :          %d ms\n", global_qualifyfreq);
20747    ast_cli(a->fd, "  Q.850 Reason header:    %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_Q850_REASON)));
20748    ast_cli(a->fd, "  Store SIP_CAUSE:        %s\n", AST_CLI_YESNO(global_store_sip_cause));
20749    ast_cli(a->fd, "\nNetwork QoS Settings:\n");
20750    ast_cli(a->fd, "---------------------------\n");
20751    ast_cli(a->fd, "  IP ToS SIP:             %s\n", ast_tos2str(global_tos_sip));
20752    ast_cli(a->fd, "  IP ToS RTP audio:       %s\n", ast_tos2str(global_tos_audio));
20753    ast_cli(a->fd, "  IP ToS RTP video:       %s\n", ast_tos2str(global_tos_video));
20754    ast_cli(a->fd, "  IP ToS RTP text:        %s\n", ast_tos2str(global_tos_text));
20755    ast_cli(a->fd, "  802.1p CoS SIP:         %d\n", global_cos_sip);
20756    ast_cli(a->fd, "  802.1p CoS RTP audio:   %d\n", global_cos_audio);
20757    ast_cli(a->fd, "  802.1p CoS RTP video:   %d\n", global_cos_video);
20758    ast_cli(a->fd, "  802.1p CoS RTP text:    %d\n", global_cos_text);
20759    ast_cli(a->fd, "  Jitterbuffer enabled:   %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_ENABLED)));
20760    if (ast_test_flag(&global_jbconf, AST_JB_ENABLED)) {
20761       ast_cli(a->fd, "  Jitterbuffer forced:    %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_FORCED)));
20762       ast_cli(a->fd, "  Jitterbuffer max size:  %ld\n", global_jbconf.max_size);
20763       ast_cli(a->fd, "  Jitterbuffer resync:    %ld\n", global_jbconf.resync_threshold);
20764       ast_cli(a->fd, "  Jitterbuffer impl:      %s\n", global_jbconf.impl);
20765       if (!strcasecmp(global_jbconf.impl, "adaptive")) {
20766          ast_cli(a->fd, "  Jitterbuffer tgt extra: %ld\n", global_jbconf.target_extra);
20767       }
20768       ast_cli(a->fd, "  Jitterbuffer log:       %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_LOG)));
20769    }
20770 
20771    ast_cli(a->fd, "\nNetwork Settings:\n");
20772    ast_cli(a->fd, "---------------------------\n");
20773    /* determine if/how SIP address can be remapped */
20774    if (localaddr == NULL)
20775       msg = "Disabled, no localnet list";
20776    else if (ast_sockaddr_isnull(&externaddr))
20777       msg = "Disabled";
20778    else if (!ast_strlen_zero(externhost))
20779       msg = "Enabled using externhost";
20780    else
20781       msg = "Enabled using externaddr";
20782    ast_cli(a->fd, "  SIP address remapping:  %s\n", msg);
20783    ast_cli(a->fd, "  Externhost:             %s\n", S_OR(externhost, "<none>"));
20784    ast_cli(a->fd, "  Externaddr:             %s\n", ast_sockaddr_stringify(&externaddr));
20785    ast_cli(a->fd, "  Externrefresh:          %d\n", externrefresh);
20786    {
20787       struct ast_ha *d;
20788       const char *prefix = "Localnet:";
20789 
20790       for (d = localaddr; d ; prefix = "", d = d->next) {
20791          const char *addr = ast_strdupa(ast_sockaddr_stringify_addr(&d->addr));
20792          const char *mask = ast_strdupa(ast_sockaddr_stringify_addr(&d->netmask));
20793          ast_cli(a->fd, "  %-24s%s/%s\n", prefix, addr, mask);
20794       }
20795    }
20796    ast_cli(a->fd, "\nGlobal Signalling Settings:\n");
20797    ast_cli(a->fd, "---------------------------\n");
20798    ast_cli(a->fd, "  Codecs:                 ");
20799    ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, sip_cfg.caps);
20800    ast_cli(a->fd, "%s\n", codec_buf);
20801    ast_cli(a->fd, "  Codec Order:            ");
20802    print_codec_to_cli(a->fd, &default_prefs);
20803    ast_cli(a->fd, "\n");
20804    ast_cli(a->fd, "  Relax DTMF:             %s\n", AST_CLI_YESNO(global_relaxdtmf));
20805    ast_cli(a->fd, "  RFC2833 Compensation:   %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE)));
20806    ast_cli(a->fd, "  Symmetric RTP:          %s\n", comedia_string(global_flags));
20807    ast_cli(a->fd, "  Compact SIP headers:    %s\n", AST_CLI_YESNO(sip_cfg.compactheaders));
20808    ast_cli(a->fd, "  RTP Keepalive:          %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
20809    ast_cli(a->fd, "  RTP Timeout:            %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
20810    ast_cli(a->fd, "  RTP Hold Timeout:       %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
20811    ast_cli(a->fd, "  MWI NOTIFY mime type:   %s\n", default_notifymime);
20812    ast_cli(a->fd, "  DNS SRV lookup:         %s\n", AST_CLI_YESNO(sip_cfg.srvlookup));
20813    ast_cli(a->fd, "  Pedantic SIP support:   %s\n", AST_CLI_YESNO(sip_cfg.pedanticsipchecking));
20814    ast_cli(a->fd, "  Reg. min duration       %d secs\n", min_expiry);
20815    ast_cli(a->fd, "  Reg. max duration:      %d secs\n", max_expiry);
20816    ast_cli(a->fd, "  Reg. default duration:  %d secs\n", default_expiry);
20817    ast_cli(a->fd, "  Sub. min duration       %d secs\n", min_subexpiry);
20818    ast_cli(a->fd, "  Sub. max duration:      %d secs\n", max_subexpiry);
20819    ast_cli(a->fd, "  Outbound reg. timeout:  %d secs\n", global_reg_timeout);
20820    ast_cli(a->fd, "  Outbound reg. attempts: %d\n", global_regattempts_max);
20821    ast_cli(a->fd, "  Outbound reg. retry 403:%d\n", global_reg_retry_403);
20822    ast_cli(a->fd, "  Notify ringing state:   %s\n", AST_CLI_YESNO(sip_cfg.notifyringing));
20823    if (sip_cfg.notifyringing) {
20824       ast_cli(a->fd, "    Include CID:          %s%s\n",
20825             AST_CLI_YESNO(sip_cfg.notifycid),
20826             sip_cfg.notifycid == IGNORE_CONTEXT ? " (Ignoring context)" : "");
20827    }
20828    ast_cli(a->fd, "  Notify hold state:      %s\n", AST_CLI_YESNO(sip_cfg.notifyhold));
20829    ast_cli(a->fd, "  SIP Transfer mode:      %s\n", transfermode2str(sip_cfg.allowtransfer));
20830    ast_cli(a->fd, "  Max Call Bitrate:       %d kbps\n", default_maxcallbitrate);
20831    ast_cli(a->fd, "  Auto-Framing:           %s\n", AST_CLI_YESNO(global_autoframing));
20832    ast_cli(a->fd, "  Outb. proxy:            %s %s\n", ast_strlen_zero(sip_cfg.outboundproxy.name) ? "<not set>" : sip_cfg.outboundproxy.name,
20833                      sip_cfg.outboundproxy.force ? "(forced)" : "");
20834    ast_cli(a->fd, "  Session Timers:         %s\n", stmode2str(global_st_mode));
20835    ast_cli(a->fd, "  Session Refresher:      %s\n", strefresherparam2str(global_st_refresher));
20836    ast_cli(a->fd, "  Session Expires:        %d secs\n", global_max_se);
20837    ast_cli(a->fd, "  Session Min-SE:         %d secs\n", global_min_se);
20838    ast_cli(a->fd, "  Timer T1:               %d\n", global_t1);
20839    ast_cli(a->fd, "  Timer T1 minimum:       %d\n", global_t1min);
20840    ast_cli(a->fd, "  Timer B:                %d\n", global_timer_b);
20841    ast_cli(a->fd, "  No premature media:     %s\n", AST_CLI_YESNO(global_prematuremediafilter));
20842    ast_cli(a->fd, "  Max forwards:           %d\n", sip_cfg.default_max_forwards);
20843 
20844    ast_cli(a->fd, "\nDefault Settings:\n");
20845    ast_cli(a->fd, "-----------------\n");
20846    ast_cli(a->fd, "  Allowed transports:     %s\n", get_transport_list(default_transports));
20847    ast_cli(a->fd, "  Outbound transport:    %s\n", sip_get_transport(default_primary_transport));
20848    ast_cli(a->fd, "  Context:                %s\n", sip_cfg.default_context);
20849    ast_cli(a->fd, "  Record on feature:      %s\n", sip_cfg.default_record_on_feature);
20850    ast_cli(a->fd, "  Record off feature:     %s\n", sip_cfg.default_record_off_feature);
20851    ast_cli(a->fd, "  Force rport:            %s\n", force_rport_string(global_flags));
20852    ast_cli(a->fd, "  DTMF:                   %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
20853    ast_cli(a->fd, "  Qualify:                %d\n", default_qualify);
20854    ast_cli(a->fd, "  Keepalive:              %d\n", default_keepalive);
20855    ast_cli(a->fd, "  Use ClientCode:         %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_USECLIENTCODE)));
20856    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)));
20857    ast_cli(a->fd, "  Language:               %s\n", default_language);
20858    ast_cli(a->fd, "  Tone zone:              %s\n", default_zone[0] != '\0' ? default_zone : "<Not set>");
20859    ast_cli(a->fd, "  MOH Interpret:          %s\n", default_mohinterpret);
20860    ast_cli(a->fd, "  MOH Suggest:            %s\n", default_mohsuggest);
20861    ast_cli(a->fd, "  Voice Mail Extension:   %s\n", default_vmexten);
20862 
20863    
20864    if (realtimepeers || realtimeregs) {
20865       ast_cli(a->fd, "\nRealtime SIP Settings:\n");
20866       ast_cli(a->fd, "----------------------\n");
20867       ast_cli(a->fd, "  Realtime Peers:         %s\n", AST_CLI_YESNO(realtimepeers));
20868       ast_cli(a->fd, "  Realtime Regs:          %s\n", AST_CLI_YESNO(realtimeregs));
20869       ast_cli(a->fd, "  Cache Friends:          %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)));
20870       ast_cli(a->fd, "  Update:                 %s\n", AST_CLI_YESNO(sip_cfg.peer_rtupdate));
20871       ast_cli(a->fd, "  Ignore Reg. Expire:     %s\n", AST_CLI_YESNO(sip_cfg.ignore_regexpire));
20872       ast_cli(a->fd, "  Save sys. name:         %s\n", AST_CLI_YESNO(sip_cfg.rtsave_sysname));
20873       ast_cli(a->fd, "  Auto Clear:             %d (%s)\n", sip_cfg.rtautoclear, ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR) ? "Enabled" : "Disabled");
20874    }
20875    ast_cli(a->fd, "\n----\n");
20876    return CLI_SUCCESS;
20877 }
20878 
20879 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
20880 {
20881 #define FORMAT  "%-30.30s  %-12.12s  %-10.10s  %-10.10s\n"
20882    char host[80];
20883    
20884    switch (cmd) {
20885    case CLI_INIT:
20886       e->command = "sip show mwi";
20887       e->usage =
20888          "Usage: sip show mwi\n"
20889          "       Provides a list of MWI subscriptions and status.\n";
20890       return NULL;
20891    case CLI_GENERATE:
20892       return NULL;
20893    }
20894    
20895    ast_cli(a->fd, FORMAT, "Host", "Username", "Mailbox", "Subscribed");
20896    
20897    ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
20898       ASTOBJ_RDLOCK(iterator);
20899       snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
20900       ast_cli(a->fd, FORMAT, host, iterator->username, iterator->mailbox, AST_CLI_YESNO(iterator->subscribed));
20901       ASTOBJ_UNLOCK(iterator);
20902    } while(0));
20903 
20904    return CLI_SUCCESS;
20905 #undef FORMAT
20906 }
20907 
20908 
20909 /*! \brief Show subscription type in string format */
20910 static const char *subscription_type2str(enum subscriptiontype subtype)
20911 {
20912    int i;
20913 
20914    for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
20915       if (subscription_types[i].type == subtype) {
20916          return subscription_types[i].text;
20917       }
20918    }
20919    return subscription_types[0].text;
20920 }
20921 
20922 /*! \brief Find subscription type in array */
20923 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
20924 {
20925    int i;
20926 
20927    for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
20928       if (subscription_types[i].type == subtype) {
20929          return &subscription_types[i];
20930       }
20931    }
20932    return &subscription_types[0];
20933 }
20934 
20935 /*
20936  * We try to structure all functions that loop on data structures as
20937  * a handler for individual entries, and a mainloop that iterates
20938  * on the main data structure. This way, moving the code to containers
20939  * that support iteration through callbacks will be a lot easier.
20940  */
20941 
20942 #define FORMAT4 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-13.13s  %-15.15s %-10.10s %-6.6d\n"
20943 #define FORMAT3 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-13.13s  %-15.15s %-10.10s %-6.6s\n"
20944 #define FORMAT2 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-7.7s  %-15.15s %-10.10s %-10.10s\n"
20945 #define FORMAT  "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-3.3s %-3.3s  %-15.15s %-10.10s %-10.10s\n"
20946 
20947 /*! \brief callback for show channel|subscription */
20948 static int show_channels_cb(void *__cur, void *__arg, int flags)
20949 {
20950    struct sip_pvt *cur = __cur;
20951    struct __show_chan_arg *arg = __arg;
20952    const struct ast_sockaddr *dst;
20953 
20954    sip_pvt_lock(cur);
20955    dst = sip_real_dst(cur);
20956 
20957    /* XXX indentation preserved to reduce diff. Will be fixed later */
20958    if (cur->subscribed == NONE && !arg->subscriptions) {
20959       /* set if SIP transfer in progress */
20960       const char *referstatus = cur->refer ? referstatus2str(cur->refer->status) : "";
20961       char formatbuf[SIPBUFSIZE/2];
20962       
20963       ast_cli(arg->fd, FORMAT, ast_sockaddr_stringify_addr(dst),
20964             S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
20965             cur->callid,
20966             cur->owner ? ast_getformatname_multiple(formatbuf, sizeof(formatbuf), ast_channel_nativeformats(cur->owner)) : "(nothing)",
20967             AST_CLI_YESNO(ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD)),
20968             cur->needdestroy ? "(d)" : "",
20969             cur->lastmsg ,
20970             referstatus,
20971             cur->relatedpeer ? cur->relatedpeer->name : "<guest>"
20972          );
20973       arg->numchans++;
20974    }
20975    if (cur->subscribed != NONE && arg->subscriptions) {
20976       struct ast_str *mailbox_str = ast_str_alloca(512);
20977       if (cur->subscribed == MWI_NOTIFICATION && cur->relatedpeer)
20978          peer_mailboxes_to_str(&mailbox_str, cur->relatedpeer);
20979       ast_cli(arg->fd, FORMAT4, ast_sockaddr_stringify_addr(dst),
20980             S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
20981                cur->callid,
20982             /* the 'complete' exten/context is hidden in the refer_to field for subscriptions */
20983             cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
20984             cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate),
20985             subscription_type2str(cur->subscribed),
20986             cur->subscribed == MWI_NOTIFICATION ? S_OR(ast_str_buffer(mailbox_str), "<none>") : "<none>",
20987             cur->expiry
20988          );
20989       arg->numchans++;
20990    }
20991    sip_pvt_unlock(cur);
20992    return 0;   /* don't care, we scan all channels */
20993 }
20994 
20995 /*! \brief CLI for show channels or subscriptions.
20996  * This is a new-style CLI handler so a single function contains
20997  * the prototype for the function, the 'generator' to produce multiple
20998  * entries in case it is required, and the actual handler for the command.
20999  */
21000 static char *sip_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
21001 {
21002    struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
21003 
21004 
21005    if (cmd == CLI_INIT) {
21006       e->command = "sip show {channels|subscriptions}";
21007       e->usage =
21008          "Usage: sip show channels\n"
21009          "       Lists all currently active SIP calls (dialogs).\n"
21010          "Usage: sip show subscriptions\n"
21011          "       Lists active SIP subscriptions.\n";
21012       return NULL;
21013    } else if (cmd == CLI_GENERATE)
21014       return NULL;
21015 
21016    if (a->argc != e->args)
21017       return CLI_SHOWUSAGE;
21018    arg.subscriptions = !strcasecmp(a->argv[e->args - 1], "subscriptions");
21019    if (!arg.subscriptions)
21020       ast_cli(arg.fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Format", "Hold", "Last Message", "Expiry", "Peer");
21021    else
21022       ast_cli(arg.fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox", "Expiry");
21023 
21024    /* iterate on the container and invoke the callback on each item */
21025    ao2_t_callback(dialogs, OBJ_NODATA, show_channels_cb, &arg, "callback to show channels");
21026    
21027    /* print summary information */
21028    ast_cli(arg.fd, "%d active SIP %s%s\n", arg.numchans,
21029       (arg.subscriptions ? "subscription" : "dialog"),
21030       ESS(arg.numchans));  /* ESS(n) returns an "s" if n>1 */
21031    return CLI_SUCCESS;
21032 #undef FORMAT
21033 #undef FORMAT2
21034 #undef FORMAT3
21035 }
21036 
21037 /*! \brief Support routine for 'sip show channel' and 'sip show history' CLI
21038  * This is in charge of generating all strings that match a prefix in the
21039  * given position. As many functions of this kind, each invokation has
21040  * O(state) time complexity so be careful in using it.
21041  */
21042 static char *complete_sipch(const char *line, const char *word, int pos, int state)
21043 {
21044    int which=0;
21045    struct sip_pvt *cur;
21046    char *c = NULL;
21047    int wordlen = strlen(word);
21048    struct ao2_iterator i;
21049 
21050    if (pos != 3) {
21051       return NULL;
21052    }
21053 
21054    i = ao2_iterator_init(dialogs, 0);
21055    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
21056       sip_pvt_lock(cur);
21057       if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
21058          c = ast_strdup(cur->callid);
21059          sip_pvt_unlock(cur);
21060          dialog_unref(cur, "drop ref in iterator loop break");
21061          break;
21062       }
21063       sip_pvt_unlock(cur);
21064       dialog_unref(cur, "drop ref in iterator loop");
21065    }
21066    ao2_iterator_destroy(&i);
21067    return c;
21068 }
21069 
21070 
21071 /*! \brief Do completion on peer name */
21072 static char *complete_sip_peer(const char *word, int state, int flags2)
21073 {
21074    char *result = NULL;
21075    int wordlen = strlen(word);
21076    int which = 0;
21077    struct ao2_iterator i = ao2_iterator_init(peers, 0);
21078    struct sip_peer *peer;
21079 
21080    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
21081       /* locking of the object is not required because only the name and flags are being compared */
21082       if (!strncasecmp(word, peer->name, wordlen) &&
21083             (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
21084             ++which > state)
21085          result = ast_strdup(peer->name);
21086       sip_unref_peer(peer, "toss iterator peer ptr before break");
21087       if (result) {
21088          break;
21089       }
21090    }
21091    ao2_iterator_destroy(&i);
21092    return result;
21093 }
21094 
21095 /*! \brief Do completion on registered peer name */
21096 static char *complete_sip_registered_peer(const char *word, int state, int flags2)
21097 {
21098        char *result = NULL;
21099        int wordlen = strlen(word);
21100        int which = 0;
21101        struct ao2_iterator i;
21102        struct sip_peer *peer;
21103        
21104        i = ao2_iterator_init(peers, 0);
21105        while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
21106           if (!strncasecmp(word, peer->name, wordlen) &&
21107          (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
21108          ++which > state && peer->expire > 0)
21109              result = ast_strdup(peer->name);
21110           if (result) {
21111              sip_unref_peer(peer, "toss iterator peer ptr before break");
21112              break;
21113           }
21114           sip_unref_peer(peer, "toss iterator peer ptr");
21115        }
21116        ao2_iterator_destroy(&i);
21117        return result;
21118 }
21119 
21120 /*! \brief Support routine for 'sip show history' CLI */
21121 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state)
21122 {
21123    if (pos == 3)
21124       return complete_sipch(line, word, pos, state);
21125 
21126    return NULL;
21127 }
21128 
21129 /*! \brief Support routine for 'sip show peer' CLI */
21130 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
21131 {
21132    if (pos == 3) {
21133       return complete_sip_peer(word, state, 0);
21134    }
21135 
21136    return NULL;
21137 }
21138 
21139 /*! \brief Support routine for 'sip unregister' CLI */
21140 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state)
21141 {
21142        if (pos == 2)
21143                return complete_sip_registered_peer(word, state, 0);
21144 
21145        return NULL;
21146 }
21147 
21148 /*! \brief Support routine for 'sip notify' CLI */
21149 static char *complete_sip_notify(const char *line, const char *word, int pos, int state)
21150 {
21151    char *c = NULL;
21152 
21153    if (pos == 2) {
21154       int which = 0;
21155       char *cat = NULL;
21156       int wordlen = strlen(word);
21157 
21158       /* do completion for notify type */
21159 
21160       if (!notify_types)
21161          return NULL;
21162       
21163       while ( (cat = ast_category_browse(notify_types, cat)) ) {
21164          if (!strncasecmp(word, cat, wordlen) && ++which > state) {
21165             c = ast_strdup(cat);
21166             break;
21167          }
21168       }
21169       return c;
21170    }
21171 
21172    if (pos > 2)
21173       return complete_sip_peer(word, state, 0);
21174 
21175    return NULL;
21176 }
21177 
21178 /*! \brief Show details of one active dialog */
21179 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
21180 {
21181    struct sip_pvt *cur;
21182    size_t len;
21183    int found = 0;
21184    struct ao2_iterator i;
21185 
21186    switch (cmd) {
21187    case CLI_INIT:
21188       e->command = "sip show channel";
21189       e->usage =
21190          "Usage: sip show channel <call-id>\n"
21191          "       Provides detailed status on a given SIP dialog (identified by SIP call-id).\n";
21192       return NULL;
21193    case CLI_GENERATE:
21194       return complete_sipch(a->line, a->word, a->pos, a->n);
21195    }
21196 
21197    if (a->argc != 4)
21198       return CLI_SHOWUSAGE;
21199    len = strlen(a->argv[3]);
21200    
21201    i = ao2_iterator_init(dialogs, 0);
21202    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
21203       sip_pvt_lock(cur);
21204 
21205       if (!strncasecmp(cur->callid, a->argv[3], len)) {
21206          char formatbuf[SIPBUFSIZE/2];
21207          ast_cli(a->fd, "\n");
21208          if (cur->subscribed != NONE) {
21209             ast_cli(a->fd, "  * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
21210          } else {
21211             ast_cli(a->fd, "  * SIP Call\n");
21212          }
21213          ast_cli(a->fd, "  Curr. trans. direction:  %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
21214          ast_cli(a->fd, "  Call-ID:                %s\n", cur->callid);
21215          ast_cli(a->fd, "  Owner channel ID:       %s\n", cur->owner ? ast_channel_name(cur->owner) : "<none>");
21216          ast_cli(a->fd, "  Our Codec Capability:   %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->caps));
21217          ast_cli(a->fd, "  Non-Codec Capability (DTMF):   %d\n", cur->noncodeccapability);
21218          ast_cli(a->fd, "  Their Codec Capability:   %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->peercaps));
21219          ast_cli(a->fd, "  Joint Codec Capability:   %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->jointcaps));
21220          ast_cli(a->fd, "  Format:                 %s\n", cur->owner ? ast_getformatname_multiple(formatbuf, sizeof(formatbuf), ast_channel_nativeformats(cur->owner)) : "(nothing)" );
21221          ast_cli(a->fd, "  T.38 support            %s\n", AST_CLI_YESNO(cur->udptl != NULL));
21222          ast_cli(a->fd, "  Video support           %s\n", AST_CLI_YESNO(cur->vrtp != NULL));
21223          ast_cli(a->fd, "  MaxCallBR:              %d kbps\n", cur->maxcallbitrate);
21224          ast_cli(a->fd, "  Theoretical Address:    %s\n", ast_sockaddr_stringify(&cur->sa));
21225          ast_cli(a->fd, "  Received Address:       %s\n", ast_sockaddr_stringify(&cur->recv));
21226          ast_cli(a->fd, "  SIP Transfer mode:      %s\n", transfermode2str(cur->allowtransfer));
21227          ast_cli(a->fd, "  Force rport:            %s\n", force_rport_string(cur->flags));
21228          if (ast_sockaddr_isnull(&cur->redirip)) {
21229             ast_cli(a->fd,
21230                "  Audio IP:               %s (local)\n",
21231                ast_sockaddr_stringify_addr(&cur->ourip));
21232          } else {
21233             ast_cli(a->fd,
21234                "  Audio IP:               %s (Outside bridge)\n",
21235                ast_sockaddr_stringify_addr(&cur->redirip));
21236          }
21237          ast_cli(a->fd, "  Our Tag:                %s\n", cur->tag);
21238          ast_cli(a->fd, "  Their Tag:              %s\n", cur->theirtag);
21239          ast_cli(a->fd, "  SIP User agent:         %s\n", cur->useragent);
21240          if (!ast_strlen_zero(cur->username)) {
21241             ast_cli(a->fd, "  Username:               %s\n", cur->username);
21242          }
21243          if (!ast_strlen_zero(cur->peername)) {
21244             ast_cli(a->fd, "  Peername:               %s\n", cur->peername);
21245          }
21246          if (!ast_strlen_zero(cur->uri)) {
21247             ast_cli(a->fd, "  Original uri:           %s\n", cur->uri);
21248          }
21249          if (!ast_strlen_zero(cur->cid_num)) {
21250             ast_cli(a->fd, "  Caller-ID:              %s\n", cur->cid_num);
21251          }
21252          ast_cli(a->fd, "  Need Destroy:           %s\n", AST_CLI_YESNO(cur->needdestroy));
21253          ast_cli(a->fd, "  Last Message:           %s\n", cur->lastmsg);
21254          ast_cli(a->fd, "  Promiscuous Redir:      %s\n", AST_CLI_YESNO(ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR)));
21255          ast_cli(a->fd, "  Route:                  ");
21256          if (cur->route) {
21257             struct sip_route *route;
21258             int first = 1;
21259 
21260             for (route = cur->route; route; route = route->next) {
21261                ast_cli(a->fd, "%s<%s>", first ? "" : ", ", route->hop);
21262                first = 0;
21263             }
21264             ast_cli(a->fd, "\n");
21265          } else {
21266             ast_cli(a->fd, "N/A\n");
21267          }
21268          ast_cli(a->fd, "  DTMF Mode:              %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
21269          ast_cli(a->fd, "  SIP Options:            ");
21270          if (cur->sipoptions) {
21271             int x;
21272             for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
21273                if (cur->sipoptions & sip_options[x].id)
21274                   ast_cli(a->fd, "%s ", sip_options[x].text);
21275             }
21276             ast_cli(a->fd, "\n");
21277          } else {
21278             ast_cli(a->fd, "(none)\n");
21279          }
21280 
21281          if (!cur->stimer) {
21282             ast_cli(a->fd, "  Session-Timer:          Uninitiallized\n");
21283          } else {
21284             ast_cli(a->fd, "  Session-Timer:          %s\n", cur->stimer->st_active ? "Active" : "Inactive");
21285             if (cur->stimer->st_active == TRUE) {
21286                ast_cli(a->fd, "  S-Timer Interval:       %d\n", cur->stimer->st_interval);
21287                ast_cli(a->fd, "  S-Timer Refresher:      %s\n", strefresher2str(cur->stimer->st_ref));
21288                ast_cli(a->fd, "  S-Timer Sched Id:       %d\n", cur->stimer->st_schedid);
21289                ast_cli(a->fd, "  S-Timer Peer Sts:       %s\n", cur->stimer->st_active_peer_ua ? "Active" : "Inactive");
21290                ast_cli(a->fd, "  S-Timer Cached Min-SE:  %d\n", cur->stimer->st_cached_min_se);
21291                ast_cli(a->fd, "  S-Timer Cached SE:      %d\n", cur->stimer->st_cached_max_se);
21292                ast_cli(a->fd, "  S-Timer Cached Ref:     %s\n", strefresherparam2str(cur->stimer->st_cached_ref));
21293                ast_cli(a->fd, "  S-Timer Cached Mode:    %s\n", stmode2str(cur->stimer->st_cached_mode));
21294             }
21295          }
21296 
21297          ast_cli(a->fd, "\n\n");
21298 
21299          found++;
21300       }
21301 
21302       sip_pvt_unlock(cur);
21303 
21304       ao2_t_ref(cur, -1, "toss dialog ptr set by iterator_next");
21305    }
21306    ao2_iterator_destroy(&i);
21307 
21308    if (!found) {
21309       ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
21310    }
21311 
21312    return CLI_SUCCESS;
21313 }
21314 
21315 /*! \brief Show history details of one dialog */
21316 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
21317 {
21318    struct sip_pvt *cur;
21319    size_t len;
21320    int found = 0;
21321    struct ao2_iterator i;
21322 
21323    switch (cmd) {
21324    case CLI_INIT:
21325       e->command = "sip show history";
21326       e->usage =
21327          "Usage: sip show history <call-id>\n"
21328          "       Provides detailed dialog history on a given SIP call (specified by call-id).\n";
21329       return NULL;
21330    case CLI_GENERATE:
21331       return complete_sip_show_history(a->line, a->word, a->pos, a->n);
21332    }
21333 
21334    if (a->argc != 4) {
21335       return CLI_SHOWUSAGE;
21336    }
21337 
21338    if (!recordhistory) {
21339       ast_cli(a->fd, "\n***Note: History recording is currently DISABLED.  Use 'sip set history on' to ENABLE.\n");
21340    }
21341 
21342    len = strlen(a->argv[3]);
21343 
21344    i = ao2_iterator_init(dialogs, 0);
21345    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
21346       sip_pvt_lock(cur);
21347       if (!strncasecmp(cur->callid, a->argv[3], len)) {
21348          struct sip_history *hist;
21349          int x = 0;
21350 
21351          ast_cli(a->fd, "\n");
21352          if (cur->subscribed != NONE) {
21353             ast_cli(a->fd, "  * Subscription\n");
21354          } else {
21355             ast_cli(a->fd, "  * SIP Call\n");
21356          }
21357          if (cur->history) {
21358             AST_LIST_TRAVERSE(cur->history, hist, list)
21359                ast_cli(a->fd, "%d. %s\n", ++x, hist->event);
21360          }
21361          if (x == 0) {
21362             ast_cli(a->fd, "Call '%s' has no history\n", cur->callid);
21363          }
21364          found++;
21365       }
21366       sip_pvt_unlock(cur);
21367       ao2_t_ref(cur, -1, "toss dialog ptr from iterator_next");
21368    }
21369    ao2_iterator_destroy(&i);
21370 
21371    if (!found) {
21372       ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
21373    }
21374 
21375    return CLI_SUCCESS;
21376 }
21377 
21378 /*! \brief Dump SIP history to debug log file at end of lifespan for SIP dialog */
21379 static void sip_dump_history(struct sip_pvt *dialog)
21380 {
21381    int x = 0;
21382    struct sip_history *hist;
21383    static int errmsg = 0;
21384 
21385    if (!dialog) {
21386       return;
21387    }
21388 
21389    if (!option_debug && !sipdebug) {
21390       if (!errmsg) {
21391          ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
21392          errmsg = 1;
21393       }
21394       return;
21395    }
21396 
21397    ast_debug(1, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
21398    if (dialog->subscribed) {
21399       ast_debug(1, "  * Subscription\n");
21400    } else {
21401       ast_debug(1, "  * SIP Call\n");
21402    }
21403    if (dialog->history) {
21404       AST_LIST_TRAVERSE(dialog->history, hist, list)
21405          ast_debug(1, "  %-3.3d. %s\n", ++x, hist->event);
21406    }
21407    if (!x) {
21408       ast_debug(1, "Call '%s' has no history\n", dialog->callid);
21409    }
21410    ast_debug(1, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
21411 }
21412 
21413 
21414 /*! \brief  Receive SIP INFO Message */
21415 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
21416 {
21417    const char *buf = "";
21418    unsigned int event;
21419    const char *c = sip_get_header(req, "Content-Type");
21420 
21421    /* Need to check the media/type */
21422    if (!strcasecmp(c, "application/dtmf-relay") ||
21423        !strcasecmp(c, "application/vnd.nortelnetworks.digits") ||
21424        !strcasecmp(c, "application/dtmf")) {
21425       unsigned int duration = 0;
21426 
21427       if (!p->owner) {  /* not a PBX call */
21428          transmit_response(p, "481 Call leg/transaction does not exist", req);
21429          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21430          return;
21431       }
21432 
21433       /* If dtmf-relay or vnd.nortelnetworks.digits, parse the signal and duration;
21434        * otherwise use the body as the signal */
21435       if (strcasecmp(c, "application/dtmf")) {
21436          const char *tmp;
21437 
21438          if (ast_strlen_zero(buf = get_content_line(req, "Signal", '='))
21439             && ast_strlen_zero(buf = get_content_line(req, "d", '='))) {
21440             ast_log(LOG_WARNING, "Unable to retrieve DTMF signal for INFO message on "
21441                   "call %s\n", p->callid);
21442             transmit_response(p, "200 OK", req);
21443             return;
21444          }
21445          if (!ast_strlen_zero((tmp = get_content_line(req, "Duration", '=')))) {
21446             sscanf(tmp, "%30u", &duration);
21447          }
21448       } else {
21449          /* Type is application/dtmf, simply use what's in the message body */
21450          buf = get_content(req);
21451       }
21452 
21453       /* An empty message body requires us to send a 200 OK */
21454       if (ast_strlen_zero(buf)) {
21455          transmit_response(p, "200 OK", req);
21456          return;
21457       }
21458 
21459       if (!duration) {
21460          duration = 100; /* 100 ms */
21461       }
21462 
21463       if (buf[0] == '*') {
21464          event = 10;
21465       } else if (buf[0] == '#') {
21466          event = 11;
21467       } else if (buf[0] == '!') {
21468          event = 16;
21469       } else if ('A' <= buf[0] && buf[0] <= 'D') {
21470          event = 12 + buf[0] - 'A';
21471       } else if ('a' <= buf[0] && buf[0] <= 'd') {
21472          event = 12 + buf[0] - 'a';
21473       } else if ((sscanf(buf, "%30u", &event) != 1) || event > 16) {
21474          ast_log(AST_LOG_WARNING, "Unable to convert DTMF event signal code to a valid "
21475                "value for INFO message on call %s\n", p->callid);
21476          transmit_response(p, "200 OK", req);
21477          return;
21478       }
21479 
21480       if (event == 16) {
21481          /* send a FLASH event */
21482          struct ast_frame f = { AST_FRAME_CONTROL, { AST_CONTROL_FLASH, } };
21483          ast_queue_frame(p->owner, &f);
21484          if (sipdebug) {
21485             ast_verbose("* DTMF-relay event received: FLASH\n");
21486          }
21487       } else {
21488          /* send a DTMF event */
21489          struct ast_frame f = { AST_FRAME_DTMF, };
21490          if (event < 10) {
21491             f.subclass.integer = '0' + event;
21492          } else if (event == 10) {
21493             f.subclass.integer = '*';
21494          } else if (event == 11) {
21495             f.subclass.integer = '#';
21496          } else {
21497             f.subclass.integer = 'A' + (event - 12);
21498          }
21499          f.len = duration;
21500          ast_queue_frame(p->owner, &f);
21501          if (sipdebug) {
21502             ast_verbose("* DTMF-relay event received: %c\n", (int) f.subclass.integer);
21503          }
21504       }
21505       transmit_response(p, "200 OK", req);
21506       return;
21507    } else if (!strcasecmp(c, "application/media_control+xml")) {
21508       /* Eh, we'll just assume it's a fast picture update for now */
21509       if (p->owner) {
21510          ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
21511       }
21512       transmit_response(p, "200 OK", req);
21513       return;
21514    } else if (!ast_strlen_zero(c = sip_get_header(req, "X-ClientCode"))) {
21515       /* Client code (from SNOM phone) */
21516       if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
21517          if (p->owner && ast_channel_cdr(p->owner)) {
21518             ast_cdr_setuserfield(p->owner, c);
21519          }
21520          if (p->owner && ast_bridged_channel(p->owner) && ast_channel_cdr(ast_bridged_channel(p->owner))) {
21521             ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
21522          }
21523          transmit_response(p, "200 OK", req);
21524       } else {
21525          transmit_response(p, "403 Forbidden", req);
21526       }
21527       return;
21528    } else if (!ast_strlen_zero(c = sip_get_header(req, "Record"))) {
21529       /* INFO messages generated by some phones to start/stop recording
21530        * on phone calls.
21531        */
21532 
21533       struct ast_call_feature *feat = NULL;
21534       int j;
21535       struct ast_frame f = { AST_FRAME_DTMF, };
21536       int suppress_warning = 0; /* Supress warning if the feature is blank */
21537 
21538       if (!p->owner) {        /* not a PBX call */
21539          transmit_response(p, "481 Call leg/transaction does not exist", req);
21540          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21541          return;
21542       }
21543 
21544       /* first, get the feature string, if it exists */
21545       ast_rdlock_call_features();
21546       if (p->relatedpeer) {
21547          if (!strcasecmp(c, "on")) {
21548             if (ast_strlen_zero(p->relatedpeer->record_on_feature)) {
21549                suppress_warning = 1;
21550             } else {
21551                feat = ast_find_call_feature(p->relatedpeer->record_on_feature);
21552             }
21553          } else if (!strcasecmp(c, "off")) {
21554             if (ast_strlen_zero(p->relatedpeer->record_off_feature)) {
21555                suppress_warning = 1;
21556             } else {
21557                feat = ast_find_call_feature(p->relatedpeer->record_off_feature);
21558             }
21559          } else {
21560             ast_log(LOG_ERROR, "Received INFO requesting to record with invalid value: %s\n", c);
21561          }
21562       }
21563       if (!feat || ast_strlen_zero(feat->exten)) {
21564          if (!suppress_warning) {
21565             ast_log(LOG_WARNING, "Recording requested, but no One Touch Monitor registered. (See features.conf)\n");
21566          }
21567          /* 403 means that we don't support this feature, so don't request it again */
21568          transmit_response(p, "403 Forbidden", req);
21569          ast_unlock_call_features();
21570          return;
21571       }
21572       /* Send the feature code to the PBX as DTMF, just like the handset had sent it */
21573       f.len = 100;
21574       for (j=0; j < strlen(feat->exten); j++) {
21575          f.subclass.integer = feat->exten[j];
21576          ast_queue_frame(p->owner, &f);
21577          if (sipdebug) {
21578             ast_verbose("* DTMF-relay event faked: %c\n", f.subclass.integer);
21579          }
21580       }
21581       ast_unlock_call_features();
21582 
21583       ast_debug(1, "Got a Request to Record the channel, state %s\n", c);
21584       transmit_response(p, "200 OK", req);
21585       return;
21586    } else if (ast_strlen_zero(c = sip_get_header(req, "Content-Length")) || !strcasecmp(c, "0")) {
21587       /* This is probably just a packet making sure the signalling is still up, just send back a 200 OK */
21588       transmit_response(p, "200 OK", req);
21589       return;
21590    }
21591 
21592    /* Other type of INFO message, not really understood by Asterisk */
21593 
21594    ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
21595    transmit_response(p, "415 Unsupported media type", req);
21596    return;
21597 }
21598 
21599 /*! \brief Enable SIP Debugging for a single IP */
21600 static char *sip_do_debug_ip(int fd, const char *arg)
21601 {
21602    if (ast_sockaddr_resolve_first_af(&debugaddr, arg, 0, 0)) {
21603       return CLI_SHOWUSAGE;
21604    }
21605 
21606    ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_sockaddr_stringify_addr(&debugaddr));
21607    sipdebug |= sip_debug_console;
21608 
21609    return CLI_SUCCESS;
21610 }
21611 
21612 /*! \brief  Turn on SIP debugging for a given peer */
21613 static char *sip_do_debug_peer(int fd, const char *arg)
21614 {
21615    struct sip_peer *peer = sip_find_peer(arg, NULL, TRUE, FINDPEERS, FALSE, 0);
21616    if (!peer) {
21617       ast_cli(fd, "No such peer '%s'\n", arg);
21618    } else if (ast_sockaddr_isnull(&peer->addr)) {
21619       ast_cli(fd, "Unable to get IP address of peer '%s'\n", arg);
21620    } else {
21621       ast_sockaddr_copy(&debugaddr, &peer->addr);
21622       ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_sockaddr_stringify_addr(&debugaddr));
21623       sipdebug |= sip_debug_console;
21624    }
21625    if (peer) {
21626       sip_unref_peer(peer, "sip_do_debug_peer: sip_unref_peer, from sip_find_peer call");
21627    }
21628    return CLI_SUCCESS;
21629 }
21630 
21631 /*! \brief Turn on SIP debugging (CLI command) */
21632 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
21633 {
21634    int oldsipdebug = sipdebug & sip_debug_console;
21635    const char *what;
21636 
21637    if (cmd == CLI_INIT) {
21638       e->command = "sip set debug {on|off|ip|peer}";
21639       e->usage =
21640          "Usage: sip set debug {off|on|ip addr[:port]|peer peername}\n"
21641          "       Globally disables dumping of SIP packets,\n"
21642          "       or enables it either globally or for a (single)\n"
21643          "       IP address or registered peer.\n";
21644       return NULL;
21645    } else if (cmd == CLI_GENERATE) {
21646       if (a->pos == 4 && !strcasecmp(a->argv[3], "peer"))
21647          return complete_sip_peer(a->word, a->n, 0);
21648       return NULL;
21649         }
21650 
21651    what = a->argv[e->args-1];      /* guaranteed to exist */
21652    if (a->argc == e->args) {       /* on/off */
21653       if (!strcasecmp(what, "on")) {
21654          sipdebug |= sip_debug_console;
21655          sipdebug_text = 1;   /*! \note this can be a special debug command - "sip debug text" or something */
21656          memset(&debugaddr, 0, sizeof(debugaddr));
21657          ast_cli(a->fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
21658          return CLI_SUCCESS;
21659       } else if (!strcasecmp(what, "off")) {
21660          sipdebug &= ~sip_debug_console;
21661          sipdebug_text = 0;
21662          ast_cli(a->fd, "SIP Debugging Disabled\n");
21663          return CLI_SUCCESS;
21664       }
21665    } else if (a->argc == e->args +1) {/* ip/peer */
21666       if (!strcasecmp(what, "ip"))
21667          return sip_do_debug_ip(a->fd, a->argv[e->args]);
21668       else if (!strcasecmp(what, "peer"))
21669          return sip_do_debug_peer(a->fd, a->argv[e->args]);
21670    }
21671    return CLI_SHOWUSAGE;   /* default, failure */
21672 }
21673 
21674 /*! \brief Cli command to send SIP notify to peer */
21675 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
21676 {
21677    struct ast_variable *varlist;
21678    int i;
21679 
21680    switch (cmd) {
21681    case CLI_INIT:
21682       e->command = "sip notify";
21683       e->usage =
21684          "Usage: sip notify <type> <peer> [<peer>...]\n"
21685          "       Send a NOTIFY message to a SIP peer or peers\n"
21686          "       Message types are defined in sip_notify.conf\n";
21687       return NULL;
21688    case CLI_GENERATE:
21689       return complete_sip_notify(a->line, a->word, a->pos, a->n);
21690    }
21691 
21692    if (a->argc < 4)
21693       return CLI_SHOWUSAGE;
21694 
21695    if (!notify_types) {
21696       ast_cli(a->fd, "No %s file found, or no types listed there\n", notify_config);
21697       return CLI_FAILURE;
21698    }
21699 
21700    varlist = ast_variable_browse(notify_types, a->argv[2]);
21701 
21702    if (!varlist) {
21703       ast_cli(a->fd, "Unable to find notify type '%s'\n", a->argv[2]);
21704       return CLI_FAILURE;
21705    }
21706 
21707    for (i = 3; i < a->argc; i++) {
21708       struct sip_pvt *p;
21709       char buf[512];
21710       struct ast_variable *header, *var;
21711 
21712       if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL, NULL))) {
21713          ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
21714          return CLI_FAILURE;
21715       }
21716 
21717       if (create_addr(p, a->argv[i], NULL, 1)) {
21718          /* Maybe they're not registered, etc. */
21719          dialog_unlink_all(p);
21720          dialog_unref(p, "unref dialog inside for loop" );
21721          /* sip_destroy(p); */
21722          ast_cli(a->fd, "Could not create address for '%s'\n", a->argv[i]);
21723          continue;
21724       }
21725 
21726       /* Notify is outgoing call */
21727       ast_set_flag(&p->flags[0], SIP_OUTGOING);
21728       sip_notify_alloc(p);
21729       p->notify->headers = header = ast_variable_new("Subscription-State", "terminated", "");
21730 
21731       for (var = varlist; var; var = var->next) {
21732          ast_copy_string(buf, var->value, sizeof(buf));
21733          ast_unescape_semicolon(buf);
21734 
21735          if (!strcasecmp(var->name, "Content")) {
21736             if (ast_str_strlen(p->notify->content))
21737                ast_str_append(&p->notify->content, 0, "\r\n");
21738             ast_str_append(&p->notify->content, 0, "%s", buf);
21739          } else if (!strcasecmp(var->name, "Content-Length")) {
21740             ast_log(LOG_WARNING, "it is not necessary to specify Content-Length in sip_notify.conf, ignoring\n");
21741          } else {
21742             header->next = ast_variable_new(var->name, buf, "");
21743             header = header->next;
21744          }
21745       }
21746 
21747       /* Now that we have the peer's address, set our ip and change callid */
21748       ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
21749       build_via(p);
21750 
21751       change_callid_pvt(p, NULL);
21752 
21753       ast_cli(a->fd, "Sending NOTIFY of type '%s' to '%s'\n", a->argv[2], a->argv[i]);
21754       sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
21755       transmit_invite(p, SIP_NOTIFY, 0, 2, NULL);
21756       dialog_unref(p, "bump down the count of p since we're done with it.");
21757    }
21758 
21759    return CLI_SUCCESS;
21760 }
21761 
21762 /*! \brief Enable/Disable SIP History logging (CLI) */
21763 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
21764 {
21765    switch (cmd) {
21766    case CLI_INIT:
21767       e->command = "sip set history {on|off}";
21768       e->usage =
21769          "Usage: sip set history {on|off}\n"
21770          "       Enables/Disables recording of SIP dialog history for debugging purposes.\n"
21771          "       Use 'sip show history' to view the history of a call number.\n";
21772       return NULL;
21773    case CLI_GENERATE:
21774       return NULL;
21775    }
21776 
21777    if (a->argc != e->args)
21778       return CLI_SHOWUSAGE;
21779 
21780    if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
21781       recordhistory = TRUE;
21782       ast_cli(a->fd, "SIP History Recording Enabled (use 'sip show history')\n");
21783    } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
21784       recordhistory = FALSE;
21785       ast_cli(a->fd, "SIP History Recording Disabled\n");
21786    } else {
21787       return CLI_SHOWUSAGE;
21788    }
21789    return CLI_SUCCESS;
21790 }
21791 
21792 /*! \brief Authenticate for outbound registration */
21793 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code)
21794 {
21795    char *header, *respheader;
21796    char digest[1024];
21797 
21798    p->authtries++;
21799    sip_auth_headers(code, &header, &respheader);
21800    memset(digest, 0, sizeof(digest));
21801    if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
21802       /* There's nothing to use for authentication */
21803       /* No digest challenge in request */
21804       if (sip_debug_test_pvt(p) && p->registry)
21805          ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
21806          /* No old challenge */
21807       return -1;
21808    }
21809    if (p->do_history)
21810       append_history(p, "RegistryAuth", "Try: %d", p->authtries);
21811    if (sip_debug_test_pvt(p) && p->registry)
21812       ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
21813    return transmit_register(p->registry, SIP_REGISTER, digest, respheader);
21814 }
21815 
21816 /*! \brief Add authentication on outbound SIP packet */
21817 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code, int sipmethod, int init)
21818 {
21819    char *header, *respheader;
21820    char digest[1024];
21821 
21822    if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
21823       return -2;
21824 
21825    p->authtries++;
21826    sip_auth_headers(code, &header, &respheader);
21827    ast_debug(2, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
21828    memset(digest, 0, sizeof(digest));
21829    if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
21830       /* No way to authenticate */
21831       return -1;
21832    }
21833    /* Now we have a reply digest */
21834    p->options->auth = digest;
21835    p->options->authheader = respheader;
21836    return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init, NULL);
21837 }
21838 
21839 /*! \brief  reply to authentication for outbound registrations
21840 \return  Returns -1 if we have no auth
21841 \note This is used for register= servers in sip.conf, SIP proxies we register
21842    with  for receiving calls from.  */
21843 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod,  char *digest, int digest_len)
21844 {
21845    char tmp[512];
21846    char *c;
21847    char oldnonce[256];
21848 
21849    /* table of recognised keywords, and places where they should be copied */
21850    const struct x {
21851       const char *key;
21852       const ast_string_field *field;
21853    } *i, keys[] = {
21854       { "realm=", &p->realm },
21855       { "nonce=", &p->nonce },
21856       { "opaque=", &p->opaque },
21857       { "qop=", &p->qop },
21858       { "domain=", &p->domain },
21859       { NULL, 0 },
21860    };
21861 
21862    ast_copy_string(tmp, sip_get_header(req, header), sizeof(tmp));
21863    if (ast_strlen_zero(tmp))
21864       return -1;
21865    if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
21866       ast_log(LOG_WARNING, "missing Digest.\n");
21867       return -1;
21868    }
21869    c = tmp + strlen("Digest ");
21870    ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
21871    while (c && *(c = ast_skip_blanks(c))) {  /* lookup for keys */
21872       for (i = keys; i->key != NULL; i++) {
21873          char *src, *separator;
21874          if (strncasecmp(c, i->key, strlen(i->key)) != 0)
21875             continue;
21876          /* Found. Skip keyword, take text in quotes or up to the separator. */
21877          c += strlen(i->key);
21878          if (*c == '"') {
21879             src = ++c;
21880             separator = "\"";
21881          } else {
21882             src = c;
21883             separator = ",";
21884          }
21885          strsep(&c, separator); /* clear separator and move ptr */
21886          ast_string_field_ptr_set(p, i->field, src);
21887          break;
21888       }
21889       if (i->key == NULL) /* not found, try ',' */
21890          strsep(&c, ",");
21891    }
21892    /* Reset nonce count */
21893    if (strcmp(p->nonce, oldnonce))
21894       p->noncecount = 0;
21895 
21896    /* Save auth data for following registrations */
21897    if (p->registry) {
21898       struct sip_registry *r = p->registry;
21899 
21900       if (strcmp(r->nonce, p->nonce)) {
21901          ast_string_field_set(r, realm, p->realm);
21902          ast_string_field_set(r, nonce, p->nonce);
21903          ast_string_field_set(r, authdomain, p->domain);
21904          ast_string_field_set(r, opaque, p->opaque);
21905          ast_string_field_set(r, qop, p->qop);
21906          r->noncecount = 0;
21907       }
21908    }
21909    return build_reply_digest(p, sipmethod, digest, digest_len);
21910 }
21911 
21912 /*! \brief  Build reply digest
21913 \return  Returns -1 if we have no auth
21914 \note Build digest challenge for authentication of registrations and calls
21915    Also used for authentication of BYE
21916 */
21917 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
21918 {
21919    char a1[256];
21920    char a2[256];
21921    char a1_hash[256];
21922    char a2_hash[256];
21923    char resp[256];
21924    char resp_hash[256];
21925    char uri[256];
21926    char opaque[256] = "";
21927    char cnonce[80];
21928    const char *username;
21929    const char *secret;
21930    const char *md5secret;
21931    struct sip_auth *auth;  /* Realm authentication credential */
21932    struct sip_auth_container *credentials;
21933 
21934    if (!ast_strlen_zero(p->domain))
21935       snprintf(uri, sizeof(uri), "%s:%s", p->socket.type == SIP_TRANSPORT_TLS ? "sips" : "sip", p->domain);
21936    else if (!ast_strlen_zero(p->uri))
21937       ast_copy_string(uri, p->uri, sizeof(uri));
21938    else
21939       snprintf(uri, sizeof(uri), "%s:%s@%s", p->socket.type == SIP_TRANSPORT_TLS ? "sips" : "sip", p->username, ast_sockaddr_stringify_host_remote(&p->sa));
21940 
21941    snprintf(cnonce, sizeof(cnonce), "%08lx", ast_random());
21942 
21943    /* Check if we have peer credentials */
21944    ao2_lock(p);
21945    credentials = p->peerauth;
21946    if (credentials) {
21947       ao2_t_ref(credentials, +1, "Ref peer auth for digest");
21948    }
21949    ao2_unlock(p);
21950    auth = find_realm_authentication(credentials, p->realm);
21951    if (!auth) {
21952       /* If not, check global credentials */
21953       if (credentials) {
21954          ao2_t_ref(credentials, -1, "Unref peer auth for digest");
21955       }
21956       ast_mutex_lock(&authl_lock);
21957       credentials = authl;
21958       if (credentials) {
21959          ao2_t_ref(credentials, +1, "Ref global auth for digest");
21960       }
21961       ast_mutex_unlock(&authl_lock);
21962       auth = find_realm_authentication(credentials, p->realm);
21963    }
21964 
21965    if (auth) {
21966       ast_debug(3, "use realm [%s] from peer [%s][%s]\n", auth->username, p->peername, p->username);
21967       username = auth->username;
21968       secret = auth->secret;
21969       md5secret = auth->md5secret;
21970       if (sipdebug)
21971          ast_debug(1, "Using realm %s authentication for call %s\n", p->realm, p->callid);
21972    } else {
21973       /* No authentication, use peer or register= config */
21974       username = p->authname;
21975       secret = p->relatedpeer 
21976          && !ast_strlen_zero(p->relatedpeer->remotesecret)
21977             ? p->relatedpeer->remotesecret : p->peersecret;
21978       md5secret = p->peermd5secret;
21979    }
21980    if (ast_strlen_zero(username)) {
21981       /* We have no authentication */
21982       if (credentials) {
21983          ao2_t_ref(credentials, -1, "Unref auth for digest");
21984       }
21985       return -1;
21986    }
21987 
21988    /* Calculate SIP digest response */
21989    snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
21990    snprintf(a2, sizeof(a2), "%s:%s", sip_methods[method].text, uri);
21991    if (!ast_strlen_zero(md5secret))
21992       ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
21993    else
21994       ast_md5_hash(a1_hash, a1);
21995    ast_md5_hash(a2_hash, a2);
21996 
21997    p->noncecount++;
21998    if (!ast_strlen_zero(p->qop))
21999       snprintf(resp, sizeof(resp), "%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, p->noncecount, cnonce, "auth", a2_hash);
22000    else
22001       snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, p->nonce, a2_hash);
22002    ast_md5_hash(resp_hash, resp);
22003 
22004    /* only include the opaque string if it's set */
22005    if (!ast_strlen_zero(p->opaque)) {
22006       snprintf(opaque, sizeof(opaque), ", opaque=\"%s\"", p->opaque);
22007    }
22008 
22009    /* XXX We hard code our qop to "auth" for now.  XXX */
22010    if (!ast_strlen_zero(p->qop))
22011       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, p->noncecount);
22012    else
22013       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);
22014 
22015    append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);
22016 
22017    if (credentials) {
22018       ao2_t_ref(credentials, -1, "Unref auth for digest");
22019    }
22020    return 0;
22021 }
22022    
22023 /*! \brief Read SIP header (dialplan function) */
22024 static int func_header_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len)
22025 {
22026    struct sip_pvt *p;
22027    const char *content = NULL;
22028    AST_DECLARE_APP_ARGS(args,
22029       AST_APP_ARG(header);
22030       AST_APP_ARG(number);
22031    );
22032    int i, number, start = 0;
22033 
22034    if (!chan) {
22035       ast_log(LOG_WARNING, "No channel was provided to %s function.\n", function);
22036       return -1;
22037    }
22038 
22039    if (ast_strlen_zero(data)) {
22040       ast_log(LOG_WARNING, "This function requires a header name.\n");
22041       return -1;
22042    }
22043 
22044    ast_channel_lock(chan);
22045    if (!IS_SIP_TECH(ast_channel_tech(chan))) {
22046       ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
22047       ast_channel_unlock(chan);
22048       return -1;
22049    }
22050 
22051    AST_STANDARD_APP_ARGS(args, data);
22052    if (!args.number) {
22053       number = 1;
22054    } else {
22055       sscanf(args.number, "%30d", &number);
22056       if (number < 1)
22057          number = 1;
22058    }
22059 
22060    p = ast_channel_tech_pvt(chan);
22061 
22062    /* If there is no private structure, this channel is no longer alive */
22063    if (!p) {
22064       ast_channel_unlock(chan);
22065       return -1;
22066    }
22067 
22068    for (i = 0; i < number; i++)
22069       content = __get_header(&p->initreq, args.header, &start);
22070 
22071    if (ast_strlen_zero(content)) {
22072       ast_channel_unlock(chan);
22073       return -1;
22074    }
22075 
22076    ast_copy_string(buf, content, len);
22077    ast_channel_unlock(chan);
22078 
22079    return 0;
22080 }
22081 
22082 static struct ast_custom_function sip_header_function = {
22083    .name = "SIP_HEADER",
22084    .read = func_header_read,
22085 };
22086 
22087 /*! \brief  Dial plan function to check if domain is local */
22088 static int func_check_sipdomain(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
22089 {
22090    if (ast_strlen_zero(data)) {
22091       ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
22092       return -1;
22093    }
22094    if (check_sip_domain(data, NULL, 0))
22095       ast_copy_string(buf, data, len);
22096    else
22097       buf[0] = '\0';
22098    return 0;
22099 }
22100 
22101 static struct ast_custom_function checksipdomain_function = {
22102    .name = "CHECKSIPDOMAIN",
22103    .read = func_check_sipdomain,
22104 };
22105 
22106 /*! \brief  ${SIPPEER()} Dialplan function - reads peer data */
22107 static int function_sippeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
22108 {
22109    struct sip_peer *peer;
22110    char *colname;
22111 
22112    if ((colname = strchr(data, ':'))) {   /*! \todo Will be deprecated after 1.4 */
22113       static int deprecation_warning = 0;
22114       *colname++ = '\0';
22115       if (deprecation_warning++ % 10 == 0)
22116          ast_log(LOG_WARNING, "SIPPEER(): usage of ':' to separate arguments is deprecated.  Please use ',' instead.\n");
22117    } else if ((colname = strchr(data, ',')))
22118       *colname++ = '\0';
22119    else
22120       colname = "ip";
22121 
22122    if (!(peer = sip_find_peer(data, NULL, TRUE, FINDPEERS, FALSE, 0)))
22123       return -1;
22124 
22125    if (!strcasecmp(colname, "ip")) {
22126       ast_copy_string(buf, ast_sockaddr_stringify_addr(&peer->addr), len);
22127    } else  if (!strcasecmp(colname, "port")) {
22128       snprintf(buf, len, "%d", ast_sockaddr_port(&peer->addr));
22129    } else  if (!strcasecmp(colname, "status")) {
22130       peer_status(peer, buf, len);
22131    } else  if (!strcasecmp(colname, "language")) {
22132       ast_copy_string(buf, peer->language, len);
22133    } else  if (!strcasecmp(colname, "regexten")) {
22134       ast_copy_string(buf, peer->regexten, len);
22135    } else  if (!strcasecmp(colname, "limit")) {
22136       snprintf(buf, len, "%d", peer->call_limit);
22137    } else  if (!strcasecmp(colname, "busylevel")) {
22138       snprintf(buf, len, "%d", peer->busy_level);
22139    } else  if (!strcasecmp(colname, "curcalls")) {
22140       snprintf(buf, len, "%d", peer->inuse);
22141    } else if (!strcasecmp(colname, "maxforwards")) {
22142       snprintf(buf, len, "%d", peer->maxforwards);
22143    } else  if (!strcasecmp(colname, "accountcode")) {
22144       ast_copy_string(buf, peer->accountcode, len);
22145    } else  if (!strcasecmp(colname, "callgroup")) {
22146       ast_print_group(buf, len, peer->callgroup);
22147    } else  if (!strcasecmp(colname, "pickupgroup")) {
22148       ast_print_group(buf, len, peer->pickupgroup);
22149    } else  if (!strcasecmp(colname, "namedcallgroup")) {
22150       struct ast_str *tmp_str = ast_str_create(1024);
22151       if (tmp_str) {
22152          ast_copy_string(buf, ast_print_namedgroups(&tmp_str, peer->named_callgroups), len);
22153          ast_free(tmp_str);
22154       }
22155    } else  if (!strcasecmp(colname, "namedpickupgroup")) {
22156       struct ast_str *tmp_str = ast_str_create(1024);
22157       if (tmp_str) {
22158          ast_copy_string(buf, ast_print_namedgroups(&tmp_str, peer->named_pickupgroups), len);
22159          ast_free(tmp_str);
22160       }
22161    } else  if (!strcasecmp(colname, "useragent")) {
22162       ast_copy_string(buf, peer->useragent, len);
22163    } else  if (!strcasecmp(colname, "mailbox")) {
22164       struct ast_str *mailbox_str = ast_str_alloca(512);
22165       peer_mailboxes_to_str(&mailbox_str, peer);
22166       ast_copy_string(buf, ast_str_buffer(mailbox_str), len);
22167    } else  if (!strcasecmp(colname, "context")) {
22168       ast_copy_string(buf, peer->context, len);
22169    } else  if (!strcasecmp(colname, "expire")) {
22170       snprintf(buf, len, "%d", peer->expire);
22171    } else  if (!strcasecmp(colname, "dynamic")) {
22172       ast_copy_string(buf, peer->host_dynamic ? "yes" : "no", len);
22173    } else  if (!strcasecmp(colname, "callerid_name")) {
22174       ast_copy_string(buf, peer->cid_name, len);
22175    } else  if (!strcasecmp(colname, "callerid_num")) {
22176       ast_copy_string(buf, peer->cid_num, len);
22177    } else  if (!strcasecmp(colname, "codecs")) {
22178       ast_getformatname_multiple(buf, len -1, peer->caps);
22179    } else if (!strcasecmp(colname, "encryption")) {
22180       snprintf(buf, len, "%d", ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP));
22181    } else  if (!strncasecmp(colname, "chanvar[", 8)) {
22182       char *chanvar=colname + 8;
22183       struct ast_variable *v;
22184 
22185       chanvar = strsep(&chanvar, "]");
22186       for (v = peer->chanvars ; v ; v = v->next) {
22187          if (!strcasecmp(v->name, chanvar)) {
22188             ast_copy_string(buf, v->value, len);
22189          }
22190       }
22191    } else  if (!strncasecmp(colname, "codec[", 6)) {
22192       char *codecnum;
22193       struct ast_format codec;
22194 
22195       codecnum = colname + 6; /* move past the '[' */
22196       codecnum = strsep(&codecnum, "]"); /* trim trailing ']' if any */
22197       if((ast_codec_pref_index(&peer->prefs, atoi(codecnum), &codec))) {
22198          ast_copy_string(buf, ast_getformatname(&codec), len);
22199       } else {
22200          buf[0] = '\0';
22201       }
22202    } else {
22203       buf[0] = '\0';
22204    }
22205 
22206    sip_unref_peer(peer, "sip_unref_peer from function_sippeer, just before return");
22207 
22208    return 0;
22209 }
22210 
22211 /*! \brief Structure to declare a dialplan function: SIPPEER */
22212 static struct ast_custom_function sippeer_function = {
22213    .name = "SIPPEER",
22214    .read = function_sippeer,
22215 };
22216 
22217 /*! \brief ${SIPCHANINFO()} Dialplan function - reads sip channel data */
22218 static int function_sipchaninfo_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
22219 {
22220    struct sip_pvt *p;
22221    static int deprecated = 0;
22222 
22223    *buf = 0;
22224 
22225    if (!chan) {
22226       ast_log(LOG_WARNING, "No channel was provided to %s function.\n", cmd);
22227       return -1;
22228    }
22229 
22230    if (!data) {
22231       ast_log(LOG_WARNING, "This function requires a parameter name.\n");
22232       return -1;
22233    }
22234 
22235    ast_channel_lock(chan);
22236    if (!IS_SIP_TECH(ast_channel_tech(chan))) {
22237       ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
22238       ast_channel_unlock(chan);
22239       return -1;
22240    }
22241 
22242    if (deprecated++ % 20 == 0) {
22243       /* Deprecated in 1.6.1 */
22244       ast_log(LOG_WARNING, "SIPCHANINFO() is deprecated.  Please transition to using CHANNEL().\n");
22245    }
22246 
22247    p = ast_channel_tech_pvt(chan);
22248 
22249    /* If there is no private structure, this channel is no longer alive */
22250    if (!p) {
22251       ast_channel_unlock(chan);
22252       return -1;
22253    }
22254 
22255    if (!strcasecmp(data, "peerip")) {
22256       ast_copy_string(buf, ast_sockaddr_stringify_addr(&p->sa), len);
22257    } else  if (!strcasecmp(data, "recvip")) {
22258       ast_copy_string(buf, ast_sockaddr_stringify_addr(&p->recv), len);
22259    } else  if (!strcasecmp(data, "from")) {
22260       ast_copy_string(buf, p->from, len);
22261    } else  if (!strcasecmp(data, "uri")) {
22262       ast_copy_string(buf, p->uri, len);
22263    } else  if (!strcasecmp(data, "useragent")) {
22264       ast_copy_string(buf, p->useragent, len);
22265    } else  if (!strcasecmp(data, "peername")) {
22266       ast_copy_string(buf, p->peername, len);
22267    } else if (!strcasecmp(data, "t38passthrough")) {
22268       if ((p->t38.state == T38_DISABLED) || (p->t38.state == T38_REJECTED)) {
22269          ast_copy_string(buf, "0", len);
22270       } else { /* T38 is offered or enabled in this call */
22271          ast_copy_string(buf, "1", len);
22272       }
22273    } else {
22274       ast_channel_unlock(chan);
22275       return -1;
22276    }
22277    ast_channel_unlock(chan);
22278 
22279    return 0;
22280 }
22281 
22282 /*! \brief Structure to declare a dialplan function: SIPCHANINFO */
22283 static struct ast_custom_function sipchaninfo_function = {
22284    .name = "SIPCHANINFO",
22285    .read = function_sipchaninfo_read,
22286 };
22287 
22288 /*! \brief update redirecting information for a channel based on headers
22289  *
22290  */
22291 static void change_redirecting_information(struct sip_pvt *p, struct sip_request *req,
22292    struct ast_party_redirecting *redirecting,
22293    struct ast_set_party_redirecting *update_redirecting, int set_call_forward)
22294 {
22295    char *redirecting_from_name = NULL;
22296    char *redirecting_from_number = NULL;
22297    char *redirecting_to_name = NULL;
22298    char *redirecting_to_number = NULL;
22299    int reason = AST_REDIRECTING_REASON_UNCONDITIONAL;
22300    int is_response = req->method == SIP_RESPONSE;
22301    int res = 0;
22302 
22303    res = get_rdnis(p, req, &redirecting_from_name, &redirecting_from_number, &reason);
22304    if (res == -1) {
22305       if (is_response) {
22306          get_name_and_number(sip_get_header(req, "TO"), &redirecting_from_name, &redirecting_from_number);
22307       } else {
22308          return;
22309       }
22310    }
22311 
22312    /* At this point, all redirecting "from" info should be filled in appropriately
22313     * on to the "to" info
22314     */
22315 
22316    if (is_response) {
22317       parse_moved_contact(p, req, &redirecting_to_name, &redirecting_to_number, set_call_forward);
22318    } else {
22319       get_name_and_number(sip_get_header(req, "TO"), &redirecting_to_name, &redirecting_to_number);
22320    }
22321 
22322    if (!ast_strlen_zero(redirecting_from_number)) {
22323       ast_debug(3, "Got redirecting from number %s\n", redirecting_from_number);
22324       update_redirecting->from.number = 1;
22325       redirecting->from.number.valid = 1;
22326       ast_free(redirecting->from.number.str);
22327       redirecting->from.number.str = redirecting_from_number;
22328    }
22329    if (!ast_strlen_zero(redirecting_from_name)) {
22330       ast_debug(3, "Got redirecting from name %s\n", redirecting_from_name);
22331       update_redirecting->from.name = 1;
22332       redirecting->from.name.valid = 1;
22333       ast_free(redirecting->from.name.str);
22334       redirecting->from.name.str = redirecting_from_name;
22335    }
22336    if (!ast_strlen_zero(p->cid_tag)) {
22337       ast_free(redirecting->from.tag);
22338       redirecting->from.tag = ast_strdup(p->cid_tag);
22339       ast_free(redirecting->to.tag);
22340       redirecting->to.tag = ast_strdup(p->cid_tag);
22341    }
22342    if (!ast_strlen_zero(redirecting_to_number)) {
22343       ast_debug(3, "Got redirecting to number %s\n", redirecting_to_number);
22344       update_redirecting->to.number = 1;
22345       redirecting->to.number.valid = 1;
22346       ast_free(redirecting->to.number.str);
22347       redirecting->to.number.str = redirecting_to_number;
22348    }
22349    if (!ast_strlen_zero(redirecting_to_name)) {
22350       ast_debug(3, "Got redirecting to name %s\n", redirecting_from_number);
22351       update_redirecting->to.name = 1;
22352       redirecting->to.name.valid = 1;
22353       ast_free(redirecting->to.name.str);
22354       redirecting->to.name.str = redirecting_to_name;
22355    }
22356    redirecting->reason = reason;
22357 }
22358 
22359 /*! \brief Parse 302 Moved temporalily response
22360    \todo XXX Doesn't redirect over TLS on sips: uri's.
22361       If we get a redirect to a SIPS: uri, this needs to be going back to the
22362       dialplan (this is a request for a secure signalling path).
22363       Note that transport=tls is deprecated, but we need to support it on incoming requests.
22364 */
22365 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward)
22366 {
22367    char contact[SIPBUFSIZE];
22368    char *contact_name = NULL;
22369    char *contact_number = NULL;
22370    char *separator, *trans;
22371    char *domain;
22372    enum sip_transport transport = SIP_TRANSPORT_UDP;
22373 
22374    ast_copy_string(contact, sip_get_header(req, "Contact"), sizeof(contact));
22375    if ((separator = strchr(contact, ',')))
22376       *separator = '\0';
22377 
22378    contact_number = get_in_brackets(contact);
22379    if ((trans = strcasestr(contact_number, ";transport="))) {
22380       trans += 11;
22381 
22382       if ((separator = strchr(trans, ';')))
22383          *separator = '\0';
22384 
22385       if (!strncasecmp(trans, "tcp", 3))
22386          transport = SIP_TRANSPORT_TCP;
22387       else if (!strncasecmp(trans, "tls", 3))
22388          transport = SIP_TRANSPORT_TLS;
22389       else {
22390          if (strncasecmp(trans, "udp", 3))
22391             ast_debug(1, "received contact with an invalid transport, '%s'\n", contact_number);
22392          /* This will assume UDP for all unknown transports */
22393          transport = SIP_TRANSPORT_UDP;
22394       }
22395    }
22396    contact_number = remove_uri_parameters(contact_number);
22397 
22398    if (p->socket.tcptls_session) {
22399       ao2_ref(p->socket.tcptls_session, -1);
22400       p->socket.tcptls_session = NULL;
22401    } else if (p->socket.ws_session) {
22402       ast_websocket_unref(p->socket.ws_session);
22403       p->socket.ws_session = NULL;
22404    }
22405 
22406    set_socket_transport(&p->socket, transport);
22407 
22408    if (set_call_forward && ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
22409       char *host = NULL;
22410       if (!strncasecmp(contact_number, "sip:", 4))
22411          contact_number += 4;
22412       else if (!strncasecmp(contact_number, "sips:", 5))
22413          contact_number += 5;
22414       separator = strchr(contact_number, '/');
22415       if (separator)
22416          *separator = '\0';
22417       if ((host = strchr(contact_number, '@'))) {
22418          *host++ = '\0';
22419          ast_debug(2, "Found promiscuous redirection to 'SIP/%s::::%s@%s'\n", contact_number, sip_get_transport(transport), host);
22420          if (p->owner)
22421             ast_channel_call_forward_build(p->owner, "SIP/%s::::%s@%s", contact_number, sip_get_transport(transport), host);
22422       } else {
22423          ast_debug(2, "Found promiscuous redirection to 'SIP/::::%s@%s'\n", sip_get_transport(transport), contact_number);
22424          if (p->owner)
22425             ast_channel_call_forward_build(p->owner, "SIP/::::%s@%s", sip_get_transport(transport), contact_number);
22426       }
22427    } else {
22428       separator = strchr(contact, '@');
22429       if (separator) {
22430          *separator++ = '\0';
22431          domain = separator;
22432       } else {
22433          /* No username part */
22434          domain = contact;
22435       }
22436       separator = strchr(contact, '/');   /* WHEN do we hae a forward slash in the URI? */
22437       if (separator)
22438          *separator = '\0';
22439 
22440       if (!strncasecmp(contact_number, "sip:", 4))
22441          contact_number += 4;
22442       else if (!strncasecmp(contact_number, "sips:", 5))
22443          contact_number += 5;
22444       separator = strchr(contact_number, ';');  /* And username ; parameters? */
22445       if (separator)
22446          *separator = '\0';
22447       ast_uri_decode(contact_number, ast_uri_sip_user);
22448       if (set_call_forward) {
22449          ast_debug(2, "Received 302 Redirect to extension '%s' (domain %s)\n", contact_number, domain);
22450          if (p->owner) {
22451             pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
22452             ast_channel_call_forward_set(p->owner, contact_number);
22453          }
22454       }
22455    }
22456 
22457    /* We've gotten the number for the contact, now get the name */
22458 
22459    if (*contact == '\"') {
22460       contact_name = contact + 1;
22461       if (!(separator = (char *)find_closing_quote(contact_name, NULL))) {
22462          ast_log(LOG_NOTICE, "No closing quote on name in Contact header? %s\n", contact);
22463       }
22464       *separator = '\0';
22465    }
22466 
22467    if (name && !ast_strlen_zero(contact_name)) {
22468       *name = ast_strdup(contact_name);
22469    }
22470    if (number) {
22471       *number = ast_strdup(contact_number);
22472    }
22473 }
22474 
22475 /*! \brief Check pending actions on SIP call 
22476  *
22477  * \note both sip_pvt and sip_pvt's owner channel (if present)
22478  *  must be locked for this function.
22479  */
22480 static void check_pendings(struct sip_pvt *p)
22481 {
22482    if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
22483       if (p->reinviteid > -1) {
22484          /* Outstanding p->reinviteid timeout, so wait... */
22485          return;
22486       } else if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA) {
22487          /* if we can't BYE, then this is really a pending CANCEL */
22488          p->invitestate = INV_CANCELLED;
22489          transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
22490          /* If the cancel occurred on an initial invite, cancel the pending BYE */
22491          if (!ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
22492             ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);
22493          }
22494          /* Actually don't destroy us yet, wait for the 487 on our original
22495             INVITE, but do set an autodestruct just in case we never get it. */
22496       } else {
22497          /* We have a pending outbound invite, don't send something
22498           * new in-transaction, unless it is a pending reinvite, then
22499           * by the time we are called here, we should probably just hang up. */
22500          if (p->pendinginvite && !p->ongoing_reinvite)
22501             return;
22502 
22503          if (p->owner) {
22504             ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
22505          }
22506          /* Perhaps there is an SD change INVITE outstanding */
22507          transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
22508          ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);
22509       }
22510       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22511    } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
22512       /* if we can't REINVITE, hold it for later */
22513       if (p->pendinginvite || p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA || p->waitid > 0) {
22514          ast_debug(2, "NOT Sending pending reinvite (yet) on '%s'\n", p->callid);
22515       } else {
22516          ast_debug(2, "Sending pending reinvite on '%s'\n", p->callid);
22517          /* Didn't get to reinvite yet, so do it now */
22518          transmit_reinvite_with_sdp(p, (p->t38.state == T38_LOCAL_REINVITE ? TRUE : FALSE), FALSE);
22519          ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE);
22520       }
22521    }
22522 }
22523 
22524 /*! \brief Reset the NEEDREINVITE flag after waiting when we get 491 on a Re-invite
22525    to avoid race conditions between asterisk servers.
22526    Called from the scheduler.
22527 */
22528 static int sip_reinvite_retry(const void *data)
22529 {
22530    struct sip_pvt *p = (struct sip_pvt *) data;
22531    struct ast_channel *owner;
22532 
22533    sip_pvt_lock(p); /* called from schedule thread which requires a lock */
22534    while ((owner = p->owner) && ast_channel_trylock(owner)) {
22535       sip_pvt_unlock(p);
22536       usleep(1);
22537       sip_pvt_lock(p);
22538    }
22539    ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
22540    p->waitid = -1;
22541    check_pendings(p);
22542    sip_pvt_unlock(p);
22543    if (owner) {
22544       ast_channel_unlock(owner);
22545    }
22546    dialog_unref(p, "unref the dialog ptr from sip_reinvite_retry, because it held a dialog ptr");
22547    return 0;
22548 }
22549 
22550 /*!
22551  * \brief Handle authentication challenge for SIP UPDATE
22552  *
22553  * This function is only called upon the receipt of a 401/407 response to an UPDATE.
22554  */
22555 static void handle_response_update(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
22556 {
22557    if (p->options) {
22558       p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
22559    }
22560    if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, SIP_UPDATE, 1)) {
22561       ast_log(LOG_NOTICE, "Failed to authenticate on UPDATE to '%s'\n", sip_get_header(&p->initreq, "From"));
22562    }
22563 }
22564 
22565 static void cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry)
22566 {
22567    struct cc_epa_entry *cc_entry = epa_entry->instance_data;
22568    struct sip_monitor_instance *monitor_instance = ao2_callback(sip_monitor_instances, 0,
22569          find_sip_monitor_instance_by_suspension_entry, epa_entry);
22570    const char *min_expires;
22571 
22572    if (!monitor_instance) {
22573       ast_log(LOG_WARNING, "Can't find monitor_instance corresponding to epa_entry %p.\n", epa_entry);
22574       return;
22575    }
22576 
22577    if (resp != 423) {
22578       ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
22579             "Received error response to our PUBLISH");
22580       ao2_ref(monitor_instance, -1);
22581       return;
22582    }
22583 
22584    /* Allrighty, the other end doesn't like our Expires value. They think it's
22585     * too small, so let's see if they've provided a more sensible value. If they
22586     * haven't, then we'll just double our Expires value and see if they like that
22587     * instead.
22588     *
22589     * XXX Ideally this logic could be placed into its own function so that SUBSCRIBE,
22590     * PUBLISH, and REGISTER could all benefit from the same shared code.
22591     */
22592    min_expires = sip_get_header(req, "Min-Expires");
22593    if (ast_strlen_zero(min_expires)) {
22594       pvt->expiry *= 2;
22595       if (pvt->expiry < 0) {
22596          /* You dork! You overflowed! */
22597          ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
22598                "PUBLISH expiry overflowed");
22599          ao2_ref(monitor_instance, -1);
22600          return;
22601       }
22602    } else if (sscanf(min_expires, "%30d", &pvt->expiry) != 1) {
22603       ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
22604             "Min-Expires has non-numeric value");
22605       ao2_ref(monitor_instance, -1);
22606       return;
22607    }
22608    /* At this point, we have most certainly changed pvt->expiry, so try transmitting
22609     * again
22610     */
22611    transmit_invite(pvt, SIP_PUBLISH, FALSE, 0, NULL);
22612    ao2_ref(monitor_instance, -1);
22613 }
22614 
22615 static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
22616 {
22617    struct sip_epa_entry *epa_entry = p->epa_entry;
22618    const char *etag = sip_get_header(req, "Sip-ETag");
22619 
22620    ast_assert(epa_entry != NULL);
22621 
22622    if (resp == 401 || resp == 407) {
22623       ast_string_field_set(p, theirtag, NULL);
22624       if (p->options) {
22625          p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
22626       }
22627       if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, SIP_PUBLISH, 0)) {
22628          ast_log(LOG_NOTICE, "Failed to authenticate on PUBLISH to '%s'\n", sip_get_header(&p->initreq, "From"));
22629          pvt_set_needdestroy(p, "Failed to authenticate on PUBLISH");
22630          sip_alreadygone(p);
22631       }
22632       return;
22633    }
22634 
22635    if (resp == 501 || resp == 405) {
22636       mark_method_unallowed(&p->allowed_methods, SIP_PUBLISH);
22637    }
22638 
22639    if (resp == 200) {
22640       p->authtries = 0;
22641       /* If I've read section 6, item 6 of RFC 3903 correctly,
22642        * an ESC will only generate a new etag when it sends a 200 OK
22643        */
22644       if (!ast_strlen_zero(etag)) {
22645          ast_copy_string(epa_entry->entity_tag, etag, sizeof(epa_entry->entity_tag));
22646       }
22647       /* The nominal case. Everything went well. Everybody is happy.
22648        * Each EPA will have a specific action to take as a result of this
22649        * development, so ... callbacks!
22650        */
22651       if (epa_entry->static_data->handle_ok) {
22652          epa_entry->static_data->handle_ok(p, req, epa_entry);
22653       }
22654    } else {
22655       /* Rather than try to make individual callbacks for each error
22656        * type, there is just a single error callback. The callback
22657        * can distinguish between error messages and do what it needs to
22658        */
22659       if (epa_entry->static_data->handle_error) {
22660          epa_entry->static_data->handle_error(p, resp, req, epa_entry);
22661       }
22662    }
22663 }
22664 
22665 /*!
22666  * \internal
22667  * \brief Set hangup source and cause.
22668  *
22669  * \param p SIP private.
22670  * \param cause Hangup cause to queue.  Zero if no cause.
22671  *
22672  * \pre p and p->owner are locked.
22673  *
22674  * \return Nothing
22675  */
22676 static void sip_queue_hangup_cause(struct sip_pvt *p, int cause)
22677 {
22678    struct ast_channel *owner = p->owner;
22679    const char *name = ast_strdupa(ast_channel_name(owner));
22680 
22681    /* Cannot hold any channel/private locks when calling. */
22682    ast_channel_ref(owner);
22683    ast_channel_unlock(owner);
22684    sip_pvt_unlock(p);
22685    ast_set_hangupsource(owner, name, 0);
22686    if (cause) {
22687       ast_queue_hangup_with_cause(owner, cause);
22688    } else {
22689       ast_queue_hangup(owner);
22690    }
22691    ast_channel_unref(owner);
22692 
22693    /* Relock things. */
22694    owner = sip_pvt_lock_full(p);
22695    if (owner) {
22696       ast_channel_unref(owner);
22697    }
22698 }
22699 
22700 /*! \brief Handle SIP response to INVITE dialogue */
22701 static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
22702 {
22703    int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
22704    int res = 0;
22705    int xmitres = 0;
22706    int reinvite = ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
22707    char *p_hdrval;
22708    int rtn;
22709    struct ast_party_connected_line connected;
22710    struct ast_set_party_connected_line update_connected;
22711 
22712    if (reinvite) {
22713       ast_debug(4, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
22714    } else {
22715       ast_debug(4, "SIP response %d to standard invite\n", resp);
22716    }
22717 
22718    if (p->alreadygone) { /* This call is already gone */
22719       ast_debug(1, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
22720       return;
22721    }
22722 
22723    /* Acknowledge sequence number - This only happens on INVITE from SIP-call */
22724    /* Don't auto congest anymore since we've gotten something useful back */
22725    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"));
22726 
22727    /* RFC3261 says we must treat every 1xx response (but not 100)
22728       that we don't recognize as if it was 183.
22729    */
22730    if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 181 && resp != 182 && resp != 183) {
22731       resp = 183;
22732    }
22733 
22734    /* For INVITE, treat all 2XX responses as we would a 200 response */
22735    if ((resp >= 200) && (resp < 300)) {
22736       resp = 200;
22737    }
22738 
22739    /* Any response between 100 and 199 is PROCEEDING */
22740    if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING) {
22741       p->invitestate = INV_PROCEEDING;
22742    }
22743 
22744    /* Final response, not 200 ? */
22745    if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA )) {
22746       p->invitestate = INV_COMPLETED;
22747    }
22748    
22749    if ((resp >= 200 && reinvite)) {
22750       p->ongoing_reinvite = 0;
22751       if (p->reinviteid > -1) {
22752          AST_SCHED_DEL_UNREF(sched, p->reinviteid, dialog_unref(p, "unref dialog for reinvite timeout because of a final response"));
22753       }
22754    }
22755 
22756    /* Final response, clear out pending invite */
22757    if ((resp == 200 || resp >= 300) && p->pendinginvite && seqno == p->pendinginvite) {
22758       p->pendinginvite = 0;
22759    }
22760 
22761    /* If this is a response to our initial INVITE, we need to set what we can use
22762     * for this peer.
22763     */
22764    if (!reinvite) {
22765       set_pvt_allowed_methods(p, req);
22766    }
22767 
22768    switch (resp) {
22769    case 100:   /* Trying */
22770    case 101:   /* Dialog establishment */
22771       if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p)) {
22772          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
22773       }
22774       check_pendings(p);
22775       break;
22776 
22777    case 180:   /* 180 Ringing */
22778    case 182:       /* 182 Queued */
22779       if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p)) {
22780          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
22781       }
22782       /* Store Route-set from provisional SIP responses so
22783        * early-dialog request can be routed properly
22784        * */
22785       parse_ok_contact(p, req);
22786       if (!reinvite) {
22787          build_route(p, req, 1, resp);
22788       }
22789       if (!req->ignore && p->owner) {
22790          if (get_rpid(p, req)) {
22791             /* Queue a connected line update */
22792             ast_party_connected_line_init(&connected);
22793             memset(&update_connected, 0, sizeof(update_connected));
22794 
22795             update_connected.id.number = 1;
22796             connected.id.number.valid = 1;
22797             connected.id.number.str = (char *) p->cid_num;
22798             connected.id.number.presentation = p->callingpres;
22799 
22800             update_connected.id.name = 1;
22801             connected.id.name.valid = 1;
22802             connected.id.name.str = (char *) p->cid_name;
22803             connected.id.name.presentation = p->callingpres;
22804 
22805             /* Invalidate any earlier private connected id representation */
22806             ast_set_party_id_all(&update_connected.priv);
22807 
22808             connected.id.tag = (char *) p->cid_tag;
22809             connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
22810             ast_channel_queue_connected_line_update(p->owner, &connected,
22811                &update_connected);
22812          }
22813          sip_handle_cc(p, req, AST_CC_CCNR);
22814          ast_queue_control(p->owner, AST_CONTROL_RINGING);
22815          if (ast_channel_state(p->owner) != AST_STATE_UP) {
22816             ast_setstate(p->owner, AST_STATE_RINGING);
22817          }
22818       }
22819       if (find_sdp(req)) {
22820          if (p->invitestate != INV_CANCELLED) {
22821             p->invitestate = INV_EARLY_MEDIA;
22822          }
22823          res = process_sdp(p, req, SDP_T38_NONE);
22824          if (!req->ignore && p->owner) {
22825             /* Queue a progress frame only if we have SDP in 180 or 182 */
22826             ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
22827          }
22828          ast_rtp_instance_activate(p->rtp);
22829       }
22830       check_pendings(p);
22831       break;
22832 
22833    case 181:   /* Call Is Being Forwarded */
22834       if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
22835          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
22836       /* Store Route-set from provisional SIP responses so
22837        * early-dialog request can be routed properly
22838        * */
22839       parse_ok_contact(p, req);
22840       if (!reinvite) {
22841          build_route(p, req, 1, resp);
22842       }
22843       if (!req->ignore && p->owner) {
22844          struct ast_party_redirecting redirecting;
22845          struct ast_set_party_redirecting update_redirecting;
22846 
22847          ast_party_redirecting_init(&redirecting);
22848          memset(&update_redirecting, 0, sizeof(update_redirecting));
22849          change_redirecting_information(p, req, &redirecting, &update_redirecting,
22850             FALSE);
22851 
22852          /* Invalidate any earlier private redirecting id representations */
22853          ast_set_party_id_all(&update_redirecting.priv_orig);
22854          ast_set_party_id_all(&update_redirecting.priv_from);
22855          ast_set_party_id_all(&update_redirecting.priv_to);
22856 
22857          ast_channel_queue_redirecting_update(p->owner, &redirecting,
22858             &update_redirecting);
22859          ast_party_redirecting_free(&redirecting);
22860          sip_handle_cc(p, req, AST_CC_CCNR);
22861       }
22862       check_pendings(p);
22863       break;
22864 
22865    case 183:   /* Session progress */
22866       if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p)) {
22867          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
22868       }
22869       /* Store Route-set from provisional SIP responses so
22870        * early-dialog request can be routed properly
22871        * */
22872       parse_ok_contact(p, req);
22873       if (!reinvite) {
22874          build_route(p, req, 1, resp);
22875       }
22876       if (!req->ignore && p->owner) {
22877          if (get_rpid(p, req)) {
22878             /* Queue a connected line update */
22879             ast_party_connected_line_init(&connected);
22880             memset(&update_connected, 0, sizeof(update_connected));
22881 
22882             update_connected.id.number = 1;
22883             connected.id.number.valid = 1;
22884             connected.id.number.str = (char *) p->cid_num;
22885             connected.id.number.presentation = p->callingpres;
22886 
22887             update_connected.id.name = 1;
22888             connected.id.name.valid = 1;
22889             connected.id.name.str = (char *) p->cid_name;
22890             connected.id.name.presentation = p->callingpres;
22891 
22892             /* Invalidate any earlier private connected id representation */
22893             ast_set_party_id_all(&update_connected.priv);
22894 
22895             connected.id.tag = (char *) p->cid_tag;
22896             connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
22897             ast_channel_queue_connected_line_update(p->owner, &connected,
22898                &update_connected);
22899          }
22900          sip_handle_cc(p, req, AST_CC_CCNR);
22901       }
22902       if (find_sdp(req)) {
22903          if (p->invitestate != INV_CANCELLED) {
22904             p->invitestate = INV_EARLY_MEDIA;
22905          }
22906          res = process_sdp(p, req, SDP_T38_NONE);
22907          if (!req->ignore && p->owner) {
22908             /* Queue a progress frame */
22909             ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
22910          }
22911          ast_rtp_instance_activate(p->rtp);
22912       } else {
22913          /* Alcatel PBXs are known to send 183s with no SDP after sending
22914           * a 100 Trying response. We're just going to treat this sort of thing
22915           * the same as we would treat a 180 Ringing
22916           */
22917          if (!req->ignore && p->owner) {
22918             ast_queue_control(p->owner, AST_CONTROL_RINGING);
22919          }
22920       }
22921       check_pendings(p);
22922       break;
22923 
22924    case 200:   /* 200 OK on invite - someone's answering our call */
22925       if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p)) {
22926          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
22927       }
22928       p->authtries = 0;
22929       if (find_sdp(req)) {
22930          if ((res = process_sdp(p, req, SDP_T38_ACCEPT)) && !req->ignore) {
22931             if (!reinvite) {
22932                /* This 200 OK's SDP is not acceptable, so we need to ack, then hangup */
22933                /* For re-invites, we try to recover */
22934                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
22935                p->hangupcause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
22936                if (p->owner) {
22937                   ast_channel_hangupcause_set(p->owner, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
22938                   sip_queue_hangup_cause(p, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
22939                }
22940             }
22941          }
22942          ast_rtp_instance_activate(p->rtp);
22943       } else if (!reinvite) {
22944          struct ast_sockaddr remote_address = {{0,}};
22945 
22946          ast_rtp_instance_get_remote_address(p->rtp, &remote_address);
22947          if (ast_sockaddr_isnull(&remote_address) || (!ast_strlen_zero(p->theirprovtag) && strcmp(p->theirtag, p->theirprovtag))) {
22948             ast_log(LOG_WARNING, "Received response: \"200 OK\" from '%s' without SDP\n", p->relatedpeer->name);
22949             ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
22950             ast_rtp_instance_activate(p->rtp);
22951          }
22952       }
22953 
22954       if (!req->ignore && p->owner) {
22955          int rpid_changed;
22956 
22957          rpid_changed = get_rpid(p, req);
22958          if (rpid_changed || !reinvite) {
22959             /* Queue a connected line update */
22960             ast_party_connected_line_init(&connected);
22961             memset(&update_connected, 0, sizeof(update_connected));
22962             if (rpid_changed
22963                || !ast_strlen_zero(p->cid_num)
22964                || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
22965                update_connected.id.number = 1;
22966                connected.id.number.valid = 1;
22967                connected.id.number.str = (char *) p->cid_num;
22968                connected.id.number.presentation = p->callingpres;
22969             }
22970             if (rpid_changed
22971                || !ast_strlen_zero(p->cid_name)
22972                || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
22973                update_connected.id.name = 1;
22974                connected.id.name.valid = 1;
22975                connected.id.name.str = (char *) p->cid_name;
22976                connected.id.name.presentation = p->callingpres;
22977             }
22978             if (update_connected.id.number || update_connected.id.name) {
22979                /* Invalidate any earlier private connected id representation */
22980                ast_set_party_id_all(&update_connected.priv);
22981 
22982                connected.id.tag = (char *) p->cid_tag;
22983                connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
22984                ast_channel_queue_connected_line_update(p->owner, &connected,
22985                   &update_connected);
22986             }
22987          }
22988       }
22989 
22990       /* Parse contact header for continued conversation */
22991       /* When we get 200 OK, we know which device (and IP) to contact for this call */
22992       /* This is important when we have a SIP proxy between us and the phone */
22993       if (outgoing) {
22994          update_call_counter(p, DEC_CALL_RINGING);
22995          parse_ok_contact(p, req);
22996          /* Save Record-Route for any later requests we make on this dialogue */
22997          if (!reinvite) {
22998             build_route(p, req, 1, resp);
22999          }
23000          if(set_address_from_contact(p)) {
23001             /* Bad contact - we don't know how to reach this device */
23002             /* We need to ACK, but then send a bye */
23003             if (!p->route && !req->ignore) {
23004                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
23005             }
23006          }
23007 
23008       }
23009 
23010       if (!req->ignore && p->owner) {
23011          if (!reinvite && !res) {
23012             ast_queue_control(p->owner, AST_CONTROL_ANSWER);
23013             if (sip_cfg.callevents) {
23014                manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
23015                   "Channel: %s\r\nChanneltype: %s\r\nUniqueid: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
23016                   ast_channel_name(p->owner), "SIP", ast_channel_uniqueid(p->owner), p->callid, p->fullcontact, p->peername);
23017             }
23018          } else { /* RE-invite */
23019             if (p->t38.state == T38_DISABLED || p->t38.state == T38_REJECTED) {
23020                ast_queue_control(p->owner, AST_CONTROL_UPDATE_RTP_PEER);
23021             } else {
23022                ast_queue_frame(p->owner, &ast_null_frame);
23023             }
23024          }
23025       } else {
23026           /* It's possible we're getting an 200 OK after we've tried to disconnect
23027               by sending CANCEL */
23028          /* First send ACK, then send bye */
23029          if (!req->ignore) {
23030             ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
23031          }
23032       }
23033 
23034       /* Check for Session-Timers related headers */
23035       if (st_get_mode(p, 0) != SESSION_TIMER_MODE_REFUSE) {
23036          p_hdrval = (char*)sip_get_header(req, "Session-Expires");
23037          if (!ast_strlen_zero(p_hdrval)) {
23038             /* UAS supports Session-Timers */
23039             enum st_refresher_param st_ref_param;
23040             int tmp_st_interval = 0;
23041             rtn = parse_session_expires(p_hdrval, &tmp_st_interval, &st_ref_param);
23042             if (rtn != 0) {
23043                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
23044             } else if (tmp_st_interval < st_get_se(p, FALSE)) {
23045                ast_log(LOG_WARNING, "Got Session-Expires less than local Min-SE in 200 OK, tearing down call\n");
23046                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
23047             }
23048             if (st_ref_param == SESSION_TIMER_REFRESHER_PARAM_UAC) {
23049                p->stimer->st_ref = SESSION_TIMER_REFRESHER_US;
23050             } else if (st_ref_param == SESSION_TIMER_REFRESHER_PARAM_UAS) {
23051                p->stimer->st_ref = SESSION_TIMER_REFRESHER_THEM;
23052             } else {
23053                ast_log(LOG_WARNING, "Unknown refresher on %s\n", p->callid);
23054             }
23055             if (tmp_st_interval) {
23056                p->stimer->st_interval = tmp_st_interval;
23057             }
23058             p->stimer->st_active = TRUE;
23059             p->stimer->st_active_peer_ua = TRUE;
23060             start_session_timer(p);
23061          } else {
23062             /* UAS doesn't support Session-Timers */
23063             if (st_get_mode(p, 0) == SESSION_TIMER_MODE_ORIGINATE) {
23064                p->stimer->st_ref = SESSION_TIMER_REFRESHER_US;
23065                p->stimer->st_active_peer_ua = FALSE;
23066                start_session_timer(p);
23067             }
23068          }
23069       }
23070 
23071 
23072       /* If I understand this right, the branch is different for a non-200 ACK only */
23073       p->invitestate = INV_TERMINATED;
23074       ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
23075       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
23076       check_pendings(p);
23077       break;
23078 
23079    case 407: /* Proxy authentication */
23080    case 401: /* Www auth */
23081       /* First we ACK */
23082       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
23083       if (p->options) {
23084          p->options->auth_type = resp;
23085       }
23086 
23087       /* Then we AUTH */
23088       ast_string_field_set(p, theirtag, NULL);  /* forget their old tag, so we don't match tags when getting response */
23089       if (!req->ignore) {
23090          if (p->authtries < MAX_AUTHTRIES) {
23091             p->invitestate = INV_CALLING;
23092          }
23093          if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, SIP_INVITE, 1)) {
23094             ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", sip_get_header(&p->initreq, "From"));
23095             pvt_set_needdestroy(p, "failed to authenticate on INVITE");
23096             sip_alreadygone(p);
23097             if (p->owner) {
23098                ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
23099             }
23100          }
23101       }
23102       break;
23103 
23104    case 403: /* Forbidden */
23105       /* First we ACK */
23106       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
23107       ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", sip_get_header(&p->initreq, "From"));
23108       if (!req->ignore && p->owner) {
23109          sip_queue_hangup_cause(p, hangup_sip2cause(resp));
23110       }
23111       break;
23112 
23113    case 404: /* Not found */
23114       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
23115       if (p->owner && !req->ignore) {
23116          sip_queue_hangup_cause(p, hangup_sip2cause(resp));
23117       }
23118       break;
23119 
23120    case 481: /* Call leg does not exist */
23121       /* Could be REFER caused INVITE with replaces */
23122       ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
23123       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
23124       if (p->owner) {
23125          ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
23126       }
23127       break;
23128 
23129    case 422: /* Session-Timers: Session interval too small */
23130       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
23131       ast_string_field_set(p, theirtag, NULL);
23132       proc_422_rsp(p, req);
23133       break;
23134 
23135    case 428: /* Use identity header - rfc 4474 - not supported by Asterisk yet */
23136       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
23137       append_history(p, "Identity", "SIP identity is required. Not supported by Asterisk.");
23138       ast_log(LOG_WARNING, "SIP identity required by proxy. SIP dialog '%s'. Giving up.\n", p->callid);
23139       if (p->owner && !req->ignore) {
23140          ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
23141       }
23142       break;
23143 
23144    case 487: /* Cancelled transaction */
23145       /* We have sent CANCEL on an outbound INVITE
23146          This transaction is already scheduled to be killed by sip_hangup().
23147       */
23148       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
23149       if (p->owner && !req->ignore) {
23150          ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_CLEARING);
23151          append_history(p, "Hangup", "Got 487 on CANCEL request from us. Queued AST hangup request");
23152       } else if (!req->ignore) {
23153          update_call_counter(p, DEC_CALL_LIMIT);
23154          append_history(p, "Hangup", "Got 487 on CANCEL request from us on call without owner. Killing this dialog.");
23155       }
23156       check_pendings(p);
23157       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23158       break;
23159    case 415: /* Unsupported media type */
23160    case 488: /* Not acceptable here */
23161    case 606: /* Not Acceptable */
23162       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
23163       if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
23164          change_t38_state(p, T38_REJECTED);
23165          /* Try to reset RTP timers */
23166          /* XXX Why is this commented away??? */
23167          //ast_rtp_set_rtptimers_onhold(p->rtp);
23168 
23169          /* Trigger a reinvite back to audio */
23170          transmit_reinvite_with_sdp(p, FALSE, FALSE);
23171       } else {
23172          /* We can't set up this call, so give up */
23173          if (p->owner && !req->ignore) {
23174             ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
23175          }
23176       }
23177       break;
23178    case 491: /* Pending */
23179       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
23180       if (p->owner && !req->ignore) {
23181          if (ast_channel_state(p->owner) != AST_STATE_UP) {
23182             ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
23183          } else {
23184             /* This is a re-invite that failed. */
23185             /* Reset the flag after a while
23186              */
23187             int wait;
23188             /* RFC 3261, if owner of call, wait between 2.1 to 4 seconds,
23189              * if not owner of call, wait 0 to 2 seconds */
23190             if (p->outgoing_call) {
23191                wait = 2100 + ast_random() % 2000;
23192             } else {
23193                wait = ast_random() % 2000;
23194             }
23195             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."));
23196             ast_debug(2, "Reinvite race. Scheduled sip_reinvite_retry in %d secs in handle_response_invite (waitid %d, dialog '%s')\n",
23197                   wait, p->waitid, p->callid);
23198          }
23199       }
23200       break;
23201 
23202    case 408: /* Request timeout */
23203    case 405: /* Not allowed */
23204    case 501: /* Not implemented */
23205       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
23206       if (p->owner) {
23207          ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
23208       }
23209       break;
23210    }
23211    if (xmitres == XMIT_ERROR) {
23212       ast_log(LOG_WARNING, "Could not transmit message in dialog %s\n", p->callid);
23213    }
23214 }
23215 
23216 /* \brief Handle SIP response in NOTIFY transaction
23217        We've sent a NOTIFY, now handle responses to it
23218   */
23219 static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
23220 {
23221    switch (resp) {
23222    case 200:   /* Notify accepted */
23223       /* They got the notify, this is the end */
23224       if (p->owner) {
23225          if (p->refer) {
23226             ast_log(LOG_NOTICE, "Got OK on REFER Notify message\n");
23227          } else {
23228             ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", ast_channel_name(p->owner));
23229          }
23230       } else {
23231          if (p->subscribed == NONE && !p->refer) {
23232             ast_debug(4, "Got 200 accepted on NOTIFY %s\n", p->callid);
23233             pvt_set_needdestroy(p, "received 200 response");
23234          }
23235          if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
23236             struct state_notify_data data = {
23237                .state = p->laststate,
23238                .device_state_info = p->last_device_state_info,
23239                .presence_state = p->last_presence_state,
23240                .presence_subtype = p->last_presence_subtype,
23241                .presence_message = p->last_presence_message,
23242             };
23243             /* Ready to send the next state we have on queue */
23244             ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
23245             extensionstate_update(p->context, p->exten, &data, p, TRUE);
23246          }
23247       }
23248       break;
23249    case 401:   /* Not www-authorized on SIP method */
23250    case 407:   /* Proxy auth */
23251       if (!p->notify) {
23252          break; /* Only device notify can use NOTIFY auth */
23253       }
23254       ast_string_field_set(p, theirtag, NULL);
23255       if (ast_strlen_zero(p->authname)) {
23256          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));
23257          pvt_set_needdestroy(p, "unable to authenticate NOTIFY");
23258       }
23259       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_NOTIFY, 0)) {
23260          ast_log(LOG_NOTICE, "Failed to authenticate on NOTIFY to '%s'\n", sip_get_header(&p->initreq, "From"));
23261          pvt_set_needdestroy(p, "failed to authenticate NOTIFY");
23262       }
23263       break;
23264    case 481: /* Call leg does not exist */
23265       pvt_set_needdestroy(p, "Received 481 response for NOTIFY");
23266       break;
23267    }
23268 }
23269 
23270 /* \brief Handle SIP response in SUBSCRIBE transaction */
23271 static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
23272 {
23273    if (p->subscribed == CALL_COMPLETION) {
23274       struct sip_monitor_instance *monitor_instance;
23275 
23276       if (resp < 300) {
23277          return;
23278       }
23279 
23280       /* Final failure response received. */
23281       monitor_instance = ao2_callback(sip_monitor_instances, 0,
23282          find_sip_monitor_instance_by_subscription_pvt, p);
23283       if (monitor_instance) {
23284          ast_cc_monitor_failed(monitor_instance->core_id,
23285             monitor_instance->device_name,
23286             "Received error response to our SUBSCRIBE");
23287       }
23288       return;
23289    }
23290 
23291    if (p->subscribed != MWI_NOTIFICATION) {
23292       return;
23293    }
23294    if (!p->mwi) {
23295       return;
23296    }
23297 
23298    switch (resp) {
23299    case 200: /* Subscription accepted */
23300       ast_debug(3, "Got 200 OK on subscription for MWI\n");
23301       set_pvt_allowed_methods(p, req);
23302       if (p->options) {
23303          if (p->options->outboundproxy) {
23304             ao2_ref(p->options->outboundproxy, -1);
23305          }
23306          ast_free(p->options);
23307          p->options = NULL;
23308       }
23309       p->mwi->subscribed = 1;
23310       if ((p->mwi->resub = ast_sched_add(sched, mwi_expiry * 1000, sip_subscribe_mwi_do, ASTOBJ_REF(p->mwi))) < 0) {
23311          ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
23312       }
23313       break;
23314    case 401:
23315    case 407:
23316       ast_string_field_set(p, theirtag, NULL);
23317       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_SUBSCRIBE, 0)) {
23318          ast_log(LOG_NOTICE, "Failed to authenticate on SUBSCRIBE to '%s'\n", sip_get_header(&p->initreq, "From"));
23319          p->mwi->call = NULL;
23320          ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
23321          pvt_set_needdestroy(p, "failed to authenticate SUBSCRIBE");
23322       }
23323       break;
23324    case 403:
23325       transmit_response_with_date(p, "200 OK", req);
23326       ast_log(LOG_WARNING, "Authentication failed while trying to subscribe for MWI.\n");
23327       p->mwi->call = NULL;
23328       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
23329       pvt_set_needdestroy(p, "received 403 response");
23330       sip_alreadygone(p);
23331       break;
23332    case 404:
23333       ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that a mailbox may not have been configured.\n");
23334       p->mwi->call = NULL;
23335       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
23336       pvt_set_needdestroy(p, "received 404 response");
23337       break;
23338    case 481:
23339       ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that our dialog did not exist.\n");
23340       p->mwi->call = NULL;
23341       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
23342       pvt_set_needdestroy(p, "received 481 response");
23343       break;
23344    case 500:
23345    case 501:
23346       ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side may have suffered a heart attack.\n");
23347       p->mwi->call = NULL;
23348       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
23349       pvt_set_needdestroy(p, "received 500/501 response");
23350       break;
23351    }
23352 }
23353 
23354 /* \brief Handle SIP response in REFER transaction
23355    We've sent a REFER, now handle responses to it
23356   */
23357 static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
23358 {
23359    enum ast_control_transfer message = AST_TRANSFER_FAILED;
23360 
23361    /* If no refer structure exists, then do nothing */
23362    if (!p->refer)
23363       return;
23364 
23365    switch (resp) {
23366    case 202:   /* Transfer accepted */
23367       /* We need  to do something here */
23368       /* The transferee is now sending INVITE to target */
23369       p->refer->status = REFER_ACCEPTED;
23370       /* Now wait for next message */
23371       ast_debug(3, "Got 202 accepted on transfer\n");
23372       /* We should hang along, waiting for NOTIFY's here */
23373       break;
23374 
23375    case 401:   /* Not www-authorized on SIP method */
23376    case 407:   /* Proxy auth */
23377       if (ast_strlen_zero(p->authname)) {
23378          ast_log(LOG_WARNING, "Asked to authenticate REFER to %s but we have no matching peer or realm auth!\n",
23379             ast_sockaddr_stringify(&p->recv));
23380          if (p->owner) {
23381             ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
23382          }
23383          pvt_set_needdestroy(p, "unable to authenticate REFER");
23384       }
23385       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_REFER, 0)) {
23386          ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", sip_get_header(&p->initreq, "From"));
23387          p->refer->status = REFER_NOAUTH;
23388          if (p->owner) {
23389             ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
23390          }
23391          pvt_set_needdestroy(p, "failed to authenticate REFER");
23392       }
23393       break;
23394    
23395    case 405:   /* Method not allowed */
23396       /* Return to the current call onhold */
23397       /* Status flag needed to be reset */
23398       ast_log(LOG_NOTICE, "SIP transfer to %s failed, REFER not allowed. \n", p->refer->refer_to);
23399       pvt_set_needdestroy(p, "received 405 response");
23400       p->refer->status = REFER_FAILED;
23401       if (p->owner) {
23402          ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
23403       }
23404       break;
23405 
23406    case 481: /* Call leg does not exist */
23407 
23408       /* A transfer with Replaces did not work */
23409       /* OEJ: We should Set flag, cancel the REFER, go back
23410       to original call - but right now we can't */
23411       ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
23412       if (p->owner)
23413          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
23414       pvt_set_needdestroy(p, "received 481 response");
23415       break;
23416 
23417    case 500:   /* Server error */
23418    case 501:   /* Method not implemented */
23419       /* Return to the current call onhold */
23420       /* Status flag needed to be reset */
23421       ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
23422       pvt_set_needdestroy(p, "received 500/501 response");
23423       p->refer->status = REFER_FAILED;
23424       if (p->owner) {
23425          ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
23426       }
23427       break;
23428    case 603:   /* Transfer declined */
23429       ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
23430       p->refer->status = REFER_FAILED;
23431       pvt_set_needdestroy(p, "received 603 response");
23432       if (p->owner) {
23433          ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
23434       }
23435       break;
23436    default:
23437       /* We should treat unrecognized 9xx as 900.  400 is actually
23438          specified as a possible response, but any 4-6xx is 
23439          theoretically possible. */
23440 
23441       if (resp < 299) { /* 1xx cases don't get here */
23442          ast_log(LOG_WARNING, "SIP transfer to %s had unxpected 2xx response (%d), confusion is possible. \n", p->refer->refer_to, resp);
23443       } else {
23444          ast_log(LOG_WARNING, "SIP transfer to %s with response (%d). \n", p->refer->refer_to, resp);
23445       }
23446 
23447       p->refer->status = REFER_FAILED;
23448       pvt_set_needdestroy(p, "received failure response");
23449       if (p->owner) {
23450          ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
23451       }
23452       break;
23453    }
23454 }
23455 
23456 /*! \brief Handle responses on REGISTER to services */
23457 static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
23458 {
23459    int expires, expires_ms;
23460    struct sip_registry *r;
23461    r=p->registry;
23462    
23463    switch (resp) {
23464    case 401:   /* Unauthorized */
23465       if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
23466          ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
23467          pvt_set_needdestroy(p, "failed to authenticate REGISTER");
23468       }
23469       break;
23470    case 403:   /* Forbidden */
23471       if (global_reg_retry_403) {
23472          ast_log(LOG_NOTICE, "Treating 403 response to REGISTER as non-fatal for %s@%s\n",
23473             p->registry->username, p->registry->hostname);
23474          ast_string_field_set(r, nonce, "");
23475          ast_string_field_set(p, nonce, "");
23476          break;
23477       }
23478       ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
23479       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 403"));
23480       r->regstate = REG_STATE_NOAUTH;
23481       pvt_set_needdestroy(p, "received 403 response");
23482       break;
23483    case 404:   /* Not found */
23484       ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username, p->registry->hostname);
23485       pvt_set_needdestroy(p, "received 404 response");
23486       if (r->call)
23487          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 404");
23488       r->regstate = REG_STATE_REJECTED;
23489       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 404"));
23490       break;
23491    case 407:   /* Proxy auth */
23492       if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
23493          ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", sip_get_header(&p->initreq, "From"), p->authtries);
23494          pvt_set_needdestroy(p, "failed to authenticate REGISTER");
23495       }
23496       break;
23497    case 408:   /* Request timeout */
23498       /* Got a timeout response, so reset the counter of failed responses */
23499       if (r) {
23500          r->regattempts = 0;
23501       } else {
23502          ast_log(LOG_WARNING, "Got a 408 response to our REGISTER on call %s after we had destroyed the registry object\n", p->callid);
23503       }
23504       break;
23505    case 423:   /* Interval too brief */
23506       r->expiry = atoi(sip_get_header(req, "Min-Expires"));
23507       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);
23508       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 423"));
23509       if (r->call) {
23510          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 423");
23511          pvt_set_needdestroy(p, "received 423 response");
23512       }
23513       if (r->expiry > max_expiry) {
23514          ast_log(LOG_WARNING, "Required expiration time from %s@%s is too high, giving up\n", p->registry->username, p->registry->hostname);
23515          r->expiry = r->configured_expiry;
23516          r->regstate = REG_STATE_REJECTED;
23517       } else {
23518          r->regstate = REG_STATE_UNREGISTERED;
23519          transmit_register(r, SIP_REGISTER, NULL, NULL);
23520       }
23521       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));
23522       break;
23523    case 479:   /* SER: Not able to process the URI - address is wrong in register*/
23524       ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username, p->registry->hostname);
23525       pvt_set_needdestroy(p, "received 479 response");
23526       if (r->call)
23527          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 479");
23528       r->regstate = REG_STATE_REJECTED;
23529       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 479"));
23530       break;
23531    case 200:   /* 200 OK */
23532       if (!r) {
23533          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));
23534          pvt_set_needdestroy(p, "received erroneous 200 response");
23535          return 0;
23536       }
23537 
23538       r->regstate = REG_STATE_REGISTERED;
23539       r->regtime = ast_tvnow();     /* Reset time of last successful registration */
23540       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));
23541       r->regattempts = 0;
23542       ast_debug(1, "Registration successful\n");
23543       if (r->timeout > -1) {
23544          ast_debug(1, "Cancelling timeout %d\n", r->timeout);
23545       }
23546       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 200"));
23547       if (r->call)
23548          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 200");
23549       p->registry = registry_unref(p->registry, "unref registry entry p->registry");
23550 
23551       /* destroy dialog now to avoid interference with next register */
23552       pvt_set_needdestroy(p, "Registration successfull");
23553 
23554       /* set us up for re-registering
23555        * figure out how long we got registered for
23556        * according to section 6.13 of RFC, contact headers override
23557        * expires headers, so check those first */
23558       expires = 0;
23559 
23560       /* XXX todo: try to save the extra call */
23561       if (!ast_strlen_zero(sip_get_header(req, "Contact"))) {
23562          const char *contact = NULL;
23563          const char *tmptmp = NULL;
23564          int start = 0;
23565          for(;;) {
23566             contact = __get_header(req, "Contact", &start);
23567             /* this loop ensures we get a contact header about our register request */
23568             if(!ast_strlen_zero(contact)) {
23569                if( (tmptmp=strstr(contact, p->our_contact))) {
23570                   contact=tmptmp;
23571                   break;
23572                }
23573             } else
23574                break;
23575          }
23576          tmptmp = strcasestr(contact, "expires=");
23577          if (tmptmp) {
23578             if (sscanf(tmptmp + 8, "%30d", &expires) != 1) {
23579                expires = 0;
23580             }
23581          }
23582          
23583       }
23584       if (!expires)
23585          expires=atoi(sip_get_header(req, "expires"));
23586       if (!expires)
23587          expires=default_expiry;
23588       
23589       expires_ms = expires * 1000;
23590       if (expires <= EXPIRY_GUARD_LIMIT)
23591          expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT), EXPIRY_GUARD_MIN);
23592       else
23593          expires_ms -= EXPIRY_GUARD_SECS * 1000;
23594       if (sipdebug)
23595          ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000);
23596       
23597       r->refresh= (int) expires_ms / 1000;
23598       
23599       /* Schedule re-registration before we expire */
23600       AST_SCHED_REPLACE_UNREF(r->expire, sched, expires_ms, sip_reregister, r,
23601                         registry_unref(_data,"unref in REPLACE del fail"),
23602                         registry_unref(r,"unref in REPLACE add fail"),
23603                         registry_addref(r,"The Addition side of REPLACE"));
23604    }
23605    return 1;
23606 }
23607 
23608 /*! \brief Handle qualification responses (OPTIONS) */
23609 static void handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
23610 {
23611    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! */
23612    int statechanged, is_reachable, was_reachable;
23613    int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);
23614 
23615    /*
23616     * Compute the response time to a ping (goes in peer->lastms.)
23617     * -1 means did not respond, 0 means unknown,
23618     * 1..maxms is a valid response, >maxms means late response.
23619     */
23620    if (pingtime < 1) {  /* zero = unknown, so round up to 1 */
23621       pingtime = 1;
23622    }
23623 
23624    if (!peer->maxms) { /* this should never happens */
23625       pvt_set_needdestroy(p, "got OPTIONS response but qualify is not enabled");
23626       return;
23627    }
23628 
23629    /* Now determine new state and whether it has changed.
23630     * Use some helper variables to simplify the writing
23631     * of the expressions.
23632     */
23633    was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
23634    is_reachable = pingtime <= peer->maxms;
23635    statechanged = peer->lastms == 0 /* yes, unknown before */
23636       || was_reachable != is_reachable;
23637 
23638    peer->lastms = pingtime;
23639    peer->call = dialog_unref(peer->call, "unref dialog peer->call");
23640    if (statechanged) {
23641       const char *s = is_reachable ? "Reachable" : "Lagged";
23642       char str_lastms[20];
23643       snprintf(str_lastms, sizeof(str_lastms), "%d", pingtime);
23644 
23645       ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
23646          peer->name, s, pingtime, peer->maxms);
23647       ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", peer->name);
23648       if (sip_cfg.peer_rtupdate) {
23649          ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", str_lastms, SENTINEL);
23650       }
23651       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
23652          "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
23653          peer->name, s, pingtime);
23654       if (is_reachable && sip_cfg.regextenonqualify)
23655          register_peer_exten(peer, TRUE);
23656    }
23657 
23658    pvt_set_needdestroy(p, "got OPTIONS response");
23659 
23660    /* Try again eventually */
23661    AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
23662          is_reachable ? peer->qualifyfreq : DEFAULT_FREQ_NOTOK,
23663          sip_poke_peer_s, peer,
23664          sip_unref_peer(_data, "removing poke peer ref"),
23665          sip_unref_peer(peer, "removing poke peer ref"),
23666          sip_ref_peer(peer, "adding poke peer ref"));
23667 }
23668 
23669 /*!
23670  * \internal
23671  * \brief Handle responses to INFO messages
23672  *
23673  * \note The INFO method MUST NOT change the state of calls or
23674  * related sessions (RFC 2976).
23675  */
23676 static void handle_response_info(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
23677 {
23678    int sipmethod = SIP_INFO;
23679 
23680    switch (resp) {
23681    case 401: /* Not www-authorized on SIP method */
23682    case 407: /* Proxy auth required */
23683       ast_log(LOG_WARNING, "Host '%s' requests authentication (%d) for '%s'\n",
23684          ast_sockaddr_stringify(&p->sa), resp, sip_methods[sipmethod].text);
23685       break;
23686    case 405: /* Method not allowed */
23687    case 501: /* Not Implemented */
23688       mark_method_unallowed(&p->allowed_methods, sipmethod);
23689       if (p->relatedpeer) {
23690          mark_method_allowed(&p->relatedpeer->disallowed_methods, sipmethod);
23691       }
23692       ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n",
23693          ast_sockaddr_stringify(&p->sa), sip_methods[sipmethod].text);
23694       break;
23695    default:
23696       if (300 <= resp && resp < 700) {
23697          ast_verb(3, "Got SIP %s response %d \"%s\" back from host '%s'\n",
23698             sip_methods[sipmethod].text, resp, rest, ast_sockaddr_stringify(&p->sa));
23699       }
23700       break;
23701    }
23702 }
23703 
23704 /*!
23705  * \internal
23706  * \brief Handle auth requests to a MESSAGE request
23707  * \return TRUE if authentication failed.
23708  */
23709 static int do_message_auth(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
23710 {
23711    char *header;
23712    char *respheader;
23713    char digest[1024];
23714 
23715    if (p->options) {
23716       p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
23717    }
23718 
23719    if (p->authtries == MAX_AUTHTRIES) {
23720       ast_log(LOG_NOTICE, "Failed to authenticate MESSAGE with host '%s'\n",
23721          ast_sockaddr_stringify(&p->sa));
23722       return -1;
23723    }
23724 
23725    ++p->authtries;
23726    sip_auth_headers((resp == 401 ? WWW_AUTH : PROXY_AUTH), &header, &respheader);
23727    memset(digest, 0, sizeof(digest));
23728    if (reply_digest(p, req, header, SIP_MESSAGE, digest, sizeof(digest))) {
23729       /* There's nothing to use for authentication */
23730       ast_debug(1, "Nothing to use for MESSAGE authentication\n");
23731       return -1;
23732    }
23733 
23734    if (p->do_history) {
23735       append_history(p, "MessageAuth", "Try: %d", p->authtries);
23736    }
23737 
23738    transmit_message(p, 0, 1);
23739    return 0;
23740 }
23741 
23742 /*!
23743  * \internal
23744  * \brief Handle responses to MESSAGE messages
23745  *
23746  * \note The MESSAGE method should not change the state of calls
23747  * or related sessions if associated with a dialog. (Implied by
23748  * RFC 3428 Section 2).
23749  */
23750 static void handle_response_message(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
23751 {
23752    int sipmethod = SIP_MESSAGE;
23753    int in_dialog = ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
23754 
23755    switch (resp) {
23756    case 401: /* Not www-authorized on SIP method */
23757    case 407: /* Proxy auth required */
23758       if (do_message_auth(p, resp, rest, req, seqno) && !in_dialog) {
23759          pvt_set_needdestroy(p, "MESSAGE authentication failed");
23760       }
23761       break;
23762    case 405: /* Method not allowed */
23763    case 501: /* Not Implemented */
23764       mark_method_unallowed(&p->allowed_methods, sipmethod);
23765       if (p->relatedpeer) {
23766          mark_method_allowed(&p->relatedpeer->disallowed_methods, sipmethod);
23767       }
23768       ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n",
23769          ast_sockaddr_stringify(&p->sa), sip_methods[sipmethod].text);
23770       if (!in_dialog) {
23771          pvt_set_needdestroy(p, "MESSAGE not implemented or allowed");
23772       }
23773       break;
23774    default:
23775       if (100 <= resp && resp < 200) {
23776          /* Must allow provisional responses for out-of-dialog requests. */
23777       } else if (200 <= resp && resp < 300) {
23778          p->authtries = 0; /* Reset authentication counter */
23779          if (!in_dialog) {
23780             pvt_set_needdestroy(p, "MESSAGE delivery accepted");
23781          }
23782       } else if (300 <= resp && resp < 700) {
23783          ast_verb(3, "Got SIP %s response %d \"%s\" back from host '%s'\n",
23784             sip_methods[sipmethod].text, resp, rest, ast_sockaddr_stringify(&p->sa));
23785          if (!in_dialog) {
23786             pvt_set_needdestroy(p, (300 <= resp && resp < 600)
23787                ? "MESSAGE delivery failed" : "MESSAGE delivery refused");
23788          }
23789       }
23790       break;
23791    }
23792 }
23793 
23794 /*! \brief Immediately stop RTP, VRTP and UDPTL as applicable */
23795 static void stop_media_flows(struct sip_pvt *p)
23796 {
23797    /* Immediately stop RTP, VRTP and UDPTL as applicable */
23798    if (p->rtp)
23799       ast_rtp_instance_stop(p->rtp);
23800    if (p->vrtp)
23801       ast_rtp_instance_stop(p->vrtp);
23802    if (p->trtp)
23803       ast_rtp_instance_stop(p->trtp);
23804    if (p->udptl)
23805       ast_udptl_stop(p->udptl);
23806 }
23807 
23808 /*! \brief Handle SIP response in dialogue
23809    \note only called by handle_incoming */
23810 static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
23811 {
23812    struct ast_channel *owner;
23813    int sipmethod;
23814    const char *c = sip_get_header(req, "Cseq");
23815    /* 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 */
23816    char *c_copy = ast_strdupa(c);
23817    /* Skip the Cseq and its subsequent spaces */
23818    const char *msg = ast_skip_blanks(ast_skip_nonblanks(c_copy));
23819 
23820    if (!msg)
23821       msg = "";
23822 
23823    sipmethod = find_sip_method(msg);
23824 
23825    owner = p->owner;
23826    if (owner) {
23827       const char *rp = NULL, *rh = NULL;
23828 
23829       ast_channel_hangupcause_set(owner, 0);
23830       if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON) && (rh = sip_get_header(req, "Reason"))) {
23831          rh = ast_skip_blanks(rh);
23832          if (!strncasecmp(rh, "Q.850", 5)) {
23833             int cause = ast_channel_hangupcause(owner);
23834             rp = strstr(rh, "cause=");
23835             if (rp && sscanf(rp + 6, "%30d", &cause) == 1) {
23836                ast_channel_hangupcause_set(owner, cause & 0x7f);
23837                if (req->debug)
23838                   ast_verbose("Using Reason header for cause code: %d\n", ast_channel_hangupcause(owner));
23839             }
23840          }
23841       }
23842 
23843       if (!ast_channel_hangupcause(owner))
23844          ast_channel_hangupcause_set(owner, hangup_sip2cause(resp));
23845    }
23846 
23847    if (p->socket.type == SIP_TRANSPORT_UDP) {
23848       int ack_res = FALSE;
23849 
23850       /* Acknowledge whatever it is destined for */
23851       if ((resp >= 100) && (resp <= 199)) {
23852          /* NON-INVITE messages do not ack a 1XX response. RFC 3261 section 17.1.2.2 */
23853          if (sipmethod == SIP_INVITE) {
23854             ack_res = __sip_semi_ack(p, seqno, 0, sipmethod);
23855          }
23856       } else {
23857          ack_res = __sip_ack(p, seqno, 0, sipmethod);
23858       }
23859 
23860       if (ack_res == FALSE) {
23861          /* RFC 3261 13.2.2.4 and 17.1.1.2 - We must re-send ACKs to re-transmitted final responses */
23862          if (sipmethod == SIP_INVITE && resp >= 200) {
23863             transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, resp < 300 ? TRUE: FALSE);
23864          }
23865 
23866          append_history(p, "Ignore", "Ignoring this retransmit\n");
23867          return;
23868       }
23869    }
23870 
23871    /* If this is a NOTIFY for a subscription clear the flag that indicates that we have a NOTIFY pending */
23872    if (!p->owner && sipmethod == SIP_NOTIFY && p->pendinginvite) {
23873       p->pendinginvite = 0;
23874    }
23875 
23876    /* Get their tag if we haven't already */
23877    if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
23878       char tag[128];
23879 
23880       gettag(req, "To", tag, sizeof(tag));
23881       ast_string_field_set(p, theirtag, tag);
23882    } else {
23883       /* Store theirtag to track for changes when 200 responses to invites are received without SDP */
23884       ast_string_field_set(p, theirprovtag, p->theirtag);
23885    }
23886 
23887    /* This needs to be configurable on a channel/peer level,
23888       not mandatory for all communication. Sadly enough, NAT implementations
23889       are not so stable so we can always rely on these headers.
23890       Temporarily disabled, while waiting for fix.
23891       Fix assigned to Rizzo :-)
23892    */
23893    /* check_via_response(p, req); */
23894 
23895    /* RFC 3261 Section 15 specifies that if we receive a 408 or 481
23896     * in response to a BYE, then we should end the current dialog
23897     * and session.  It is known that at least one phone manufacturer
23898     * potentially will send a 404 in response to a BYE, so we'll be
23899     * liberal in what we accept and end the dialog and session if we
23900     * receive any of those responses to a BYE.
23901     */
23902    if ((resp == 404 || resp == 408 || resp == 481) && sipmethod == SIP_BYE) {
23903       pvt_set_needdestroy(p, "received 4XX response to a BYE");
23904       return;
23905    }
23906 
23907    if (p->relatedpeer && sipmethod == SIP_OPTIONS) {
23908       /* We don't really care what the response is, just that it replied back.
23909          Well, as long as it's not a 100 response...  since we might
23910          need to hang around for something more "definitive" */
23911       if (resp != 100)
23912          handle_response_peerpoke(p, resp, req);
23913    } else if (sipmethod == SIP_REFER && resp >= 200) {
23914       handle_response_refer(p, resp, rest, req, seqno);
23915    } else if (sipmethod == SIP_PUBLISH) {
23916       /* SIP PUBLISH transcends this morass of doodoo and instead
23917        * we just always call the response handler. Good gravy!
23918        */
23919       handle_response_publish(p, resp, rest, req, seqno);
23920    } else if (sipmethod == SIP_INFO) {
23921       /* More good gravy! */
23922       handle_response_info(p, resp, rest, req, seqno);
23923    } else if (sipmethod == SIP_MESSAGE) {
23924       /* More good gravy! */
23925       handle_response_message(p, resp, rest, req, seqno);
23926    } else if (sipmethod == SIP_NOTIFY) {
23927       /* The gravy train continues to roll */
23928       handle_response_notify(p, resp, rest, req, seqno);
23929    } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
23930       switch(resp) {
23931       case 100:   /* 100 Trying */
23932       case 101:   /* 101 Dialog establishment */
23933       case 183:   /* 183 Session Progress */
23934       case 180:   /* 180 Ringing */
23935       case 182:   /* 182 Queued */
23936       case 181:   /* 181 Call Is Being Forwarded */
23937          if (sipmethod == SIP_INVITE)
23938             handle_response_invite(p, resp, rest, req, seqno);
23939          break;
23940       case 200:   /* 200 OK */
23941          p->authtries = 0; /* Reset authentication counter */
23942          if (sipmethod == SIP_INVITE) {
23943             handle_response_invite(p, resp, rest, req, seqno);
23944          } else if (sipmethod == SIP_REGISTER) {
23945             handle_response_register(p, resp, rest, req, seqno);
23946          } else if (sipmethod == SIP_SUBSCRIBE) {
23947             ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
23948             handle_response_subscribe(p, resp, rest, req, seqno);
23949          } else if (sipmethod == SIP_BYE) {     /* Ok, we're ready to go */
23950             pvt_set_needdestroy(p, "received 200 response");
23951             ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
23952          }
23953          break;
23954       case 401: /* Not www-authorized on SIP method */
23955       case 407: /* Proxy auth required */
23956          if (sipmethod == SIP_INVITE)
23957             handle_response_invite(p, resp, rest, req, seqno);
23958          else if (sipmethod == SIP_SUBSCRIBE)
23959             handle_response_subscribe(p, resp, rest, req, seqno);
23960          else if (p->registry && sipmethod == SIP_REGISTER)
23961             handle_response_register(p, resp, rest, req, seqno);
23962          else if (sipmethod == SIP_UPDATE) {
23963             handle_response_update(p, resp, rest, req, seqno);
23964          } else if (sipmethod == SIP_BYE) {
23965             if (p->options)
23966                p->options->auth_type = resp;
23967             if (ast_strlen_zero(p->authname)) {
23968                ast_log(LOG_WARNING, "Asked to authenticate %s, to %s but we have no matching peer!\n",
23969                      msg, ast_sockaddr_stringify(&p->recv));
23970                pvt_set_needdestroy(p, "unable to authenticate BYE");
23971             } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp,  sipmethod, 0)) {
23972                ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, sip_get_header(&p->initreq, "From"));
23973                pvt_set_needdestroy(p, "failed to authenticate BYE");
23974             }
23975          } else {
23976             ast_log(LOG_WARNING, "Got authentication request (%d) on %s to '%s'\n", resp, sip_methods[sipmethod].text, sip_get_header(req, "To"));
23977             pvt_set_needdestroy(p, "received 407 response");
23978          }
23979          break;
23980       case 403: /* Forbidden - we failed authentication */
23981          if (sipmethod == SIP_INVITE)
23982             handle_response_invite(p, resp, rest, req, seqno);
23983          else if (sipmethod == SIP_SUBSCRIBE)
23984             handle_response_subscribe(p, resp, rest, req, seqno);
23985          else if (p->registry && sipmethod == SIP_REGISTER)
23986             handle_response_register(p, resp, rest, req, seqno);
23987          else {
23988             ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
23989             pvt_set_needdestroy(p, "received 403 response");
23990          }
23991          break;
23992       case 404: /* Not found */
23993          if (p->registry && sipmethod == SIP_REGISTER)
23994             handle_response_register(p, resp, rest, req, seqno);
23995          else if (sipmethod == SIP_INVITE)
23996             handle_response_invite(p, resp, rest, req, seqno);
23997          else if (sipmethod == SIP_SUBSCRIBE)
23998             handle_response_subscribe(p, resp, rest, req, seqno);
23999          else if (owner)
24000             ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
24001          break;
24002       case 423: /* Interval too brief */
24003          if (sipmethod == SIP_REGISTER)
24004             handle_response_register(p, resp, rest, req, seqno);
24005          break;
24006       case 408: /* Request timeout - terminate dialog */
24007          if (sipmethod == SIP_INVITE)
24008             handle_response_invite(p, resp, rest, req, seqno);
24009          else if (sipmethod == SIP_REGISTER)
24010             handle_response_register(p, resp, rest, req, seqno);
24011          else if (sipmethod == SIP_BYE) {
24012             pvt_set_needdestroy(p, "received 408 response");
24013             ast_debug(4, "Got timeout on bye. Thanks for the answer. Now, kill this call\n");
24014          } else {
24015             if (owner)
24016                ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
24017             pvt_set_needdestroy(p, "received 408 response");
24018          }
24019          break;
24020 
24021       case 428:
24022       case 422: /* Session-Timers: Session Interval Too Small */
24023          if (sipmethod == SIP_INVITE) {
24024             handle_response_invite(p, resp, rest, req, seqno);
24025          }
24026          break;
24027 
24028       case 481: /* Call leg does not exist */
24029          if (sipmethod == SIP_INVITE) {
24030             handle_response_invite(p, resp, rest, req, seqno);
24031          } else if (sipmethod == SIP_SUBSCRIBE) {
24032             handle_response_subscribe(p, resp, rest, req, seqno);
24033          } else if (sipmethod == SIP_BYE) {
24034             /* The other side has no transaction to bye,
24035             just assume it's all right then */
24036             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
24037          } else if (sipmethod == SIP_CANCEL) {
24038             /* The other side has no transaction to cancel,
24039             just assume it's all right then */
24040             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
24041          } else {
24042             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
24043             /* Guessing that this is not an important request */
24044          }
24045          break;
24046       case 487:
24047          if (sipmethod == SIP_INVITE)
24048             handle_response_invite(p, resp, rest, req, seqno);
24049          break;
24050       case 415: /* Unsupported media type */
24051       case 488: /* Not acceptable here - codec error */
24052       case 606: /* Not Acceptable */
24053          if (sipmethod == SIP_INVITE)
24054             handle_response_invite(p, resp, rest, req, seqno);
24055          break;
24056       case 491: /* Pending */
24057          if (sipmethod == SIP_INVITE)
24058             handle_response_invite(p, resp, rest, req, seqno);
24059          else {
24060             ast_debug(1, "Got 491 on %s, unsupported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
24061             pvt_set_needdestroy(p, "received 491 response");
24062          }
24063          break;
24064       case 405: /* Method not allowed */
24065       case 501: /* Not Implemented */
24066          mark_method_unallowed(&p->allowed_methods, sipmethod);
24067          if (p->relatedpeer) {
24068             mark_method_allowed(&p->relatedpeer->disallowed_methods, sipmethod);
24069          }
24070          if (sipmethod == SIP_INVITE)
24071             handle_response_invite(p, resp, rest, req, seqno);
24072          else
24073             ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_sockaddr_stringify(&p->sa), msg);
24074          break;
24075       default:
24076          if ((resp >= 200) && (resp < 300)) { /* on any 2XX response do the following */
24077             if (sipmethod == SIP_INVITE) {
24078                handle_response_invite(p, resp, rest, req, seqno);
24079             }
24080          } else if ((resp >= 300) && (resp < 700)) {
24081             /* Fatal response */
24082             if ((resp != 487))
24083                ast_verb(3, "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_sockaddr_stringify(&p->sa));
24084    
24085             if (sipmethod == SIP_INVITE)
24086                stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
24087 
24088             /* XXX Locking issues?? XXX */
24089             switch(resp) {
24090             case 300: /* Multiple Choices */
24091             case 301: /* Moved permanently */
24092             case 302: /* Moved temporarily */
24093             case 305: /* Use Proxy */
24094                if (p->owner) {
24095                   struct ast_party_redirecting redirecting;
24096                   struct ast_set_party_redirecting update_redirecting;
24097 
24098                   ast_party_redirecting_init(&redirecting);
24099                   memset(&update_redirecting, 0, sizeof(update_redirecting));
24100                   change_redirecting_information(p, req, &redirecting,
24101                      &update_redirecting, TRUE);
24102                   ast_channel_set_redirecting(p->owner, &redirecting,
24103                      &update_redirecting);
24104                   ast_party_redirecting_free(&redirecting);
24105                }
24106                /* Fall through */
24107             case 486: /* Busy here */
24108             case 600: /* Busy everywhere */
24109             case 603: /* Decline */
24110                if (p->owner) {
24111                   sip_handle_cc(p, req, AST_CC_CCBS);
24112                   ast_queue_control(p->owner, AST_CONTROL_BUSY);
24113                }
24114                break;
24115             case 482: /* Loop Detected */
24116             case 480: /* Temporarily Unavailable */
24117             case 404: /* Not Found */
24118             case 410: /* Gone */
24119             case 400: /* Bad Request */
24120             case 500: /* Server error */
24121                if (sipmethod == SIP_SUBSCRIBE) {
24122                   handle_response_subscribe(p, resp, rest, req, seqno);
24123                   break;
24124                }
24125                /* Fall through */
24126             case 502: /* Bad gateway */
24127             case 503: /* Service Unavailable */
24128             case 504: /* Server Timeout */
24129                if (owner)
24130                   ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
24131                break;
24132             case 484: /* Address Incomplete */
24133                if (owner && sipmethod != SIP_BYE) {
24134                   switch (ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)) {
24135                   case SIP_PAGE2_ALLOWOVERLAP_YES:
24136                      ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
24137                      break;
24138                   default:
24139                      ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(404));
24140                      break;
24141                   }
24142                }
24143                break;
24144             default:
24145                /* Send hangup */ 
24146                if (owner && sipmethod != SIP_BYE)
24147                   ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
24148                break;
24149             }
24150             /* ACK on invite */
24151             if (sipmethod == SIP_INVITE)
24152                transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
24153             sip_alreadygone(p);
24154             if (!p->owner) {
24155                pvt_set_needdestroy(p, "transaction completed");
24156             }
24157          } else if ((resp >= 100) && (resp < 200)) {
24158             if (sipmethod == SIP_INVITE) {
24159                if (!req->ignore && sip_cancel_destroy(p))
24160                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
24161                if (find_sdp(req))
24162                   process_sdp(p, req, SDP_T38_NONE);
24163                if (p->owner) {
24164                   /* Queue a progress frame */
24165                   ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
24166                }
24167             }
24168          } else
24169             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));
24170       }
24171    } else { 
24172       /* Responses to OUTGOING SIP requests on INCOMING calls
24173          get handled here. As well as out-of-call message responses */
24174       if (req->debug)
24175          ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
24176 
24177       if (sipmethod == SIP_INVITE && resp == 200) {
24178          /* Tags in early session is replaced by the tag in 200 OK, which is
24179          the final reply to our INVITE */
24180          char tag[128];
24181 
24182          gettag(req, "To", tag, sizeof(tag));
24183          ast_string_field_set(p, theirtag, tag);
24184       }
24185 
24186       switch(resp) {
24187       case 200:
24188          if (sipmethod == SIP_INVITE) {
24189             handle_response_invite(p, resp, rest, req, seqno);
24190          } else if (sipmethod == SIP_CANCEL) {
24191             ast_debug(1, "Got 200 OK on CANCEL\n");
24192 
24193             /* Wait for 487, then destroy */
24194          } else if (sipmethod == SIP_BYE) {
24195             pvt_set_needdestroy(p, "transaction completed");
24196          }
24197          break;
24198       case 401:   /* www-auth */
24199       case 407:
24200          if (sipmethod == SIP_INVITE)
24201             handle_response_invite(p, resp, rest, req, seqno);
24202          else if (sipmethod == SIP_BYE) {
24203             if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, sipmethod, 0)) {
24204                ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, sip_get_header(&p->initreq, "From"));
24205                pvt_set_needdestroy(p, "failed to authenticate BYE");
24206             }
24207          }
24208          break;
24209       case 481:   /* Call leg does not exist */
24210          if (sipmethod == SIP_INVITE) {
24211             /* Re-invite failed */
24212             handle_response_invite(p, resp, rest, req, seqno);
24213          } else if (sipmethod == SIP_BYE) {
24214             pvt_set_needdestroy(p, "received 481 response");
24215          } else if (sipdebug) {
24216             ast_debug(1, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
24217          }
24218          break;
24219       case 501: /* Not Implemented */
24220          if (sipmethod == SIP_INVITE)
24221             handle_response_invite(p, resp, rest, req, seqno);
24222          break;
24223       default: /* Errors without handlers */
24224          if ((resp >= 100) && (resp < 200)) {
24225             if (sipmethod == SIP_INVITE) {   /* re-invite */
24226                if (!req->ignore && sip_cancel_destroy(p))
24227                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
24228             }
24229          } else if ((resp >= 200) && (resp < 300)) { /* on any unrecognized 2XX response do the following */
24230             if (sipmethod == SIP_INVITE) {
24231                handle_response_invite(p, resp, rest, req, seqno);
24232             }
24233          } else if ((resp >= 300) && (resp < 700)) {
24234             if ((resp != 487))
24235                ast_verb(3, "Incoming call: Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_sockaddr_stringify(&p->sa));
24236             switch(resp) {
24237             case 415: /* Unsupported media type */
24238             case 488: /* Not acceptable here - codec error */
24239             case 603: /* Decline */
24240             case 500: /* Server error */
24241             case 502: /* Bad gateway */
24242             case 503: /* Service Unavailable */
24243             case 504: /* Server timeout */
24244 
24245                /* re-invite failed */
24246                if (sipmethod == SIP_INVITE && sip_cancel_destroy(p))
24247                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
24248                break;
24249             }
24250          }
24251          break;
24252       }
24253    }
24254 }
24255 
24256 
24257 /*! \brief Park SIP call support function
24258    Starts in a new thread, then parks the call
24259    XXX Should we add a wait period after streaming audio and before hangup?? Sometimes the
24260       audio can't be heard before hangup
24261 */
24262 static void *sip_park_thread(void *stuff)
24263 {
24264    struct ast_channel *transferee, *transferer; /* Chan1: The transferee, Chan2: The transferer */
24265    struct sip_pvt *transferer_pvt;
24266    struct sip_dual *d;
24267    int ext;
24268    int res;
24269 
24270    d = stuff;
24271    transferee = d->chan1;
24272    transferer = d->chan2;
24273    transferer_pvt = ast_channel_tech_pvt(transferer);
24274 
24275    ast_debug(4, "SIP Park: Transferer channel %s, Transferee %s\n", ast_channel_name(transferer), ast_channel_name(transferee));
24276 
24277    res = ast_park_call_exten(transferee, transferer, d->park_exten, d->park_context, 0, &ext);
24278 
24279    sip_pvt_lock(transferer_pvt);
24280 #ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
24281    if (res) {
24282       destroy_msg_headers(transferer_pvt);
24283       ast_string_field_set(transferer_pvt, msg_body, "Unable to park call.");
24284       transmit_message(transferer_pvt, 0, 0);
24285    } else {
24286       /* Then tell the transferer what happened */
24287       destroy_msg_headers(transferer_pvt);
24288       sprintf(buf, "Call parked on extension '%d'.", ext);
24289       ast_string_field_set(transferer_pvt, msg_body, buf);
24290       transmit_message(transferer_pvt, 0, 0);
24291    }
24292 #endif
24293 
24294    /* Any way back to the current call??? */
24295    /* Transmit response to the REFER request */
24296    ast_set_flag(&transferer_pvt->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
24297    if (!res)   {
24298       /* Transfer succeeded */
24299       append_history(transferer_pvt, "SIPpark", "Parked call on %d", ext);
24300       transmit_notify_with_sipfrag(transferer_pvt, d->seqno, "200 OK", TRUE);
24301       sip_pvt_unlock(transferer_pvt);
24302       ast_channel_hangupcause_set(transferer, AST_CAUSE_NORMAL_CLEARING);
24303       ast_debug(1, "SIP Call parked on extension '%d'\n", ext);
24304    } else {
24305       transmit_notify_with_sipfrag(transferer_pvt, d->seqno, "503 Service Unavailable", TRUE);
24306       append_history(transferer_pvt, "SIPpark", "Parking failed\n");
24307       sip_pvt_unlock(transferer_pvt);
24308       ast_log(AST_LOG_NOTICE, "SIP Call parked failed for %s\n", ast_channel_name(transferee));
24309       ast_hangup(transferee);
24310    }
24311    ast_hangup(transferer);
24312 
24313    deinit_req(&d->req);
24314    ast_free(d->park_exten);
24315    ast_free(d->park_context);
24316    ast_free(d);
24317    return NULL;
24318 }
24319 
24320 /*! DO NOT hold any locks while calling sip_park */
24321 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)
24322 {
24323    struct sip_dual *d;
24324    struct ast_channel *transferee, *transferer;
24325    pthread_t th;
24326 
24327    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));
24328    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));
24329    d = ast_calloc(1, sizeof(*d));
24330    if (!transferee || !transferer || !d) {
24331       if (transferee) {
24332          ast_hangup(transferee);
24333       }
24334       if (transferer) {
24335          ast_hangup(transferer);
24336       }
24337       ast_free(d);
24338       return -1;
24339    }
24340    d->park_exten = ast_strdup(park_exten);
24341    d->park_context = ast_strdup(park_context);
24342    if (!d->park_exten || !d->park_context) {
24343       ast_hangup(transferee);
24344       ast_hangup(transferer);
24345       ast_free(d->park_exten);
24346       ast_free(d->park_context);
24347       ast_free(d);
24348       return -1;
24349    }
24350 
24351    /* Make formats okay */
24352    ast_format_copy(ast_channel_readformat(transferee), ast_channel_readformat(chan1));
24353    ast_format_copy(ast_channel_writeformat(transferee), ast_channel_writeformat(chan1));
24354 
24355    /* Prepare for taking over the channel */
24356    if (ast_channel_masquerade(transferee, chan1)) {
24357       ast_hangup(transferee);
24358       ast_hangup(transferer);
24359       ast_free(d->park_exten);
24360       ast_free(d->park_context);
24361       ast_free(d);
24362       return -1;
24363    }
24364 
24365    /* Setup the extensions and such */
24366    ast_channel_context_set(transferee, ast_channel_context(chan1));
24367    ast_channel_exten_set(transferee, ast_channel_exten(chan1));
24368    ast_channel_priority_set(transferee, ast_channel_priority(chan1));
24369 
24370    ast_do_masquerade(transferee);
24371 
24372    /* We make a clone of the peer channel too, so we can play
24373       back the announcement */
24374 
24375    /* Make formats okay */
24376    ast_format_copy(ast_channel_readformat(transferer), ast_channel_readformat(chan2));
24377    ast_format_copy(ast_channel_writeformat(transferer), ast_channel_writeformat(chan2));
24378    ast_channel_parkinglot_set(transferer, ast_channel_parkinglot(chan2));
24379 
24380    /* Prepare for taking over the channel */
24381    if (ast_channel_masquerade(transferer, chan2)) {
24382       ast_hangup(transferee);
24383       ast_hangup(transferer);
24384       ast_free(d->park_exten);
24385       ast_free(d->park_context);
24386       ast_free(d);
24387       return -1;
24388    }
24389 
24390    /* Setup the extensions and such */
24391    ast_channel_context_set(transferer, ast_channel_context(chan2));
24392    ast_channel_exten_set(transferer, ast_channel_exten(chan2));
24393    ast_channel_priority_set(transferer, ast_channel_priority(chan2));
24394 
24395    ast_do_masquerade(transferer);
24396 
24397    /* Save original request for followup */
24398    copy_request(&d->req, req);
24399    d->chan1 = transferee;  /* Transferee */
24400    d->chan2 = transferer;  /* Transferer */
24401    d->seqno = seqno;
24402    if (ast_pthread_create_detached_background(&th, NULL, sip_park_thread, d) < 0) {
24403       /* Could not start thread */
24404       ast_hangup(transferer);
24405       ast_hangup(transferee);
24406       deinit_req(&d->req);
24407       ast_free(d->park_exten);
24408       ast_free(d->park_context);
24409       ast_free(d);   /* We don't need it anymore. If thread is created, d will be free'd
24410                by sip_park_thread() */
24411       return -1;
24412    }
24413    return 0;
24414 }
24415 
24416 
24417 /*! \brief SIP pickup support function
24418  * Starts in a new thread, then pickup the call
24419  */
24420 static void *sip_pickup_thread(void *stuff)
24421 {
24422    struct ast_channel *chan;
24423    chan = stuff;
24424 
24425    if (ast_pickup_call(chan)) {
24426       ast_channel_hangupcause_set(chan, AST_CAUSE_CALL_REJECTED);
24427    } else {
24428       ast_channel_hangupcause_set(chan, AST_CAUSE_NORMAL_CLEARING);
24429    }
24430    ast_hangup(chan);
24431    ast_channel_unref(chan);
24432    chan = NULL;
24433    return NULL;
24434 }
24435 
24436 /*! \brief Pickup a call using the subsystem in features.c
24437  * This is executed in a separate thread
24438  */
24439 static int sip_pickup(struct ast_channel *chan)
24440 {
24441    pthread_t threadid;
24442 
24443    ast_channel_ref(chan);
24444 
24445    if (ast_pthread_create_detached_background(&threadid, NULL, sip_pickup_thread, chan)) {
24446       ast_debug(1, "Unable to start Group pickup thread on channel %s\n", ast_channel_name(chan));
24447       ast_channel_unref(chan);
24448       return -1;
24449    }
24450    ast_debug(1, "Started Group pickup thread on channel %s\n", ast_channel_name(chan));
24451    return 0;
24452 }
24453 
24454 
24455 /*! \brief Turn off generator data
24456    XXX Does this function belong in the SIP channel?
24457 */
24458 static void ast_quiet_chan(struct ast_channel *chan)
24459 {
24460    if (chan && ast_channel_state(chan) == AST_STATE_UP) {
24461       if (ast_test_flag(ast_channel_flags(chan), AST_FLAG_MOH))
24462          ast_moh_stop(chan);
24463       else if (ast_channel_generatordata(chan))
24464          ast_deactivate_generator(chan);
24465    }
24466 }
24467 
24468 /*! \brief Attempt transfer of SIP call
24469    This fix for attended transfers on a local PBX */
24470 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target)
24471 {
24472    int res = 0;
24473    struct ast_channel *peera = NULL,
24474       *peerb = NULL,
24475       *peerc = NULL,
24476       *peerd = NULL;
24477 
24478 
24479    /* We will try to connect the transferee with the target and hangup
24480       all channels to the transferer */
24481    ast_debug(4, "Sip transfer:--------------------\n");
24482    if (transferer->chan1)
24483       ast_debug(4, "-- Transferer to PBX channel: %s State %s\n", ast_channel_name(transferer->chan1), ast_state2str(ast_channel_state(transferer->chan1)));
24484    else
24485       ast_debug(4, "-- No transferer first channel - odd??? \n");
24486    if (target->chan1)
24487       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)));
24488    else
24489       ast_debug(4, "-- No target first channel ---\n");
24490    if (transferer->chan2)
24491       ast_debug(4, "-- Bridged call to transferee: %s State %s\n", ast_channel_name(transferer->chan2), ast_state2str(ast_channel_state(transferer->chan2)));
24492    else
24493       ast_debug(4, "-- No bridged call to transferee\n");
24494    if (target->chan2)
24495       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)");
24496    else
24497       ast_debug(4, "-- No target second channel ---\n");
24498    ast_debug(4, "-- END Sip transfer:--------------------\n");
24499    if (transferer->chan2) { /* We have a bridge on the transferer's channel */
24500       peera = transferer->chan1; /* Transferer - PBX -> transferee channel * the one we hangup */
24501       peerb = target->chan1;     /* Transferer - PBX -> target channel - This will get lost in masq */
24502       peerc = transferer->chan2; /* Asterisk to Transferee */
24503       peerd = target->chan2;     /* Asterisk to Target */
24504       ast_debug(3, "SIP transfer: Four channels to handle\n");
24505    } else if (target->chan2) {   /* Transferer has no bridge (IVR), but transferee */
24506       peera = target->chan1;     /* Transferer to PBX -> target channel */
24507       peerb = transferer->chan1; /* Transferer to IVR*/
24508       peerc = target->chan2;     /* Asterisk to Target */
24509       peerd = transferer->chan2; /* Nothing */
24510       ast_debug(3, "SIP transfer: Three channels to handle\n");
24511    }
24512 
24513    if (peera && peerb && peerc && (peerb != peerc)) {
24514       ast_quiet_chan(peera);     /* Stop generators */
24515       /* no need to quiet peerb since it should be hungup after the
24516          transfer and the masquerade needs to be able to see if MOH is
24517          playing on it */
24518       ast_quiet_chan(peerc);
24519       if (peerd)
24520          ast_quiet_chan(peerd);
24521 
24522       ast_debug(4, "SIP transfer: trying to masquerade %s into %s\n", ast_channel_name(peerc), ast_channel_name(peerb));
24523       if (ast_channel_masquerade(peerb, peerc)) {
24524          ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", ast_channel_name(peerb), ast_channel_name(peerc));
24525          res = -1;
24526       } else
24527          ast_debug(4, "SIP transfer: Succeeded to masquerade channels.\n");
24528       return res;
24529    } else {
24530       ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
24531       if (transferer->chan1)
24532          ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
24533       if (target->chan1)
24534          ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
24535       return -1;
24536    }
24537    return 0;
24538 }
24539 
24540 /*! \brief Get tag from packet
24541  *
24542  * \return Returns the pointer to the provided tag buffer,
24543  *         or NULL if the tag was not found.
24544  */
24545 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
24546 {
24547    const char *thetag;
24548 
24549    if (!tagbuf)
24550       return NULL;
24551    tagbuf[0] = '\0';    /* reset the buffer */
24552    thetag = sip_get_header(req, header);
24553    thetag = strcasestr(thetag, ";tag=");
24554    if (thetag) {
24555       thetag += 5;
24556       ast_copy_string(tagbuf, thetag, tagbufsize);
24557       return strsep(&tagbuf, ";");
24558    }
24559    return NULL;
24560 }
24561 
24562 static int handle_cc_notify(struct sip_pvt *pvt, struct sip_request *req)
24563 {
24564    struct sip_monitor_instance *monitor_instance = ao2_callback(sip_monitor_instances, 0,
24565          find_sip_monitor_instance_by_subscription_pvt, pvt);
24566    const char *status = get_content_line(req, "cc-state", ':');
24567    struct cc_epa_entry *cc_entry;
24568    char *uri;
24569 
24570    if (!monitor_instance) {
24571       transmit_response(pvt, "400 Bad Request", req);
24572       return -1;
24573    }
24574 
24575    if (ast_strlen_zero(status)) {
24576       ao2_ref(monitor_instance, -1);
24577       transmit_response(pvt, "400 Bad Request", req);
24578       return -1;
24579    }
24580 
24581    if (!strcmp(status, "queued")) {
24582       /* We've been told that we're queued. This is the endpoint's way of telling
24583        * us that it has accepted our CC request. We need to alert the core of this
24584        * development
24585        */
24586       ast_cc_monitor_request_acked(monitor_instance->core_id, "SIP endpoint %s accepted request", monitor_instance->device_name);
24587       transmit_response(pvt, "200 OK", req);
24588       ao2_ref(monitor_instance, -1);
24589       return 0;
24590    }
24591 
24592    /* It's open! Yay! */
24593    uri = get_content_line(req, "cc-URI", ':');
24594    if (ast_strlen_zero(uri)) {
24595       uri = get_in_brackets((char *)sip_get_header(req, "From"));
24596    }
24597 
24598    ast_string_field_set(monitor_instance, notify_uri, uri);
24599    if (monitor_instance->suspension_entry) {
24600       cc_entry = monitor_instance->suspension_entry->instance_data;
24601       if (cc_entry->current_state == CC_CLOSED) {
24602          /* If we've created a suspension entry and the current state is closed, then that means
24603           * we got a notice from the CC core earlier to suspend monitoring, but because this particular
24604           * call leg had not yet notified us that it was ready for recall, it meant that we
24605           * could not yet send a PUBLISH. Now, however, we can.
24606           */
24607          construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body,
24608                sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
24609          transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_INITIAL, monitor_instance->notify_uri);
24610       } else {
24611          ast_cc_monitor_callee_available(monitor_instance->core_id, "SIP monitored callee has become available");
24612       }
24613    } else {
24614       ast_cc_monitor_callee_available(monitor_instance->core_id, "SIP monitored callee has become available");
24615    }
24616    ao2_ref(monitor_instance, -1);
24617    transmit_response(pvt, "200 OK", req);
24618 
24619    return 0;
24620 }
24621 
24622 /*! \brief Handle incoming notifications */
24623 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e)
24624 {
24625    /* This is mostly a skeleton for future improvements */
24626    /* Mostly created to return proper answers on notifications on outbound REFER's */
24627    int res = 0;
24628    const char *event = sip_get_header(req, "Event");
24629    char *sep;
24630 
24631    if( (sep = strchr(event, ';')) ) {  /* XXX bug here - overwriting string ? */
24632       *sep++ = '\0';
24633    }
24634 
24635    if (sipdebug)
24636       ast_debug(2, "Got NOTIFY Event: %s\n", event);
24637 
24638    if (!strcmp(event, "refer")) {
24639       /* Save nesting depth for now, since there might be other events we will
24640          support in the future */
24641 
24642       /* Handle REFER notifications */
24643       char *buf, *cmd, *code;
24644       int respcode;
24645       int success = TRUE;
24646 
24647       /* EventID for each transfer... EventID is basically the REFER cseq
24648 
24649        We are getting notifications on a call that we transferred
24650        We should hangup when we are getting a 200 OK in a sipfrag
24651        Check if we have an owner of this event */
24652 
24653       /* Check the content type */
24654       if (strncasecmp(sip_get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
24655          /* We need a sipfrag */
24656          transmit_response(p, "400 Bad request", req);
24657          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
24658          return -1;
24659       }
24660 
24661       /* Get the text of the attachment */
24662       if (ast_strlen_zero(buf = get_content(req))) {
24663          ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
24664          transmit_response(p, "400 Bad request", req);
24665          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
24666          return -1;
24667       }
24668 
24669       /*
24670       From the RFC...
24671       A minimal, but complete, implementation can respond with a single
24672       NOTIFY containing either the body:
24673          SIP/2.0 100 Trying
24674       
24675       if the subscription is pending, the body:
24676          SIP/2.0 200 OK
24677       if the reference was successful, the body:
24678          SIP/2.0 503 Service Unavailable
24679       if the reference failed, or the body:
24680          SIP/2.0 603 Declined
24681 
24682       if the REFER request was accepted before approval to follow the
24683       reference could be obtained and that approval was subsequently denied
24684       (see Section 2.4.7).
24685       
24686       If there are several REFERs in the same dialog, we need to
24687       match the ID of the event header...
24688       */
24689       ast_debug(3, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
24690       cmd = ast_skip_blanks(buf);
24691       code = cmd;
24692       /* We are at SIP/2.0 */
24693       while(*code && (*code > 32)) {   /* Search white space */
24694          code++;
24695       }
24696       *code++ = '\0';
24697       code = ast_skip_blanks(code);
24698       sep = code;
24699       sep++;
24700       while(*sep && (*sep > 32)) {  /* Search white space */
24701          sep++;
24702       }
24703       *sep++ = '\0';       /* Response string */
24704       respcode = atoi(code);
24705       switch (respcode) {
24706       case 200:   /* OK: The new call is up, hangup this call */
24707          /* Hangup the call that we are replacing */
24708          break;
24709       case 301: /* Moved permenantly */
24710       case 302: /* Moved temporarily */
24711          /* Do we get the header in the packet in this case? */
24712          success = FALSE;
24713          break;
24714       case 503:   /* Service Unavailable: The new call failed */
24715       case 603:   /* Declined: Not accepted */
24716             /* Cancel transfer, continue the current call */
24717          success = FALSE;
24718          break;
24719       case 0:     /* Parse error */
24720             /* Cancel transfer, continue the current call */
24721          ast_log(LOG_NOTICE, "Error parsing sipfrag in NOTIFY in response to REFER.\n");
24722          success = FALSE;
24723          break;
24724       default:
24725          if (respcode < 200) {
24726             /* ignore provisional responses */
24727             success = -1;
24728          } else {
24729             ast_log(LOG_NOTICE, "Got unknown code '%d' in NOTIFY in response to REFER.\n", respcode);
24730             success = FALSE;
24731          }
24732          break;
24733       }
24734       if (success == FALSE) {
24735          ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
24736       }
24737 
24738       if (p->owner && success != -1) {
24739          enum ast_control_transfer message = success ? AST_TRANSFER_SUCCESS : AST_TRANSFER_FAILED;
24740          ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
24741       }
24742       /* Confirm that we received this packet */
24743       transmit_response(p, "200 OK", req);
24744    } else if (!strcmp(event, "message-summary")) {
24745       const char *mailbox = NULL;
24746       char *c = ast_strdupa(get_content_line(req, "Voice-Message", ':'));
24747 
24748       if (!p->mwi) {
24749          struct sip_peer *peer = sip_find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
24750 
24751          if (peer) {
24752             mailbox = ast_strdupa(peer->unsolicited_mailbox);
24753             sip_unref_peer(peer, "removing unsolicited mwi ref");
24754          }
24755       } else {
24756          mailbox = p->mwi->mailbox;
24757       }
24758 
24759       if (!ast_strlen_zero(mailbox) && !ast_strlen_zero(c)) {
24760          char *old = strsep(&c, " ");
24761          char *new = strsep(&old, "/");
24762          struct ast_event *event;
24763 
24764          if ((event = ast_event_new(AST_EVENT_MWI,
24765                      AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
24766                      AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, "SIP_Remote",
24767                      AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(new),
24768                      AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(old),
24769                      AST_EVENT_IE_END))) {
24770             ast_event_queue_and_cache(event);
24771          }
24772          transmit_response(p, "200 OK", req);
24773       } else {
24774          transmit_response(p, "489 Bad event", req);
24775          res = -1;
24776       }
24777    } else if (!strcmp(event, "keep-alive")) {
24778        /* Used by Sipura/Linksys for NAT pinhole,
24779         * just confirm that we received the packet. */
24780       transmit_response(p, "200 OK", req);
24781    } else if (!strcmp(event, "call-completion")) {
24782       res = handle_cc_notify(p, req);
24783    } else {
24784       /* We don't understand this event. */
24785       transmit_response(p, "489 Bad event", req);
24786       res = -1;
24787    }
24788 
24789    if (!p->lastinvite)
24790       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
24791 
24792    return res;
24793 }
24794 
24795 /*! \brief Handle incoming OPTIONS request
24796    An OPTIONS request should be answered like an INVITE from the same UA, including SDP
24797 */
24798 static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e)
24799 {
24800    const char *msg;
24801    enum sip_get_dest_result gotdest;
24802    int res;
24803 
24804    if (p->lastinvite) {
24805       /* if this is a request in an active dialog, just confirm that the dialog exists. */
24806       transmit_response_with_allow(p, "200 OK", req, 0);
24807       return 0;
24808    }
24809 
24810    if (sip_cfg.auth_options_requests) {
24811       /* Do authentication if this OPTIONS request began the dialog */
24812       copy_request(&p->initreq, req);
24813       set_pvt_allowed_methods(p, req);
24814       res = check_user(p, req, SIP_OPTIONS, e, XMIT_UNRELIABLE, addr);
24815       if (res == AUTH_CHALLENGE_SENT) {
24816          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
24817          return 0;
24818       }
24819       if (res < 0) { /* Something failed in authentication */
24820          ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", sip_get_header(req, "From"));
24821          transmit_response(p, "403 Forbidden", req);
24822          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
24823          return 0;
24824       }
24825    }
24826 
24827    /* must go through authentication before getting here */
24828    gotdest = get_destination(p, req, NULL);
24829    build_contact(p);
24830 
24831    if (ast_strlen_zero(p->context))
24832       ast_string_field_set(p, context, sip_cfg.default_context);
24833 
24834    if (ast_shutting_down()) {
24835       msg = "503 Unavailable";
24836    } else {
24837       msg = "404 Not Found";
24838       switch (gotdest) {
24839       case SIP_GET_DEST_INVALID_URI:
24840          msg = "416 Unsupported URI scheme";
24841          break;
24842       case SIP_GET_DEST_EXTEN_MATCHMORE:
24843       case SIP_GET_DEST_REFUSED:
24844       case SIP_GET_DEST_EXTEN_NOT_FOUND:
24845          //msg = "404 Not Found";
24846          break;
24847       case SIP_GET_DEST_EXTEN_FOUND:
24848          msg = "200 OK";
24849          break;
24850       }
24851    }
24852    transmit_response_with_allow(p, msg, req, 0);
24853 
24854    /* Destroy if this OPTIONS was the opening request, but not if
24855       it's in the middle of a normal call flow. */
24856    sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
24857 
24858    return 0;
24859 }
24860 
24861 /*! \brief Handle the transfer part of INVITE with a replaces: header,
24862     meaning a target pickup or an attended transfer.
24863     Used only once.
24864    XXX 'ignore' is unused.
24865 
24866    \note this function is called by handle_request_invite(). Four locks
24867    held at the beginning of this function, p, p->owner, p->refer->refer_call and
24868    p->refere->refer_call->owner.  only p's lock should remain at the end of this
24869    function.  p's lock as well as the channel p->owner's lock are held by
24870    handle_request_do(), we unlock p->owner before the masq.  By setting nounlock
24871    we are indicating to handle_request_do() that we have already unlocked the owner.
24872  */
24873 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, int *nounlock)
24874 {
24875    int earlyreplace = 0;
24876    int oneleggedreplace = 0;     /* Call with no bridge, propably IVR or voice message */
24877    struct ast_channel *c = p->owner;   /* Our incoming call */
24878    struct ast_channel *replacecall = p->refer->refer_call->owner; /* The channel we're about to take over */
24879    struct ast_channel *targetcall;     /* The bridge to the take-over target */
24880 
24881    /* Check if we're in ring state */
24882    if (ast_channel_state(replacecall) == AST_STATE_RING)
24883       earlyreplace = 1;
24884 
24885    /* Check if we have a bridge */
24886    if (!(targetcall = ast_bridged_channel(replacecall))) {
24887       /* We have no bridge */
24888       if (!earlyreplace) {
24889          ast_debug(2, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", ast_channel_name(replacecall));
24890          oneleggedreplace = 1;
24891       }
24892    }
24893    if (targetcall && ast_channel_state(targetcall) == AST_STATE_RINGING)
24894       ast_debug(4, "SIP transfer: Target channel is in ringing state\n");
24895 
24896    if (targetcall)
24897       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));
24898    else
24899       ast_debug(4, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", ast_channel_name(replacecall));
24900 
24901    if (req->ignore) {
24902       ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
24903       /* We should answer something here. If we are here, the
24904          call we are replacing exists, so an accepted
24905          can't harm */
24906       transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE, FALSE);
24907       /* Do something more clever here */
24908       if (c) {
24909          *nounlock = 1;
24910          ast_channel_unlock(c);
24911       }
24912       ast_channel_unlock(replacecall);
24913       sip_pvt_unlock(p->refer->refer_call);
24914       return 1;
24915    }
24916    if (!c) {
24917       /* What to do if no channel ??? */
24918       ast_log(LOG_ERROR, "Unable to create new channel.  Invite/replace failed.\n");
24919       transmit_response_reliable(p, "503 Service Unavailable", req);
24920       append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
24921       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
24922       ast_channel_unlock(replacecall);
24923       sip_pvt_unlock(p->refer->refer_call);
24924       return 1;
24925    }
24926    append_history(p, "Xfer", "INVITE/Replace received");
24927    /* We have three channels to play with
24928       channel c: New incoming call
24929       targetcall: Call from PBX to target
24930       p->refer->refer_call: SIP pvt dialog from transferer to pbx.
24931       replacecall: The owner of the previous
24932       We need to masq C into refer_call to connect to
24933       targetcall;
24934       If we are talking to internal audio stream, target call is null.
24935    */
24936 
24937    /* Fake call progress */
24938    transmit_response(p, "100 Trying", req);
24939    ast_setstate(c, AST_STATE_RING);
24940 
24941    /* Masquerade the new call into the referred call to connect to target call
24942       Targetcall is not touched by the masq */
24943 
24944    /* Answer the incoming call and set channel to UP state */
24945    transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE, FALSE);
24946 
24947    ast_setstate(c, AST_STATE_UP);
24948 
24949    /* Stop music on hold and other generators */
24950    ast_quiet_chan(replacecall);
24951    ast_quiet_chan(targetcall);
24952    ast_debug(4, "Invite/Replaces: preparing to masquerade %s into %s\n", ast_channel_name(c), ast_channel_name(replacecall));
24953 
24954    /* Make sure that the masq does not free our PVT for the old call */
24955    if (! earlyreplace && ! oneleggedreplace )
24956       ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER);  /* Delay hangup */
24957 
24958    /* Prepare the masquerade - if this does not happen, we will be gone */
24959    if(ast_channel_masquerade(replacecall, c))
24960       ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
24961    else
24962       ast_debug(4, "Invite/Replaces: Going to masquerade %s into %s\n", ast_channel_name(c), ast_channel_name(replacecall));
24963 
24964    /* C should now be in place of replacecall. all channel locks and pvt locks should be removed
24965     * before issuing the masq.  Since we are unlocking both the pvt (p) and its owner channel (c)
24966     * it is possible for channel c to be destroyed on us.  To prevent this, we must give c a reference
24967     * before any unlocking takes place and remove it only once we are completely done with it */
24968    ast_channel_ref(c);
24969    ast_channel_unlock(replacecall);
24970    ast_channel_unlock(c);
24971    sip_pvt_unlock(p->refer->refer_call);
24972    sip_pvt_unlock(p);
24973    if (ast_do_masquerade(replacecall)) {
24974       ast_log(LOG_WARNING, "Failed to perform masquerade with INVITE replaces\n");
24975    }
24976    if (earlyreplace || oneleggedreplace ) {
24977       ast_channel_lock(c);
24978       ast_channel_hangupcause_set(c, AST_CAUSE_SWITCH_CONGESTION);
24979       ast_channel_unlock(c);
24980    }
24981 
24982    /* c and c's tech pvt must be unlocked at this point for ast_hangup */
24983    ast_hangup(c);
24984    /* this indicates to handle_request_do that the owner channel has already been unlocked */
24985    *nounlock = 1;
24986    /* lock PVT structure again after hangup */
24987    sip_pvt_lock(p);
24988    ast_channel_unref(c);
24989    return 0;
24990 }
24991 
24992 /*! \note No channel or pvt locks should be held while calling this function. */
24993 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context)
24994 {
24995    struct ast_str *str = ast_str_alloca(AST_MAX_EXTENSION + AST_MAX_CONTEXT + 2);
24996    struct ast_app *pickup = pbx_findapp("Pickup");
24997 
24998    if (!pickup) {
24999       ast_log(LOG_ERROR, "Unable to perform pickup: Application 'Pickup' not loaded (app_directed_pickup.so).\n");
25000       return -1;
25001    }
25002 
25003    ast_str_set(&str, 0, "%s@%s", extension, sip_cfg.notifycid == IGNORE_CONTEXT ? "PICKUPMARK" : context);
25004 
25005    ast_debug(2, "About to call Pickup(%s)\n", ast_str_buffer(str));
25006 
25007    /* There is no point in capturing the return value since pickup_exec
25008       doesn't return anything meaningful unless the passed data is an empty
25009       string (which in our case it will not be) */
25010    pbx_exec(channel, pickup, ast_str_buffer(str));
25011 
25012    return 0;
25013 }
25014 
25015 /*! \brief Called to deny a T38 reinvite if the core does not respond to our request */
25016 static int sip_t38_abort(const void *data)
25017 {
25018    struct sip_pvt *p = (struct sip_pvt *) data;
25019 
25020    sip_pvt_lock(p);
25021    /* an application may have taken ownership of the T.38 negotiation on this
25022     * channel while we were waiting to grab the lock... if it did, the scheduler
25023     * id will have been reset to -1, which is our indication that we do *not*
25024     * want to abort the negotiation process
25025     */
25026    if (p->t38id != -1) {
25027       change_t38_state(p, T38_REJECTED);
25028       transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
25029       p->t38id = -1;
25030       dialog_unref(p, "unref the dialog ptr from sip_t38_abort, because it held a dialog ptr");
25031    }
25032    sip_pvt_unlock(p);
25033    return 0;
25034 }
25035 
25036 /*!
25037  * \brief bare-bones support for SIP UPDATE
25038  *
25039  * XXX This is not even close to being RFC 3311-compliant. We don't advertise
25040  * that we support the UPDATE method, so no one should ever try sending us
25041  * an UPDATE anyway. However, Asterisk can send an UPDATE to change connected
25042  * line information, so we need to be prepared to handle this. The way we distinguish
25043  * such an UPDATE is through the X-Asterisk-rpid-update header.
25044  *
25045  * Actually updating the media session may be some future work.
25046  */
25047 static int handle_request_update(struct sip_pvt *p, struct sip_request *req)
25048 {
25049    if (ast_strlen_zero(sip_get_header(req, "X-Asterisk-rpid-update"))) {
25050       transmit_response(p, "501 Method Not Implemented", req);
25051       return 0;
25052    }
25053    if (!p->owner) {
25054       transmit_response(p, "481 Call/Transaction Does Not Exist", req);
25055       return 0;
25056    }
25057    if (get_rpid(p, req)) {
25058       struct ast_party_connected_line connected;
25059       struct ast_set_party_connected_line update_connected;
25060 
25061       ast_party_connected_line_init(&connected);
25062       memset(&update_connected, 0, sizeof(update_connected));
25063 
25064       update_connected.id.number = 1;
25065       connected.id.number.valid = 1;
25066       connected.id.number.str = (char *) p->cid_num;
25067       connected.id.number.presentation = p->callingpres;
25068 
25069       update_connected.id.name = 1;
25070       connected.id.name.valid = 1;
25071       connected.id.name.str = (char *) p->cid_name;
25072       connected.id.name.presentation = p->callingpres;
25073 
25074       /* Invalidate any earlier private connected id representation */
25075       ast_set_party_id_all(&update_connected.priv);
25076 
25077       connected.id.tag = (char *) p->cid_tag;
25078       connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
25079       ast_channel_queue_connected_line_update(p->owner, &connected, &update_connected);
25080    }
25081    transmit_response(p, "200 OK", req);
25082    return 0;
25083 }
25084 
25085 /*
25086  * \internal \brief Check Session Timers for an INVITE request
25087  *
25088  * \retval 0 ok
25089  * \retval -1 failure
25090  */
25091 static int handle_request_invite_st(struct sip_pvt *p, struct sip_request *req,
25092       const char *required, int reinvite)
25093 {
25094    const char *p_uac_se_hdr;       /* UAC's Session-Expires header string                      */
25095    const char *p_uac_min_se;       /* UAC's requested Min-SE interval (char string)            */
25096    int uac_max_se = -1;            /* UAC's Session-Expires in integer format                  */
25097    int uac_min_se = -1;            /* UAC's Min-SE in integer format                           */
25098    int st_active = FALSE;          /* Session-Timer on/off boolean                             */
25099    int st_interval = 0;            /* Session-Timer negotiated refresh interval                */
25100    enum st_refresher tmp_st_ref = SESSION_TIMER_REFRESHER_AUTO; /* Session-Timer refresher     */
25101    int dlg_min_se = -1;
25102    int dlg_max_se = global_max_se;
25103    int rtn;
25104 
25105    /* Session-Timers */
25106    if ((p->sipoptions & SIP_OPT_TIMER)) {
25107       enum st_refresher_param st_ref_param = SESSION_TIMER_REFRESHER_PARAM_UNKNOWN;
25108 
25109       /* The UAC has requested session-timers for this session. Negotiate
25110       the session refresh interval and who will be the refresher */
25111       ast_debug(2, "Incoming INVITE with 'timer' option supported\n");
25112 
25113       /* Allocate Session-Timers struct w/in the dialog */
25114       if (!p->stimer) {
25115          sip_st_alloc(p);
25116       }
25117 
25118       /* Parse the Session-Expires header */
25119       p_uac_se_hdr = sip_get_header(req, "Session-Expires");
25120       if (!ast_strlen_zero(p_uac_se_hdr)) {
25121          ast_debug(2, "INVITE also has \"Session-Expires\" header.\n");
25122          rtn = parse_session_expires(p_uac_se_hdr, &uac_max_se, &st_ref_param);
25123          tmp_st_ref = (st_ref_param == SESSION_TIMER_REFRESHER_PARAM_UAC) ? SESSION_TIMER_REFRESHER_THEM : SESSION_TIMER_REFRESHER_US;
25124          if (rtn != 0) {
25125             transmit_response_reliable(p, "400 Session-Expires Invalid Syntax", req);
25126             return -1;
25127          }
25128       }
25129 
25130       /* Parse the Min-SE header */
25131       p_uac_min_se = sip_get_header(req, "Min-SE");
25132       if (!ast_strlen_zero(p_uac_min_se)) {
25133          ast_debug(2, "INVITE also has \"Min-SE\" header.\n");
25134          rtn = parse_minse(p_uac_min_se, &uac_min_se);
25135          if (rtn != 0) {
25136             transmit_response_reliable(p, "400 Min-SE Invalid Syntax", req);
25137             return -1;
25138          }
25139       }
25140 
25141       dlg_min_se = st_get_se(p, FALSE);
25142       switch (st_get_mode(p, 1)) {
25143       case SESSION_TIMER_MODE_ACCEPT:
25144       case SESSION_TIMER_MODE_ORIGINATE:
25145          if (uac_max_se > 0 && uac_max_se < dlg_min_se) {
25146             transmit_response_with_minse(p, "422 Session Interval Too Small", req, dlg_min_se);
25147             return -1;
25148          }
25149 
25150          p->stimer->st_active_peer_ua = TRUE;
25151          st_active = TRUE;
25152          if (st_ref_param == SESSION_TIMER_REFRESHER_PARAM_UNKNOWN) {
25153             tmp_st_ref = st_get_refresher(p);
25154          }
25155 
25156          dlg_max_se = st_get_se(p, TRUE);
25157          if (uac_max_se > 0) {
25158             if (dlg_max_se >= uac_min_se) {
25159                st_interval = (uac_max_se < dlg_max_se) ? uac_max_se : dlg_max_se;
25160             } else {
25161                st_interval = uac_max_se;
25162             }
25163          } else if (uac_min_se > 0) {
25164             st_interval = MAX(dlg_max_se, uac_min_se);
25165          } else {
25166             st_interval = dlg_max_se;
25167          }
25168          break;
25169 
25170       case SESSION_TIMER_MODE_REFUSE:
25171          if (p->reqsipoptions & SIP_OPT_TIMER) {
25172             transmit_response_with_unsupported(p, "420 Option Disabled", req, required);
25173             ast_log(LOG_WARNING, "Received SIP INVITE with supported but disabled option: %s\n", required);
25174             return -1;
25175          }
25176          break;
25177 
25178       default:
25179          ast_log(LOG_ERROR, "Internal Error %d at %s:%d\n", st_get_mode(p, 1), __FILE__, __LINE__);
25180          break;
25181       }
25182    } else {
25183       /* The UAC did not request session-timers.  Asterisk (UAS), will now decide
25184       (based on session-timer-mode in sip.conf) whether to run session-timers for
25185       this session or not. */
25186       switch (st_get_mode(p, 1)) {
25187       case SESSION_TIMER_MODE_ORIGINATE:
25188          st_active = TRUE;
25189          st_interval = st_get_se(p, TRUE);
25190          tmp_st_ref = SESSION_TIMER_REFRESHER_US;
25191          p->stimer->st_active_peer_ua = (p->sipoptions & SIP_OPT_TIMER) ? TRUE : FALSE;
25192          break;
25193 
25194       default:
25195          break;
25196       }
25197    }
25198 
25199    if (reinvite == 0) {
25200       /* Session-Timers: Start session refresh timer based on negotiation/config */
25201       if (st_active == TRUE) {
25202          p->stimer->st_active = TRUE;
25203          p->stimer->st_interval = st_interval;
25204          p->stimer->st_ref = tmp_st_ref;
25205       }
25206    } else {
25207       if (p->stimer->st_active == TRUE) {
25208          /* Session-Timers:  A re-invite request sent within a dialog will serve as
25209          a refresh request, no matter whether the re-invite was sent for refreshing
25210          the session or modifying it.*/
25211          ast_debug (2, "Restarting session-timers on a refresh - %s\n", p->callid);
25212 
25213          /* The UAC may be adjusting the session-timers mid-session */
25214          if (st_interval > 0) {
25215             p->stimer->st_interval = st_interval;
25216             p->stimer->st_ref      = tmp_st_ref;
25217          }
25218       }
25219    }
25220 
25221    return 0;
25222 }
25223 
25224 /*!
25225  * \brief Handle incoming INVITE request
25226  * \note If the INVITE has a Replaces header, it is part of an
25227  * attended transfer. If so, we do not go through the dial
25228  * plan but try to find the active call and masquerade
25229  * into it
25230  */
25231 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)
25232 {
25233    int res = INV_REQ_SUCCESS;
25234    int gotdest;
25235    const char *p_replaces;
25236    char *replace_id = NULL;
25237    int refer_locked = 0;
25238    const char *required;
25239    unsigned int required_profile = 0;
25240    struct ast_channel *c = NULL;    /* New channel */
25241    struct sip_peer *authpeer = NULL;   /* Matching Peer */
25242    int reinvite = 0;
25243    struct ast_party_redirecting redirecting;
25244    struct ast_set_party_redirecting update_redirecting;
25245 
25246    struct {
25247       char exten[AST_MAX_EXTENSION];
25248       char context[AST_MAX_CONTEXT];
25249    } pickup = {
25250          .exten = "",
25251    };
25252 
25253    /* Find out what they support */
25254    if (!p->sipoptions) {
25255       const char *supported = sip_get_header(req, "Supported");
25256       if (!ast_strlen_zero(supported)) {
25257          p->sipoptions = parse_sip_options(supported, NULL, 0);
25258       }
25259    }
25260 
25261    /* Find out what they require */
25262    required = sip_get_header(req, "Require");
25263    if (!ast_strlen_zero(required)) {
25264       char unsupported[256] = { 0, };
25265       required_profile = parse_sip_options(required, unsupported, ARRAY_LEN(unsupported));
25266 
25267       /* If there are any options required that we do not support,
25268        * then send a 420 with only those unsupported options listed */
25269       if (!ast_strlen_zero(unsupported)) {
25270          transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, unsupported);
25271          ast_log(LOG_WARNING, "Received SIP INVITE with unsupported required extension: required:%s unsupported:%s\n", required, unsupported);
25272          p->invitestate = INV_COMPLETED;
25273          if (!p->lastinvite)
25274             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25275          res = INV_REQ_ERROR;
25276          goto request_invite_cleanup;
25277       }
25278    }
25279 
25280    /* The option tags may be present in Supported: or Require: headers.
25281    Include the Require: option tags for further processing as well */
25282    p->sipoptions |= required_profile;
25283    p->reqsipoptions = required_profile;
25284 
25285    /* Check if this is a loop */
25286    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) {
25287       /* This is a call to ourself.  Send ourselves an error code and stop
25288          processing immediately, as SIP really has no good mechanism for
25289          being able to call yourself */
25290       /* If pedantic is on, we need to check the tags. If they're different, this is
25291          in fact a forked call through a SIP proxy somewhere. */
25292       int different;
25293       const char *initial_rlpart2 = REQ_OFFSET_TO_STR(&p->initreq, rlpart2);
25294       const char *this_rlpart2 = REQ_OFFSET_TO_STR(req, rlpart2);
25295       if (sip_cfg.pedanticsipchecking)
25296          different = sip_uri_cmp(initial_rlpart2, this_rlpart2);
25297       else
25298          different = strcmp(initial_rlpart2, this_rlpart2);
25299       if (!different) {
25300          transmit_response(p, "482 Loop Detected", req);
25301          p->invitestate = INV_COMPLETED;
25302          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25303          res = INV_REQ_FAILED;
25304          goto request_invite_cleanup;
25305       } else {
25306          /*! This is a spiral. What we need to do is to just change the outgoing INVITE
25307           * so that it now routes to the new Request URI. Since we created the INVITE ourselves
25308           * that should be all we need to do.
25309           *
25310           * \todo XXX This needs to be reviewed.  YOu don't change the request URI really, you route the packet
25311           * correctly instead...
25312           */
25313          char *uri = ast_strdupa(this_rlpart2);
25314          char *at = strchr(uri, '@');
25315          char *peerorhost;
25316          ast_debug(2, "Potential spiral detected. Original RURI was %s, new RURI is %s\n", initial_rlpart2, this_rlpart2);
25317          transmit_response(p, "100 Trying", req);
25318          if (at) {
25319             *at = '\0';
25320          }
25321          /* Parse out "sip:" */
25322          if ((peerorhost = strchr(uri, ':'))) {
25323             *peerorhost++ = '\0';
25324          }
25325          ast_string_field_set(p, theirtag, NULL);
25326          /* Treat this as if there were a call forward instead...
25327           */
25328          ast_channel_call_forward_set(p->owner, peerorhost);
25329          ast_queue_control(p->owner, AST_CONTROL_BUSY);
25330          res = INV_REQ_FAILED;
25331          goto request_invite_cleanup;
25332       }
25333    }
25334 
25335    if (!req->ignore && p->pendinginvite) {
25336       if (!ast_test_flag(&p->flags[0], SIP_OUTGOING) && (p->invitestate == INV_COMPLETED || p->invitestate == INV_TERMINATED)) {
25337          /* What do these circumstances mean? We have received an INVITE for an "incoming" dialog for which we
25338           * have sent a final response. We have not yet received an ACK, though (which is why p->pendinginvite is non-zero).
25339           * We also know that the INVITE is not a retransmission, because otherwise the "ignore" flag would be set.
25340           * This means that either we are receiving a reinvite for a terminated dialog, or we are receiving an INVITE with
25341           * credentials based on one we challenged earlier.
25342           *
25343           * The action to take in either case is to treat the INVITE as though it contains an implicit ACK for the previous
25344           * transaction. Calling __sip_ack will take care of this by clearing the p->pendinginvite and removing the response
25345           * from the previous transaction from the list of outstanding packets.
25346           */
25347          __sip_ack(p, p->pendinginvite, 1, 0);
25348       } else {
25349          /* We already have a pending invite. Sorry. You are on hold. */
25350          p->glareinvite = seqno;
25351          if (p->rtp && find_sdp(req)) {
25352             struct ast_sockaddr addr;
25353             if (get_ip_and_port_from_sdp(req, SDP_AUDIO, &addr)) {
25354                ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Audio may not work properly on this call.\n");
25355             } else {
25356                ast_rtp_instance_set_alt_remote_address(p->rtp, &addr);
25357             }
25358             if (p->vrtp) {
25359                if (get_ip_and_port_from_sdp(req, SDP_VIDEO, &addr)) {
25360                   ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Video may not work properly on this call.\n");
25361                } else {
25362                   ast_rtp_instance_set_alt_remote_address(p->vrtp, &addr);
25363                }
25364             }
25365          }
25366          transmit_response_reliable(p, "491 Request Pending", req);
25367          check_via(p, req);
25368          ast_debug(1, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
25369          /* Don't destroy dialog here */
25370          res = INV_REQ_FAILED;
25371          goto request_invite_cleanup;
25372       }
25373    }
25374 
25375    p_replaces = sip_get_header(req, "Replaces");
25376    if (!ast_strlen_zero(p_replaces)) {
25377       /* We have a replaces header */
25378       char *ptr;
25379       char *fromtag = NULL;
25380       char *totag = NULL;
25381       char *start, *to;
25382       int error = 0;
25383 
25384       if (p->owner) {
25385          ast_debug(3, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
25386          transmit_response_reliable(p, "400 Bad request", req);   /* The best way to not not accept the transfer */
25387          check_via(p, req);
25388          copy_request(&p->initreq, req);
25389          /* Do not destroy existing call */
25390          res = INV_REQ_ERROR;
25391          goto request_invite_cleanup;
25392       }
25393 
25394       if (sipdebug)
25395          ast_debug(3, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
25396       /* Create a buffer we can manipulate */
25397       replace_id = ast_strdupa(p_replaces);
25398       ast_uri_decode(replace_id, ast_uri_sip_user);
25399 
25400       if (!p->refer && !sip_refer_alloc(p)) {
25401          transmit_response_reliable(p, "500 Server Internal Error", req);
25402          append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
25403          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25404          p->invitestate = INV_COMPLETED;
25405          res = INV_REQ_ERROR;
25406          check_via(p, req);
25407          copy_request(&p->initreq, req);
25408          goto request_invite_cleanup;
25409       }
25410 
25411       /*  Todo: (When we find phones that support this)
25412          if the replaces header contains ";early-only"
25413          we can only replace the call in early
25414          stage, not after it's up.
25415 
25416          If it's not in early mode, 486 Busy.
25417       */
25418 
25419       /* Skip leading whitespace */
25420       replace_id = ast_skip_blanks(replace_id);
25421 
25422       start = replace_id;
25423       while ( (ptr = strsep(&start, ";")) ) {
25424          ptr = ast_skip_blanks(ptr); /* XXX maybe unnecessary ? */
25425          if ( (to = strcasestr(ptr, "to-tag=") ) )
25426             totag = to + 7;   /* skip the keyword */
25427          else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
25428             fromtag = to + 9; /* skip the keyword */
25429             fromtag = strsep(&fromtag, "&"); /* trim what ? */
25430          }
25431       }
25432 
25433       if (sipdebug)
25434          ast_debug(4, "Invite/replaces: Will use Replace-Call-ID : %s Fromtag: %s Totag: %s\n",
25435                  replace_id,
25436                  fromtag ? fromtag : "<no from tag>",
25437                  totag ? totag : "<no to tag>");
25438 
25439       /* Try to find call that we are replacing.
25440          If we have a Replaces header, we need to cancel that call if we succeed with this call.
25441          First we cheat a little and look for a magic call-id from phones that support
25442          dialog-info+xml so we can do technology independent pickup... */
25443       if (strncmp(replace_id, "pickup-", 7) == 0) {
25444          struct sip_pvt *subscription = NULL;
25445          replace_id += 7; /* Worst case we are looking at \0 */
25446 
25447          if ((subscription = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
25448             ast_log(LOG_NOTICE, "Unable to find subscription with call-id: %s\n", replace_id);
25449             transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
25450             error = 1;
25451          } else {
25452             ast_log(LOG_NOTICE, "Trying to pick up %s@%s\n", subscription->exten, subscription->context);
25453             ast_copy_string(pickup.exten, subscription->exten, sizeof(pickup.exten));
25454             ast_copy_string(pickup.context, subscription->context, sizeof(pickup.context));
25455             sip_pvt_unlock(subscription);
25456             if (subscription->owner) {
25457                ast_channel_unlock(subscription->owner);
25458             }
25459             subscription = dialog_unref(subscription, "unref dialog subscription");
25460          }
25461       }
25462 
25463       /* This locks both refer_call pvt and refer_call pvt's owner!!!*/
25464       if (!error && ast_strlen_zero(pickup.exten) && (p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
25465          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
25466          transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
25467          error = 1;
25468       } else {
25469          refer_locked = 1;
25470       }
25471 
25472       /* The matched call is the call from the transferer to Asterisk .
25473          We want to bridge the bridged part of the call to the
25474          incoming invite, thus taking over the refered call */
25475 
25476       if (p->refer->refer_call == p) {
25477          ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
25478          transmit_response_reliable(p, "400 Bad request", req);   /* The best way to not not accept the transfer */
25479          error = 1;
25480       }
25481 
25482       if (!error && ast_strlen_zero(pickup.exten) && !p->refer->refer_call->owner) {
25483          /* Oops, someting wrong anyway, no owner, no call */
25484          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
25485          /* Check for better return code */
25486          transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replace)", req);
25487          error = 1;
25488       }
25489 
25490       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) {
25491          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
25492          transmit_response_reliable(p, "603 Declined (Replaces)", req);
25493          error = 1;
25494       }
25495 
25496       if (error) {   /* Give up this dialog */
25497          append_history(p, "Xfer", "INVITE/Replace Failed.");
25498          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25499          sip_pvt_unlock(p);
25500          if (p->refer->refer_call) {
25501             sip_pvt_unlock(p->refer->refer_call);
25502             if (p->refer->refer_call->owner) {
25503                ast_channel_unlock(p->refer->refer_call->owner);
25504             }
25505             p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
25506          }
25507          refer_locked = 0;
25508          p->invitestate = INV_COMPLETED;
25509          res = INV_REQ_ERROR;
25510          check_via(p, req);
25511          copy_request(&p->initreq, req);
25512          goto request_invite_cleanup;
25513       }
25514    }
25515 
25516    /* Check if this is an INVITE that sets up a new dialog or
25517       a re-invite in an existing dialog */
25518 
25519    if (!req->ignore) {
25520       int newcall = (p->initreq.headers ? TRUE : FALSE);
25521 
25522       if (sip_cancel_destroy(p))
25523          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
25524       /* This also counts as a pending invite */
25525       p->pendinginvite = seqno;
25526       check_via(p, req);
25527 
25528       copy_request(&p->initreq, req);     /* Save this INVITE as the transaction basis */
25529       if (sipdebug)
25530          ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
25531       if (!p->owner) {  /* Not a re-invite */
25532          if (req->debug)
25533             ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
25534          if (newcall)
25535             append_history(p, "Invite", "New call: %s", p->callid);
25536          parse_ok_contact(p, req);
25537       } else { /* Re-invite on existing call */
25538          ast_clear_flag(&p->flags[0], SIP_OUTGOING);  /* This is now an inbound dialog */
25539          if (get_rpid(p, req)) {
25540             struct ast_party_connected_line connected;
25541             struct ast_set_party_connected_line update_connected;
25542 
25543             ast_party_connected_line_init(&connected);
25544             memset(&update_connected, 0, sizeof(update_connected));
25545 
25546             update_connected.id.number = 1;
25547             connected.id.number.valid = 1;
25548             connected.id.number.str = (char *) p->cid_num;
25549             connected.id.number.presentation = p->callingpres;
25550 
25551             update_connected.id.name = 1;
25552             connected.id.name.valid = 1;
25553             connected.id.name.str = (char *) p->cid_name;
25554             connected.id.name.presentation = p->callingpres;
25555 
25556             /* Invalidate any earlier private connected id representation */
25557             ast_set_party_id_all(&update_connected.priv);
25558 
25559             connected.id.tag = (char *) p->cid_tag;
25560             connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
25561             ast_channel_queue_connected_line_update(p->owner, &connected,
25562                &update_connected);
25563          }
25564          /* Handle SDP here if we already have an owner */
25565          if (find_sdp(req)) {
25566             if (process_sdp(p, req, SDP_T38_INITIATE)) {
25567                if (!ast_strlen_zero(sip_get_header(req, "Content-Encoding"))) {
25568                   /* Asterisk does not yet support any Content-Encoding methods.  Always
25569                    * attempt to process the sdp, but return a 415 if a Content-Encoding header
25570                    * was present after processing failed.  */
25571                   transmit_response_reliable(p, "415 Unsupported Media type", req);
25572                } else {
25573                   transmit_response_reliable(p, "488 Not acceptable here", req);
25574                }
25575                if (!p->lastinvite)
25576                   sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25577                res = INV_REQ_ERROR;
25578                goto request_invite_cleanup;
25579             }
25580             ast_queue_control(p->owner, AST_CONTROL_SRCUPDATE);
25581          } else {
25582             ast_format_cap_copy(p->jointcaps, p->caps);
25583             ast_debug(1, "Hm....  No sdp for the moment\n");
25584             /* Some devices signal they want to be put off hold by sending a re-invite
25585                *without* an SDP, which is supposed to mean "Go back to your state"
25586                and since they put os on remote hold, we go back to off hold */
25587             if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
25588                ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
25589                /* Activate a re-invite */
25590                ast_queue_frame(p->owner, &ast_null_frame);
25591                change_hold_state(p, req, FALSE, 0);
25592             }
25593          }
25594          if (p->do_history) /* This is a response, note what it was for */
25595             append_history(p, "ReInv", "Re-invite received");
25596       }
25597    } else if (req->debug)
25598       ast_verbose("Ignoring this INVITE request\n");
25599 
25600    if (!p->lastinvite && !req->ignore && !p->owner) {
25601       /* This is a new invite */
25602       /* Handle authentication if this is our first invite */
25603       int cc_recall_core_id = -1;
25604       set_pvt_allowed_methods(p, req);
25605       res = check_user_full(p, req, SIP_INVITE, e, XMIT_RELIABLE, addr, &authpeer);
25606       if (res == AUTH_CHALLENGE_SENT) {
25607          p->invitestate = INV_COMPLETED;     /* Needs to restart in another INVITE transaction */
25608          goto request_invite_cleanup;
25609       }
25610       if (res < 0) { /* Something failed in authentication */
25611          ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", sip_get_header(req, "From"));
25612          transmit_response_reliable(p, "403 Forbidden", req);
25613          p->invitestate = INV_COMPLETED;
25614          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25615          goto request_invite_cleanup;
25616       }
25617 
25618       /* Successful authentication and peer matching so record the peer related to this pvt (for easy access to peer settings) */
25619       if (p->relatedpeer) {
25620          p->relatedpeer = sip_unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
25621       }
25622       if (authpeer) {
25623          p->relatedpeer = sip_ref_peer(authpeer, "setting dialog's relatedpeer pointer");
25624       }
25625 
25626       req->authenticated = 1;
25627 
25628       /* We have a successful authentication, process the SDP portion if there is one */
25629       if (find_sdp(req)) {
25630          if (process_sdp(p, req, SDP_T38_INITIATE)) {
25631             /* Asterisk does not yet support any Content-Encoding methods.  Always
25632              * attempt to process the sdp, but return a 415 if a Content-Encoding header
25633              * was present after processing fails. */
25634             if (!ast_strlen_zero(sip_get_header(req, "Content-Encoding"))) {
25635                transmit_response_reliable(p, "415 Unsupported Media type", req);
25636             } else {
25637                /* Unacceptable codecs */
25638                transmit_response_reliable(p, "488 Not acceptable here", req);
25639             }
25640             p->invitestate = INV_COMPLETED;
25641             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25642             ast_debug(1, "No compatible codecs for this SIP call.\n");
25643             res = INV_REQ_ERROR;
25644             goto request_invite_cleanup;
25645          }
25646       } else { /* No SDP in invite, call control session */
25647          ast_format_cap_copy(p->jointcaps, p->caps);
25648          ast_debug(2, "No SDP in Invite, third party call control\n");
25649       }
25650 
25651       /* Initialize the context if it hasn't been already */
25652       if (ast_strlen_zero(p->context))
25653          ast_string_field_set(p, context, sip_cfg.default_context);
25654 
25655 
25656       /* Check number of concurrent calls -vs- incoming limit HERE */
25657       ast_debug(1, "Checking SIP call limits for device %s\n", p->username);
25658       if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
25659          if (res < 0) {
25660             ast_log(LOG_NOTICE, "Failed to place call for device %s, too many calls\n", p->username);
25661             transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
25662             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25663             p->invitestate = INV_COMPLETED;
25664 
25665             res = AUTH_SESSION_LIMIT;
25666          }
25667 
25668          goto request_invite_cleanup;
25669       }
25670       gotdest = get_destination(p, NULL, &cc_recall_core_id);  /* Get destination right away */
25671       extract_uri(p, req);       /* Get the Contact URI */
25672       build_contact(p);       /* Build our contact header */
25673 
25674       if (p->rtp) {
25675          ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
25676          ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
25677       }
25678 
25679       if (!replace_id && (gotdest != SIP_GET_DEST_EXTEN_FOUND)) { /* No matching extension found */
25680          switch(gotdest) {
25681          case SIP_GET_DEST_INVALID_URI:
25682             transmit_response_reliable(p, "416 Unsupported URI scheme", req);
25683             break;
25684          case SIP_GET_DEST_EXTEN_MATCHMORE:
25685             if (ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)
25686                == SIP_PAGE2_ALLOWOVERLAP_YES) {
25687                transmit_response_reliable(p, "484 Address Incomplete", req);
25688                break;
25689             }
25690             /*
25691              * XXX We would have to implement collecting more digits in
25692              * chan_sip for any other schemes of overlap dialing.
25693              *
25694              * For SIP_PAGE2_ALLOWOVERLAP_DTMF it is better to do this in
25695              * the dialplan using the Incomplete application rather than
25696              * having the channel driver do it.
25697              */
25698             /* Fall through */
25699          case SIP_GET_DEST_EXTEN_NOT_FOUND:
25700             {
25701                char *decoded_exten = ast_strdupa(p->exten);
25702                transmit_response_reliable(p, "404 Not Found", req);
25703                ast_uri_decode(decoded_exten, ast_uri_sip_user);
25704                ast_log(LOG_NOTICE, "Call from '%s' (%s) to extension"
25705                   " '%s' rejected because extension not found in context '%s'.\n",
25706                   S_OR(p->username, p->peername), ast_sockaddr_stringify(&p->recv), decoded_exten, p->context);
25707             }
25708             break;
25709          case SIP_GET_DEST_REFUSED:
25710          default:
25711             transmit_response_reliable(p, "403 Forbidden", req);
25712          } /* end switch */
25713 
25714          p->invitestate = INV_COMPLETED;
25715          update_call_counter(p, DEC_CALL_LIMIT);
25716          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25717          res = INV_REQ_FAILED;
25718          goto request_invite_cleanup;
25719       } else {
25720          /* If no extension was specified, use the s one */
25721          /* Basically for calling to IP/Host name only */
25722          if (ast_strlen_zero(p->exten))
25723             ast_string_field_set(p, exten, "s");
25724          /* Initialize our tag */
25725 
25726          make_our_tag(p);
25727 
25728          if (handle_request_invite_st(p, req, required, reinvite)) {
25729             p->invitestate = INV_COMPLETED;
25730             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25731             res = INV_REQ_ERROR;
25732             goto request_invite_cleanup;
25733          }
25734 
25735          /* First invitation - create the channel.  Allocation
25736           * failures are handled below. */
25737 
25738          c = sip_new(p, AST_STATE_DOWN, S_OR(p->peername, NULL), NULL, p->logger_callid);
25739 
25740          if (cc_recall_core_id != -1) {
25741             ast_setup_cc_recall_datastore(c, cc_recall_core_id);
25742             ast_cc_agent_set_interfaces_chanvar(c);
25743          }
25744          *recount = 1;
25745 
25746          /* Save Record-Route for any later requests we make on this dialogue */
25747          build_route(p, req, 0, 0);
25748 
25749          if (c) {
25750             ast_party_redirecting_init(&redirecting);
25751             memset(&update_redirecting, 0, sizeof(update_redirecting));
25752             change_redirecting_information(p, req, &redirecting, &update_redirecting,
25753                FALSE); /*Will return immediately if no Diversion header is present */
25754             ast_channel_set_redirecting(c, &redirecting, &update_redirecting);
25755             ast_party_redirecting_free(&redirecting);
25756          }
25757       }
25758    } else {
25759       ast_party_redirecting_init(&redirecting);
25760       memset(&update_redirecting, 0, sizeof(update_redirecting));
25761       if (sipdebug) {
25762          if (!req->ignore)
25763             ast_debug(2, "Got a SIP re-invite for call %s\n", p->callid);
25764          else
25765             ast_debug(2, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
25766       }
25767       if (!req->ignore)
25768          reinvite = 1;
25769 
25770       if (handle_request_invite_st(p, req, required, reinvite)) {
25771          p->invitestate = INV_COMPLETED;
25772          if (!p->lastinvite) {
25773             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25774          }
25775          res = INV_REQ_ERROR;
25776          goto request_invite_cleanup;
25777       }
25778 
25779       c = p->owner;
25780       change_redirecting_information(p, req, &redirecting, &update_redirecting, FALSE); /*Will return immediately if no Diversion header is present */
25781       if (c) {
25782          ast_channel_set_redirecting(c, &redirecting, &update_redirecting);
25783       }
25784       ast_party_redirecting_free(&redirecting);
25785    }
25786 
25787    /* Check if OLI/ANI-II is present in From: */
25788    parse_oli(req, p->owner);
25789 
25790    if (p->stimer->st_active == TRUE) {
25791       if (reinvite == 0) {
25792          start_session_timer(p);
25793       } else {
25794          restart_session_timer(p);
25795       }
25796    }
25797 
25798    if (!req->ignore && p)
25799       p->lastinvite = seqno;
25800 
25801    if (c && replace_id) {  /* Attended transfer or call pickup - we're the target */
25802       if (!ast_strlen_zero(pickup.exten)) {
25803          append_history(p, "Xfer", "INVITE/Replace received");
25804 
25805          /* Let the caller know we're giving it a shot */
25806          transmit_response(p, "100 Trying", req);
25807          p->invitestate = INV_PROCEEDING;
25808          ast_setstate(c, AST_STATE_RING);
25809 
25810          /* Do the pickup itself */
25811          ast_channel_unlock(c);
25812          *nounlock = 1;
25813 
25814          /* since p->owner (c) is unlocked, we need to go ahead and unlock pvt for both
25815           * magic pickup and ast_hangup.  Both of these functions will attempt to lock
25816           * p->owner again, which can cause a deadlock if we already hold a lock on p.
25817           * Locking order is, channel then pvt.  Dead lock avoidance must be used if
25818           * called the other way around. */
25819          sip_pvt_unlock(p);
25820          do_magic_pickup(c, pickup.exten, pickup.context);
25821          /* Now we're either masqueraded or we failed to pickup, in either case we... */
25822          ast_hangup(c);
25823          sip_pvt_lock(p); /* pvt is expected to remain locked on return, so re-lock it */
25824 
25825          res = INV_REQ_FAILED;
25826          goto request_invite_cleanup;
25827       } else {
25828          /* Go and take over the target call */
25829          if (sipdebug)
25830             ast_debug(4, "Sending this call to the invite/replcaes handler %s\n", p->callid);
25831          res = handle_invite_replaces(p, req, addr, seqno, nounlock);
25832          refer_locked = 0;
25833          goto request_invite_cleanup;
25834       }
25835    }
25836 
25837 
25838    if (c) { /* We have a call  -either a new call or an old one (RE-INVITE) */
25839       enum ast_channel_state c_state = ast_channel_state(c);
25840 
25841       if (c_state != AST_STATE_UP && reinvite &&
25842          (p->invitestate == INV_TERMINATED || p->invitestate == INV_CONFIRMED)) {
25843          /* If these conditions are true, and the channel is still in the 'ringing'
25844           * state, then this likely means that we have a situation where the initial
25845           * INVITE transaction has completed *but* the channel's state has not yet been
25846           * changed to UP. The reason this could happen is if the reinvite is received
25847           * on the SIP socket prior to an application calling ast_read on this channel
25848           * to read the answer frame we earlier queued on it. In this case, the reinvite
25849           * is completely legitimate so we need to handle this the same as if the channel
25850           * were already UP. Thus we are purposely falling through to the AST_STATE_UP case.
25851           */
25852          c_state = AST_STATE_UP;
25853       }
25854 
25855       switch(c_state) {
25856       case AST_STATE_DOWN:
25857          ast_debug(2, "%s: New call is still down.... Trying... \n", ast_channel_name(c));
25858          transmit_provisional_response(p, "100 Trying", req, 0);
25859          p->invitestate = INV_PROCEEDING;
25860          ast_setstate(c, AST_STATE_RING);
25861          if (strcmp(p->exten, ast_pickup_ext())) { /* Call to extension -start pbx on this call */
25862             enum ast_pbx_result result;
25863 
25864             result = ast_pbx_start(c);
25865 
25866             switch(result) {
25867             case AST_PBX_FAILED:
25868                ast_log(LOG_WARNING, "Failed to start PBX :(\n");
25869                p->invitestate = INV_COMPLETED;
25870                transmit_response_reliable(p, "503 Unavailable", req);
25871                break;
25872             case AST_PBX_CALL_LIMIT:
25873                ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
25874                p->invitestate = INV_COMPLETED;
25875                transmit_response_reliable(p, "480 Temporarily Unavailable", req);
25876                res = AUTH_SESSION_LIMIT;
25877                break;
25878             case AST_PBX_SUCCESS:
25879                /* nothing to do */
25880                break;
25881             }
25882 
25883             if (result) {
25884 
25885                /* Unlock locks so ast_hangup can do its magic */
25886                ast_channel_unlock(c);
25887                *nounlock = 1;
25888                sip_pvt_unlock(p);
25889                ast_hangup(c);
25890                sip_pvt_lock(p);
25891                c = NULL;
25892             }
25893          } else { /* Pickup call in call group */
25894             if (sip_pickup(c)) {
25895                ast_log(LOG_WARNING, "Failed to start Group pickup by %s\n", ast_channel_name(c));
25896                transmit_response_reliable(p, "480 Temporarily Unavailable", req);
25897                sip_alreadygone(p);
25898                ast_channel_hangupcause_set(c, AST_CAUSE_FAILURE);
25899 
25900                /* Unlock locks so ast_hangup can do its magic */
25901                ast_channel_unlock(c);
25902                *nounlock = 1;
25903 
25904                p->invitestate = INV_COMPLETED;
25905                sip_pvt_unlock(p);
25906                ast_hangup(c);
25907                sip_pvt_lock(p);
25908                c = NULL;
25909             }
25910          }
25911          break;
25912       case AST_STATE_RING:
25913          transmit_provisional_response(p, "100 Trying", req, 0);
25914          p->invitestate = INV_PROCEEDING;
25915          break;
25916       case AST_STATE_RINGING:
25917          transmit_provisional_response(p, "180 Ringing", req, 0);
25918          p->invitestate = INV_PROCEEDING;
25919          break;
25920       case AST_STATE_UP:
25921          ast_debug(2, "%s: This call is UP.... \n", ast_channel_name(c));
25922 
25923          transmit_response(p, "100 Trying", req);
25924 
25925          if (p->t38.state == T38_PEER_REINVITE) {
25926             if (p->t38id > -1) {
25927                /* reset t38 abort timer */
25928                AST_SCHED_DEL_UNREF(sched, p->t38id, dialog_unref(p, "remove ref for t38id"));
25929             }
25930             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."));
25931          } else if (p->t38.state == T38_ENABLED) {
25932             ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
25933             transmit_response_with_t38_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ?  XMIT_UNRELIABLE : XMIT_CRITICAL)));
25934          } else if ((p->t38.state == T38_DISABLED) || (p->t38.state == T38_REJECTED)) {
25935             /* If this is not a re-invite or something to ignore - it's critical */
25936             if (p->srtp && !ast_test_flag(p->srtp, SRTP_CRYPTO_OFFER_OK)) {
25937                ast_log(LOG_WARNING, "Target does not support required crypto\n");
25938                transmit_response_reliable(p, "488 Not Acceptable Here (crypto)", req);
25939             } else {
25940                ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
25941                transmit_response_with_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ?  XMIT_UNRELIABLE : XMIT_CRITICAL)), p->session_modify == TRUE ? FALSE : TRUE, FALSE);
25942                ast_queue_control(p->owner, AST_CONTROL_UPDATE_RTP_PEER);
25943             }
25944          }
25945 
25946          p->invitestate = INV_TERMINATED;
25947          break;
25948       default:
25949          ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", ast_channel_state(c));
25950          transmit_response(p, "100 Trying", req);
25951          break;
25952       }
25953    } else {
25954       if (p && (p->autokillid == -1)) {
25955          const char *msg;
25956 
25957          if ((ast_format_cap_is_empty(p->jointcaps)))
25958             msg = "488 Not Acceptable Here (codec error)";
25959          else {
25960             ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
25961             msg = "503 Unavailable";
25962          }
25963          transmit_response_reliable(p, msg, req);
25964          p->invitestate = INV_COMPLETED;
25965          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25966       }
25967    }
25968 
25969 request_invite_cleanup:
25970 
25971    if (refer_locked && p->refer && p->refer->refer_call) {
25972       sip_pvt_unlock(p->refer->refer_call);
25973       if (p->refer->refer_call->owner) {
25974          ast_channel_unlock(p->refer->refer_call->owner);
25975       }
25976       p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
25977    }
25978    if (authpeer) {
25979       authpeer = sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_invite authpeer");
25980    }
25981 
25982    return res;
25983 }
25984 
25985 /*! \brief Check for the presence of OLI tag(s) in the From header and set on the channel
25986  */
25987 static void parse_oli(struct sip_request *req, struct ast_channel *chan)
25988 {
25989    const char *from = NULL;
25990    const char *s = NULL;
25991    int ani2 = 0;
25992 
25993    if (!chan || !req) {
25994       /* null pointers are not helpful */
25995       return;
25996    }
25997 
25998    from = sip_get_header(req, "From");
25999    if (ast_strlen_zero(from)) {
26000       /* no From header */
26001       return;
26002    }
26003 
26004    /* Look for the possible OLI tags. */
26005    if ((s = strcasestr(from, ";isup-oli="))) {
26006       s += 10;
26007    } else if ((s = strcasestr(from, ";ss7-oli="))) {
26008       s += 9;
26009    } else if ((s = strcasestr(from, ";oli="))) {
26010       s += 5;
26011    }
26012 
26013    if (ast_strlen_zero(s)) {
26014       /* OLI tag is missing, or present with nothing following the '=' sign */
26015       return;
26016    }
26017 
26018    /* just in case OLI is quoted */
26019    if (*s == '\"') {
26020       s++;
26021    }
26022 
26023    if (sscanf(s, "%d", &ani2)) {
26024       ast_channel_caller(chan)->ani2 = ani2;
26025    }
26026 
26027    return;
26028 }
26029 
26030 /*! \brief  Find all call legs and bridge transferee with target
26031  * called from handle_request_refer
26032  *
26033  * \note this function assumes two locks to begin with, sip_pvt transferer and current.chan1 (the pvt's owner)... 
26034  * 2 additional locks are held at the beginning of the function, targetcall_pvt, and targetcall_pvt's owner
26035  * channel (which is stored in target.chan1).  These 2 locks _MUST_ be let go by the end of the function.  Do
26036  * not be confused into thinking a pvt's owner is the same thing as the channels locked at the beginning of
26037  * this function, after the masquerade this may not be true.  Be consistent and unlock only the exact same
26038  * pointers that were locked to begin with.
26039  *
26040  * If this function is successful, only the transferer pvt lock will remain on return.  Setting nounlock indicates
26041  * to handle_request_do() that the pvt's owner it locked does not require an unlock.
26042  */
26043 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, uint32_t seqno, int *nounlock)
26044 {
26045    struct sip_dual target;    /* Chan 1: Call from tranferer to Asterisk */
26046                /* Chan 2: Call from Asterisk to target */
26047    int res = 0;
26048    struct sip_pvt *targetcall_pvt;
26049    struct ast_party_connected_line connected_to_transferee;
26050    struct ast_party_connected_line connected_to_target;
26051    char transferer_linkedid[32];
26052    struct ast_channel *chans[2];
26053 
26054    /* Check if the call ID of the replaces header does exist locally */
26055    if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag,
26056       transferer->refer->replaces_callid_fromtag))) {
26057       if (transferer->refer->localtransfer) {
26058          /* We did not find the refered call. Sorry, can't accept then */
26059          /* Let's fake a response from someone else in order
26060             to follow the standard */
26061          transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
26062          append_history(transferer, "Xfer", "Refer failed");
26063          ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
26064          transferer->refer->status = REFER_FAILED;
26065          return -1;
26066       }
26067       /* Fall through for remote transfers that we did not find locally */
26068       ast_debug(3, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
26069       return 0;
26070    }
26071 
26072    /* Ok, we can accept this transfer */
26073    append_history(transferer, "Xfer", "Refer accepted");
26074    if (!targetcall_pvt->owner) { /* No active channel */
26075       ast_debug(4, "SIP attended transfer: Error: No owner of target call\n");
26076       /* Cancel transfer */
26077       transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
26078       append_history(transferer, "Xfer", "Refer failed");
26079       ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
26080       transferer->refer->status = REFER_FAILED;
26081       sip_pvt_unlock(targetcall_pvt);
26082       if (targetcall_pvt)
26083          ao2_t_ref(targetcall_pvt, -1, "Drop targetcall_pvt pointer");
26084       return -1;
26085    }
26086 
26087    /* We have a channel, find the bridge */
26088    target.chan1 = ast_channel_ref(targetcall_pvt->owner);            /* Transferer to Asterisk */
26089    target.chan2 = ast_bridged_channel(targetcall_pvt->owner);  /* Asterisk to target */
26090    if (target.chan2) {
26091       ast_channel_ref(target.chan2);
26092    }
26093 
26094    if (!target.chan2 || !(ast_channel_state(target.chan2) == AST_STATE_UP || ast_channel_state(target.chan2) == AST_STATE_RINGING) ) {
26095       /* Wrong state of new channel */
26096       if (target.chan2)
26097          ast_debug(4, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(ast_channel_state(target.chan2)));
26098       else if (ast_channel_state(target.chan1) != AST_STATE_RING)
26099          ast_debug(4, "SIP attended transfer: Error: No target channel\n");
26100       else
26101          ast_debug(4, "SIP attended transfer: Attempting transfer in ringing state\n");
26102    }
26103 
26104    /* Transfer */
26105    if (sipdebug) {
26106       if (current->chan2)  /* We have two bridges */
26107          ast_debug(4, "SIP attended transfer: trying to bridge %s and %s\n", ast_channel_name(target.chan1), ast_channel_name(current->chan2));
26108       else        /* One bridge, propably transfer of IVR/voicemail etc */
26109          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));
26110    }
26111 
26112    ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);   /* Delay hangup */
26113 
26114    ast_copy_string(transferer_linkedid, ast_channel_linkedid(transferer->owner), sizeof(transferer_linkedid));
26115 
26116    /* Perform the transfer */
26117    chans[0] = transferer->owner;
26118    chans[1] = target.chan1;
26119    ast_manager_event_multichan(EVENT_FLAG_CALL, "Transfer", 2, chans,
26120       "TransferMethod: SIP\r\n"
26121       "TransferType: Attended\r\n"
26122       "Channel: %s\r\n"
26123       "Uniqueid: %s\r\n"
26124       "SIP-Callid: %s\r\n"
26125       "TargetChannel: %s\r\n"
26126       "TargetUniqueid: %s\r\n",
26127       ast_channel_name(transferer->owner),
26128       ast_channel_uniqueid(transferer->owner),
26129       transferer->callid,
26130       ast_channel_name(target.chan1),
26131       ast_channel_uniqueid(target.chan1));
26132    ast_party_connected_line_init(&connected_to_transferee);
26133    ast_party_connected_line_init(&connected_to_target);
26134    /* No need to lock current->chan1 here since it was locked in sipsock_read */
26135    ast_party_connected_line_copy(&connected_to_transferee, ast_channel_connected(current->chan1));
26136    /* No need to lock target.chan1 here since it was locked in get_sip_pvt_byid_locked */
26137    ast_party_connected_line_copy(&connected_to_target, ast_channel_connected(target.chan1));
26138    /* Reset any earlier private connected id representation */
26139    ast_party_id_reset(&connected_to_transferee.priv);
26140    ast_party_id_reset(&connected_to_target.priv);
26141    connected_to_target.source = connected_to_transferee.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
26142    res = attempt_transfer(current, &target);
26143    if (res) {
26144       /* Failed transfer */
26145       transmit_notify_with_sipfrag(transferer, seqno, "486 Busy Here", TRUE);
26146       append_history(transferer, "Xfer", "Refer failed");
26147       ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
26148       /* if transfer failed, go ahead and unlock targetcall_pvt and it's owner channel */
26149       sip_pvt_unlock(targetcall_pvt);
26150       ast_channel_unlock(target.chan1);
26151    } else {
26152       /* Transfer succeeded! */
26153       const char *xfersound = pbx_builtin_getvar_helper(target.chan1, "ATTENDED_TRANSFER_COMPLETE_SOUND");
26154 
26155       /* target.chan1 was locked in get_sip_pvt_byid_locked, do not unlock target.chan1 before this */
26156       ast_cel_report_event(target.chan1, AST_CEL_ATTENDEDTRANSFER, NULL, transferer_linkedid, target.chan2);
26157 
26158       /* Tell transferer that we're done. */
26159       transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
26160       append_history(transferer, "Xfer", "Refer succeeded");
26161       transferer->refer->status = REFER_200OK;
26162       if (target.chan2 && !ast_strlen_zero(xfersound) && ast_streamfile(target.chan2, xfersound, ast_channel_language(target.chan2)) >= 0) {
26163          ast_waitstream(target.chan2, "");
26164       }
26165 
26166       /* By forcing the masquerade, we know that target.chan1 and target.chan2 are bridged. We then
26167        * can queue connected line updates where they need to go.
26168        *
26169        * before a masquerade, all channel and pvt locks must be unlocked.  Any recursive
26170        * channel locks held before this function invalidates channel container locking order.
26171        * Since we are unlocking both the pvt (transferer) and its owner channel (current.chan1)
26172        * it is possible for current.chan1 to be destroyed in the pbx thread.  To prevent this
26173        * we must give c a reference before any unlocking takes place.
26174        */
26175 
26176       ast_channel_ref(current->chan1);
26177       ast_channel_unlock(current->chan1); /* current.chan1 is p->owner before the masq, it was locked by socket_read()*/
26178       ast_channel_unlock(target.chan1);
26179       *nounlock = 1;  /* we just unlocked the dialog's channel and have no plans of locking it again. */
26180       sip_pvt_unlock(targetcall_pvt);
26181       sip_pvt_unlock(transferer);
26182 
26183       ast_do_masquerade(target.chan1);
26184 
26185       if (target.chan2) {
26186          ast_indicate(target.chan2, AST_CONTROL_UNHOLD);
26187       }
26188 
26189       if (current->chan2 && ast_channel_state(current->chan2) == AST_STATE_RING) {
26190          ast_indicate(target.chan1, AST_CONTROL_RINGING);
26191       }
26192 
26193       if (target.chan2) {
26194          ast_channel_queue_connected_line_update(target.chan1, &connected_to_transferee, NULL);
26195          ast_channel_queue_connected_line_update(target.chan2, &connected_to_target, NULL);
26196       } else {
26197          /* Since target.chan1 isn't actually connected to another channel, there is no way for us
26198           * to queue a frame so that its connected line status will be updated.
26199           *
26200           * Instead, we use the somewhat hackish approach of using a special control frame type that
26201           * instructs ast_read to perform a specific action. In this case, the frame we queue tells
26202           * ast_read to call the connected line interception macro configured for target.chan1.
26203           */
26204          struct ast_control_read_action_payload *frame_payload;
26205          int payload_size;
26206          int frame_size;
26207          unsigned char connected_line_data[1024];
26208          payload_size = ast_connected_line_build_data(connected_line_data,
26209             sizeof(connected_line_data), &connected_to_target, NULL);
26210          frame_size = payload_size + sizeof(*frame_payload);
26211          if (payload_size != -1) {
26212             frame_payload = ast_alloca(frame_size);
26213             frame_payload->payload_size = payload_size;
26214             memcpy(frame_payload->payload, connected_line_data, payload_size);
26215             frame_payload->action = AST_FRAME_READ_ACTION_CONNECTED_LINE_MACRO;
26216             ast_queue_control_data(target.chan1, AST_CONTROL_READ_ACTION, frame_payload, frame_size);
26217          }
26218          /* In addition to queueing the read action frame so that target.chan1's connected line info
26219           * will be updated, we also are going to queue a plain old connected line update on target.chan1. This
26220           * way, either Dial or Queue can apply this connected line update to the outgoing ringing channel.
26221           */
26222          ast_channel_queue_connected_line_update(target.chan1, &connected_to_transferee, NULL);
26223 
26224       }
26225       sip_pvt_lock(transferer); /* the transferer pvt is expected to remain locked on return */
26226 
26227       ast_channel_unref(current->chan1);
26228    }
26229 
26230    /* at this point if the transfer is successful only the transferer pvt should be locked. */
26231    ast_party_connected_line_free(&connected_to_target);
26232    ast_party_connected_line_free(&connected_to_transferee);
26233    ast_channel_unref(target.chan1);
26234    if (target.chan2) {
26235       ast_channel_unref(target.chan2);
26236    }
26237    if (targetcall_pvt)
26238       ao2_t_ref(targetcall_pvt, -1, "drop targetcall_pvt");
26239    return 1;
26240 }
26241 
26242 
26243 /*! \brief Handle incoming REFER request */
26244 /*! \page SIP_REFER SIP transfer Support (REFER)
26245 
26246    REFER is used for call transfer in SIP. We get a REFER
26247    to place a new call with an INVITE somwhere and then
26248    keep the transferor up-to-date of the transfer. If the
26249    transfer fails, get back on line with the orginal call.
26250 
26251    - REFER can be sent outside or inside of a dialog.
26252      Asterisk only accepts REFER inside of a dialog.
26253 
26254    - If we get a replaces header, it is an attended transfer
26255 
26256    \par Blind transfers
26257    The transferor provides the transferee
26258    with the transfer targets contact. The signalling between
26259    transferer or transferee should not be cancelled, so the
26260    call is recoverable if the transfer target can not be reached
26261    by the transferee.
26262 
26263    In this case, Asterisk receives a TRANSFER from
26264    the transferor, thus is the transferee. We should
26265    try to set up a call to the contact provided
26266    and if that fails, re-connect the current session.
26267    If the new call is set up, we issue a hangup.
26268    In this scenario, we are following section 5.2
26269    in the SIP CC Transfer draft. (Transfer without
26270    a GRUU)
26271 
26272    \par Transfer with consultation hold
26273    In this case, the transferor
26274    talks to the transfer target before the transfer takes place.
26275    This is implemented with SIP hold and transfer.
26276    Note: The invite From: string could indicate a transfer.
26277    (Section 6. Transfer with consultation hold)
26278    The transferor places the transferee on hold, starts a call
26279    with the transfer target to alert them to the impending
26280    transfer, terminates the connection with the target, then
26281    proceeds with the transfer (as in Blind transfer above)
26282 
26283    \par Attended transfer
26284    The transferor places the transferee
26285    on hold, calls the transfer target to alert them,
26286    places the target on hold, then proceeds with the transfer
26287    using a Replaces header field in the Refer-to header. This
26288    will force the transfee to send an Invite to the target,
26289    with a replaces header that instructs the target to
26290    hangup the call between the transferor and the target.
26291    In this case, the Refer/to: uses the AOR address. (The same
26292    URI that the transferee used to establish the session with
26293    the transfer target (To: ). The Require: replaces header should
26294    be in the INVITE to avoid the wrong UA in a forked SIP proxy
26295    scenario to answer and have no call to replace with.
26296 
26297    The referred-by header is *NOT* required, but if we get it,
26298    can be copied into the INVITE to the transfer target to
26299    inform the target about the transferor
26300 
26301    "Any REFER request has to be appropriately authenticated.".
26302    
26303    We can't destroy dialogs, since we want the call to continue.
26304    
26305    */
26306 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, uint32_t seqno, int *nounlock)
26307 {
26308    /*!
26309     * Chan1: Call between asterisk and transferer
26310     * Chan2: Call between asterisk and transferee
26311     */
26312    struct sip_dual current = { 0, };
26313    struct ast_channel *chans[2] = { 0, };
26314    char *refer_to = NULL;
26315    char *refer_to_domain = NULL;
26316    char *refer_to_context = NULL;
26317    char *referred_by = NULL;
26318    char *callid = NULL;
26319    int localtransfer = 0;
26320    int attendedtransfer = 0;
26321    int res = 0;
26322    struct ast_party_redirecting redirecting;
26323    struct ast_set_party_redirecting update_redirecting;
26324 
26325    if (req->debug) {
26326       ast_verbose("Call %s got a SIP call transfer from %s: (REFER)!\n",
26327          p->callid,
26328          ast_test_flag(&p->flags[0], SIP_OUTGOING) ? "callee" : "caller");
26329    }
26330 
26331    if (!p->owner) {
26332       /* This is a REFER outside of an existing SIP dialog */
26333       /* We can't handle that, so decline it */
26334       ast_debug(3, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
26335       transmit_response(p, "603 Declined (No dialog)", req);
26336       if (!req->ignore) {
26337          append_history(p, "Xfer", "Refer failed. Outside of dialog.");
26338          sip_alreadygone(p);
26339          pvt_set_needdestroy(p, "outside of dialog");
26340       }
26341       res = 0;
26342       goto handle_refer_cleanup;
26343    }
26344 
26345    /* Check if transfer is allowed from this device */
26346    if (p->allowtransfer == TRANSFER_CLOSED ) {
26347       /* Transfer not allowed, decline */
26348       transmit_response(p, "603 Declined (policy)", req);
26349       append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
26350       /* Do not destroy SIP session */
26351       res = 0;
26352       goto handle_refer_cleanup;
26353    }
26354 
26355    if (!req->ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
26356       /* Already have a pending REFER */
26357       transmit_response(p, "491 Request pending", req);
26358       append_history(p, "Xfer", "Refer failed. Request pending.");
26359       res = 0;
26360       goto handle_refer_cleanup;
26361    }
26362 
26363    /* Allocate memory for call transfer data */
26364    if (!p->refer && !sip_refer_alloc(p)) {
26365       transmit_response(p, "500 Internal Server Error", req);
26366       append_history(p, "Xfer", "Refer failed. Memory allocation error.");
26367       res = -3;
26368       goto handle_refer_cleanup;
26369    }
26370 
26371    res = get_refer_info(p, req); /* Extract headers */
26372 
26373    p->refer->status = REFER_SENT;
26374 
26375    if (res != 0) {
26376       switch (res) {
26377       case -2: /* Syntax error */
26378          transmit_response(p, "400 Bad Request (Refer-to missing)", req);
26379          append_history(p, "Xfer", "Refer failed. Refer-to missing.");
26380          if (req->debug) {
26381             ast_debug(1, "SIP transfer to black hole can't be handled (no refer-to: )\n");
26382          }
26383          break;
26384       case -3:
26385          transmit_response(p, "603 Declined (Non sip: uri)", req);
26386          append_history(p, "Xfer", "Refer failed. Non SIP uri");
26387          if (req->debug) {
26388             ast_debug(1, "SIP transfer to non-SIP uri denied\n");
26389          }
26390          break;
26391       default:
26392          /* Refer-to extension not found, fake a failed transfer */
26393          transmit_response(p, "202 Accepted", req);
26394          append_history(p, "Xfer", "Refer failed. Bad extension.");
26395          transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
26396          ast_clear_flag(&p->flags[0], SIP_GOTREFER);
26397          if (req->debug) {
26398             ast_debug(1, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
26399          }
26400          break;
26401       }
26402       res = 0;
26403       goto handle_refer_cleanup;
26404    }
26405    if (ast_strlen_zero(p->context)) {
26406       ast_string_field_set(p, context, sip_cfg.default_context);
26407    }
26408 
26409    /* If we do not support SIP domains, all transfers are local */
26410    if (sip_cfg.allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
26411       p->refer->localtransfer = 1;
26412       if (sipdebug) {
26413          ast_debug(3, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
26414       }
26415    } else if (AST_LIST_EMPTY(&domain_list) || check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
26416       /* This PBX doesn't bother with SIP domains or domain is local, so this transfer is local */
26417       p->refer->localtransfer = 1;
26418    } else if (sipdebug) {
26419       ast_debug(3, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
26420    }
26421 
26422    /* Is this a repeat of a current request? Ignore it */
26423    /* Don't know what else to do right now. */
26424    if (req->ignore) {
26425       goto handle_refer_cleanup;
26426    }
26427 
26428    /* If this is a blind transfer, we have the following
26429    channels to work with:
26430    - chan1, chan2: The current call between transferer and transferee (2 channels)
26431    - target_channel: A new call from the transferee to the target (1 channel)
26432    We need to stay tuned to what happens in order to be able
26433    to bring back the call to the transferer */
26434 
26435    /* If this is a attended transfer, we should have all call legs within reach:
26436    - chan1, chan2: The call between the transferer and transferee (2 channels)
26437    - target_channel, targetcall_pvt: The call between the transferer and the target (2 channels)
26438    We want to bridge chan2 with targetcall_pvt!
26439    
26440    The replaces call id in the refer message points
26441    to the call leg between Asterisk and the transferer.
26442    So we need to connect the target and the transferee channel
26443    and hangup the two other channels silently
26444    
26445    If the target is non-local, the call ID could be on a remote
26446    machine and we need to send an INVITE with replaces to the
26447    target. We basically handle this as a blind transfer
26448    and let the sip_call function catch that we need replaces
26449    header in the INVITE.
26450    */
26451 
26452    /* Get the transferer's channel */
26453    chans[0] = current.chan1 = p->owner;
26454 
26455    /* Find the other part of the bridge (2) - transferee */
26456    chans[1] = current.chan2 = ast_bridged_channel(current.chan1);
26457 
26458    ast_channel_ref(current.chan1);
26459    if (current.chan2) {
26460       ast_channel_ref(current.chan2);
26461    }
26462 
26463    if (sipdebug) {
26464       ast_debug(3, "SIP %s transfer: Transferer channel %s, transferee channel %s\n",
26465          p->refer->attendedtransfer ? "attended" : "blind",
26466          ast_channel_name(current.chan1),
26467          current.chan2 ? ast_channel_name(current.chan2) : "<none>");
26468    }
26469 
26470    if (!current.chan2 && !p->refer->attendedtransfer) {
26471       /* No bridged channel, propably IVR or echo or similar... */
26472       /* Guess we should masquerade or something here */
26473       /* Until we figure it out, refuse transfer of such calls */
26474       if (sipdebug) {
26475          ast_debug(3, "Refused SIP transfer on non-bridged channel.\n");
26476       }
26477       p->refer->status = REFER_FAILED;
26478       append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
26479       transmit_response(p, "603 Declined", req);
26480       res = -1;
26481       goto handle_refer_cleanup;
26482    }
26483 
26484    if (current.chan2) {
26485       if (sipdebug) {
26486          ast_debug(4, "Got SIP transfer, applying to bridged peer '%s'\n", ast_channel_name(current.chan2));
26487       }
26488       ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
26489    }
26490 
26491    ast_set_flag(&p->flags[0], SIP_GOTREFER);
26492 
26493    /* From here on failures will be indicated with NOTIFY requests */
26494    transmit_response(p, "202 Accepted", req);
26495 
26496    /* Attended transfer: Find all call legs and bridge transferee with target*/
26497    if (p->refer->attendedtransfer) {
26498       /* both p and p->owner _MUST_ be locked while calling local_attended_transfer */
26499       if ((res = local_attended_transfer(p, &current, req, seqno, nounlock))) {
26500          goto handle_refer_cleanup; /* We're done with the transfer */
26501       }
26502       /* Fall through for remote transfers that we did not find locally */
26503       if (sipdebug) {
26504          ast_debug(4, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
26505       }
26506       /* Fallthrough if we can't find the call leg internally */
26507    }
26508 
26509    /* Copy data we can not safely access after letting the pvt lock go. */
26510    refer_to = ast_strdupa(p->refer->refer_to);
26511    refer_to_domain = ast_strdupa(p->refer->refer_to_domain);
26512    refer_to_context = ast_strdupa(p->refer->refer_to_context);
26513    referred_by = ast_strdupa(p->refer->referred_by);
26514    callid = ast_strdupa(p->callid);
26515    localtransfer = p->refer->localtransfer;
26516    attendedtransfer = p->refer->attendedtransfer;
26517 
26518    if (!*nounlock) {
26519       ast_channel_unlock(p->owner);
26520       *nounlock = 1;
26521    }
26522    sip_pvt_unlock(p);
26523 
26524    /* Parking a call.  DO NOT hold any locks while calling ast_parking_ext_valid() */
26525    if (localtransfer && ast_parking_ext_valid(refer_to, current.chan1, refer_to_context)) {
26526       sip_pvt_lock(p);
26527       ast_clear_flag(&p->flags[0], SIP_GOTREFER);
26528       p->refer->status = REFER_200OK;
26529       append_history(p, "Xfer", "REFER to call parking.");
26530       sip_pvt_unlock(p);
26531 
26532       ast_manager_event_multichan(EVENT_FLAG_CALL, "Transfer", 2, chans,
26533          "TransferMethod: SIP\r\n"
26534          "TransferType: Blind\r\n"
26535          "Channel: %s\r\n"
26536          "Uniqueid: %s\r\n"
26537          "SIP-Callid: %s\r\n"
26538          "TargetChannel: %s\r\n"
26539          "TargetUniqueid: %s\r\n"
26540          "TransferExten: %s\r\n"
26541          "Transfer2Parking: Yes\r\n",
26542          ast_channel_name(current.chan1),
26543          ast_channel_uniqueid(current.chan1),
26544          callid,
26545          ast_channel_name(current.chan2),
26546          ast_channel_uniqueid(current.chan2),
26547          refer_to);
26548 
26549       if (sipdebug) {
26550          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));
26551       }
26552 
26553       /* DO NOT hold any locks while calling sip_park */
26554       if (sip_park(current.chan2, current.chan1, req, seqno, refer_to, refer_to_context)) {
26555          sip_pvt_lock(p);
26556          transmit_notify_with_sipfrag(p, seqno, "500 Internal Server Error", TRUE);
26557       } else {
26558          sip_pvt_lock(p);
26559       }
26560       goto handle_refer_cleanup;
26561    }
26562 
26563    /* Blind transfers and remote attended xfers.
26564     * Locks should not be held while calling pbx_builtin_setvar_helper. This function
26565     * locks the channel being passed into it.*/
26566    if (current.chan1 && current.chan2) {
26567       ast_debug(3, "chan1->name: %s\n", ast_channel_name(current.chan1));
26568       pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", ast_channel_name(current.chan2));
26569    }
26570 
26571    if (current.chan2) {
26572       pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", ast_channel_name(current.chan1));
26573       pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", refer_to_domain);
26574       pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
26575       /* One for the new channel */
26576       pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
26577       /* Attended transfer to remote host, prepare headers for the INVITE */
26578       if (!ast_strlen_zero(referred_by)) {
26579          pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", referred_by);
26580       }
26581 
26582       /* When a call is transferred to voicemail from a Digium phone, there may be
26583        * a Diversion header present in the REFER with an appropriate reason parameter
26584        * set. We need to update the redirecting information appropriately.
26585        */
26586       ast_channel_lock(p->owner);
26587       sip_pvt_lock(p);
26588       ast_party_redirecting_init(&redirecting);
26589       memset(&update_redirecting, 0, sizeof(update_redirecting));
26590       change_redirecting_information(p, req, &redirecting, &update_redirecting, FALSE);
26591 
26592       /* Do not hold the pvt lock during a call that causes an indicate or an async_goto.
26593        * Those functions lock channels which will invalidate locking order if the pvt lock
26594        * is held.*/
26595       sip_pvt_unlock(p);
26596       ast_channel_unlock(p->owner);
26597       ast_channel_update_redirecting(current.chan2, &redirecting, &update_redirecting);
26598       ast_party_redirecting_free(&redirecting);
26599    }
26600 
26601    sip_pvt_lock(p);
26602    /* Generate a Replaces string to be used in the INVITE during attended transfer */
26603    if (!ast_strlen_zero(p->refer->replaces_callid)) {
26604       char tempheader[SIPBUFSIZE];
26605       snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid,
26606          p->refer->replaces_callid_totag ? ";to-tag=" : "",
26607          p->refer->replaces_callid_totag,
26608          p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
26609          p->refer->replaces_callid_fromtag);
26610 
26611       if (current.chan2) {
26612          sip_pvt_unlock(p);
26613          pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader);
26614          sip_pvt_lock(p);
26615       }
26616    }
26617 
26618    /* Connect the call */
26619 
26620    /* FAKE ringing if not attended transfer */
26621    if (!p->refer->attendedtransfer) {
26622       transmit_notify_with_sipfrag(p, seqno, "180 Ringing", FALSE);
26623    }
26624 
26625    /* For blind transfer, this will lead to a new call */
26626    /* For attended transfer to remote host, this will lead to
26627       a new SIP call with a replaces header, if the dial plan allows it
26628    */
26629    if (!current.chan2) {
26630       /* We have no bridge, so we're talking with Asterisk somehow */
26631       /* We need to masquerade this call */
26632       /* What to do to fix this situation:
26633          * Set up the new call in a new channel
26634          * Let the new channel masq into this channel
26635          Please add that code here :-)
26636       */
26637       p->refer->status = REFER_FAILED;
26638       transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
26639       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
26640       append_history(p, "Xfer", "Refer failed (only bridged calls).");
26641       res = -1;
26642       goto handle_refer_cleanup;
26643    }
26644    ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);   /* Delay hangup */
26645 
26646    sip_pvt_unlock(p);
26647 
26648    /* For blind transfers, move the call to the new extensions. For attended transfers on multiple
26649     * servers - generate an INVITE with Replaces. Either way, let the dial plan decided
26650     * indicate before masquerade so the indication actually makes it to the real channel
26651     * when using local channels with MOH passthru */
26652    ast_indicate(current.chan2, AST_CONTROL_UNHOLD);
26653    res = ast_async_goto(current.chan2, refer_to_context, refer_to, 1);
26654 
26655    if (!res) {
26656       ast_manager_event_multichan(EVENT_FLAG_CALL, "Transfer", 2, chans,
26657          "TransferMethod: SIP\r\n"
26658          "TransferType: Blind\r\n"
26659          "Channel: %s\r\n"
26660          "Uniqueid: %s\r\n"
26661          "SIP-Callid: %s\r\n"
26662          "TargetChannel: %s\r\n"
26663          "TargetUniqueid: %s\r\n"
26664          "TransferExten: %s\r\n"
26665          "TransferContext: %s\r\n",
26666          ast_channel_name(current.chan1),
26667          ast_channel_uniqueid(current.chan1),
26668          callid,
26669          ast_channel_name(current.chan2),
26670          ast_channel_uniqueid(current.chan2),
26671          refer_to,
26672          refer_to_context);
26673       /* Success  - we have a new channel */
26674       ast_debug(3, "%s transfer succeeded. Telling transferer.\n", attendedtransfer? "Attended" : "Blind");
26675 
26676       /* XXX - what to we put in CEL 'extra' for attended transfers to external systems? NULL for now */
26677       ast_channel_lock(current.chan1);
26678       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);
26679       ast_channel_unlock(current.chan1);
26680 
26681       sip_pvt_lock(p);
26682       transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
26683       if (p->refer->localtransfer) {
26684          p->refer->status = REFER_200OK;
26685       }
26686       if (p->owner) {
26687          ast_channel_hangupcause_set(p->owner, AST_CAUSE_NORMAL_CLEARING);
26688       }
26689       append_history(p, "Xfer", "Refer succeeded.");
26690       ast_clear_flag(&p->flags[0], SIP_GOTREFER);
26691       /* Do not hangup call, the other side do that when we say 200 OK */
26692       /* We could possibly implement a timer here, auto congestion */
26693       res = 0;
26694    } else {
26695       sip_pvt_lock(p);
26696       ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Don't delay hangup */
26697       ast_debug(3, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
26698       append_history(p, "Xfer", "Refer failed.");
26699       /* Failure of some kind */
26700       p->refer->status = REFER_FAILED;
26701       transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
26702       ast_clear_flag(&p->flags[0], SIP_GOTREFER);
26703       res = -1;
26704    }
26705 
26706 handle_refer_cleanup:
26707    if (current.chan1) {
26708       ast_channel_unref(current.chan1);
26709    }
26710    if (current.chan2) {
26711       ast_channel_unref(current.chan2);
26712    }
26713 
26714    /* Make sure we exit with the pvt locked */
26715    return res;
26716 }
26717 
26718 /*! \brief Handle incoming CANCEL request */
26719 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
26720 {
26721 
26722    check_via(p, req);
26723    sip_alreadygone(p);
26724 
26725    if (p->owner && ast_channel_state(p->owner) == AST_STATE_UP) {
26726       /* This call is up, cancel is ignored, we need a bye */
26727       transmit_response(p, "200 OK", req);
26728       ast_debug(1, "Got CANCEL on an answered call. Ignoring... \n");
26729       return 0;
26730    }
26731 
26732    /* At this point, we could have cancelled the invite at the same time
26733       as the other side sends a CANCEL. Our final reply with error code
26734       might not have been received by the other side before the CANCEL
26735       was sent, so let's just give up retransmissions and waiting for
26736       ACK on our error code. The call is hanging up any way. */
26737    if (p->invitestate == INV_TERMINATED || p->invitestate == INV_COMPLETED) {
26738       __sip_pretend_ack(p);
26739    }
26740    if (p->invitestate != INV_TERMINATED)
26741       p->invitestate = INV_CANCELLED;
26742 
26743    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD))
26744       update_call_counter(p, DEC_CALL_LIMIT);
26745 
26746    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
26747    if (p->owner) {
26748       sip_queue_hangup_cause(p, 0);
26749    } else {
26750       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
26751    }
26752    if (ast_str_strlen(p->initreq.data) > 0) {
26753       struct sip_pkt *pkt, *prev_pkt;
26754       /* If the CANCEL we are receiving is a retransmission, and we already have scheduled
26755        * a reliable 487, then we don't want to schedule another one on top of the previous
26756        * one.
26757        *
26758        * As odd as this may sound, we can't rely on the previously-transmitted "reliable"
26759        * response in this situation. What if we've sent all of our reliable responses
26760        * already and now all of a sudden, we get this second CANCEL?
26761        *
26762        * The only way to do this correctly is to cancel our previously-scheduled reliably-
26763        * transmitted response and send a new one in its place.
26764        */
26765       for (pkt = p->packets, prev_pkt = NULL; pkt; prev_pkt = pkt, pkt = pkt->next) {
26766          if (pkt->seqno == p->lastinvite && pkt->response_code == 487) {
26767             AST_SCHED_DEL(sched, pkt->retransid);
26768             UNLINK(pkt, p->packets, prev_pkt);
26769             dialog_unref(pkt->owner, "unref packet->owner from dialog");
26770             if (pkt->data) {
26771                ast_free(pkt->data);
26772             }
26773             ast_free(pkt);
26774             break;
26775          }
26776       }
26777       transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
26778       transmit_response(p, "200 OK", req);
26779       return 1;
26780    } else {
26781       transmit_response(p, "481 Call Leg Does Not Exist", req);
26782       return 0;
26783    }
26784 }
26785 
26786 /*! \brief Handle incoming BYE request */
26787 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
26788 {
26789    struct ast_channel *c=NULL;
26790    int res;
26791    struct ast_channel *bridged_to;
26792    const char *required;
26793 
26794    /* If we have an INCOMING invite that we haven't answered, terminate that transaction */
26795    if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !req->ignore) {
26796       transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
26797    }
26798 
26799    __sip_pretend_ack(p);
26800 
26801    p->invitestate = INV_TERMINATED;
26802 
26803    copy_request(&p->initreq, req);
26804    if (sipdebug)
26805       ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
26806    check_via(p, req);
26807    sip_alreadygone(p);
26808 
26809    /* Get RTCP quality before end of call */
26810    if (p->do_history || p->owner) {
26811       char quality_buf[AST_MAX_USER_FIELD], *quality;
26812       struct ast_channel *bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
26813 
26814       /* We need to get the lock on bridge because ast_rtp_instance_set_stats_vars will attempt
26815        * to lock the bridge. This may get hairy...
26816        */
26817       while (bridge && ast_channel_trylock(bridge)) {
26818          ast_channel_unlock(p->owner);
26819          do {
26820             /* Can't use DEADLOCK_AVOIDANCE since p is an ao2 object */
26821             sip_pvt_unlock(p);
26822             usleep(1);
26823             sip_pvt_lock(p);
26824          } while (p->owner && ast_channel_trylock(p->owner));
26825          bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
26826       }
26827 
26828 
26829       if (p->rtp && (quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
26830          if (p->do_history) {
26831             append_history(p, "RTCPaudio", "Quality:%s", quality);
26832 
26833             if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_JITTER, quality_buf, sizeof(quality_buf)))) {
26834                append_history(p, "RTCPaudioJitter", "Quality:%s", quality);
26835             }
26836             if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_LOSS, quality_buf, sizeof(quality_buf)))) {
26837                append_history(p, "RTCPaudioLoss", "Quality:%s", quality);
26838             }
26839             if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_RTT, quality_buf, sizeof(quality_buf)))) {
26840                append_history(p, "RTCPaudioRTT", "Quality:%s", quality);
26841             }
26842          }
26843 
26844          if (p->owner) {
26845             ast_rtp_instance_set_stats_vars(p->owner, p->rtp);
26846          }
26847 
26848       }
26849 
26850       if (bridge) {
26851          struct sip_pvt *q = ast_channel_tech_pvt(bridge);
26852 
26853          if (IS_SIP_TECH(ast_channel_tech(bridge)) && q && q->rtp) {
26854             ast_rtp_instance_set_stats_vars(bridge, q->rtp);
26855          }
26856          ast_channel_unlock(bridge);
26857       }
26858 
26859       if (p->vrtp && (quality = ast_rtp_instance_get_quality(p->vrtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
26860          if (p->do_history) {
26861             append_history(p, "RTCPvideo", "Quality:%s", quality);
26862          }
26863          if (p->owner) {
26864             pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", quality);
26865          }
26866       }
26867       if (p->trtp && (quality = ast_rtp_instance_get_quality(p->trtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
26868          if (p->do_history) {
26869             append_history(p, "RTCPtext", "Quality:%s", quality);
26870          }
26871          if (p->owner) {
26872             pbx_builtin_setvar_helper(p->owner, "RTPTEXTQOS", quality);
26873          }
26874       }
26875    }
26876 
26877    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
26878    stop_session_timer(p); /* Stop Session-Timer */
26879 
26880    if (!ast_strlen_zero(sip_get_header(req, "Also"))) {
26881       ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method.  Ask vendor to support REFER instead\n",
26882          ast_sockaddr_stringify(&p->recv));
26883       if (ast_strlen_zero(p->context))
26884          ast_string_field_set(p, context, sip_cfg.default_context);
26885       res = get_also_info(p, req);
26886       if (!res) {
26887          c = p->owner;
26888          if (c) {
26889             bridged_to = ast_bridged_channel(c);
26890             if (bridged_to) {
26891                /* Don't actually hangup here... */
26892                ast_queue_control(c, AST_CONTROL_UNHOLD);
26893                ast_channel_unlock(c);  /* async_goto can do a masquerade, no locks can be held during a masq */
26894                ast_async_goto(bridged_to, p->context, p->refer->refer_to, 1);
26895                ast_channel_lock(c);
26896             } else
26897                ast_queue_hangup(p->owner);
26898          }
26899       } else {
26900          ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_sockaddr_stringify(&p->recv));
26901          if (p->owner)
26902             ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
26903       }
26904    } else if (p->owner) {
26905       sip_queue_hangup_cause(p, 0);
26906       sip_scheddestroy_final(p, DEFAULT_TRANS_TIMEOUT);
26907       ast_debug(3, "Received bye, issuing owner hangup\n");
26908    } else {
26909       sip_scheddestroy_final(p, DEFAULT_TRANS_TIMEOUT);
26910       ast_debug(3, "Received bye, no owner, selfdestruct soon.\n");
26911    }
26912    ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
26913 
26914    /* Find out what they require */
26915    required = sip_get_header(req, "Require");
26916    if (!ast_strlen_zero(required)) {
26917       char unsupported[256] = { 0, };
26918       parse_sip_options(required, unsupported, ARRAY_LEN(unsupported));
26919       /* If there are any options required that we do not support,
26920        * then send a 420 with only those unsupported options listed */
26921       if (!ast_strlen_zero(unsupported)) {
26922          transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, unsupported);
26923          ast_log(LOG_WARNING, "Received SIP BYE with unsupported required extension: required:%s unsupported:%s\n", required, unsupported);
26924       } else {
26925          transmit_response(p, "200 OK", req);
26926       }
26927    } else {
26928       transmit_response(p, "200 OK", req);
26929    }
26930 
26931    return 1;
26932 }
26933 
26934 /*! \brief Handle incoming MESSAGE request */
26935 static int handle_request_message(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e)
26936 {
26937    if (!req->ignore) {
26938       if (req->debug)
26939          ast_verbose("Receiving message!\n");
26940       receive_message(p, req, addr, e);
26941    } else
26942       transmit_response(p, "202 Accepted", req);
26943    return 1;
26944 }
26945 
26946 static int sip_msg_send(const struct ast_msg *msg, const char *to, const char *from);
26947 
26948 static const struct ast_msg_tech sip_msg_tech = {
26949    .name = "sip",
26950    .msg_send = sip_msg_send,
26951 };
26952 
26953 /*!
26954  * \internal
26955  * \brief Check if the given header name is blocked.
26956  *
26957  * \details Determine if the given header name from the user is
26958  * blocked for outgoing MESSAGE packets.
26959  *
26960  * \param header_name Name of header to see if it is blocked.
26961  *
26962  * \retval TRUE if the given header is blocked.
26963  */
26964 static int block_msg_header(const char *header_name)
26965 {
26966    int idx;
26967 
26968    /*
26969     * Don't block Content-Type or Max-Forwards headers because the
26970     * user can override them.
26971     */
26972    static const char *hdr[] = {
26973       "To",
26974       "From",
26975       "Via",
26976       "Route",
26977       "Contact",
26978       "Call-ID",
26979       "CSeq",
26980       "Allow",
26981       "Content-Length",
26982       "Request-URI",
26983    };
26984 
26985    for (idx = 0; idx < ARRAY_LEN(hdr); ++idx) {
26986       if (!strcasecmp(header_name, hdr[idx])) {
26987          /* Block addition of this header. */
26988          return 1;
26989       }
26990    }
26991    return 0;
26992 }
26993 
26994 static int sip_msg_send(const struct ast_msg *msg, const char *to, const char *from)
26995 {
26996    struct sip_pvt *pvt;
26997    int res;
26998    char *to_uri;
26999    char *to_host;
27000    char *to_user;
27001    const char *var;
27002    const char *val;
27003    struct ast_msg_var_iterator *iter;
27004    struct sip_peer *peer_ptr;
27005 
27006    if (!(pvt = sip_alloc(NULL, NULL, 0, SIP_MESSAGE, NULL, NULL))) {
27007       return -1;
27008    }
27009 
27010         for (iter = ast_msg_var_iterator_init(msg);
27011         ast_msg_var_iterator_next(msg, iter, &var, &val);
27012         ast_msg_var_unref_current(iter)) {
27013       if (!strcasecmp(var, "Request-URI")) {
27014          ast_string_field_set(pvt, fullcontact, val);
27015          ast_msg_var_unref_current(iter);
27016          break;
27017       }
27018    }
27019    ast_msg_var_iterator_destroy(iter);
27020 
27021    to_uri = ast_strdupa(to);
27022    to_uri = get_in_brackets(to_uri);
27023    parse_uri(to_uri, "sip:,sips:", &to_user, NULL, &to_host, NULL);
27024 
27025    if (ast_strlen_zero(to_host)) {
27026       ast_log(LOG_WARNING, "MESSAGE(to) is invalid for SIP - '%s'\n", to);
27027       dialog_unlink_all(pvt);
27028       dialog_unref(pvt, "MESSAGE(to) is invalid for SIP");
27029       return -1;
27030    }
27031 
27032    if (!ast_strlen_zero(from)) {
27033       if ((peer_ptr = sip_find_peer(from, NULL, 0, 1, 0, 0))) {
27034          ast_string_field_set(pvt, fromname, S_OR(peer_ptr->cid_name, peer_ptr->name));
27035          ast_string_field_set(pvt, fromuser, S_OR(peer_ptr->cid_num, peer_ptr->name));
27036          sip_unref_peer(peer_ptr, "sip_unref_peer, from sip_msg_send, sip_find_peer");
27037       } else if (strchr(from, '<')) { /* from is callerid-style */
27038          char *sender;
27039          char *name = NULL, *location = NULL, *user = NULL, *domain = NULL;
27040 
27041          sender = ast_strdupa(from);
27042          ast_callerid_parse(sender, &name, &location);
27043          if (ast_strlen_zero(location)) {
27044             /* This can occur if either
27045              *  1) A name-addr style From header does not close the angle brackets
27046              *  properly.
27047              *  2) The From header is not in name-addr style and the content of the
27048              *  From contains characters other than 0-9, *, #, or +.
27049              *
27050              *  In both cases, ast_callerid_parse() should have parsed the From header
27051              *  as a name rather than a number. So we just need to set the location
27052              *  to what was parsed as a name, and set the name NULL since there was
27053              *  no name present.
27054              */
27055             location = name;
27056             name = NULL;
27057          }
27058          ast_string_field_set(pvt, fromname, name);
27059          if (strchr(location, ':')) { /* Must be a URI */
27060             parse_uri(location, "sip:,sips:", &user, NULL, &domain, NULL);
27061             SIP_PEDANTIC_DECODE(user);
27062             SIP_PEDANTIC_DECODE(domain);
27063             extract_host_from_hostport(&domain);
27064             ast_string_field_set(pvt, fromuser, user);
27065             ast_string_field_set(pvt, fromdomain, domain);
27066          } else { /* Treat it as an exten/user */
27067             ast_string_field_set(pvt, fromuser, location);
27068          }
27069       } else { /* assume we just have the name, use defaults for the rest */
27070          ast_string_field_set(pvt, fromname, from);
27071       }
27072    }
27073 
27074    sip_pvt_lock(pvt);
27075 
27076    /* Look up the host to contact */
27077    if (create_addr(pvt, to_host, NULL, TRUE)) {
27078       sip_pvt_unlock(pvt);
27079       dialog_unlink_all(pvt);
27080       dialog_unref(pvt, "create_addr failed sending a MESSAGE");
27081       return -1;
27082    }
27083 
27084    if (!ast_strlen_zero(to_user)) {
27085       ast_string_field_set(pvt, username, to_user);
27086    }
27087    ast_sip_ouraddrfor(&pvt->sa, &pvt->ourip, pvt);
27088    build_via(pvt);
27089    ast_set_flag(&pvt->flags[0], SIP_OUTGOING);
27090 
27091    /* XXX Does pvt->expiry need to be set? */
27092 
27093    /* Save additional MESSAGE headers in case of authentication request. */
27094    for (iter = ast_msg_var_iterator_init(msg);
27095       ast_msg_var_iterator_next(msg, iter, &var, &val);
27096       ast_msg_var_unref_current(iter)) {
27097       if (!strcasecmp(var, "Max-Forwards")) {
27098          /* Decrement Max-Forwards for SIP loop prevention. */
27099          if (sscanf(val, "%30d", &pvt->maxforwards) != 1 || pvt->maxforwards < 1) {
27100             sip_pvt_unlock(pvt);
27101             dialog_unlink_all(pvt);
27102             dialog_unref(pvt, "MESSAGE(Max-Forwards) reached zero.");
27103             ast_log(LOG_NOTICE,
27104                "MESSAGE(Max-Forwards) reached zero.  MESSAGE not sent.\n");
27105             return -1;
27106          }
27107          --pvt->maxforwards;
27108          continue;
27109       }
27110       if (block_msg_header(var)) {
27111          /* Block addition of this header. */
27112          continue;
27113       }
27114       add_msg_header(pvt, var, val);
27115    }
27116    ast_msg_var_iterator_destroy(iter);
27117 
27118    ast_string_field_set(pvt, msg_body, ast_msg_get_body(msg));
27119    res = transmit_message(pvt, 1, 0);
27120 
27121    sip_pvt_unlock(pvt);
27122    sip_scheddestroy(pvt, DEFAULT_TRANS_TIMEOUT);
27123    dialog_unref(pvt, "sent a MESSAGE");
27124 
27125    return res;
27126 }
27127 
27128 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)
27129 {
27130    int etag_present = !ast_strlen_zero(etag);
27131    int body_present = req->lines > 0;
27132 
27133    ast_assert(expires_int != NULL);
27134 
27135    if (ast_strlen_zero(expires)) {
27136       /* Section 6, item 4, second bullet point of RFC 3903 says to
27137        * use a locally-configured default expiration if none is provided
27138        * in the request
27139        */
27140       *expires_int = DEFAULT_PUBLISH_EXPIRES;
27141    } else if (sscanf(expires, "%30d", expires_int) != 1) {
27142       return SIP_PUBLISH_UNKNOWN;
27143    }
27144 
27145    if (*expires_int == 0) {
27146       return SIP_PUBLISH_REMOVE;
27147    } else if (!etag_present && body_present) {
27148       return SIP_PUBLISH_INITIAL;
27149    } else if (etag_present && !body_present) {
27150       return SIP_PUBLISH_REFRESH;
27151    } else if (etag_present && body_present) {
27152       return SIP_PUBLISH_MODIFY;
27153    }
27154 
27155    return SIP_PUBLISH_UNKNOWN;
27156 }
27157 
27158 #ifdef HAVE_LIBXML2
27159 static int pidf_validate_tuple(struct ast_xml_node *tuple_node)
27160 {
27161    const char *id;
27162    int status_found = FALSE;
27163    struct ast_xml_node *tuple_children;
27164    struct ast_xml_node *tuple_children_iterator;
27165    /* Tuples have to have an id attribute or they're invalid */
27166    if (!(id = ast_xml_get_attribute(tuple_node, "id"))) {
27167       ast_log(LOG_WARNING, "Tuple XML element has no attribute 'id'\n");
27168       return FALSE;
27169    }
27170    /* We don't care what it actually is, just that it's there */
27171    ast_xml_free_attr(id);
27172    /* This is a tuple. It must have a status element */
27173    if (!(tuple_children = ast_xml_node_get_children(tuple_node))) {
27174       /* The tuple has no children. It sucks */
27175       ast_log(LOG_WARNING, "Tuple XML element has no child elements\n");
27176       return FALSE;
27177    }
27178    for (tuple_children_iterator = tuple_children; tuple_children_iterator;
27179          tuple_children_iterator = ast_xml_node_get_next(tuple_children_iterator)) {
27180       /* Similar to the wording used regarding tuples, the status element should appear
27181        * first. However, we will once again relax things and accept the status at any
27182        * position. We will enforce that only a single status element can be present.
27183        */
27184       if (strcmp(ast_xml_node_get_name(tuple_children_iterator), "status")) {
27185          /* Not the status, we don't care */
27186          continue;
27187       }
27188       if (status_found == TRUE) {
27189          /* THERE CAN BE ONLY ONE!!! */
27190          ast_log(LOG_WARNING, "Multiple status elements found in tuple. Only one allowed\n");
27191          return FALSE;
27192       }
27193       status_found = TRUE;
27194    }
27195    return status_found;
27196 }
27197 
27198 
27199 static int pidf_validate_presence(struct ast_xml_doc *doc)
27200 {
27201    struct ast_xml_node *presence_node = ast_xml_get_root(doc);
27202    struct ast_xml_node *child_nodes;
27203    struct ast_xml_node *node_iterator;
27204    struct ast_xml_ns *ns;
27205    const char *entity;
27206    const char *namespace;
27207    const char presence_namespace[] = "urn:ietf:params:xml:ns:pidf";
27208 
27209    if (!presence_node) {
27210       ast_log(LOG_WARNING, "Unable to retrieve root node of the XML document\n");
27211       return FALSE;
27212    }
27213    /* Okay, we managed to open the document! YAY! Now, let's start making sure it's all PIDF-ified
27214     * correctly.
27215     */
27216    if (strcmp(ast_xml_node_get_name(presence_node), "presence")) {
27217       ast_log(LOG_WARNING, "Root node of PIDF document is not 'presence'. Invalid\n");
27218       return FALSE;
27219    }
27220 
27221    /* The presence element must have an entity attribute and an xmlns attribute. Furthermore
27222     * the xmlns attribute must be "urn:ietf:params:xml:ns:pidf"
27223     */
27224    if (!(entity = ast_xml_get_attribute(presence_node, "entity"))) {
27225       ast_log(LOG_WARNING, "Presence element of PIDF document has no 'entity' attribute\n");
27226       return FALSE;
27227    }
27228    /* We're not interested in what the entity is, just that it exists */
27229    ast_xml_free_attr(entity);
27230 
27231    if (!(ns = ast_xml_find_namespace(doc, presence_node, NULL))) {
27232       ast_log(LOG_WARNING, "Couldn't find default namespace...\n");
27233       return FALSE;
27234    }
27235 
27236    namespace = ast_xml_get_ns_href(ns);
27237    if (ast_strlen_zero(namespace) || strcmp(namespace, presence_namespace)) {
27238       ast_log(LOG_WARNING, "PIDF document has invalid namespace value %s\n", namespace);
27239       return FALSE;
27240    }
27241 
27242    if (!(child_nodes = ast_xml_node_get_children(presence_node))) {
27243       ast_log(LOG_WARNING, "PIDF document has no elements as children of 'presence'. Invalid\n");
27244       return FALSE;
27245    }
27246 
27247    /* Check for tuple elements. RFC 3863 says that PIDF documents can have any number of
27248     * tuples, including 0. The big thing here is that if there are tuple elements present,
27249     * they have to have a single status element within.
27250     *
27251     * The RFC is worded such that tuples should appear as the first elements as children of
27252     * the presence element. However, we'll be accepting of documents which may place other elements
27253     * before the tuple(s).
27254     */
27255    for (node_iterator = child_nodes; node_iterator;
27256          node_iterator = ast_xml_node_get_next(node_iterator)) {
27257       if (strcmp(ast_xml_node_get_name(node_iterator), "tuple")) {
27258          /* Not a tuple. We don't give a rat's hind quarters */
27259          continue;
27260       }
27261       if (pidf_validate_tuple(node_iterator) == FALSE) {
27262          ast_log(LOG_WARNING, "Unable to validate tuple\n");
27263          return FALSE;
27264       }
27265    }
27266 
27267    return TRUE;
27268 }
27269 
27270 /*!
27271  * \brief Makes sure that body is properly formatted PIDF
27272  *
27273  * Specifically, we check that the document has a "presence" element
27274  * at the root and that within that, there is at least one "tuple" element
27275  * that contains a "status" element.
27276  *
27277  * XXX This function currently assumes a default namespace is used. Of course
27278  * if you're not using a default namespace, you're probably a stupid jerk anyway.
27279  *
27280  * \param req The SIP request to check
27281  * \param[out] pidf_doc The validated PIDF doc.
27282  * \retval FALSE The XML was malformed or the basic PIDF structure was marred
27283  * \retval TRUE The PIDF document is of a valid format
27284  */
27285 static int sip_pidf_validate(struct sip_request *req, struct ast_xml_doc **pidf_doc)
27286 {
27287    struct ast_xml_doc *doc;
27288    const char *content_type = sip_get_header(req, "Content-Type");
27289    char *pidf_body;
27290    int res;
27291 
27292    if (ast_strlen_zero(content_type) || strcmp(content_type, "application/pidf+xml")) {
27293       ast_log(LOG_WARNING, "Content type is not PIDF\n");
27294       return FALSE;
27295    }
27296 
27297    if (!(pidf_body = get_content(req))) {
27298       ast_log(LOG_WARNING, "Unable to get PIDF body\n");
27299       return FALSE;
27300    }
27301 
27302    if (!(doc = ast_xml_read_memory(pidf_body, strlen(pidf_body)))) {
27303       ast_log(LOG_WARNING, "Unable to open XML PIDF document. Is it malformed?\n");
27304       return FALSE;
27305    }
27306 
27307    res = pidf_validate_presence(doc);
27308    if (res == TRUE) {
27309       *pidf_doc = doc;
27310    } else {
27311       ast_xml_close(doc);
27312    }
27313    return res;
27314 }
27315 
27316 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)
27317 {
27318    const char *uri = REQ_OFFSET_TO_STR(req, rlpart2);
27319    struct ast_cc_agent *agent;
27320    struct sip_cc_agent_pvt *agent_pvt;
27321    struct ast_xml_doc *pidf_doc = NULL;
27322    const char *basic_status = NULL;
27323    struct ast_xml_node *presence_node;
27324    struct ast_xml_node *presence_children;
27325    struct ast_xml_node *tuple_node;
27326    struct ast_xml_node *tuple_children;
27327    struct ast_xml_node *status_node;
27328    struct ast_xml_node *status_children;
27329    struct ast_xml_node *basic_node;
27330    int res = 0;
27331 
27332    if (!((agent = find_sip_cc_agent_by_notify_uri(uri)) || (agent = find_sip_cc_agent_by_subscribe_uri(uri)))) {
27333       ast_log(LOG_WARNING, "Could not find agent using uri '%s'\n", uri);
27334       transmit_response(pvt, "412 Conditional Request Failed", req);
27335       return -1;
27336    }
27337 
27338    agent_pvt = agent->private_data;
27339 
27340    if (sip_pidf_validate(req, &pidf_doc) == FALSE) {
27341       res = -1;
27342       goto cc_publish_cleanup;
27343    }
27344 
27345    /* It's important to note that the PIDF validation routine has no knowledge
27346     * of what we specifically want in this instance. A valid PIDF document could
27347     * have no tuples, or it could have tuples whose status element has no basic
27348     * element contained within. While not violating the PIDF spec, these are
27349     * insufficient for our needs in this situation
27350     */
27351    presence_node = ast_xml_get_root(pidf_doc);
27352    if (!(presence_children = ast_xml_node_get_children(presence_node))) {
27353       ast_log(LOG_WARNING, "No tuples within presence element.\n");
27354       res = -1;
27355       goto cc_publish_cleanup;
27356    }
27357 
27358    if (!(tuple_node = ast_xml_find_element(presence_children, "tuple", NULL, NULL))) {
27359       ast_log(LOG_NOTICE, "Couldn't find tuple node?\n");
27360       res = -1;
27361       goto cc_publish_cleanup;
27362    }
27363 
27364    /* We already made sure that the tuple has a status node when we validated the PIDF
27365     * document earlier. So there's no need to enclose this operation in an if statement.
27366     */
27367    tuple_children = ast_xml_node_get_children(tuple_node);
27368    /* coverity[null_returns: FALSE] */
27369    status_node = ast_xml_find_element(tuple_children, "status", NULL, NULL);
27370 
27371    if (!(status_children = ast_xml_node_get_children(status_node))) {
27372       ast_log(LOG_WARNING, "No basic elements within status element.\n");
27373       res = -1;
27374       goto cc_publish_cleanup;
27375    }
27376 
27377    if (!(basic_node = ast_xml_find_element(status_children, "basic", NULL, NULL))) {
27378       ast_log(LOG_WARNING, "Couldn't find basic node?\n");
27379       res = -1;
27380       goto cc_publish_cleanup;
27381    }
27382 
27383    basic_status = ast_xml_get_text(basic_node);
27384 
27385    if (ast_strlen_zero(basic_status)) {
27386       ast_log(LOG_NOTICE, "NOthing in basic node?\n");
27387       res = -1;
27388       goto cc_publish_cleanup;
27389    }
27390 
27391    if (!strcmp(basic_status, "open")) {
27392       agent_pvt->is_available = TRUE;
27393       ast_cc_agent_caller_available(agent->core_id, "Received PUBLISH stating SIP caller %s is available",
27394             agent->device_name);
27395    } else if (!strcmp(basic_status, "closed")) {
27396       agent_pvt->is_available = FALSE;
27397       ast_cc_agent_caller_busy(agent->core_id, "Received PUBLISH stating SIP caller %s is busy",
27398             agent->device_name);
27399    } else {
27400       ast_log(LOG_NOTICE, "Invalid content in basic element: %s\n", basic_status);
27401    }
27402 
27403 cc_publish_cleanup:
27404    if (basic_status) {
27405       ast_xml_free_text(basic_status);
27406    }
27407    if (pidf_doc) {
27408       ast_xml_close(pidf_doc);
27409    }
27410    ao2_ref(agent, -1);
27411    if (res) {
27412       transmit_response(pvt, "400 Bad Request", req);
27413    }
27414    return res;
27415 }
27416 
27417 #endif /* HAVE_LIBXML2 */
27418 
27419 static int handle_sip_publish_initial(struct sip_pvt *p, struct sip_request *req, struct event_state_compositor *esc, const int expires)
27420 {
27421    struct sip_esc_entry *esc_entry = create_esc_entry(esc, req, expires);
27422    int res = 0;
27423 
27424    if (!esc_entry) {
27425       transmit_response(p, "503 Internal Server Failure", req);
27426       return -1;
27427    }
27428 
27429    if (esc->callbacks->initial_handler) {
27430       res = esc->callbacks->initial_handler(p, req, esc, esc_entry);
27431    }
27432 
27433    if (!res) {
27434       transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 0);
27435    }
27436 
27437    ao2_ref(esc_entry, -1);
27438    return res;
27439 }
27440 
27441 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)
27442 {
27443    struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
27444    int expires_ms = expires * 1000;
27445    int res = 0;
27446 
27447    if (!esc_entry) {
27448       transmit_response(p, "412 Conditional Request Failed", req);
27449       return -1;
27450    }
27451 
27452    AST_SCHED_REPLACE_UNREF(esc_entry->sched_id, sched, expires_ms, publish_expire, esc_entry,
27453          ao2_ref(_data, -1),
27454          ao2_ref(esc_entry, -1),
27455          ao2_ref(esc_entry, +1));
27456 
27457    if (esc->callbacks->refresh_handler) {
27458       res = esc->callbacks->refresh_handler(p, req, esc, esc_entry);
27459    }
27460 
27461    if (!res) {
27462       transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
27463    }
27464 
27465    ao2_ref(esc_entry, -1);
27466    return res;
27467 }
27468 
27469 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)
27470 {
27471    struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
27472    int expires_ms = expires * 1000;
27473    int res = 0;
27474 
27475    if (!esc_entry) {
27476       transmit_response(p, "412 Conditional Request Failed", req);
27477       return -1;
27478    }
27479 
27480    AST_SCHED_REPLACE_UNREF(esc_entry->sched_id, sched, expires_ms, publish_expire, esc_entry,
27481          ao2_ref(_data, -1),
27482          ao2_ref(esc_entry, -1),
27483          ao2_ref(esc_entry, +1));
27484 
27485    if (esc->callbacks->modify_handler) {
27486       res = esc->callbacks->modify_handler(p, req, esc, esc_entry);
27487    }
27488 
27489    if (!res) {
27490       transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
27491    }
27492 
27493    ao2_ref(esc_entry, -1);
27494    return res;
27495 }
27496 
27497 static int handle_sip_publish_remove(struct sip_pvt *p, struct sip_request *req, struct event_state_compositor *esc, const char * const etag)
27498 {
27499    struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
27500    int res = 0;
27501 
27502    if (!esc_entry) {
27503       transmit_response(p, "412 Conditional Request Failed", req);
27504       return -1;
27505    }
27506 
27507    AST_SCHED_DEL(sched, esc_entry->sched_id);
27508    /* Scheduler's ref of the esc_entry */
27509    ao2_ref(esc_entry, -1);
27510 
27511    if (esc->callbacks->remove_handler) {
27512       res = esc->callbacks->remove_handler(p, req, esc, esc_entry);
27513    }
27514 
27515    if (!res) {
27516       transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
27517    }
27518 
27519    /* Ref from finding the esc_entry earlier in function */
27520    ao2_unlink(esc->compositor, esc_entry);
27521    ao2_ref(esc_entry, -1);
27522    return res;
27523 }
27524 
27525 static int handle_request_publish(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const uint32_t seqno, const char *uri)
27526 {
27527    const char *etag = sip_get_header(req, "SIP-If-Match");
27528    const char *event = sip_get_header(req, "Event");
27529    struct event_state_compositor *esc;
27530    enum sip_publish_type publish_type;
27531    const char *expires_str = sip_get_header(req, "Expires");
27532    int expires_int;
27533    int auth_result;
27534    int handler_result = -1;
27535 
27536    if (ast_strlen_zero(event)) {
27537       transmit_response(p, "489 Bad Event", req);
27538       pvt_set_needdestroy(p, "missing Event: header");
27539       return -1;
27540    }
27541 
27542    if (!(esc = get_esc(event))) {
27543       transmit_response(p, "489 Bad Event", req);
27544       pvt_set_needdestroy(p, "unknown event package in publish");
27545       return -1;
27546    }
27547 
27548    auth_result = check_user(p, req, SIP_PUBLISH, uri, XMIT_UNRELIABLE, addr);
27549    if (auth_result == AUTH_CHALLENGE_SENT) {
27550       p->lastinvite = seqno;
27551       return 0;
27552    } else if (auth_result < 0) {
27553       ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", sip_get_header(req, "From"));
27554       transmit_response(p, "403 Forbidden", req);
27555       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
27556       ast_string_field_set(p, theirtag, NULL);
27557       return 0;
27558    } else if (auth_result == AUTH_SUCCESSFUL && p->lastinvite) {
27559       /* We need to stop retransmitting the 401 */
27560       __sip_ack(p, p->lastinvite, 1, 0);
27561    }
27562 
27563    publish_type = determine_sip_publish_type(req, event, etag, expires_str, &expires_int);
27564 
27565    if (expires_int > max_expiry) {
27566       expires_int = max_expiry;
27567    } else if (expires_int < min_expiry && expires_int > 0) {
27568       transmit_response_with_minexpires(p, "423 Interval too small", req, min_expiry);
27569       pvt_set_needdestroy(p, "Expires is less that the min expires allowed.");
27570       return 0;
27571    }
27572    p->expiry = expires_int;
27573 
27574    /* It is the responsibility of these handlers to formulate any response
27575     * sent for a PUBLISH
27576     */
27577    switch (publish_type) {
27578    case SIP_PUBLISH_UNKNOWN:
27579       transmit_response(p, "400 Bad Request", req);
27580       break;
27581    case SIP_PUBLISH_INITIAL:
27582       handler_result = handle_sip_publish_initial(p, req, esc, expires_int);
27583       break;
27584    case SIP_PUBLISH_REFRESH:
27585       handler_result = handle_sip_publish_refresh(p, req, esc, etag, expires_int);
27586       break;
27587    case SIP_PUBLISH_MODIFY:
27588       handler_result = handle_sip_publish_modify(p, req, esc, etag, expires_int);
27589       break;
27590    case SIP_PUBLISH_REMOVE:
27591       handler_result = handle_sip_publish_remove(p, req, esc, etag);
27592       break;
27593    default:
27594       transmit_response(p, "400 Impossible Condition", req);
27595       break;
27596    }
27597    if (!handler_result && p->expiry > 0) {
27598       sip_scheddestroy(p, (p->expiry + 10) * 1000);
27599    } else {
27600       pvt_set_needdestroy(p, "forcing expiration");
27601    }
27602 
27603    return handler_result;
27604 }
27605 
27606 /*! \internal \brief Subscribe to MWI events for the specified peer
27607  * \note The peer cannot be locked during this method.  sip_send_mwi_peer will
27608  * attempt to lock the peer after the event subscription lock is held; if the peer is locked during
27609  * this method then we will attempt to lock the event subscription lock but after the peer, creating
27610  * a locking inversion.
27611  */
27612 static void add_peer_mwi_subs(struct sip_peer *peer)
27613 {
27614    struct sip_mailbox *mailbox;
27615 
27616    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
27617       if (mailbox->event_sub) {
27618          ast_event_unsubscribe(mailbox->event_sub);
27619       }
27620 
27621       mailbox->event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, "SIP mbox event", peer,
27622          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
27623          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
27624          AST_EVENT_IE_END);
27625    }
27626 }
27627 
27628 static int handle_cc_subscribe(struct sip_pvt *p, struct sip_request *req)
27629 {
27630    const char *uri = REQ_OFFSET_TO_STR(req, rlpart2);
27631    char *param_separator;
27632    struct ast_cc_agent *agent;
27633    struct sip_cc_agent_pvt *agent_pvt;
27634    const char *expires_str = sip_get_header(req, "Expires");
27635    int expires = -1; /* Just need it to be non-zero */
27636 
27637    if (!ast_strlen_zero(expires_str)) {
27638       sscanf(expires_str, "%30d", &expires);
27639    }
27640 
27641    if ((param_separator = strchr(uri, ';'))) {
27642       *param_separator = '\0';
27643    }
27644 
27645    p->subscribed = CALL_COMPLETION;
27646 
27647    if (!(agent = find_sip_cc_agent_by_subscribe_uri(uri))) {
27648       if (!expires) {
27649          /* Typically, if a 0 Expires reaches us and we can't find
27650           * the corresponding agent, it means that the CC transaction
27651           * has completed and so the calling side is just trying to
27652           * clean up its subscription. We'll just respond with a
27653           * 200 OK and be done with it
27654           */
27655          transmit_response(p, "200 OK", req);
27656          return 0;
27657       }
27658       ast_log(LOG_WARNING, "Invalid URI '%s' in CC subscribe\n", uri);
27659       transmit_response(p, "404 Not Found", req);
27660       return -1;
27661    }
27662 
27663    agent_pvt = agent->private_data;
27664 
27665    if (!expires) {
27666       /* We got sent a SUBSCRIBE and found an agent. This means that CC
27667        * is being canceled.
27668        */
27669       ast_cc_failed(agent->core_id, "CC is being canceled by %s", agent->device_name);
27670       transmit_response(p, "200 OK", req);
27671       ao2_ref(agent, -1);
27672       return 0;
27673    }
27674 
27675    agent_pvt->subscribe_pvt = dialog_ref(p, "SIP CC agent gains reference to subscription dialog");
27676    ast_cc_agent_accept_request(agent->core_id, "SIP caller %s has requested CC via SUBSCRIBE",
27677          agent->device_name);
27678 
27679    /* We don't send a response here. That is done in the agent's ack callback or in the
27680     * agent destructor, should a failure occur before we have responded
27681     */
27682    ao2_ref(agent, -1);
27683    return 0;
27684 }
27685 
27686 /*! \brief  Handle incoming SUBSCRIBE request */
27687 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e)
27688 {
27689    int res = 0;
27690    struct sip_peer *authpeer = NULL;
27691    char *event = ast_strdupa(sip_get_header(req, "Event")); /* Get Event package name */
27692    int resubscribe = (p->subscribed != NONE) && !req->ignore;
27693    char *options;
27694 
27695    if (p->initreq.headers) {
27696       /* We already have a dialog */
27697       if (p->initreq.method != SIP_SUBSCRIBE) {
27698          /* This is a SUBSCRIBE within another SIP dialog, which we do not support */
27699          /* For transfers, this could happen, but since we haven't seen it happening, let us just refuse this */
27700          transmit_response(p, "403 Forbidden (within dialog)", req);
27701          /* Do not destroy session, since we will break the call if we do */
27702          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);
27703          return 0;
27704       } else if (req->debug) {
27705          if (resubscribe)
27706             ast_debug(1, "Got a re-subscribe on existing subscription %s\n", p->callid);
27707          else
27708             ast_debug(1, "Got a new subscription %s (possibly with auth) or retransmission\n", p->callid);
27709       }
27710    }
27711 
27712    /* Check if we have a global disallow setting on subscriptions.
27713       if so, we don't have to check peer settings after auth, which saves a lot of processing
27714    */
27715    if (!sip_cfg.allowsubscribe) {
27716       transmit_response(p, "403 Forbidden (policy)", req);
27717       pvt_set_needdestroy(p, "forbidden");
27718       return 0;
27719    }
27720 
27721    if (!req->ignore && !resubscribe) { /* Set up dialog, new subscription */
27722       const char *to = sip_get_header(req, "To");
27723       char totag[128];
27724       set_pvt_allowed_methods(p, req);
27725 
27726       /* Check to see if a tag was provided, if so this is actually a resubscription of a dialog we no longer know about */
27727       if (!ast_strlen_zero(to) && gettag(req, "To", totag, sizeof(totag))) {
27728          if (req->debug)
27729             ast_verbose("Received resubscription for a dialog we no longer know about. Telling remote side to subscribe again.\n");
27730          transmit_response(p, "481 Subscription does not exist", req);
27731          pvt_set_needdestroy(p, "subscription does not exist");
27732          return 0;
27733       }
27734 
27735       /* Use this as the basis */
27736       if (req->debug)
27737          ast_verbose("Creating new subscription\n");
27738 
27739       copy_request(&p->initreq, req);
27740       if (sipdebug)
27741          ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
27742       check_via(p, req);
27743       build_route(p, req, 0, 0);
27744    } else if (req->debug && req->ignore)
27745       ast_verbose("Ignoring this SUBSCRIBE request\n");
27746 
27747    /* Find parameters to Event: header value and remove them for now */
27748    if (ast_strlen_zero(event)) {
27749       transmit_response(p, "489 Bad Event", req);
27750       ast_debug(2, "Received SIP subscribe for unknown event package: <none>\n");
27751       pvt_set_needdestroy(p, "unknown event package in subscribe");
27752       return 0;
27753    }
27754    if ((options = strchr(event, ';')) != NULL) {
27755       *options++ = '\0';
27756    }
27757 
27758    /* Handle authentication if we're new and not a retransmission. We can't just
27759     * use if !req->ignore, because then we'll end up sending
27760     * a 200 OK if someone retransmits without sending auth */
27761    if (p->subscribed == NONE || resubscribe) {
27762       res = check_user_full(p, req, SIP_SUBSCRIBE, e, XMIT_UNRELIABLE, addr, &authpeer);
27763 
27764       /* if an authentication response was sent, we are done here */
27765       if (res == AUTH_CHALLENGE_SENT)  /* authpeer = NULL here */
27766          return 0;
27767       if (res != AUTH_SUCCESSFUL) {
27768          ast_log(LOG_NOTICE, "Failed to authenticate device %s for SUBSCRIBE\n", sip_get_header(req, "From"));
27769          transmit_response(p, "403 Forbidden", req);
27770 
27771          pvt_set_needdestroy(p, "authentication failed");
27772          return 0;
27773       }
27774    }
27775 
27776    /* At this point, we hold a reference to authpeer (if not NULL).  It
27777     * must be released when done.
27778     */
27779 
27780    /* Check if this device  is allowed to subscribe at all */
27781    if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
27782       transmit_response(p, "403 Forbidden (policy)", req);
27783       pvt_set_needdestroy(p, "subscription not allowed");
27784       if (authpeer) {
27785          sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 1)");
27786       }
27787       return 0;
27788    }
27789 
27790    /* Get full contact header - this needs to be used as a request URI in NOTIFY's */
27791    parse_ok_contact(p, req);
27792    build_contact(p);
27793 
27794    /* Initialize tag for new subscriptions */
27795    if (ast_strlen_zero(p->tag)) {
27796       make_our_tag(p);
27797    }
27798 
27799    if (!strcmp(event, "presence") || !strcmp(event, "dialog")) { /* Presence, RFC 3842 */
27800       int gotdest;
27801       const char *accept;
27802       int start = 0;
27803       enum subscriptiontype subscribed = NONE;
27804       const char *unknown_accept = NULL;
27805 
27806                 /* Get destination right away */
27807                 gotdest = get_destination(p, NULL, NULL);
27808       if (gotdest != SIP_GET_DEST_EXTEN_FOUND) {
27809          if (gotdest == SIP_GET_DEST_INVALID_URI) {
27810             transmit_response(p, "416 Unsupported URI scheme", req);
27811          } else {
27812             transmit_response(p, "404 Not Found", req);
27813          }
27814          pvt_set_needdestroy(p, "subscription target not found");
27815          if (authpeer) {
27816             sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 2)");
27817          }
27818          return 0;
27819       }
27820 
27821       /* Header from Xten Eye-beam Accept: multipart/related, application/rlmi+xml, application/pidf+xml, application/xpidf+xml */
27822       accept = __get_header(req, "Accept", &start);
27823       while ((subscribed == NONE) && !ast_strlen_zero(accept)) {
27824          if (strstr(accept, "application/pidf+xml")) {
27825             if (strstr(p->useragent, "Polycom")) {
27826                subscribed = XPIDF_XML; /* Older versions of Polycom firmware will claim pidf+xml, but really they only support xpidf+xml */
27827             } else {
27828                subscribed = PIDF_XML; /* RFC 3863 format */
27829             }
27830          } else if (strstr(accept, "application/dialog-info+xml")) {
27831             subscribed = DIALOG_INFO_XML;
27832             /* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
27833          } else if (strstr(accept, "application/cpim-pidf+xml")) {
27834             subscribed = CPIM_PIDF_XML;    /* RFC 3863 format */
27835          } else if (strstr(accept, "application/xpidf+xml")) {
27836             subscribed = XPIDF_XML;        /* Early pre-RFC 3863 format with MSN additions (Microsoft Messenger) */
27837          } else {
27838             unknown_accept = accept;
27839          }
27840          /* check to see if there is another Accept header present */
27841          accept = __get_header(req, "Accept", &start);
27842       }
27843 
27844       if (!start) {
27845          if (p->subscribed == NONE) { /* if the subscribed field is not already set, and there is no accept header... */
27846             transmit_response(p, "489 Bad Event", req);
27847             ast_log(LOG_WARNING,"SUBSCRIBE failure: no Accept header: pvt: "
27848                "stateid: %d, laststate: %d, dialogver: %u, subscribecont: "
27849                "'%s', subscribeuri: '%s'\n",
27850                p->stateid,
27851                p->laststate,
27852                p->dialogver,
27853                p->subscribecontext,
27854                p->subscribeuri);
27855             pvt_set_needdestroy(p, "no Accept header");
27856             if (authpeer) {
27857                sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 2)");
27858             }
27859             return 0;
27860          }
27861          /* if p->subscribed is non-zero, then accept is not obligatory; according to rfc 3265 section 3.1.3, at least.
27862             so, we'll just let it ride, keeping the value from a previous subscription, and not abort the subscription */
27863       } else if (subscribed == NONE) {
27864          /* Can't find a format for events that we know about */
27865          char buf[200];
27866 
27867          if (!ast_strlen_zero(unknown_accept)) {
27868             snprintf(buf, sizeof(buf), "489 Bad Event (format %s)", unknown_accept);
27869          } else {
27870             snprintf(buf, sizeof(buf), "489 Bad Event");
27871          }
27872          transmit_response(p, buf, req);
27873          ast_log(LOG_WARNING,"SUBSCRIBE failure: unrecognized format:"
27874             "'%s' pvt: subscribed: %d, stateid: %d, laststate: %d,"
27875             "dialogver: %u, subscribecont: '%s', subscribeuri: '%s'\n",
27876             unknown_accept,
27877             (int)p->subscribed,
27878             p->stateid,
27879             p->laststate,
27880             p->dialogver,
27881             p->subscribecontext,
27882             p->subscribeuri);
27883          pvt_set_needdestroy(p, "unrecognized format");
27884          if (authpeer) {
27885             sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 2)");
27886          }
27887          return 0;
27888       } else {
27889          p->subscribed = subscribed;
27890       }
27891    } else if (!strcmp(event, "message-summary")) {
27892       int start = 0;
27893       int found_supported = 0;
27894       const char *accept;
27895 
27896       accept = __get_header(req, "Accept", &start);
27897       while (!found_supported && !ast_strlen_zero(accept)) {
27898          found_supported = strcmp(accept, "application/simple-message-summary") ? 0 : 1;
27899          if (!found_supported && (option_debug > 2)) {
27900             ast_debug(1, "Received SIP mailbox subscription for unknown format: %s\n", accept);
27901          }
27902          accept = __get_header(req, "Accept", &start);
27903       }
27904       if (start && !found_supported) {
27905          /* Format requested that we do not support */
27906          transmit_response(p, "406 Not Acceptable", req);
27907          ast_debug(2, "Received SIP mailbox subscription for unknown format: %s\n", accept);
27908          pvt_set_needdestroy(p, "unknown format");
27909          if (authpeer) {
27910             sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 3)");
27911          }
27912          return 0;
27913       }
27914       /* Looks like they actually want a mailbox status
27915         This version of Asterisk supports mailbox subscriptions
27916         The subscribed URI needs to exist in the dial plan
27917         In most devices, this is configurable to the voicemailmain extension you use
27918       */
27919       if (!authpeer || AST_LIST_EMPTY(&authpeer->mailboxes)) {
27920          if (!authpeer) {
27921             transmit_response(p, "404 Not found", req);
27922          } else {
27923             transmit_response(p, "404 Not found (no mailbox)", req);
27924             ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", S_OR(authpeer->name, ""));
27925          }
27926          pvt_set_needdestroy(p, "received 404 response");
27927 
27928          if (authpeer) {
27929             sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 3)");
27930          }
27931          return 0;
27932       }
27933 
27934       p->subscribed = MWI_NOTIFICATION;
27935       if (ast_test_flag(&authpeer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY)) {
27936          ao2_unlock(p);
27937          add_peer_mwi_subs(authpeer);
27938          ao2_lock(p);
27939       }
27940       if (authpeer->mwipvt != p) {  /* Destroy old PVT if this is a new one */
27941          /* We only allow one subscription per peer */
27942          if (authpeer->mwipvt) {
27943             dialog_unlink_all(authpeer->mwipvt);
27944             authpeer->mwipvt = dialog_unref(authpeer->mwipvt, "unref dialog authpeer->mwipvt");
27945          }
27946          authpeer->mwipvt = dialog_ref(p, "setting peers' mwipvt to p");
27947       }
27948 
27949       if (p->relatedpeer != authpeer) {
27950          if (p->relatedpeer) {
27951             sip_unref_peer(p->relatedpeer, "Unref previously stored relatedpeer ptr");
27952          }
27953          p->relatedpeer = sip_ref_peer(authpeer, "setting dialog's relatedpeer pointer");
27954       }
27955       /* Do not release authpeer here */
27956    } else if (!strcmp(event, "call-completion")) {
27957       handle_cc_subscribe(p, req);
27958    } else { /* At this point, Asterisk does not understand the specified event */
27959       transmit_response(p, "489 Bad Event", req);
27960       ast_debug(2, "Received SIP subscribe for unknown event package: %s\n", event);
27961       pvt_set_needdestroy(p, "unknown event package");
27962       if (authpeer) {
27963          sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 5)");
27964       }
27965       return 0;
27966    }
27967 
27968    if (!req->ignore) {
27969       p->lastinvite = seqno;
27970    }
27971    if (!p->needdestroy) {
27972       p->expiry = atoi(sip_get_header(req, "Expires"));
27973 
27974       /* check if the requested expiry-time is within the approved limits from sip.conf */
27975       if (p->expiry > max_subexpiry) {
27976          p->expiry = max_subexpiry;
27977       } else if (p->expiry < min_subexpiry && p->expiry > 0) {
27978          transmit_response_with_minexpires(p, "423 Interval too small", req, min_subexpiry);
27979          ast_log(LOG_WARNING, "Received subscription for extension \"%s\" context \"%s\" "
27980             "with Expire header less than 'subminexpire' limit. Received \"Expire: %d\" min is %d\n",
27981             p->exten, p->context, p->expiry, min_subexpiry);
27982          pvt_set_needdestroy(p, "Expires is less that the min expires allowed.");
27983          if (authpeer) {
27984             sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 6)");
27985          }
27986          return 0;
27987       }
27988 
27989       if (sipdebug) {
27990          const char *action = p->expiry > 0 ? "Adding" : "Removing";
27991          if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer) {
27992             ast_debug(2, "%s subscription for mailbox notification - peer %s\n",
27993                   action, p->relatedpeer->name);
27994          } else if (p->subscribed == CALL_COMPLETION) {
27995             ast_debug(2, "%s CC subscription for peer %s\n", action, p->username);
27996          } else {
27997             ast_debug(2, "%s subscription for extension %s context %s for peer %s\n",
27998                   action, p->exten, p->context, p->username);
27999          }
28000       }
28001       if (p->autokillid > -1 && sip_cancel_destroy(p))   /* Remove subscription expiry for renewals */
28002          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
28003       if (p->expiry > 0)
28004          sip_scheddestroy(p, (p->expiry + 10) * 1000);   /* Set timer for destruction of call at expiration */
28005 
28006       if (p->subscribed == MWI_NOTIFICATION) {
28007          ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
28008          transmit_response(p, "200 OK", req);
28009          if (p->relatedpeer) {   /* Send first notification */
28010             struct sip_peer *peer = p->relatedpeer;
28011             sip_ref_peer(peer, "ensure a peer ref is held during MWI sending");
28012             ao2_unlock(p);
28013             sip_send_mwi_to_peer(peer, 0);
28014             ao2_lock(p);
28015             sip_unref_peer(peer, "release a peer ref now that MWI is sent");
28016          }
28017       } else if (p->subscribed != CALL_COMPLETION) {
28018          struct state_notify_data data = { 0, };
28019          char *subtype = NULL;
28020          char *message = NULL;
28021          struct ao2_container *device_state_info = NULL;
28022 
28023          if (p->expiry > 0 && !resubscribe) {
28024             /* Add subscription for extension state from the PBX core */
28025             if (p->stateid != -1) {
28026                ast_extension_state_del(p->stateid, cb_extensionstate);
28027             }
28028             dialog_ref(p, "copying dialog ptr into extension state struct");
28029             p->stateid = ast_extension_state_add_destroy_extended(p->context, p->exten, cb_extensionstate, cb_extensionstate_destroy, p);
28030             if (p->stateid == -1) {
28031                dialog_unref(p, "copying dialog ptr into extension state struct failed");
28032             }
28033          }
28034 
28035          sip_pvt_unlock(p);
28036          data.state = ast_extension_state_extended(NULL, p->context, p->exten, &device_state_info);
28037          sip_pvt_lock(p);
28038 
28039          if (data.state < 0) {
28040             ao2_cleanup(device_state_info);
28041             if (p->expiry > 0) {
28042                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));
28043             }
28044             transmit_response(p, "404 Not found", req);
28045             pvt_set_needdestroy(p, "no extension for SUBSCRIBE");
28046             if (authpeer) {
28047                sip_unref_peer(authpeer, "sip_unref_peer, from handle_request_subscribe (authpeer 6)");
28048             }
28049             return 0;
28050          }
28051          if (allow_notify_user_presence(p)) {
28052             data.presence_state = ast_hint_presence_state(NULL, p->context, p->exten, &subtype, &message);
28053             data.presence_subtype = subtype;
28054             data.presence_message = message;
28055          }
28056          ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
28057          transmit_response(p, "200 OK", req);
28058          /* RFC 3265: A notification must be sent on every subscribe, so force it */
28059          data.device_state_info = device_state_info;
28060          if (data.state & AST_EXTENSION_RINGING) {
28061             /* save last_ringing_channel_time if this state really contains a ringing channel
28062              * because extensionstate_update() doesn't do it if forced
28063              */
28064             struct ast_channel *ringing = find_ringing_channel(data.device_state_info, p);
28065             if (ringing) {
28066                p->last_ringing_channel_time = ast_channel_creationtime(ringing);
28067                ao2_ref(ringing, -1);
28068             }
28069             /* If there is no channel, this likely indicates that the ringing indication
28070              * is due to a custom device state. These do not have associated channels.
28071              */
28072          }
28073          extensionstate_update(p->context, p->exten, &data, p, TRUE);
28074          append_history(p, "Subscribestatus", "%s", ast_extension_state2str(data.state));
28075          /* hide the 'complete' exten/context in the refer_to field for later display */
28076          ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
28077          /* Deleted the slow iteration of all sip dialogs to find old subscribes from this peer for exten@context */
28078 
28079          ao2_cleanup(device_state_info);
28080          ast_free(subtype);
28081          ast_free(message);
28082       }
28083       if (!p->expiry) {
28084          pvt_set_needdestroy(p, "forcing expiration");
28085       }
28086    }
28087 
28088    if (authpeer) {
28089       sip_unref_peer(authpeer, "unref pointer into (*authpeer)");
28090    }
28091    return 1;
28092 }
28093 
28094 /*! \brief Handle incoming REGISTER request */
28095 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e)
28096 {
28097    enum check_auth_result res;
28098 
28099    /* If this is not the intial request, and the initial request isn't
28100     * a register, something screwy happened, so bail */
28101    if (p->initreq.headers && p->initreq.method != SIP_REGISTER) {
28102       ast_log(LOG_WARNING, "Ignoring spurious REGISTER with Call-ID: %s\n", p->callid);
28103       return -1;
28104    }
28105 
28106    /* Use this as the basis */
28107    copy_request(&p->initreq, req);
28108    if (sipdebug)
28109       ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
28110    check_via(p, req);
28111 
28112    if ((res = register_verify(p, addr, req, e)) < 0) {
28113       const char *reason;
28114 
28115       switch (res) {
28116       case AUTH_SECRET_FAILED:
28117          reason = "Wrong password";
28118          break;
28119       case AUTH_USERNAME_MISMATCH:
28120          reason = "Username/auth name mismatch";
28121          break;
28122       case AUTH_NOT_FOUND:
28123          reason = "No matching peer found";
28124          break;
28125       case AUTH_UNKNOWN_DOMAIN:
28126          reason = "Not a local domain";
28127          break;
28128       case AUTH_PEER_NOT_DYNAMIC:
28129          reason = "Peer is not supposed to register";
28130          break;
28131       case AUTH_ACL_FAILED:
28132          reason = "Device does not match ACL";
28133          break;
28134       case AUTH_BAD_TRANSPORT:
28135          reason = "Device not configured to use this transport type";
28136          break;
28137       case AUTH_RTP_FAILED:
28138          reason = "RTP initialization failed";
28139          break;
28140       default:
28141          reason = "Unknown failure";
28142          break;
28143       }
28144       ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
28145          sip_get_header(req, "To"), ast_sockaddr_stringify(addr),
28146          reason);
28147       append_history(p, "RegRequest", "Failed : Account %s : %s", sip_get_header(req, "To"), reason);
28148    } else {
28149       req->authenticated = 1;
28150       append_history(p, "RegRequest", "Succeeded : Account %s", sip_get_header(req, "To"));
28151    }
28152 
28153    if (res != AUTH_CHALLENGE_SENT) {
28154       /* Destroy the session, but keep us around for just a bit in case they don't
28155          get our 200 OK */
28156       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
28157    }
28158 
28159    return res;
28160 }
28161 
28162 /*!
28163  * \brief Handle incoming SIP requests (methods)
28164  * \note
28165  * This is where all incoming requests go first.
28166  * \note
28167  * called with p and p->owner locked
28168  */
28169 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock)
28170 {
28171    /* Called with p->lock held, as well as p->owner->lock if appropriate, keeping things
28172       relatively static */
28173    const char *cmd;
28174    const char *cseq;
28175    const char *useragent;
28176    const char *via;
28177    const char *callid;
28178    int via_pos = 0;
28179    uint32_t seqno;
28180    int len;
28181    int respid;
28182    int res = 0;
28183    const char *e;
28184    int error = 0;
28185    int oldmethod = p->method;
28186    int acked = 0;
28187 
28188    /* RFC 3261 - 8.1.1 A valid SIP request must contain To, From, CSeq, Call-ID and Via.
28189     * 8.2.6.2 Response must have To, From, Call-ID CSeq, and Via related to the request,
28190     * so we can check to make sure these fields exist for all requests and responses */
28191    cseq = sip_get_header(req, "Cseq");
28192    cmd = REQ_OFFSET_TO_STR(req, header[0]);
28193    /* Save the via_pos so we can check later that responses only have 1 Via header */
28194    via = __get_header(req, "Via", &via_pos);
28195    /* This must exist already because we've called find_call by now */
28196    callid = sip_get_header(req, "Call-ID");
28197 
28198    /* Must have Cseq */
28199    if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq) || ast_strlen_zero(via)) {
28200       ast_log(LOG_ERROR, "Dropping this SIP message with Call-ID '%s', it's incomplete.\n", callid);
28201       error = 1;
28202    }
28203    if (!error && sscanf(cseq, "%30u%n", &seqno, &len) != 1) {
28204       ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
28205       error = 1;
28206    }
28207    if (error) {
28208       if (!p->initreq.headers) { /* New call */
28209          pvt_set_needdestroy(p, "no headers");
28210       }
28211       return -1;
28212    }
28213    /* Get the command XXX */
28214 
28215    cmd = REQ_OFFSET_TO_STR(req, rlpart1);
28216    e = ast_skip_blanks(REQ_OFFSET_TO_STR(req, rlpart2));
28217 
28218    /* Save useragent of the client */
28219    useragent = sip_get_header(req, "User-Agent");
28220    if (!ast_strlen_zero(useragent))
28221       ast_string_field_set(p, useragent, useragent);
28222 
28223    /* Find out SIP method for incoming request */
28224    if (req->method == SIP_RESPONSE) {  /* Response to our request */
28225       /* ignore means "don't do anything with it" but still have to
28226        * respond appropriately.
28227        * But in this case this is a response already, so we really
28228        * have nothing to do with this message, and even setting the
28229        * ignore flag is pointless.
28230        */
28231       if (ast_strlen_zero(e)) {
28232          return 0;
28233       }
28234       if (sscanf(e, "%30d %n", &respid, &len) != 1) {
28235          ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
28236          return 0;
28237       }
28238       if (respid <= 0) {
28239          ast_log(LOG_WARNING, "Invalid SIP response code: '%d'\n", respid);
28240          return 0;
28241       }
28242       /* RFC 3261 - 8.1.3.3 If more than one Via header field value is present in a reponse
28243        * the UAC SHOULD discard the message. This is not perfect, as it will not catch multiple
28244        * headers joined with a comma. Fixing that would pretty much involve writing a new parser */
28245       if (!ast_strlen_zero(__get_header(req, "via", &via_pos))) {
28246          ast_log(LOG_WARNING, "Misrouted SIP response '%s' with Call-ID '%s', too many vias\n", e, callid);
28247          return 0;
28248       }
28249       if (p->ocseq && (p->ocseq < seqno)) {
28250          ast_debug(1, "Ignoring out of order response %u (expecting %u)\n", seqno, p->ocseq);
28251          return -1;
28252       } else {
28253          if ((respid == 200) || ((respid >= 300) && (respid <= 399))) {
28254             extract_uri(p, req);
28255          }
28256 
28257          if (p->owner) {
28258             struct ast_control_pvt_cause_code *cause_code;
28259             int data_size = sizeof(*cause_code);
28260             /* size of the string making up the cause code is "SIP " + cause length */
28261             data_size += 4 + strlen(REQ_OFFSET_TO_STR(req, rlpart2));
28262             cause_code = ast_alloca(data_size);
28263             memset(cause_code, 0, data_size);
28264 
28265             ast_copy_string(cause_code->chan_name, ast_channel_name(p->owner), AST_CHANNEL_NAME);
28266 
28267             snprintf(cause_code->code, data_size - sizeof(*cause_code) + 1, "SIP %s", REQ_OFFSET_TO_STR(req, rlpart2));
28268 
28269             cause_code->ast_cause = hangup_sip2cause(respid);
28270             if (global_store_sip_cause) {
28271                cause_code->emulate_sip_cause = 1;
28272             }
28273 
28274             ast_queue_control_data(p->owner, AST_CONTROL_PVT_CAUSE_CODE, cause_code, data_size);
28275             ast_channel_hangupcause_hash_set(p->owner, cause_code, data_size);
28276          }
28277 
28278          handle_response(p, respid, e + len, req, seqno);
28279       }
28280       return 0;
28281    }
28282 
28283    /* New SIP request coming in
28284       (could be new request in existing SIP dialog as well...)
28285     */
28286    p->method = req->method;   /* Find out which SIP method they are using */
28287    ast_debug(4, "**** Received %s (%d) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd);
28288 
28289    if (p->icseq && (p->icseq > seqno) ) {
28290       if (p->pendinginvite && seqno == p->pendinginvite && (req->method == SIP_ACK || req->method == SIP_CANCEL)) {
28291          ast_debug(2, "Got CANCEL or ACK on INVITE with transactions in between.\n");
28292       } else {
28293          ast_debug(1, "Ignoring too old SIP packet packet %u (expecting >= %u)\n", seqno, p->icseq);
28294          if (req->method == SIP_INVITE) {
28295             unsigned int ran = (ast_random() % 10) + 1;
28296             char seconds[4];
28297             snprintf(seconds, sizeof(seconds), "%u", ran);
28298             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 */
28299          } else if (req->method != SIP_ACK) {
28300             transmit_response(p, "500 Server error", req);  /* We must respond according to RFC 3261 sec 12.2 */
28301          }
28302          return -1;
28303       }
28304    } else if (p->icseq &&
28305          p->icseq == seqno &&
28306          req->method != SIP_ACK &&
28307          (p->method != SIP_CANCEL || p->alreadygone)) {
28308       /* ignore means "don't do anything with it" but still have to
28309          respond appropriately.  We do this if we receive a repeat of
28310          the last sequence number  */
28311       req->ignore = 1;
28312       ast_debug(3, "Ignoring SIP message because of retransmit (%s Seqno %u, ours %u)\n", sip_methods[p->method].text, p->icseq, seqno);
28313    }
28314 
28315    /* RFC 3261 section 9. "CANCEL has no effect on a request to which a UAS has
28316     * already given a final response." */
28317    if (!p->pendinginvite && (req->method == SIP_CANCEL)) {
28318       transmit_response(p, "481 Call/Transaction Does Not Exist", req);
28319       return res;
28320    }
28321 
28322    if (seqno >= p->icseq)
28323       /* Next should follow monotonically (but not necessarily
28324          incrementally -- thanks again to the genius authors of SIP --
28325          increasing */
28326       p->icseq = seqno;
28327 
28328    /* Find their tag if we haven't got it */
28329    if (ast_strlen_zero(p->theirtag)) {
28330       char tag[128];
28331 
28332       gettag(req, "From", tag, sizeof(tag));
28333       ast_string_field_set(p, theirtag, tag);
28334    }
28335    snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
28336 
28337    if (sip_cfg.pedanticsipchecking) {
28338       /* If this is a request packet without a from tag, it's not
28339          correct according to RFC 3261  */
28340       /* Check if this a new request in a new dialog with a totag already attached to it,
28341          RFC 3261 - section 12.2 - and we don't want to mess with recovery  */
28342       if (!p->initreq.headers && req->has_to_tag) {
28343          /* If this is a first request and it got a to-tag, it is not for us */
28344          if (!req->ignore && req->method == SIP_INVITE) {
28345             /* Just because we think this is a dialog-starting INVITE with a to-tag
28346              * doesn't mean it actually is. It could be a reinvite for an established, but
28347              * unknown dialog. In such a case, we need to change our tag to the
28348              * incoming INVITE's to-tag so that they will recognize the 481 we send and
28349              * so that we will properly match their incoming ACK.
28350              */
28351             char totag[128];
28352             gettag(req, "To", totag, sizeof(totag));
28353             ast_string_field_set(p, tag, totag);
28354             p->pendinginvite = p->icseq;
28355             transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
28356             /* Will cease to exist after ACK */
28357             return res;
28358          } else if (req->method != SIP_ACK) {
28359             transmit_response(p, "481 Call/Transaction Does Not Exist", req);
28360             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
28361             return res;
28362          }
28363          /* Otherwise, this is an ACK. It will always have a to-tag */
28364       }
28365    }
28366 
28367    if (!e && (p->method == SIP_INVITE || p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_NOTIFY || p->method == SIP_PUBLISH)) {
28368       transmit_response(p, "400 Bad request", req);
28369       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
28370       return -1;
28371    }
28372 
28373    /* Handle various incoming SIP methods in requests */
28374    switch (p->method) {
28375    case SIP_OPTIONS:
28376       res = handle_request_options(p, req, addr, e);
28377       break;
28378    case SIP_INVITE:
28379       res = handle_request_invite(p, req, addr, seqno, recount, e, nounlock);
28380 
28381       if (res < 9) {
28382          sip_report_security_event(p, req, res);
28383       }
28384 
28385       switch (res) {
28386       case INV_REQ_SUCCESS:
28387          res = 1;
28388          break;
28389       case INV_REQ_FAILED:
28390          res = 0;
28391          break;
28392       case INV_REQ_ERROR:
28393          res = -1;
28394          break;
28395       default:
28396          res = 0;
28397          break;
28398       }
28399 
28400       break;
28401    case SIP_REFER:
28402       res = handle_request_refer(p, req, seqno, nounlock);
28403       break;
28404    case SIP_CANCEL:
28405       res = handle_request_cancel(p, req);
28406       break;
28407    case SIP_BYE:
28408       res = handle_request_bye(p, req);
28409       break;
28410    case SIP_MESSAGE:
28411       res = handle_request_message(p, req, addr, e);
28412       break;
28413    case SIP_PUBLISH:
28414       res = handle_request_publish(p, req, addr, seqno, e);
28415       break;
28416    case SIP_SUBSCRIBE:
28417       res = handle_request_subscribe(p, req, addr, seqno, e);
28418       break;
28419    case SIP_REGISTER:
28420       res = handle_request_register(p, req, addr, e);
28421       sip_report_security_event(p, req, res);
28422       break;
28423    case SIP_INFO:
28424       if (req->debug)
28425          ast_verbose("Receiving INFO!\n");
28426       if (!req->ignore)
28427          handle_request_info(p, req);
28428       else  /* if ignoring, transmit response */
28429          transmit_response(p, "200 OK", req);
28430       break;
28431    case SIP_NOTIFY:
28432       res = handle_request_notify(p, req, addr, seqno, e);
28433       break;
28434    case SIP_UPDATE:
28435       res = handle_request_update(p, req);
28436       break;
28437    case SIP_ACK:
28438       /* Make sure we don't ignore this */
28439       if (seqno == p->pendinginvite) {
28440          p->invitestate = INV_TERMINATED;
28441          p->pendinginvite = 0;
28442          acked = __sip_ack(p, seqno, 1 /* response */, 0);
28443          if (p->owner && find_sdp(req)) {
28444             if (process_sdp(p, req, SDP_T38_NONE)) {
28445                return -1;
28446             }
28447             if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
28448                ast_queue_control(p->owner, AST_CONTROL_SRCCHANGE);
28449             }
28450          }
28451          check_pendings(p);
28452       } else if (p->glareinvite == seqno) {
28453          /* handle ack for the 491 pending sent for glareinvite */
28454          p->glareinvite = 0;
28455          acked = __sip_ack(p, seqno, 1, 0);
28456       }
28457       if (!acked) {
28458          /* Got an ACK that did not match anything. Ignore
28459           * silently and restore previous method */
28460          p->method = oldmethod;
28461       }
28462       if (!p->lastinvite && ast_strlen_zero(p->nonce)) {
28463          pvt_set_needdestroy(p, "unmatched ACK");
28464       }
28465       break;
28466    default:
28467       transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
28468       ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n",
28469          cmd, ast_sockaddr_stringify(&p->sa));
28470       /* If this is some new method, and we don't have a call, destroy it now */
28471       if (!p->initreq.headers) {
28472          pvt_set_needdestroy(p, "unimplemented method");
28473       }
28474       break;
28475    }
28476    return res;
28477 }
28478 
28479 /*! \brief Read data from SIP UDP socket
28480 \note sipsock_read locks the owner channel while we are processing the SIP message
28481 \return 1 on error, 0 on success
28482 \note Successful messages is connected to SIP call and forwarded to handle_incoming()
28483 */
28484 static int sipsock_read(int *id, int fd, short events, void *ignore)
28485 {
28486    struct sip_request req;
28487    struct ast_sockaddr addr;
28488    int res;
28489    static char readbuf[65535];
28490 
28491    memset(&req, 0, sizeof(req));
28492    res = ast_recvfrom(fd, readbuf, sizeof(readbuf) - 1, 0, &addr);
28493    if (res < 0) {
28494 #if !defined(__FreeBSD__)
28495       if (errno == EAGAIN)
28496          ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
28497       else
28498 #endif
28499       if (errno != ECONNREFUSED)
28500          ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
28501       return 1;
28502    }
28503 
28504    readbuf[res] = '\0';
28505 
28506    if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
28507       return 1;
28508    }
28509 
28510    if (ast_str_set(&req.data, 0, "%s", readbuf) == AST_DYNSTR_BUILD_FAILED) {
28511       return -1;
28512    }
28513 
28514    req.socket.fd = sipsock;
28515    set_socket_transport(&req.socket, SIP_TRANSPORT_UDP);
28516    req.socket.tcptls_session  = NULL;
28517    req.socket.port = htons(ast_sockaddr_port(&bindaddr));
28518 
28519    handle_request_do(&req, &addr);
28520    deinit_req(&req);
28521 
28522    return 1;
28523 }
28524 
28525 /*! \brief Handle incoming SIP message - request or response
28526 
28527    This is used for all transports (udp, tcp and tcp/tls)
28528 */
28529 static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr)
28530 {
28531    struct sip_pvt *p;
28532    struct ast_channel *owner_chan_ref = NULL;
28533    int recount = 0;
28534    int nounlock = 0;
28535 
28536    if (sip_debug_test_addr(addr))   /* Set the debug flag early on packet level */
28537       req->debug = 1;
28538    if (sip_cfg.pedanticsipchecking)
28539       lws2sws(req->data);  /* Fix multiline headers */
28540    if (req->debug) {
28541       ast_verbose("\n<--- SIP read from %s:%s --->\n%s\n<------------->\n",
28542          sip_get_transport(req->socket.type), ast_sockaddr_stringify(addr), ast_str_buffer(req->data));
28543    }
28544 
28545    if (parse_request(req) == -1) { /* Bad packet, can't parse */
28546       ast_str_reset(req->data); /* nulling this out is NOT a good idea here. */
28547       return 1;
28548    }
28549    req->method = find_sip_method(REQ_OFFSET_TO_STR(req, rlpart1));
28550 
28551    if (req->debug)
28552       ast_verbose("--- (%d headers %d lines)%s ---\n", req->headers, req->lines, (req->headers + req->lines == 0) ? " Nat keepalive" : "");
28553 
28554    if (req->headers < 2) { /* Must have at least two headers */
28555       ast_str_reset(req->data); /* nulling this out is NOT a good idea here. */
28556       return 1;
28557    }
28558    ast_mutex_lock(&netlock);
28559 
28560    /* Find the active SIP dialog or create a new one */
28561    p = find_call(req, addr, req->method); /* returns p with a reference only. _NOT_ locked*/
28562    if (p == NULL) {
28563       ast_debug(1, "Invalid SIP message - rejected , no callid, len %zu\n", ast_str_strlen(req->data));
28564       ast_mutex_unlock(&netlock);
28565       return 1;
28566    }
28567 
28568    if (p->logger_callid) {
28569       ast_callid_threadassoc_add(p->logger_callid);
28570    }
28571 
28572    /* Lock both the pvt and the owner if owner is present.  This will
28573     * not fail. */
28574    owner_chan_ref = sip_pvt_lock_full(p);
28575 
28576    copy_socket_data(&p->socket, &req->socket);
28577 
28578    ast_sockaddr_copy(&p->recv, addr);
28579 
28580    /* if we have an owner, then this request has been authenticated */
28581    if (p->owner) {
28582       req->authenticated = 1;
28583    }
28584 
28585    if (p->do_history) /* This is a request or response, note what it was for */
28586       append_history(p, "Rx", "%s / %s / %s", ast_str_buffer(req->data), sip_get_header(req, "CSeq"), REQ_OFFSET_TO_STR(req, rlpart2));
28587 
28588    if (handle_incoming(p, req, addr, &recount, &nounlock) == -1) {
28589       /* Request failed */
28590       ast_debug(1, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
28591    }
28592 
28593    if (recount) {
28594       ast_update_use_count();
28595    }
28596 
28597    if (p->owner && !nounlock) {
28598       ast_channel_unlock(p->owner);
28599    }
28600    if (owner_chan_ref) {
28601       ast_channel_unref(owner_chan_ref);
28602    }
28603    sip_pvt_unlock(p);
28604    ao2_t_ref(p, -1, "throw away dialog ptr from find_call at end of routine"); /* p is gone after the return */
28605    ast_mutex_unlock(&netlock);
28606 
28607    if (p->logger_callid) {
28608       ast_callid_threadassoc_remove();
28609    }
28610 
28611    return 1;
28612 }
28613 
28614 /*! \brief Returns the port to use for this socket
28615  *
28616  * \param type The type of transport used
28617  * \param port Port we are checking to see if it's the standard port.
28618  * \note port is expected in host byte order
28619  */
28620 static int sip_standard_port(enum sip_transport type, int port)
28621 {
28622    if (type & SIP_TRANSPORT_TLS)
28623       return port == STANDARD_TLS_PORT;
28624    else
28625       return port == STANDARD_SIP_PORT;
28626 }
28627 
28628 static int threadinfo_locate_cb(void *obj, void *arg, int flags)
28629 {
28630    struct sip_threadinfo *th = obj;
28631    struct ast_sockaddr *s = arg;
28632 
28633    if (!ast_sockaddr_cmp(s, &th->tcptls_session->remote_address)) {
28634       return CMP_MATCH | CMP_STOP;
28635    }
28636 
28637    return 0;
28638 }
28639 
28640 /*!
28641  * \brief Find thread for TCP/TLS session (based on IP/Port
28642  *
28643  * \note This function returns an astobj2 reference
28644  */
28645 static struct ast_tcptls_session_instance *sip_tcp_locate(struct ast_sockaddr *s)
28646 {
28647    struct sip_threadinfo *th;
28648    struct ast_tcptls_session_instance *tcptls_instance = NULL;
28649 
28650    if ((th = ao2_callback(threadt, 0, threadinfo_locate_cb, s))) {
28651       tcptls_instance = (ao2_ref(th->tcptls_session, +1), th->tcptls_session);
28652       ao2_t_ref(th, -1, "decrement ref from callback");
28653    }
28654 
28655    return tcptls_instance;
28656 }
28657 
28658 /*!
28659  * \brief Helper for dns resolution to filter by address family.
28660  *
28661  * \note return 0 if addr is [::] else it returns addr's family.
28662  */
28663 int get_address_family_filter(unsigned int transport)
28664 {
28665    const struct ast_sockaddr *addr = NULL;
28666 
28667    if ((transport == SIP_TRANSPORT_UDP) || !transport) {
28668       addr = &bindaddr;
28669    } else if (transport == SIP_TRANSPORT_TCP || transport == SIP_TRANSPORT_WS) {
28670       addr = &sip_tcp_desc.local_address;
28671    } else if (transport == SIP_TRANSPORT_TLS || transport == SIP_TRANSPORT_WSS) {
28672       addr = &sip_tls_desc.local_address;
28673    }
28674 
28675    if (ast_sockaddr_is_ipv6(addr) && ast_sockaddr_is_any(addr)) {
28676       return 0;
28677    }
28678 
28679    return addr->ss.ss_family;
28680 }
28681 
28682 /*! \todo Get socket for dialog, prepare if needed, and return file handle  */
28683 static int sip_prepare_socket(struct sip_pvt *p)
28684 {
28685    struct sip_socket *s = &p->socket;
28686    static const char name[] = "SIP socket";
28687    struct sip_threadinfo *th = NULL;
28688    struct ast_tcptls_session_instance *tcptls_session;
28689    struct ast_tcptls_session_args *ca;
28690    struct ast_sockaddr sa_tmp;
28691    pthread_t launched;
28692 
28693    /* check to see if a socket is already active */
28694    if ((s->fd != -1) && (s->type == SIP_TRANSPORT_UDP)) {
28695       return s->fd;
28696    }
28697    if ((s->type & (SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS)) &&
28698          (s->tcptls_session) &&
28699          (s->tcptls_session->fd != -1)) {
28700       return s->tcptls_session->fd;
28701    }
28702    if ((s->type & (SIP_TRANSPORT_WS | SIP_TRANSPORT_WSS))) {
28703       return s->ws_session ? ast_websocket_fd(s->ws_session) : -1;
28704    }
28705 
28706    /*! \todo Check this... This might be wrong, depending on the proxy configuration
28707       If proxy is in "force" mode its correct.
28708     */
28709    if (p->outboundproxy && p->outboundproxy->transport) {
28710       s->type = p->outboundproxy->transport;
28711    }
28712 
28713    if (s->type == SIP_TRANSPORT_UDP) {
28714       s->fd = sipsock;
28715       return s->fd;
28716    }
28717 
28718    /* At this point we are dealing with a TCP/TLS connection
28719     * 1. We need to check to see if a connection thread exists
28720     *    for this address, if so use that.
28721     * 2. If a thread does not exist for this address, but the tcptls_session
28722     *    exists on the socket, the connection was closed.
28723     * 3. If no tcptls_session thread exists for the address, and no tcptls_session
28724     *    already exists on the socket, create a new one and launch a new thread.
28725     */
28726 
28727    /* 1.  check for existing threads */
28728    ast_sockaddr_copy(&sa_tmp, sip_real_dst(p));
28729    if ((tcptls_session = sip_tcp_locate(&sa_tmp))) {
28730       s->fd = tcptls_session->fd;
28731       if (s->tcptls_session) {
28732          ao2_ref(s->tcptls_session, -1);
28733          s->tcptls_session = NULL;
28734       }
28735       s->tcptls_session = tcptls_session;
28736       return s->fd;
28737    /* 2.  Thread not found, if tcptls_session already exists, it once had a thread and is now terminated */
28738    } else if (s->tcptls_session) {
28739       return s->fd; /* XXX whether reconnection is ever necessary here needs to be investigated further */
28740    }
28741 
28742    /* 3.  Create a new TCP/TLS client connection */
28743    /* create new session arguments for the client connection */
28744    if (!(ca = ao2_alloc(sizeof(*ca), sip_tcptls_client_args_destructor)) ||
28745       !(ca->name = ast_strdup(name))) {
28746       goto create_tcptls_session_fail;
28747    }
28748    ca->accept_fd = -1;
28749    ast_sockaddr_copy(&ca->remote_address,sip_real_dst(p));
28750    /* if type is TLS, we need to create a tls cfg for this session arg */
28751    if (s->type == SIP_TRANSPORT_TLS) {
28752       if (!(ca->tls_cfg = ast_calloc(1, sizeof(*ca->tls_cfg)))) {
28753          goto create_tcptls_session_fail;
28754       }
28755       memcpy(ca->tls_cfg, &default_tls_cfg, sizeof(*ca->tls_cfg));
28756 
28757       if (!(ca->tls_cfg->certfile = ast_strdup(default_tls_cfg.certfile)) ||
28758          !(ca->tls_cfg->pvtfile = ast_strdup(default_tls_cfg.pvtfile)) ||
28759          !(ca->tls_cfg->cipher = ast_strdup(default_tls_cfg.cipher)) ||
28760          !(ca->tls_cfg->cafile = ast_strdup(default_tls_cfg.cafile)) ||
28761          !(ca->tls_cfg->capath = ast_strdup(default_tls_cfg.capath))) {
28762 
28763          goto create_tcptls_session_fail;
28764       }
28765 
28766       /* this host is used as the common name in ssl/tls */
28767       if (!ast_strlen_zero(p->tohost)) {
28768          ast_copy_string(ca->hostname, p->tohost, sizeof(ca->hostname));
28769       }
28770    }
28771 
28772    /* Create a client connection for address, this does not start the connection, just sets it up. */
28773    if (!(s->tcptls_session = ast_tcptls_client_create(ca))) {
28774       goto create_tcptls_session_fail;
28775    }
28776 
28777    s->fd = s->tcptls_session->fd;
28778 
28779    /* client connections need to have the sip_threadinfo object created before
28780     * the thread is detached.  This ensures the alert_pipe is up before it will
28781     * be used.  Note that this function links the new threadinfo object into the
28782     * threadt container. */
28783    if (!(th = sip_threadinfo_create(s->tcptls_session, s->type))) {
28784       goto create_tcptls_session_fail;
28785    }
28786 
28787    /* Give the new thread a reference to the tcptls_session */
28788    ao2_ref(s->tcptls_session, +1);
28789 
28790    if (ast_pthread_create_detached_background(&launched, NULL, sip_tcp_worker_fn, s->tcptls_session)) {
28791       ast_debug(1, "Unable to launch '%s'.", ca->name);
28792       ao2_ref(s->tcptls_session, -1); /* take away the thread ref we just gave it */
28793       goto create_tcptls_session_fail;
28794    }
28795 
28796    return s->fd;
28797 
28798 create_tcptls_session_fail:
28799    if (ca) {
28800       ao2_t_ref(ca, -1, "failed to create client, getting rid of client tcptls_session arguments");
28801    }
28802    if (s->tcptls_session) {
28803       ast_tcptls_close_session_file(s->tcptls_session);
28804       s->fd = -1;
28805       ao2_ref(s->tcptls_session, -1);
28806       s->tcptls_session = NULL;
28807    }
28808    if (th) {
28809       ao2_t_unlink(threadt, th, "Removing tcptls thread info object, thread failed to open");
28810    }
28811 
28812    return -1;
28813 }
28814 
28815 /*!
28816  * \brief Get cached MWI info
28817  * \return TRUE if found MWI in cache
28818  */
28819 static int get_cached_mwi(struct sip_peer *peer, int *new, int *old)
28820 {
28821    struct sip_mailbox *mailbox;
28822    int in_cache;
28823 
28824    in_cache = 0;
28825    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
28826       struct ast_event *event;
28827       event = ast_event_get_cached(AST_EVENT_MWI,
28828          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
28829          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
28830          AST_EVENT_IE_END);
28831       if (!event)
28832          continue;
28833       *new += ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
28834       *old += ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
28835       ast_event_destroy(event);
28836       in_cache = 1;
28837    }
28838 
28839    return in_cache;
28840 }
28841 
28842 /*! \brief Send message waiting indication to alert peer that they've got voicemail
28843  *  \note Both peer and associated sip_pvt must be unlocked prior to calling this function
28844  *  \returns -1 on failure, 0 on success
28845  */
28846 static int sip_send_mwi_to_peer(struct sip_peer *peer, int cache_only)
28847 {
28848    /* Called with peer lock, but releases it */
28849    struct sip_pvt *p;
28850    int newmsgs = 0, oldmsgs = 0;
28851    const char *vmexten = NULL;
28852 
28853    ao2_lock(peer);
28854 
28855    if (peer->vmexten) {
28856       vmexten = ast_strdupa(peer->vmexten);
28857    }
28858 
28859    if (ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY) && !peer->mwipvt) {
28860       update_peer_lastmsgssent(peer, -1, 1);
28861       ao2_unlock(peer);
28862       return -1;
28863    }
28864 
28865    /* Do we have an IP address? If not, skip this peer */
28866    if (ast_sockaddr_isnull(&peer->addr) && ast_sockaddr_isnull(&peer->defaddr)) {
28867       update_peer_lastmsgssent(peer, -1, 1);
28868       ao2_unlock(peer);
28869       return -1;
28870    }
28871 
28872    /* Attempt to use cached mwi to get message counts. */
28873    if (!get_cached_mwi(peer, &newmsgs, &oldmsgs) && !cache_only) {
28874       /* Fall back to manually checking the mailbox if not cache_only and get_cached_mwi failed */
28875       struct ast_str *mailbox_str = ast_str_alloca(512);
28876       peer_mailboxes_to_str(&mailbox_str, peer);
28877       /* if there is no mailbox do nothing */
28878       if (!ast_str_strlen(mailbox_str)) {
28879          ao2_unlock(peer);
28880          return -1;
28881       }
28882       ao2_unlock(peer);
28883       /* If there is no mailbox do nothing */
28884       if (!ast_str_strlen(mailbox_str)) {
28885          update_peer_lastmsgssent(peer, -1, 0);
28886          return 0;
28887       }
28888       ast_app_inboxcount(ast_str_buffer(mailbox_str), &newmsgs, &oldmsgs);
28889       ao2_lock(peer);
28890    }
28891 
28892    if (peer->mwipvt) {
28893       /* Base message on subscription */
28894       p = dialog_ref(peer->mwipvt, "sip_send_mwi_to_peer: Setting dialog ptr p from peer->mwipvt");
28895       ao2_unlock(peer);
28896    } else {
28897       ao2_unlock(peer);
28898       /* Build temporary dialog for this message */
28899       if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL, NULL))) {
28900          update_peer_lastmsgssent(peer, -1, 0);
28901          return -1;
28902       }
28903 
28904       /* If we don't set the socket type to 0, then create_addr_from_peer will fail immediately if the peer
28905        * uses any transport other than UDP. We set the type to 0 here and then let create_addr_from_peer copy
28906        * the peer's socket information to the sip_pvt we just allocated
28907        */
28908       set_socket_transport(&p->socket, 0);
28909       if (create_addr_from_peer(p, peer)) {
28910          /* Maybe they're not registered, etc. */
28911          dialog_unlink_all(p);
28912          dialog_unref(p, "unref dialog p just created via sip_alloc");
28913          update_peer_lastmsgssent(peer, -1, 0);
28914          return -1;
28915       }
28916       /* Recalculate our side, and recalculate Call ID */
28917       ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
28918       build_via(p);
28919 
28920       ao2_lock(peer);
28921       if (!ast_strlen_zero(peer->mwi_from)) {
28922          ast_string_field_set(p, mwi_from, peer->mwi_from);
28923       } else if (!ast_strlen_zero(default_mwi_from)) {
28924          ast_string_field_set(p, mwi_from, default_mwi_from);
28925       }
28926       ao2_unlock(peer);
28927 
28928       /* Change the dialog callid. */
28929       change_callid_pvt(p, NULL);
28930 
28931       /* Destroy this session after 32 secs */
28932       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
28933    }
28934 
28935    /* 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,
28936       we really need to have a lock on it */
28937    sip_pvt_lock(p);
28938 
28939    /* Send MWI */
28940    ast_set_flag(&p->flags[0], SIP_OUTGOING);
28941    /* the following will decrement the refcount on p as it finishes */
28942    transmit_notify_with_mwi(p, newmsgs, oldmsgs, vmexten);
28943    sip_pvt_unlock(p);
28944    dialog_unref(p, "unref dialog ptr p just before it goes out of scope at the end of sip_send_mwi_to_peer.");
28945 
28946    update_peer_lastmsgssent(peer, ((newmsgs > 0x7fff ? 0x7fff0000 : (newmsgs << 16)) | (oldmsgs > 0xffff ? 0xffff : oldmsgs)), 0);
28947 
28948    return 0;
28949 }
28950 
28951 /*!
28952  * \brief helper function for the monitoring thread -- seems to be called with the assumption that the dialog is locked
28953  *
28954  * \return CMP_MATCH for items to be unlinked from dialogs_rtpcheck.
28955  */
28956 static int check_rtp_timeout(struct sip_pvt *dialog, time_t t)
28957 {
28958    int timeout;
28959    int hold_timeout;
28960    int keepalive;
28961 
28962    if (!dialog->rtp) {
28963       /*
28964        * We have no RTP.  Since we don't do much with video RTP for
28965        * now, stop checking this dialog.
28966        */
28967       return CMP_MATCH;
28968    }
28969 
28970    /* If we have no active owner, no need to check timers */
28971    if (!dialog->owner) {
28972       return CMP_MATCH;
28973    }
28974 
28975    /* If the call is redirected outside Asterisk, no need to check timers */
28976    if (!ast_sockaddr_isnull(&dialog->redirip)) {
28977       return CMP_MATCH;
28978    }
28979 
28980    /* If the call is involved in a T38 fax session do not check RTP timeout */
28981    if (dialog->t38.state == T38_ENABLED) {
28982       return CMP_MATCH;
28983    }
28984    /* If the call is not in UP state return for later check. */
28985    if (ast_channel_state(dialog->owner) != AST_STATE_UP) {
28986       return 0;
28987    }
28988 
28989    /* Store these values locally to avoid multiple function calls */
28990    timeout = ast_rtp_instance_get_timeout(dialog->rtp);
28991    hold_timeout = ast_rtp_instance_get_hold_timeout(dialog->rtp);
28992    keepalive = ast_rtp_instance_get_keepalive(dialog->rtp);
28993 
28994    /* If we have no timers set, return now */
28995    if (!keepalive && !timeout && !hold_timeout) {
28996       return CMP_MATCH;
28997    }
28998 
28999    /* Check AUDIO RTP keepalives */
29000    if (dialog->lastrtptx && keepalive && (t > dialog->lastrtptx + keepalive)) {
29001       /* Need to send an empty RTP packet */
29002       dialog->lastrtptx = time(NULL);
29003       ast_rtp_instance_sendcng(dialog->rtp, 0);
29004    }
29005 
29006    /*! \todo Check video RTP keepalives
29007 
29008       Do we need to move the lastrtptx to the RTP structure to have one for audio and one
29009       for video? It really does belong to the RTP structure.
29010    */
29011 
29012    /* Check AUDIO RTP timers */
29013    if (dialog->lastrtprx && (timeout || hold_timeout) && (t > dialog->lastrtprx + timeout)) {
29014       if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD) || (hold_timeout && (t > dialog->lastrtprx + hold_timeout))) {
29015          /* Needs a hangup */
29016          if (timeout) {
29017             if (!dialog->owner || ast_channel_trylock(dialog->owner)) {
29018                /*
29019                 * Don't block, just try again later.
29020                 * If there was no owner, the call is dead already.
29021                 */
29022                return 0;
29023             }
29024             ast_log(LOG_NOTICE, "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
29025                ast_channel_name(dialog->owner), (long) (t - dialog->lastrtprx));
29026             manager_event(EVENT_FLAG_CALL, "SessionTimeout", "Source: RTPTimeout\r\n"
29027                   "Channel: %s\r\nUniqueid: %s\r\n", ast_channel_name(dialog->owner), ast_channel_uniqueid(dialog->owner));
29028             /* Issue a softhangup */
29029             ast_softhangup_nolock(dialog->owner, AST_SOFTHANGUP_DEV);
29030             ast_channel_unlock(dialog->owner);
29031             /* forget the timeouts for this call, since a hangup
29032                has already been requested and we don't want to
29033                repeatedly request hangups
29034             */
29035             ast_rtp_instance_set_timeout(dialog->rtp, 0);
29036             ast_rtp_instance_set_hold_timeout(dialog->rtp, 0);
29037             if (dialog->vrtp) {
29038                ast_rtp_instance_set_timeout(dialog->vrtp, 0);
29039                ast_rtp_instance_set_hold_timeout(dialog->vrtp, 0);
29040             }
29041             /* finally unlink the dialog from dialogs_rtpcheck. */
29042             return CMP_MATCH;
29043          }
29044       }
29045    }
29046    return 0;
29047 }
29048 
29049 /*! \brief The SIP monitoring thread
29050 \note This thread monitors all the SIP sessions and peers that needs notification of mwi
29051    (and thus do not have a separate thread) indefinitely
29052 */
29053 static void *do_monitor(void *data)
29054 {
29055    int res;
29056    time_t t;
29057    int reloading;
29058 
29059    /* Add an I/O event to our SIP UDP socket */
29060    if (sipsock > -1) {
29061       sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
29062    }
29063 
29064    /* From here on out, we die whenever asked */
29065    for(;;) {
29066       /* Check for a reload request */
29067       ast_mutex_lock(&sip_reload_lock);
29068       reloading = sip_reloading;
29069       sip_reloading = FALSE;
29070       ast_mutex_unlock(&sip_reload_lock);
29071       if (reloading) {
29072          ast_verb(1, "Reloading SIP\n");
29073          sip_do_reload(sip_reloadreason);
29074 
29075          /* Change the I/O fd of our UDP socket */
29076          if (sipsock > -1) {
29077             if (sipsock_read_id) {
29078                sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
29079             } else {
29080                sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
29081             }
29082          } else if (sipsock_read_id) {
29083             ast_io_remove(io, sipsock_read_id);
29084             sipsock_read_id = NULL;
29085          }
29086       }
29087 
29088       /* Check for dialogs needing to be killed */
29089       t = time(NULL);
29090 
29091       /*
29092        * Check dialogs with rtp and rtptimeout.
29093        * All dialogs which have rtp are in dialogs_rtpcheck.
29094        */
29095       ao2_t_callback(dialogs_rtpcheck, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE,
29096          dialog_checkrtp_cb, &t,
29097          "callback to check rtptimeout and hangup calls if necessary");
29098       /*
29099        * Check dialogs marked to be destroyed.
29100        * All dialogs with needdestroy set are in dialogs_needdestroy.
29101        */
29102       ao2_t_callback(dialogs_needdestroy, OBJ_NODATA | OBJ_MULTIPLE, dialog_needdestroy,
29103          NULL, "callback to check dialogs which need to be destroyed");
29104 
29105       /* XXX TODO The scheduler usage in this module does not have sufficient
29106        * synchronization being done between running the scheduler and places
29107        * scheduling tasks.  As it is written, any scheduled item may not run
29108        * any sooner than about  1 second, regardless of whether a sooner time
29109        * was asked for. */
29110 
29111       pthread_testcancel();
29112       /* Wait for sched or io */
29113       res = ast_sched_wait(sched);
29114       if ((res < 0) || (res > 1000)) {
29115          res = 1000;
29116       }
29117       res = ast_io_wait(io, res);
29118       if (res > 20) {
29119          ast_debug(1, "chan_sip: ast_io_wait ran %d all at once\n", res);
29120       }
29121       ast_mutex_lock(&monlock);
29122       res = ast_sched_runq(sched);
29123       if (res >= 20) {
29124          ast_debug(1, "chan_sip: ast_sched_runq ran %d all at once\n", res);
29125       }
29126       ast_mutex_unlock(&monlock);
29127    }
29128 
29129    /* Never reached */
29130    return NULL;
29131 }
29132 
29133 /*! \brief Start the channel monitor thread */
29134 static int restart_monitor(void)
29135 {
29136    /* If we're supposed to be stopped -- stay stopped */
29137    if (monitor_thread == AST_PTHREADT_STOP)
29138       return 0;
29139    ast_mutex_lock(&monlock);
29140    if (monitor_thread == pthread_self()) {
29141       ast_mutex_unlock(&monlock);
29142       ast_log(LOG_WARNING, "Cannot kill myself\n");
29143       return -1;
29144    }
29145    if (monitor_thread != AST_PTHREADT_NULL) {
29146       /* Wake up the thread */
29147       pthread_kill(monitor_thread, SIGURG);
29148    } else {
29149       /* Start a new monitor */
29150       if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
29151          ast_mutex_unlock(&monlock);
29152          ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
29153          return -1;
29154       }
29155    }
29156    ast_mutex_unlock(&monlock);
29157    return 0;
29158 }
29159 
29160 static void acl_change_event_cb(const struct ast_event *event, void *userdata)
29161 {
29162    ast_log(LOG_NOTICE, "Reloading chan_sip in response to ACL change event.\n");
29163 
29164    ast_mutex_lock(&sip_reload_lock);
29165 
29166    if (sip_reloading) {
29167       ast_verbose("Previous SIP reload not yet done\n");
29168    } else {
29169       sip_reloading = TRUE;
29170       sip_reloadreason = CHANNEL_ACL_RELOAD;
29171    }
29172 
29173    ast_mutex_unlock(&sip_reload_lock);
29174 
29175    restart_monitor();
29176 }
29177 
29178 /*! \brief Session-Timers: Restart session timer */
29179 static void restart_session_timer(struct sip_pvt *p)
29180 {
29181    if (!p->stimer) {
29182       ast_log(LOG_WARNING, "Null stimer in restart_session_timer - %s\n", p->callid);
29183       return;
29184    }
29185 
29186    if (p->stimer->st_active == TRUE) {
29187       ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
29188       AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
29189             dialog_unref(p, "Removing session timer ref"));
29190       start_session_timer(p);
29191    }
29192 }
29193 
29194 
29195 /*! \brief Session-Timers: Stop session timer */
29196 static void stop_session_timer(struct sip_pvt *p)
29197 {
29198    if (!p->stimer) {
29199       ast_log(LOG_WARNING, "Null stimer in stop_session_timer - %s\n", p->callid);
29200       return;
29201    }
29202 
29203    if (p->stimer->st_active == TRUE) {
29204       p->stimer->st_active = FALSE;
29205       ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
29206       AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
29207             dialog_unref(p, "removing session timer ref"));
29208    }
29209 }
29210 
29211 
29212 /*! \brief Session-Timers: Start session timer */
29213 static void start_session_timer(struct sip_pvt *p)
29214 {
29215    unsigned int timeout_ms;
29216 
29217    if (!p->stimer) {
29218       ast_log(LOG_WARNING, "Null stimer in start_session_timer - %s\n", p->callid);
29219       return;
29220    }
29221 
29222    if (p->stimer->st_schedid > -1) {
29223       /* in the event a timer is already going, stop it */
29224       ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
29225       AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
29226          dialog_unref(p, "unref stimer->st_schedid from dialog"));
29227    }
29228 
29229    /*
29230     * RFC 4028 Section 10
29231     * If the side not performing refreshes does not receive a
29232     * session refresh request before the session expiration, it SHOULD send
29233     * a BYE to terminate the session, slightly before the session
29234     * expiration.  The minimum of 32 seconds and one third of the session
29235     * interval is RECOMMENDED.
29236     */
29237 
29238    timeout_ms = (1000 * p->stimer->st_interval);
29239    if (p->stimer->st_ref == SESSION_TIMER_REFRESHER_US) {
29240       timeout_ms /= 2;
29241    } else {
29242       timeout_ms -= MIN(timeout_ms / 3, 32000);
29243    }
29244 
29245    p->stimer->st_schedid = ast_sched_add(sched, timeout_ms, proc_session_timer,
29246          dialog_ref(p, "adding session timer ref"));
29247 
29248    if (p->stimer->st_schedid < 0) {
29249       dialog_unref(p, "removing session timer ref");
29250       ast_log(LOG_ERROR, "ast_sched_add failed - %s\n", p->callid);
29251    } else {
29252       p->stimer->st_active = TRUE;
29253       ast_debug(2, "Session timer started: %d - %s %ums\n", p->stimer->st_schedid, p->callid, timeout_ms);
29254    }
29255 }
29256 
29257 
29258 /*! \brief Session-Timers: Process session refresh timeout event */
29259 static int proc_session_timer(const void *vp)
29260 {
29261    struct sip_pvt *p = (struct sip_pvt *) vp;
29262    int res = 0;
29263 
29264    if (!p->stimer) {
29265       ast_log(LOG_WARNING, "Null stimer in proc_session_timer - %s\n", p->callid);
29266       goto return_unref;
29267    }
29268 
29269    ast_debug(2, "Session timer expired: %d - %s\n", p->stimer->st_schedid, p->callid);
29270 
29271    if (!p->owner) {
29272       goto return_unref;
29273    }
29274 
29275    if ((p->stimer->st_active != TRUE) || (ast_channel_state(p->owner) != AST_STATE_UP)) {
29276       goto return_unref;
29277    }
29278 
29279    if (p->stimer->st_ref == SESSION_TIMER_REFRESHER_US) {
29280       res = 1;
29281       if (T38_ENABLED == p->t38.state) {
29282          transmit_reinvite_with_sdp(p, TRUE, TRUE);
29283       } else {
29284          transmit_reinvite_with_sdp(p, FALSE, TRUE);
29285       }
29286    } else {
29287       if (p->stimer->quit_flag) {
29288          goto return_unref;
29289       }
29290       ast_log(LOG_WARNING, "Session-Timer expired - %s\n", p->callid);
29291       sip_pvt_lock(p);
29292       while (p->owner && ast_channel_trylock(p->owner)) {
29293          sip_pvt_unlock(p);
29294          usleep(1);
29295          if (p->stimer && p->stimer->quit_flag) {
29296             goto return_unref;
29297          }
29298          sip_pvt_lock(p);
29299       }
29300 
29301       manager_event(EVENT_FLAG_CALL, "SessionTimeout", "Source: SIPSessionTimer\r\n"
29302             "Channel: %s\r\nUniqueid: %s\r\n", ast_channel_name(p->owner), ast_channel_uniqueid(p->owner));
29303       ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
29304       ast_channel_unlock(p->owner);
29305       sip_pvt_unlock(p);
29306    }
29307 
29308 return_unref:
29309    if (!res) {
29310       /* An error occurred.  Stop session timer processing */
29311       if (p->stimer) {
29312          ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
29313          p->stimer->st_schedid = -1;
29314          stop_session_timer(p);
29315       }
29316 
29317       /* If we are not asking to be rescheduled, then we need to release our
29318        * reference to the dialog. */
29319       dialog_unref(p, "removing session timer ref");
29320    }
29321 
29322    return res;
29323 }
29324 
29325 
29326 /*! \brief Session-Timers: Function for parsing Min-SE header */
29327 int parse_minse (const char *p_hdrval, int *const p_interval)
29328 {
29329    if (ast_strlen_zero(p_hdrval)) {
29330       ast_log(LOG_WARNING, "Null Min-SE header\n");
29331       return -1;
29332    }
29333 
29334    *p_interval = 0;
29335    p_hdrval = ast_skip_blanks(p_hdrval);
29336    if (!sscanf(p_hdrval, "%30d", p_interval)) {
29337       ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
29338       return -1;
29339    }
29340 
29341    ast_debug(2, "Received Min-SE: %d\n", *p_interval);
29342    return 0;
29343 }
29344 
29345 
29346 /*! \brief Session-Timers: Function for parsing Session-Expires header */
29347 int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher_param *const p_ref)
29348 {
29349    char *p_token;
29350    int  ref_idx;
29351    char *p_se_hdr;
29352 
29353    if (ast_strlen_zero(p_hdrval)) {
29354       ast_log(LOG_WARNING, "Null Session-Expires header\n");
29355       return -1;
29356    }
29357 
29358    *p_ref = SESSION_TIMER_REFRESHER_PARAM_UNKNOWN;
29359    *p_interval = 0;
29360 
29361    p_se_hdr = ast_strdupa(p_hdrval);
29362    p_se_hdr = ast_skip_blanks(p_se_hdr);
29363 
29364    while ((p_token = strsep(&p_se_hdr, ";"))) {
29365       p_token = ast_skip_blanks(p_token);
29366       if (!sscanf(p_token, "%30d", p_interval)) {
29367          ast_log(LOG_WARNING, "Parsing of Session-Expires failed\n");
29368          return -1;
29369       }
29370 
29371       ast_debug(2, "Session-Expires: %d\n", *p_interval);
29372 
29373       if (!p_se_hdr)
29374          continue;
29375 
29376       p_se_hdr = ast_skip_blanks(p_se_hdr);
29377       ref_idx = strlen("refresher=");
29378       if (!strncasecmp(p_se_hdr, "refresher=", ref_idx)) {
29379          p_se_hdr += ref_idx;
29380          p_se_hdr = ast_skip_blanks(p_se_hdr);
29381 
29382          if (!strncasecmp(p_se_hdr, "uac", strlen("uac"))) {
29383             *p_ref = SESSION_TIMER_REFRESHER_PARAM_UAC;
29384             ast_debug(2, "Refresher: UAC\n");
29385          } else if (!strncasecmp(p_se_hdr, "uas", strlen("uas"))) {
29386             *p_ref = SESSION_TIMER_REFRESHER_PARAM_UAS;
29387             ast_debug(2, "Refresher: UAS\n");
29388          } else {
29389             ast_log(LOG_WARNING, "Invalid refresher value %s\n", p_se_hdr);
29390             return -1;
29391          }
29392          break;
29393       }
29394    }
29395    return 0;
29396 }
29397 
29398 
29399 /*! \brief Handle 422 response to INVITE with session-timer requested
29400 
29401    Session-Timers:   An INVITE originated by Asterisk that asks for session-timers support
29402    from the UAS can result into a 422 response. This is how a UAS or an intermediary proxy
29403    server tells Asterisk that the session refresh interval offered by Asterisk is too low
29404    for them.  The proc_422_rsp() function handles a 422 response.  It extracts the Min-SE
29405    header that comes back in 422 and sends a new INVITE accordingly. */
29406 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp)
29407 {
29408    int rtn;
29409    const char *p_hdrval;
29410    int minse;
29411 
29412    p_hdrval = sip_get_header(rsp, "Min-SE");
29413    if (ast_strlen_zero(p_hdrval)) {
29414       ast_log(LOG_WARNING, "422 response without a Min-SE header %s\n", p_hdrval);
29415       return;
29416    }
29417    rtn = parse_minse(p_hdrval, &minse);
29418    if (rtn != 0) {
29419       ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
29420       return;
29421    }
29422    p->stimer->st_cached_min_se = minse;
29423    if (p->stimer->st_interval < minse) {
29424       p->stimer->st_interval = minse;
29425    }
29426    transmit_invite(p, SIP_INVITE, 1, 2, NULL);
29427 }
29428 
29429 
29430 /*! \brief Get Max or Min SE (session timer expiry)
29431  * \param p pointer to the SIP dialog
29432  * \param max if true, get max se, otherwise min se
29433 */
29434 int st_get_se(struct sip_pvt *p, int max)
29435 {
29436    if (max == TRUE) {
29437       if (p->stimer->st_cached_max_se) {
29438          return  p->stimer->st_cached_max_se;
29439       }
29440       if (p->relatedpeer) {
29441          p->stimer->st_cached_max_se = p->relatedpeer->stimer.st_max_se;
29442          return (p->stimer->st_cached_max_se);
29443       }
29444       p->stimer->st_cached_max_se = global_max_se;
29445       return (p->stimer->st_cached_max_se);
29446    } 
29447    /* Find Min SE timer */
29448    if (p->stimer->st_cached_min_se) {
29449       return p->stimer->st_cached_min_se;
29450    } 
29451    if (p->relatedpeer) {
29452       p->stimer->st_cached_min_se = p->relatedpeer->stimer.st_min_se;
29453       return (p->stimer->st_cached_min_se);
29454    }
29455    p->stimer->st_cached_min_se = global_min_se;
29456    return (p->stimer->st_cached_min_se);
29457 }
29458 
29459 
29460 /*! \brief Get the entity (UAC or UAS) that's acting as the session-timer refresher
29461  * \note This is only called when processing an INVITE, so in that case Asterisk is
29462  *       always currently the UAS. If this is ever used to process responses, the
29463  *       function will have to be changed.
29464  * \param p pointer to the SIP dialog
29465 */
29466 enum st_refresher st_get_refresher(struct sip_pvt *p)
29467 {
29468    if (p->stimer->st_cached_ref != SESSION_TIMER_REFRESHER_AUTO) {
29469       return p->stimer->st_cached_ref;
29470    }
29471 
29472    if (p->relatedpeer) {
29473       p->stimer->st_cached_ref = (p->relatedpeer->stimer.st_ref == SESSION_TIMER_REFRESHER_PARAM_UAC) ? SESSION_TIMER_REFRESHER_THEM : SESSION_TIMER_REFRESHER_US;
29474       return p->stimer->st_cached_ref;
29475    }
29476    
29477    p->stimer->st_cached_ref = (global_st_refresher == SESSION_TIMER_REFRESHER_PARAM_UAC) ? SESSION_TIMER_REFRESHER_THEM : SESSION_TIMER_REFRESHER_US;
29478    return p->stimer->st_cached_ref;
29479 }
29480 
29481 
29482 /*!
29483  * \brief Get the session-timer mode 
29484  * \param p pointer to the SIP dialog 
29485  * \param no_cached, set this to true in order to force a peername lookup on
29486  *        the session timer mode.
29487 */
29488 enum st_mode st_get_mode(struct sip_pvt *p, int no_cached)
29489 {
29490    if (!p->stimer) {
29491       sip_st_alloc(p);
29492       if (!p->stimer) {
29493          return SESSION_TIMER_MODE_INVALID;
29494       }
29495    }
29496 
29497    if (!no_cached && p->stimer->st_cached_mode != SESSION_TIMER_MODE_INVALID)
29498       return p->stimer->st_cached_mode;
29499 
29500    if (p->relatedpeer) {
29501       p->stimer->st_cached_mode = p->relatedpeer->stimer.st_mode_oper;
29502       return p->stimer->st_cached_mode;
29503    }
29504 
29505    p->stimer->st_cached_mode = global_st_mode;
29506    return global_st_mode;
29507 }
29508 
29509 /*! \brief Send keep alive packet to peer */
29510 static int sip_send_keepalive(const void *data)
29511 {
29512    struct sip_peer *peer = (struct sip_peer*) data;
29513    int res = 0;
29514    const char keepalive[] = "\r\n";
29515 
29516    peer->keepalivesend = -1;
29517 
29518    if (!peer->keepalive || ast_sockaddr_isnull(&peer->addr)) {
29519       sip_unref_peer(peer, "release keepalive peer ref");
29520       return 0;
29521    }
29522 
29523    /* Send the packet out using the proper method for this peer */
29524    if ((peer->socket.fd != -1) && (peer->socket.type == SIP_TRANSPORT_UDP)) {
29525       res = ast_sendto(peer->socket.fd, keepalive, sizeof(keepalive), 0, &peer->addr);
29526    } else if ((peer->socket.type & (SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS)) &&
29527          (peer->socket.tcptls_session) &&
29528          (peer->socket.tcptls_session->fd != -1)) {
29529       res = sip_tcptls_write(peer->socket.tcptls_session, keepalive, sizeof(keepalive));
29530    } else if (peer->socket.type == SIP_TRANSPORT_UDP) {
29531       res = ast_sendto(sipsock, keepalive, sizeof(keepalive), 0, &peer->addr);
29532    }
29533 
29534    if (res == -1) {
29535       switch (errno) {
29536       case EBADF:             /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
29537       case EHOSTUNREACH:      /* Host can't be reached */
29538       case ENETDOWN:          /* Interface down */
29539       case ENETUNREACH:       /* Network failure */
29540       case ECONNREFUSED:      /* ICMP port unreachable */
29541          res = XMIT_ERROR;       /* Don't bother with trying to transmit again */
29542       }
29543    }
29544 
29545    if (res != sizeof(keepalive)) {
29546       ast_log(LOG_WARNING, "sip_send_keepalive to %s returned %d: %s\n", ast_sockaddr_stringify(&peer->addr), res, strerror(errno));
29547    }
29548 
29549    AST_SCHED_REPLACE_UNREF(peer->keepalivesend, sched,
29550             peer->keepalive * 1000, sip_send_keepalive, peer,
29551             sip_unref_peer(_data, "removing keepalive peer ref"),
29552             sip_unref_peer(peer, "removing keepalive peer ref"),
29553             sip_ref_peer(peer, "adding keepalive peer ref"));
29554 
29555    sip_unref_peer(peer, "release keepalive peer ref");
29556 
29557    return 0;
29558 }
29559 
29560 /*! \brief React to lack of answer to Qualify poke */
29561 static int sip_poke_noanswer(const void *data)
29562 {
29563    struct sip_peer *peer = (struct sip_peer *)data;
29564 
29565    peer->pokeexpire = -1;
29566 
29567    if (peer->lastms > -1) {
29568       ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE!  Last qualify: %d\n", peer->name, peer->lastms);
29569       if (sip_cfg.peer_rtupdate) {
29570          ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", "-1", SENTINEL);
29571       }
29572       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
29573       if (sip_cfg.regextenonqualify) {
29574          register_peer_exten(peer, FALSE);
29575       }
29576    }
29577 
29578    if (peer->call) {
29579       dialog_unlink_all(peer->call);
29580       peer->call = dialog_unref(peer->call, "unref dialog peer->call");
29581       /* peer->call = sip_destroy(peer->call);*/
29582    }
29583 
29584    /* Don't send a devstate change if nothing changed. */
29585    if (peer->lastms > -1) {
29586       peer->lastms = -1;
29587       ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", peer->name);
29588    }
29589 
29590    /* Try again quickly */
29591    AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
29592          DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer,
29593          sip_unref_peer(_data, "removing poke peer ref"),
29594          sip_unref_peer(peer, "removing poke peer ref"),
29595          sip_ref_peer(peer, "adding poke peer ref"));
29596 
29597    /* Release the ref held by the running scheduler entry */
29598    sip_unref_peer(peer, "release peer poke noanswer ref");
29599 
29600    return 0;
29601 }
29602 
29603 /*! \brief Check availability of peer, also keep NAT open
29604 \note This is done with 60 seconds between each ping,
29605    unless forced by cli or manager. If peer is unreachable,
29606    we check every 10th second by default.
29607 \note Do *not* hold a pvt lock while calling this function.
29608    This function calls sip_alloc, which can cause a deadlock
29609    if another sip_pvt is held.
29610 */
29611 static int sip_poke_peer(struct sip_peer *peer, int force)
29612 {
29613    struct sip_pvt *p;
29614    int xmitres = 0;
29615    
29616    if ((!peer->maxms && !force) || ast_sockaddr_isnull(&peer->addr)) {
29617       /* IF we have no IP, or this isn't to be monitored, return
29618         immediately after clearing things out */
29619       AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
29620             sip_unref_peer(peer, "removing poke peer ref"));
29621       
29622       peer->lastms = 0;
29623       if (peer->call) {
29624          peer->call = dialog_unref(peer->call, "unref dialog peer->call");
29625       }
29626       return 0;
29627    }
29628    if (peer->call) {
29629       if (sipdebug) {
29630          ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
29631       }
29632       dialog_unlink_all(peer->call);
29633       peer->call = dialog_unref(peer->call, "unref dialog peer->call");
29634       /* peer->call = sip_destroy(peer->call); */
29635    }
29636    if (!(p = sip_alloc(NULL, NULL, 0, SIP_OPTIONS, NULL, NULL))) {
29637       return -1;
29638    }
29639    peer->call = dialog_ref(p, "copy sip alloc from p to peer->call");
29640 
29641    p->sa = peer->addr;
29642    p->recv = peer->addr;
29643    copy_socket_data(&p->socket, &peer->socket);
29644    ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
29645    ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
29646    ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
29647 
29648    /* Send OPTIONs to peer's fullcontact */
29649    if (!ast_strlen_zero(peer->fullcontact)) {
29650       ast_string_field_set(p, fullcontact, peer->fullcontact);
29651    }
29652 
29653    if (!ast_strlen_zero(peer->fromuser)) {
29654       ast_string_field_set(p, fromuser, peer->fromuser);
29655    }
29656 
29657    if (!ast_strlen_zero(peer->tohost)) {
29658       ast_string_field_set(p, tohost, peer->tohost);
29659    } else {
29660       ast_string_field_set(p, tohost, ast_sockaddr_stringify_host_remote(&peer->addr));
29661    }
29662 
29663    /* Recalculate our side, and recalculate Call ID */
29664    ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
29665    build_via(p);
29666 
29667    /* Change the dialog callid. */
29668    change_callid_pvt(p, NULL);
29669 
29670    AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
29671          sip_unref_peer(peer, "removing poke peer ref"));
29672    
29673    if (p->relatedpeer)
29674       p->relatedpeer = sip_unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
29675    p->relatedpeer = sip_ref_peer(peer, "setting the relatedpeer field in the dialog");
29676    ast_set_flag(&p->flags[0], SIP_OUTGOING);
29677 #ifdef VOCAL_DATA_HACK
29678    ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
29679    xmitres = transmit_invite(p, SIP_INVITE, 0, 2, NULL); /* sinks the p refcount */
29680 #else
29681    xmitres = transmit_invite(p, SIP_OPTIONS, 0, 2, NULL); /* sinks the p refcount */
29682 #endif
29683    peer->ps = ast_tvnow();
29684    if (xmitres == XMIT_ERROR) {
29685       /* Immediately unreachable, network problems */
29686       sip_poke_noanswer(sip_ref_peer(peer, "add ref for peerexpire (fake, for sip_poke_noanswer to remove)"));
29687    } else if (!force) {
29688       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, peer->maxms * 2, sip_poke_noanswer, peer,
29689             sip_unref_peer(_data, "removing poke peer ref"),
29690             sip_unref_peer(peer, "removing poke peer ref"),
29691             sip_ref_peer(peer, "adding poke peer ref"));
29692    }
29693    dialog_unref(p, "unref dialog at end of sip_poke_peer, obtained from sip_alloc, just before it goes out of scope");
29694    return 0;
29695 }
29696 
29697 /*! \brief Part of PBX channel interface
29698 \note
29699 \par  Return values:---
29700 
29701    If we have qualify on and the device is not reachable, regardless of registration
29702    state we return AST_DEVICE_UNAVAILABLE
29703 
29704    For peers with call limit:
29705       - not registered        AST_DEVICE_UNAVAILABLE
29706       - registered, no call         AST_DEVICE_NOT_INUSE
29707       - registered, active calls    AST_DEVICE_INUSE
29708       - registered, call limit reached AST_DEVICE_BUSY
29709       - registered, onhold       AST_DEVICE_ONHOLD
29710       - registered, ringing         AST_DEVICE_RINGING
29711 
29712    For peers without call limit:
29713       - not registered        AST_DEVICE_UNAVAILABLE
29714       - registered            AST_DEVICE_NOT_INUSE
29715       - fixed IP (!dynamic)         AST_DEVICE_NOT_INUSE
29716    
29717    Peers that does not have a known call and can't be reached by OPTIONS
29718       - unreachable           AST_DEVICE_UNAVAILABLE
29719 
29720    If we return AST_DEVICE_UNKNOWN, the device state engine will try to find
29721    out a state by walking the channel list.
29722 
29723    The queue system (\ref app_queue.c) treats a member as "active"
29724    if devicestate is != AST_DEVICE_UNAVAILBALE && != AST_DEVICE_INVALID
29725 
29726    When placing a call to the queue member, queue system sets a member to busy if
29727    != AST_DEVICE_NOT_INUSE and != AST_DEVICE_UNKNOWN
29728 
29729 */
29730 static int sip_devicestate(const char *data)
29731 {
29732    char *host;
29733    char *tmp;
29734    struct sip_peer *p;
29735 
29736    int res = AST_DEVICE_INVALID;
29737 
29738    /* make sure data is not null. Maybe unnecessary, but better be safe */
29739    host = ast_strdupa(data ? data : "");
29740    if ((tmp = strchr(host, '@')))
29741       host = tmp + 1;
29742 
29743    ast_debug(3, "Checking device state for peer %s\n", host);
29744 
29745    /* If sip_find_peer asks for a realtime peer, then this breaks rtautoclear.  This
29746     * is because when a peer tries to autoexpire, the last thing it does is to
29747     * queue up an event telling the system that the devicestate has changed
29748     * (presumably to unavailable).  If we ask for a realtime peer here, this would
29749     * load it BACK into memory, thus defeating the point of trying to clear dead
29750     * hosts out of memory.
29751     */
29752    if ((p = sip_find_peer(host, NULL, FALSE, FINDALLDEVICES, TRUE, 0))) {
29753       if (!(ast_sockaddr_isnull(&p->addr) && ast_sockaddr_isnull(&p->defaddr))) {
29754          /* we have an address for the peer */
29755 
29756          /* Check status in this order
29757             - Hold
29758             - Ringing
29759             - Busy (enforced only by call limit)
29760             - Inuse (we have a call)
29761             - Unreachable (qualify)
29762             If we don't find any of these state, report AST_DEVICE_NOT_INUSE
29763             for registered devices */
29764 
29765          if (p->onhold)
29766             /* First check for hold or ring states */
29767             res = AST_DEVICE_ONHOLD;
29768          else if (p->ringing) {
29769             if (p->ringing == p->inuse)
29770                res = AST_DEVICE_RINGING;
29771             else
29772                res = AST_DEVICE_RINGINUSE;
29773          } else if (p->call_limit && (p->inuse == p->call_limit))
29774             /* check call limit */
29775             res = AST_DEVICE_BUSY;
29776          else if (p->call_limit && p->busy_level && p->inuse >= p->busy_level)
29777             /* We're forcing busy before we've reached the call limit */
29778             res = AST_DEVICE_BUSY;
29779          else if (p->call_limit && p->inuse)
29780             /* Not busy, but we do have a call */
29781             res = AST_DEVICE_INUSE;
29782          else if (p->maxms && ((p->lastms > p->maxms) || (p->lastms < 0)))
29783             /* We don't have a call. Are we reachable at all? Requires qualify= */
29784             res = AST_DEVICE_UNAVAILABLE;
29785          else  /* Default reply if we're registered and have no other data */
29786             res = AST_DEVICE_NOT_INUSE;
29787       } else {
29788          /* there is no address, it's unavailable */
29789          res = AST_DEVICE_UNAVAILABLE;
29790       }
29791       sip_unref_peer(p, "sip_unref_peer, from sip_devicestate, release ref from sip_find_peer");
29792    }
29793 
29794    return res;
29795 }
29796 
29797 /*! \brief PBX interface function -build SIP pvt structure
29798  * SIP calls initiated by the PBX arrive here.
29799  *
29800  * \verbatim
29801  * SIP Dial string syntax:
29802  *    SIP/devicename
29803  * or SIP/username@domain (SIP uri)
29804  * or SIP/username[:password[:md5secret[:authname[:transport]]]]@host[:port]
29805  * or SIP/devicename/extension
29806  * or SIP/devicename/extension/IPorHost
29807  * or SIP/username@domain//IPorHost
29808  * and there is an optional [!dnid] argument you can append to alter the
29809  * To: header.
29810  * \endverbatim
29811  */
29812 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)
29813 {
29814    struct sip_pvt *p;
29815    struct ast_channel *tmpc = NULL;
29816    char *ext = NULL, *host;
29817    char tmp[256];
29818    char tmp2[256];
29819    char *dnid;
29820    char *secret = NULL;
29821    char *md5secret = NULL;
29822    char *authname = NULL;
29823    char *trans = NULL;
29824    char dialstring[256];
29825    char *remote_address;
29826    enum sip_transport transport = 0;
29827    struct ast_callid *callid;
29828    AST_DECLARE_APP_ARGS(args,
29829       AST_APP_ARG(peerorhost);
29830       AST_APP_ARG(exten);
29831       AST_APP_ARG(remote_address);
29832    );
29833 
29834    /* mask request with some set of allowed formats.
29835     * XXX this needs to be fixed.
29836     * The original code uses AST_FORMAT_AUDIO_MASK, but it is
29837     * unclear what to use here. We have global_capabilities, which is
29838     * configured from sip.conf, and sip_tech.capabilities, which is
29839     * hardwired to all audio formats.
29840     */
29841    if (!(ast_format_cap_has_type(cap, AST_FORMAT_TYPE_AUDIO))) {
29842       ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format %s while capability is %s\n",
29843       ast_getformatname_multiple(tmp, sizeof(tmp), cap),
29844       ast_getformatname_multiple(tmp2, sizeof(tmp2), sip_cfg.caps));
29845       *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;   /* Can't find codec to connect to host */
29846       return NULL;
29847    }
29848    ast_debug(1, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), cap));
29849 
29850    if (ast_strlen_zero(dest)) {
29851       ast_log(LOG_ERROR, "Unable to create channel with empty destination.\n");
29852       *cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
29853       return NULL;
29854    }
29855 
29856    callid = ast_read_threadstorage_callid();
29857    if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE, NULL, callid))) {
29858       ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", dest);
29859       *cause = AST_CAUSE_SWITCH_CONGESTION;
29860       if (callid) {
29861          ast_callid_unref(callid);
29862       }
29863       return NULL;
29864    }
29865 
29866    p->outgoing_call = TRUE;
29867 
29868    snprintf(dialstring, sizeof(dialstring), "%s/%s", type, dest);
29869    ast_string_field_set(p, dialstring, dialstring);
29870 
29871    if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
29872       dialog_unlink_all(p);
29873       dialog_unref(p, "unref dialog p from mem fail");
29874       /* sip_destroy(p); */
29875       ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
29876       *cause = AST_CAUSE_SWITCH_CONGESTION;
29877       if (callid) {
29878          ast_callid_unref(callid);
29879       }
29880       return NULL;
29881    }
29882 
29883    /* Save the destination, the SIP dial string */
29884    ast_copy_string(tmp, dest, sizeof(tmp));
29885 
29886    /* Find DNID and take it away */
29887    dnid = strchr(tmp, '!');
29888    if (dnid != NULL) {
29889       *dnid++ = '\0';
29890       ast_string_field_set(p, todnid, dnid);
29891    }
29892 
29893    /* Divvy up the items separated by slashes */
29894    AST_NONSTANDARD_APP_ARGS(args, tmp, '/');
29895 
29896    /* Find at sign - @ */
29897    host = strchr(args.peerorhost, '@');
29898    if (host) {
29899       *host++ = '\0';
29900       ext = args.peerorhost;
29901       secret = strchr(ext, ':');
29902    }
29903    if (secret) {
29904       *secret++ = '\0';
29905       md5secret = strchr(secret, ':');
29906    }
29907    if (md5secret) {
29908       *md5secret++ = '\0';
29909       authname = strchr(md5secret, ':');
29910    }
29911    if (authname) {
29912       *authname++ = '\0';
29913       trans = strchr(authname, ':');
29914    }
29915    if (trans) {
29916       *trans++ = '\0';
29917       if (!strcasecmp(trans, "tcp"))
29918          transport = SIP_TRANSPORT_TCP;
29919       else if (!strcasecmp(trans, "tls"))
29920          transport = SIP_TRANSPORT_TLS;
29921       else {
29922          if (strcasecmp(trans, "udp"))
29923             ast_log(LOG_WARNING, "'%s' is not a valid transport option to Dial() for SIP calls, using udp by default.\n", trans);
29924          transport = SIP_TRANSPORT_UDP;
29925       }
29926    } else { /* use default */
29927       transport = SIP_TRANSPORT_UDP;
29928    }
29929 
29930    if (!host) {
29931       ext = args.exten;
29932       host = args.peerorhost;
29933       remote_address = args.remote_address;
29934    } else {
29935       remote_address = args.remote_address;
29936       if (!ast_strlen_zero(args.exten)) {
29937          ast_log(LOG_NOTICE, "Conflicting extension values given. Using '%s' and not '%s'\n", ext, args.exten);
29938       }
29939    }
29940 
29941    if (!ast_strlen_zero(remote_address)) {
29942       p->options->outboundproxy = proxy_from_config(remote_address, 0, NULL);
29943       if (!p->options->outboundproxy) {
29944          ast_log(LOG_WARNING, "Unable to parse outboundproxy %s. We will not use this remote IP address\n", remote_address);
29945       }
29946    }
29947 
29948    set_socket_transport(&p->socket, transport);
29949 
29950    /* We now have
29951       host = peer name, DNS host name or DNS domain (for SRV)
29952       ext = extension (user part of URI)
29953       dnid = destination of the call (applies to the To: header)
29954    */
29955    if (create_addr(p, host, NULL, 1)) {
29956       *cause = AST_CAUSE_UNREGISTERED;
29957       ast_debug(3, "Cant create SIP call - target device not registered\n");
29958       dialog_unlink_all(p);
29959       dialog_unref(p, "unref dialog p UNREGISTERED");
29960       /* sip_destroy(p); */
29961       if (callid) {
29962          ast_callid_unref(callid);
29963       }
29964       return NULL;
29965    }
29966    if (ast_strlen_zero(p->peername) && ext)
29967       ast_string_field_set(p, peername, ext);
29968    /* Recalculate our side, and recalculate Call ID */
29969    ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
29970    /* When chan_sip is first loaded or reloaded, we need to check for NAT and set the appropiate flags
29971       now that we have the auto_* settings. */
29972    check_for_nat(&p->sa, p);
29973    /* If there is a peer related to this outgoing call and it hasn't re-registered after
29974       a reload, we need to set the peer's NAT flags accordingly. */
29975    if (p->relatedpeer) {
29976 
29977       if (!ast_strlen_zero(p->relatedpeer->fullcontact) && !p->natdetected &&
29978          (ast_test_flag(&p->flags[2], SIP_PAGE3_NAT_AUTO_RPORT) && !ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT))) {
29979          /* We need to make an attempt to determine if a peer is behind NAT
29980             if the peer has the auto_force_rport flag set. */
29981          struct ast_sockaddr tmpaddr;
29982 
29983          __set_address_from_contact(p->relatedpeer->fullcontact, &tmpaddr, 0);
29984 
29985          check_for_nat(&tmpaddr, p);
29986       }
29987 
29988       set_peer_nat(p, p->relatedpeer);
29989    }
29990 
29991    do_setnat(p);
29992 
29993    build_via(p);
29994 
29995    /* Change the dialog callid. */
29996    change_callid_pvt(p, NULL);
29997 
29998    /* We have an extension to call, don't use the full contact here */
29999    /* This to enable dialing registered peers with extension dialling,
30000       like SIP/peername/extension   
30001       SIP/peername will still use the full contact
30002     */
30003    if (ext) {
30004       ast_string_field_set(p, username, ext);
30005       ast_string_field_set(p, fullcontact, NULL);
30006    }
30007    if (secret && !ast_strlen_zero(secret))
30008       ast_string_field_set(p, peersecret, secret);
30009 
30010    if (md5secret && !ast_strlen_zero(md5secret))
30011       ast_string_field_set(p, peermd5secret, md5secret);
30012 
30013    if (authname && !ast_strlen_zero(authname))
30014       ast_string_field_set(p, authname, authname);
30015 #if 0
30016    printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
30017 #endif
30018    ast_format_cap_append(p->prefcaps, cap);
30019    ast_format_cap_joint_copy(cap, p->caps, p->jointcaps);
30020 
30021    sip_pvt_lock(p);
30022 
30023    tmpc = sip_new(p, AST_STATE_DOWN, host, requestor ? ast_channel_linkedid(requestor) : NULL, callid);  /* Place the call */
30024    if (callid) {
30025       callid = ast_callid_unref(callid);
30026    }
30027 
30028    if (sip_cfg.callevents)
30029       manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
30030          "Channel: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
30031          p->owner ? ast_channel_name(p->owner) : "", "SIP", p->callid, p->fullcontact, p->peername);
30032    sip_pvt_unlock(p);
30033    if (!tmpc) {
30034       dialog_unlink_all(p);
30035       /* sip_destroy(p); */
30036    } else {
30037       ast_channel_unlock(tmpc);
30038    }
30039    dialog_unref(p, "toss pvt ptr at end of sip_request_call");
30040    ast_update_use_count();
30041    restart_monitor();
30042    return tmpc;
30043 }
30044 
30045 /*! \brief Parse insecure= setting in sip.conf and set flags according to setting */
30046 static void set_insecure_flags (struct ast_flags *flags, const char *value, int lineno)
30047 {
30048    if (ast_strlen_zero(value))
30049       return;
30050 
30051    if (!ast_false(value)) {
30052       char buf[64];
30053       char *word, *next;
30054 
30055       ast_copy_string(buf, value, sizeof(buf));
30056       next = buf;
30057       while ((word = strsep(&next, ","))) {
30058          if (!strcasecmp(word, "port"))
30059             ast_set_flag(&flags[0], SIP_INSECURE_PORT);
30060          else if (!strcasecmp(word, "invite"))
30061             ast_set_flag(&flags[0], SIP_INSECURE_INVITE);
30062          else
30063             ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", value, lineno);
30064       }
30065    }
30066 }
30067 
30068 /*!
30069   \brief Handle T.38 configuration options common to users and peers
30070   \returns non-zero if any config options were handled, zero otherwise
30071 */
30072 static int handle_t38_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v,
30073                int *maxdatagram)
30074 {
30075    int res = 1;
30076 
30077    if (!strcasecmp(v->name, "t38pt_udptl")) {
30078       char *buf = ast_strdupa(v->value);
30079       char *word, *next = buf;
30080 
30081       ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT);
30082 
30083       while ((word = strsep(&next, ","))) {
30084          if (ast_true(word) || !strcasecmp(word, "fec")) {
30085             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
30086             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_FEC);
30087          } else if (!strcasecmp(word, "redundancy")) {
30088             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
30089             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY);
30090          } else if (!strcasecmp(word, "none")) {
30091             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
30092             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL);
30093          } else if (!strncasecmp(word, "maxdatagram=", 12)) {
30094             if (sscanf(&word[12], "%30u", maxdatagram) != 1) {
30095                ast_log(LOG_WARNING, "Invalid maxdatagram '%s' at line %d of %s\n", v->value, v->lineno, config);
30096                *maxdatagram = global_t38_maxdatagram;
30097             }
30098          }
30099       }
30100    } else if (!strcasecmp(v->name, "t38pt_usertpsource")) {
30101       ast_set_flag(&mask[1], SIP_PAGE2_UDPTL_DESTINATION);
30102       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_UDPTL_DESTINATION);
30103    } else {
30104       res = 0;
30105    }
30106 
30107    return res;
30108 }
30109 
30110 /*!
30111   \brief Handle flag-type options common to configuration of devices - peers
30112   \param flags array of three struct ast_flags
30113   \param mask array of three struct ast_flags
30114   \param v linked list of config variables to process
30115   \returns non-zero if any config options were handled, zero otherwise
30116 */
30117 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
30118 {
30119    int res = 1;
30120 
30121    if (!strcasecmp(v->name, "trustrpid")) {
30122       ast_set_flag(&mask[0], SIP_TRUSTRPID);
30123       ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
30124    } else if (!strcasecmp(v->name, "sendrpid")) {
30125       ast_set_flag(&mask[0], SIP_SENDRPID);
30126       if (!strcasecmp(v->value, "pai")) {
30127          ast_set_flag(&flags[0], SIP_SENDRPID_PAI);
30128       } else if (!strcasecmp(v->value, "rpid")) {
30129          ast_set_flag(&flags[0], SIP_SENDRPID_RPID);
30130       } else if (ast_true(v->value)) {
30131          ast_set_flag(&flags[0], SIP_SENDRPID_RPID);
30132       }
30133    } else if (!strcasecmp(v->name, "rpid_update")) {
30134       ast_set_flag(&mask[1], SIP_PAGE2_RPID_UPDATE);
30135       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RPID_UPDATE);
30136    } else if (!strcasecmp(v->name, "rpid_immediate")) {
30137       ast_set_flag(&mask[1], SIP_PAGE2_RPID_IMMEDIATE);
30138       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RPID_IMMEDIATE);
30139    } else if (!strcasecmp(v->name, "trust_id_outbound")) {
30140       ast_set_flag(&mask[1], SIP_PAGE2_TRUST_ID_OUTBOUND);
30141       ast_clear_flag(&flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND);
30142       if (!strcasecmp(v->value, "legacy")) {
30143          ast_set_flag(&flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND_LEGACY);
30144       } else if (ast_true(v->value)) {
30145          ast_set_flag(&flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND_YES);
30146       } else if (ast_false(v->value)) {
30147          ast_set_flag(&flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND_NO);
30148       } else {
30149          ast_log(LOG_WARNING, "Unknown trust_id_outbound mode '%s' on line %d, using legacy\n", v->value, v->lineno);
30150          ast_set_flag(&flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND_LEGACY);
30151       }
30152    } else if (!strcasecmp(v->name, "g726nonstandard")) {
30153       ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
30154       ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
30155    } else if (!strcasecmp(v->name, "useclientcode")) {
30156       ast_set_flag(&mask[0], SIP_USECLIENTCODE);
30157       ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
30158    } else if (!strcasecmp(v->name, "dtmfmode")) {
30159       ast_set_flag(&mask[0], SIP_DTMF);
30160       ast_clear_flag(&flags[0], SIP_DTMF);
30161       if (!strcasecmp(v->value, "inband"))
30162          ast_set_flag(&flags[0], SIP_DTMF_INBAND);
30163       else if (!strcasecmp(v->value, "rfc2833"))
30164          ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
30165       else if (!strcasecmp(v->value, "info"))
30166          ast_set_flag(&flags[0], SIP_DTMF_INFO);
30167       else if (!strcasecmp(v->value, "shortinfo"))
30168          ast_set_flag(&flags[0], SIP_DTMF_SHORTINFO);
30169       else if (!strcasecmp(v->value, "auto"))
30170          ast_set_flag(&flags[0], SIP_DTMF_AUTO);
30171       else {
30172          ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
30173          ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
30174       }
30175    } else if (!strcasecmp(v->name, "nat")) {
30176       sip_parse_nat_option(v->value, mask, flags);
30177    } else if (!strcasecmp(v->name, "directmedia") || !strcasecmp(v->name, "canreinvite")) {
30178       ast_set_flag(&mask[0], SIP_REINVITE);
30179       ast_clear_flag(&flags[0], SIP_REINVITE);
30180       if (ast_true(v->value)) {
30181          ast_set_flag(&flags[0], SIP_DIRECT_MEDIA | SIP_DIRECT_MEDIA_NAT);
30182       } else if (!ast_false(v->value)) {
30183          char buf[64];
30184          char *word, *next = buf;
30185 
30186          ast_copy_string(buf, v->value, sizeof(buf));
30187          while ((word = strsep(&next, ","))) {
30188             if (!strcasecmp(word, "update")) {
30189                ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_DIRECT_MEDIA);
30190             } else if (!strcasecmp(word, "nonat")) {
30191                ast_set_flag(&flags[0], SIP_DIRECT_MEDIA);
30192                ast_clear_flag(&flags[0], SIP_DIRECT_MEDIA_NAT);
30193             } else if (!strcasecmp(word, "outgoing")) {
30194                ast_set_flag(&flags[0], SIP_DIRECT_MEDIA);
30195                ast_set_flag(&mask[2], SIP_PAGE3_DIRECT_MEDIA_OUTGOING);
30196                ast_set_flag(&flags[2], SIP_PAGE3_DIRECT_MEDIA_OUTGOING);
30197             } else {
30198                ast_log(LOG_WARNING, "Unknown directmedia mode '%s' on line %d\n", v->value, v->lineno);
30199             }
30200          }
30201       }
30202    } else if (!strcasecmp(v->name, "insecure")) {
30203       ast_set_flag(&mask[0], SIP_INSECURE);
30204       ast_clear_flag(&flags[0], SIP_INSECURE);
30205       set_insecure_flags(&flags[0], v->value, v->lineno);   
30206    } else if (!strcasecmp(v->name, "progressinband")) {
30207       ast_set_flag(&mask[0], SIP_PROG_INBAND);
30208       ast_clear_flag(&flags[0], SIP_PROG_INBAND);
30209       if (ast_true(v->value))
30210          ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
30211       else if (strcasecmp(v->value, "never"))
30212          ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
30213    } else if (!strcasecmp(v->name, "promiscredir")) {
30214       ast_set_flag(&mask[0], SIP_PROMISCREDIR);
30215       ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
30216    } else if (!strcasecmp(v->name, "videosupport")) {
30217       if (!strcasecmp(v->value, "always")) {
30218          ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
30219          ast_set_flag(&flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
30220       } else {
30221          ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
30222          ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
30223       }
30224    } else if (!strcasecmp(v->name, "textsupport")) {
30225       ast_set_flag(&mask[1], SIP_PAGE2_TEXTSUPPORT);
30226       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_TEXTSUPPORT);
30227       res = 1;
30228    } else if (!strcasecmp(v->name, "allowoverlap")) {
30229       ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
30230       ast_clear_flag(&flags[1], SIP_PAGE2_ALLOWOVERLAP);
30231       if (ast_true(v->value)) {
30232          ast_set_flag(&flags[1], SIP_PAGE2_ALLOWOVERLAP_YES);
30233       } else if (!strcasecmp(v->value, "dtmf")){
30234          ast_set_flag(&flags[1], SIP_PAGE2_ALLOWOVERLAP_DTMF);
30235       }
30236    } else if (!strcasecmp(v->name, "allowsubscribe")) {
30237       ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
30238       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
30239    } else if (!strcasecmp(v->name, "ignoresdpversion")) {
30240       ast_set_flag(&mask[1], SIP_PAGE2_IGNORESDPVERSION);
30241       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_IGNORESDPVERSION);
30242    } else if (!strcasecmp(v->name, "faxdetect")) {
30243       ast_set_flag(&mask[1], SIP_PAGE2_FAX_DETECT);
30244       if (ast_true(v->value)) {
30245          ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
30246       } else if (ast_false(v->value)) {
30247          ast_clear_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
30248       } else {
30249          char *buf = ast_strdupa(v->value);
30250          char *word, *next = buf;
30251 
30252          while ((word = strsep(&next, ","))) {
30253             if (!strcasecmp(word, "cng")) {
30254                ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_CNG);
30255             } else if (!strcasecmp(word, "t38")) {
30256                ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_T38);
30257             } else {
30258                ast_log(LOG_WARNING, "Unknown faxdetect mode '%s' on line %d.\n", word, v->lineno);
30259             }
30260          }
30261       }
30262    } else if (!strcasecmp(v->name, "rfc2833compensate")) {
30263       ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
30264       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
30265    } else if (!strcasecmp(v->name, "buggymwi")) {
30266       ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
30267       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
30268    } else
30269       res = 0;
30270 
30271    return res;
30272 }
30273 
30274 /*! \brief Add SIP domain to list of domains we are responsible for */
30275 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
30276 {
30277    struct domain *d;
30278 
30279    if (ast_strlen_zero(domain)) {
30280       ast_log(LOG_WARNING, "Zero length domain.\n");
30281       return 1;
30282    }
30283 
30284    if (!(d = ast_calloc(1, sizeof(*d))))
30285       return 0;
30286 
30287    ast_copy_string(d->domain, domain, sizeof(d->domain));
30288 
30289    if (!ast_strlen_zero(context))
30290       ast_copy_string(d->context, context, sizeof(d->context));
30291 
30292    d->mode = mode;
30293 
30294    AST_LIST_LOCK(&domain_list);
30295    AST_LIST_INSERT_TAIL(&domain_list, d, list);
30296    AST_LIST_UNLOCK(&domain_list);
30297 
30298    if (sipdebug)
30299       ast_debug(1, "Added local SIP domain '%s'\n", domain);
30300 
30301    return 1;
30302 }
30303 
30304 /*! \brief  check_sip_domain: Check if domain part of uri is local to our server */
30305 static int check_sip_domain(const char *domain, char *context, size_t len)
30306 {
30307    struct domain *d;
30308    int result = 0;
30309 
30310    AST_LIST_LOCK(&domain_list);
30311    AST_LIST_TRAVERSE(&domain_list, d, list) {
30312       if (strcasecmp(d->domain, domain)) {
30313          continue;
30314       }
30315 
30316       if (len && !ast_strlen_zero(d->context))
30317          ast_copy_string(context, d->context, len);
30318 
30319       result = 1;
30320       break;
30321    }
30322    AST_LIST_UNLOCK(&domain_list);
30323 
30324    return result;
30325 }
30326 
30327 /*! \brief Clear our domain list (at reload) */
30328 static void clear_sip_domains(void)
30329 {
30330    struct domain *d;
30331 
30332    AST_LIST_LOCK(&domain_list);
30333    while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
30334       ast_free(d);
30335    AST_LIST_UNLOCK(&domain_list);
30336 }
30337 
30338 /*!
30339  * \internal
30340  * \brief Realm authentication container destructor.
30341  *
30342  * \param obj Container object to destroy.
30343  *
30344  * \return Nothing
30345  */
30346 static void destroy_realm_authentication(void *obj)
30347 {
30348    struct sip_auth_container *credentials = obj;
30349    struct sip_auth *auth;
30350 
30351    while ((auth = AST_LIST_REMOVE_HEAD(&credentials->list, node))) {
30352       ast_free(auth);
30353    }
30354 }
30355 
30356 /*!
30357  * \internal
30358  * \brief Add realm authentication to credentials.
30359  *
30360  * \param credentials Realm authentication container to create/add authentication credentials.
30361  * \param configuration Credential configuration value.
30362  * \param lineno Line number in config file.
30363  *
30364  * \return Nothing
30365  */
30366 static void add_realm_authentication(struct sip_auth_container **credentials, const char *configuration, int lineno)
30367 {
30368    char *authcopy;
30369    char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
30370    struct sip_auth *auth;
30371 
30372    if (ast_strlen_zero(configuration)) {
30373       /* Nothing to add */
30374       return;
30375    }
30376 
30377    ast_debug(1, "Auth config ::  %s\n", configuration);
30378 
30379    authcopy = ast_strdupa(configuration);
30380    username = authcopy;
30381 
30382    /* split user[:secret] and relm */
30383    realm = strrchr(username, '@');
30384    if (realm)
30385       *realm++ = '\0';
30386    if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
30387       ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
30388       return;
30389    }
30390 
30391    /* parse username at ':' for secret, or '#" for md5secret */
30392    if ((secret = strchr(username, ':'))) {
30393       *secret++ = '\0';
30394    } else if ((md5secret = strchr(username, '#'))) {
30395       *md5secret++ = '\0';
30396    }
30397 
30398    /* Create the continer if needed. */
30399    if (!*credentials) {
30400       *credentials = ao2_t_alloc(sizeof(**credentials), destroy_realm_authentication,
30401          "Create realm auth container.");
30402       if (!*credentials) {
30403          /* Failed to create the credentials container. */
30404          return;
30405       }
30406    }
30407 
30408    /* Create the authentication credential entry. */
30409    auth = ast_calloc(1, sizeof(*auth));
30410    if (!auth) {
30411       return;
30412    }
30413    ast_copy_string(auth->realm, realm, sizeof(auth->realm));
30414    ast_copy_string(auth->username, username, sizeof(auth->username));
30415    if (secret)
30416       ast_copy_string(auth->secret, secret, sizeof(auth->secret));
30417    if (md5secret)
30418       ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
30419 
30420    /* Add credential to container list. */
30421    AST_LIST_INSERT_TAIL(&(*credentials)->list, auth, node);
30422 
30423    ast_verb(3, "Added authentication for realm %s\n", realm);
30424 }
30425 
30426 /*!
30427  * \internal
30428  * \brief Find authentication for a specific realm.
30429  *
30430  * \param credentials Realm authentication container to search.
30431  * \param realm Authentication realm to find.
30432  *
30433  * \return Found authentication credential or NULL.
30434  */
30435 static struct sip_auth *find_realm_authentication(struct sip_auth_container *credentials, const char *realm)
30436 {
30437    struct sip_auth *auth;
30438 
30439    if (credentials) {
30440       AST_LIST_TRAVERSE(&credentials->list, auth, node) {
30441          if (!strcasecmp(auth->realm, realm)) {
30442             break;
30443          }
30444       }
30445    } else {
30446       auth = NULL;
30447    }
30448 
30449    return auth;
30450 }
30451 
30452 /*! \brief
30453  * implement the setvar config line
30454  */
30455 static struct ast_variable *add_var(const char *buf, struct ast_variable *list)
30456 {
30457    struct ast_variable *tmpvar = NULL;
30458    char *varname = ast_strdupa(buf), *varval = NULL;
30459    
30460    if ((varval = strchr(varname, '='))) {
30461       *varval++ = '\0';
30462       if ((tmpvar = ast_variable_new(varname, varval, ""))) {
30463          tmpvar->next = list;
30464          list = tmpvar;
30465       }
30466    }
30467    return list;
30468 }
30469 
30470 /*! \brief Set peer defaults before configuring specific configurations */
30471 static void set_peer_defaults(struct sip_peer *peer)
30472 {
30473    if (peer->expire == 0) {
30474       /* Don't reset expire or port time during reload
30475          if we have an active registration
30476       */
30477       peer->expire = -1;
30478       peer->pokeexpire = -1;
30479       peer->keepalivesend = -1;
30480       set_socket_transport(&peer->socket, SIP_TRANSPORT_UDP);
30481    }
30482    peer->type = SIP_TYPE_PEER;
30483    ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
30484    ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
30485    ast_copy_flags(&peer->flags[2], &global_flags[2], SIP_PAGE3_FLAGS_TO_COPY);
30486    ast_string_field_set(peer, context, sip_cfg.default_context);
30487    ast_string_field_set(peer, record_on_feature, sip_cfg.default_record_on_feature);
30488    ast_string_field_set(peer, record_off_feature, sip_cfg.default_record_off_feature);
30489    ast_string_field_set(peer, messagecontext, sip_cfg.messagecontext);
30490    ast_string_field_set(peer, subscribecontext, sip_cfg.default_subscribecontext);
30491    ast_string_field_set(peer, language, default_language);
30492    ast_string_field_set(peer, mohinterpret, default_mohinterpret);
30493    ast_string_field_set(peer, mohsuggest, default_mohsuggest);
30494    ast_string_field_set(peer, engine, default_engine);
30495    ast_sockaddr_setnull(&peer->addr);
30496    ast_sockaddr_setnull(&peer->defaddr);
30497    ast_format_cap_copy(peer->caps, sip_cfg.caps);
30498    peer->maxcallbitrate = default_maxcallbitrate;
30499    peer->rtptimeout = global_rtptimeout;
30500    peer->rtpholdtimeout = global_rtpholdtimeout;
30501    peer->rtpkeepalive = global_rtpkeepalive;
30502    peer->allowtransfer = sip_cfg.allowtransfer;
30503    peer->autoframing = global_autoframing;
30504    peer->t38_maxdatagram = global_t38_maxdatagram;
30505    peer->qualifyfreq = global_qualifyfreq;
30506    if (global_callcounter)
30507       peer->call_limit=INT_MAX;
30508    ast_string_field_set(peer, vmexten, default_vmexten);
30509    ast_string_field_set(peer, secret, "");
30510    ast_string_field_set(peer, description, "");
30511    ast_string_field_set(peer, remotesecret, "");
30512    ast_string_field_set(peer, md5secret, "");
30513    ast_string_field_set(peer, cid_num, "");
30514    ast_string_field_set(peer, cid_name, "");
30515    ast_string_field_set(peer, cid_tag, "");
30516    ast_string_field_set(peer, fromdomain, "");
30517    ast_string_field_set(peer, fromuser, "");
30518    ast_string_field_set(peer, regexten, "");
30519    peer->callgroup = 0;
30520    peer->pickupgroup = 0;
30521    peer->maxms = default_qualify;
30522    peer->keepalive = default_keepalive;
30523    peer->prefs = default_prefs;
30524    ast_string_field_set(peer, zone, default_zone);
30525    peer->stimer.st_mode_oper = global_st_mode;  /* Session-Timers */
30526    peer->stimer.st_ref = global_st_refresher;
30527    peer->stimer.st_min_se = global_min_se;
30528    peer->stimer.st_max_se = global_max_se;
30529    peer->timer_t1 = global_t1;
30530    peer->timer_b = global_timer_b;
30531    clear_peer_mailboxes(peer);
30532    peer->disallowed_methods = sip_cfg.disallowed_methods;
30533    peer->transports = default_transports;
30534    peer->default_outbound_transport = default_primary_transport;
30535    if (peer->outboundproxy) {
30536       ao2_ref(peer->outboundproxy, -1);
30537       peer->outboundproxy = NULL;
30538    }
30539 }
30540 
30541 /*! \brief Create temporary peer (used in autocreatepeer mode) */
30542 static struct sip_peer *temp_peer(const char *name)
30543 {
30544    struct sip_peer *peer;
30545 
30546    if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
30547       return NULL;
30548 
30549    if (ast_string_field_init(peer, 512)) {
30550       ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
30551       return NULL;
30552    }
30553    
30554    if (!(peer->cc_params = ast_cc_config_params_init())) {
30555       ao2_t_ref(peer, -1, "failed to allocate cc_params for peer");
30556       return NULL;
30557    }
30558 
30559    if (!(peer->caps = ast_format_cap_alloc_nolock())) {
30560       ao2_t_ref(peer, -1, "failed to allocate format capabilities, drop peer");
30561       return NULL;
30562    }
30563 
30564    ast_atomic_fetchadd_int(&apeerobjs, 1);
30565    set_peer_defaults(peer);
30566 
30567    ast_copy_string(peer->name, name, sizeof(peer->name));
30568 
30569    peer->selfdestruct = TRUE;
30570    peer->host_dynamic = TRUE;
30571    peer->prefs = default_prefs;
30572    reg_source_db(peer);
30573 
30574    return peer;
30575 }
30576 
30577 /*! \todo document this function */
30578 static void add_peer_mailboxes(struct sip_peer *peer, const char *value)
30579 {
30580    char *next, *mbox, *context;
30581 
30582    next = ast_strdupa(value);
30583 
30584    while ((mbox = context = strsep(&next, ","))) {
30585       struct sip_mailbox *mailbox;
30586       int duplicate = 0;
30587       /* remove leading/trailing whitespace from mailbox string */
30588       mbox = ast_strip(mbox);
30589       strsep(&context, "@");
30590 
30591       if (ast_strlen_zero(mbox)) {
30592          continue;
30593       }
30594 
30595       /* Check whether the mailbox is already in the list */
30596       AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
30597          if (!strcmp(mailbox->mailbox, mbox) && !strcmp(S_OR(mailbox->context, ""), S_OR(context, ""))) {
30598             duplicate = 1;
30599             break;
30600          }
30601       }
30602       if (duplicate) {
30603          continue;
30604       }
30605 
30606       if (!(mailbox = ast_calloc(1, sizeof(*mailbox) + strlen(mbox) + strlen(S_OR(context, ""))))) {
30607          continue;
30608       }
30609 
30610       if (!ast_strlen_zero(context)) {
30611          mailbox->context = mailbox->mailbox + strlen(mbox) + 1;
30612          strcpy(mailbox->context, context); /* SAFE */
30613       }
30614       strcpy(mailbox->mailbox, mbox); /* SAFE */
30615 
30616       AST_LIST_INSERT_TAIL(&peer->mailboxes, mailbox, entry);
30617    }
30618 }
30619 
30620 /*! \brief Build peer from configuration (file or realtime static/dynamic) */
30621 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only)
30622 {
30623    struct sip_peer *peer = NULL;
30624    struct ast_acl_list *oldacl = NULL;
30625    struct ast_acl_list *olddirectmediaacl = NULL;
30626    int found = 0;
30627    int firstpass = 1;
30628    uint16_t port = 0;
30629    int format = 0;      /* Ama flags */
30630    int timerb_set = 0, timert1_set = 0;
30631    time_t regseconds = 0;
30632    struct ast_flags peerflags[3] = {{(0)}};
30633    struct ast_flags mask[3] = {{(0)}};
30634    struct sip_peer tmp_peer;
30635    const char *srvlookup = NULL;
30636    static int deprecation_warning = 1;
30637    int alt_fullcontact = alt ? 1 : 0, headercount = 0;
30638    struct ast_str *fullcontact = ast_str_alloca(512);
30639    int acl_change_subscription_needed = 0;
30640 
30641    if (!realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
30642       /* Note we do NOT use sip_find_peer here, to avoid realtime recursion */
30643       /* We also use a case-sensitive comparison (unlike sip_find_peer) so
30644          that case changes made to the peer name will be properly handled
30645          during reload
30646       */
30647       ast_copy_string(tmp_peer.name, name, sizeof(tmp_peer.name));
30648       peer = ao2_t_find(peers, &tmp_peer, OBJ_POINTER | OBJ_UNLINK, "find and unlink peer from peers table");
30649    }
30650 
30651    if (peer) {
30652       /* Already in the list, remove it and it will be added back (or FREE'd)  */
30653       found++;
30654       /* we've unlinked the peer from the peers container but not unlinked from the peers_by_ip container yet
30655         this leads to a wrong refcounter and the peer object is never destroyed */
30656       if (!ast_sockaddr_isnull(&peer->addr)) {
30657          ao2_t_unlink(peers_by_ip, peer, "ao2_unlink peer from peers_by_ip table");
30658       }
30659       if (!(peer->the_mark))
30660          firstpass = 0;
30661    } else {
30662       if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct"))) {
30663          return NULL;
30664       }
30665       if (!(peer->caps = ast_format_cap_alloc_nolock())) {
30666          ao2_t_ref(peer, -1, "failed to allocate format capabilities, drop peer");
30667          return NULL;
30668       }
30669       if (ast_string_field_init(peer, 512)) {
30670          ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
30671          return NULL;
30672       }
30673 
30674       if (!(peer->cc_params = ast_cc_config_params_init())) {
30675          ao2_t_ref(peer, -1, "failed to allocate cc_params for peer");
30676          return NULL;
30677       }
30678 
30679       if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
30680          ast_atomic_fetchadd_int(&rpeerobjs, 1);
30681          ast_debug(3, "-REALTIME- peer built. Name: %s. Peer objects: %d\n", name, rpeerobjs);
30682       } else
30683          ast_atomic_fetchadd_int(&speerobjs, 1);
30684    }
30685 
30686    /* Note that our peer HAS had its reference count increased */
30687    if (firstpass) {
30688       oldacl = peer->acl;
30689       peer->acl = NULL;
30690       olddirectmediaacl = peer->directmediaacl;
30691       peer->directmediaacl = NULL;
30692       set_peer_defaults(peer);   /* Set peer defaults */
30693       peer->type = 0;
30694    }
30695 
30696    /* in case the case of the peer name has changed, update the name */
30697    ast_copy_string(peer->name, name, sizeof(peer->name));
30698 
30699    /* If we have channel variables, remove them (reload) */
30700    if (peer->chanvars) {
30701       ast_variables_destroy(peer->chanvars);
30702       peer->chanvars = NULL;
30703       /* XXX should unregister ? */
30704    }
30705 
30706    if (found)
30707       peer->portinuri = 0;
30708 
30709    /* If we have realm authentication information, remove them (reload) */
30710    ao2_lock(peer);
30711    if (peer->auth) {
30712       ao2_t_ref(peer->auth, -1, "Removing old peer authentication");
30713       peer->auth = NULL;
30714    }
30715    ao2_unlock(peer);
30716 
30717    /* clear the transport information.  We will detect if a default value is required after parsing the config */
30718    peer->default_outbound_transport = 0;
30719    peer->transports = 0;
30720 
30721    if (!devstate_only) {
30722       struct sip_mailbox *mailbox;
30723       AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
30724          mailbox->delme = 1;
30725       }
30726    }
30727 
30728    /* clear named callgroup and named pickup group container */
30729    peer->named_callgroups = ast_unref_namedgroups(peer->named_callgroups);
30730    peer->named_pickupgroups = ast_unref_namedgroups(peer->named_pickupgroups);
30731 
30732    for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
30733       if (!devstate_only) {
30734          if (handle_common_options(&peerflags[0], &mask[0], v)) {
30735             continue;
30736          }
30737          if (handle_t38_options(&peerflags[0], &mask[0], v, &peer->t38_maxdatagram)) {
30738             continue;
30739          }
30740          if (!strcasecmp(v->name, "transport")) {
30741             char *val = ast_strdupa(v->value);
30742             char *trans;
30743 
30744             peer->transports = peer->default_outbound_transport = 0;
30745             while ((trans = strsep(&val, ","))) {
30746                trans = ast_skip_blanks(trans);
30747 
30748                if (!strncasecmp(trans, "udp", 3)) {
30749                   peer->transports |= SIP_TRANSPORT_UDP;
30750                } else if (!strncasecmp(trans, "wss", 3)) {
30751                   peer->transports |= SIP_TRANSPORT_WSS;
30752                } else if (!strncasecmp(trans, "ws", 2)) {
30753                   peer->transports |= SIP_TRANSPORT_WS;
30754                } else if (sip_cfg.tcp_enabled && !strncasecmp(trans, "tcp", 3)) {
30755                   peer->transports |= SIP_TRANSPORT_TCP;
30756                } else if (default_tls_cfg.enabled && !strncasecmp(trans, "tls", 3)) {
30757                   peer->transports |= SIP_TRANSPORT_TLS;
30758                } else if (!strncasecmp(trans, "tcp", 3) || !strncasecmp(trans, "tls", 3)) {
30759                   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);
30760                } else {
30761                   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);
30762                }
30763 
30764                if (!peer->default_outbound_transport) { /*!< The first transport listed should be default outbound */
30765                   peer->default_outbound_transport = peer->transports;
30766                }
30767             }
30768          } else if (realtime && !strcasecmp(v->name, "regseconds")) {
30769             ast_get_time_t(v->value, &regseconds, 0, NULL);
30770          } else if (realtime && !strcasecmp(v->name, "name")) {
30771             ast_copy_string(peer->name, v->value, sizeof(peer->name));
30772          } else if (realtime && !strcasecmp(v->name, "useragent")) {
30773             ast_string_field_set(peer, useragent, v->value);
30774          } else if (!strcasecmp(v->name, "type")) {
30775             if (!strcasecmp(v->value, "peer")) {
30776                peer->type |= SIP_TYPE_PEER;
30777             } else if (!strcasecmp(v->value, "user")) {
30778                peer->type |= SIP_TYPE_USER;
30779             } else if (!strcasecmp(v->value, "friend")) {
30780                peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
30781             }
30782          } else if (!strcasecmp(v->name, "remotesecret")) {
30783             ast_string_field_set(peer, remotesecret, v->value);
30784          } else if (!strcasecmp(v->name, "secret")) {
30785             ast_string_field_set(peer, secret, v->value);
30786          } else if (!strcasecmp(v->name, "description")) {
30787             ast_string_field_set(peer, description, v->value);
30788          } else if (!strcasecmp(v->name, "md5secret")) {
30789             ast_string_field_set(peer, md5secret, v->value);
30790          } else if (!strcasecmp(v->name, "auth")) {
30791             add_realm_authentication(&peer->auth, v->value, v->lineno);
30792          } else if (!strcasecmp(v->name, "callerid")) {
30793             char cid_name[80] = { '\0' }, cid_num[80] = { '\0' };
30794 
30795             ast_callerid_split(v->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
30796             ast_string_field_set(peer, cid_name, cid_name);
30797             ast_string_field_set(peer, cid_num, cid_num);
30798          } else if (!strcasecmp(v->name, "mwi_from")) {
30799             ast_string_field_set(peer, mwi_from, v->value);
30800          } else if (!strcasecmp(v->name, "fullname")) {
30801             ast_string_field_set(peer, cid_name, v->value);
30802          } else if (!strcasecmp(v->name, "trunkname")) {
30803             /* This is actually for a trunk, so we don't want to override callerid */
30804             ast_string_field_set(peer, cid_name, "");
30805          } else if (!strcasecmp(v->name, "cid_number")) {
30806             ast_string_field_set(peer, cid_num, v->value);
30807          } else if (!strcasecmp(v->name, "cid_tag")) {
30808             ast_string_field_set(peer, cid_tag, v->value);
30809          } else if (!strcasecmp(v->name, "context")) {
30810             ast_string_field_set(peer, context, v->value);
30811             ast_set_flag(&peer->flags[1], SIP_PAGE2_HAVEPEERCONTEXT);
30812          } else if (!strcasecmp(v->name, "recordonfeature")) {
30813             ast_string_field_set(peer, record_on_feature, v->value);
30814          } else if (!strcasecmp(v->name, "recordofffeature")) {
30815             ast_string_field_set(peer, record_off_feature, v->value);
30816          } else if (!strcasecmp(v->name, "outofcall_message_context")) {
30817             ast_string_field_set(peer, messagecontext, v->value);
30818          } else if (!strcasecmp(v->name, "subscribecontext")) {
30819             ast_string_field_set(peer, subscribecontext, v->value);
30820          } else if (!strcasecmp(v->name, "fromdomain")) {
30821             char *fromdomainport;
30822             ast_string_field_set(peer, fromdomain, v->value);
30823             if ((fromdomainport = strchr(peer->fromdomain, ':'))) {
30824                *fromdomainport++ = '\0';
30825                if (!(peer->fromdomainport = port_str2int(fromdomainport, 0))) {
30826                   ast_log(LOG_NOTICE, "'%s' is not a valid port number for fromdomain.\n",fromdomainport);
30827                }
30828             } else {
30829                peer->fromdomainport = STANDARD_SIP_PORT;
30830             }
30831          } else if (!strcasecmp(v->name, "usereqphone")) {
30832             ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
30833          } else if (!strcasecmp(v->name, "fromuser")) {
30834             ast_string_field_set(peer, fromuser, v->value);
30835          } else if (!strcasecmp(v->name, "outboundproxy")) {
30836             struct sip_proxy *proxy;
30837             if (ast_strlen_zero(v->value)) {
30838                ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf\n", v->lineno);
30839                continue;
30840             }
30841             proxy = proxy_from_config(v->value, v->lineno, peer->outboundproxy);
30842             if (!proxy) {
30843                ast_log(LOG_WARNING, "failure parsing the outbound proxy on line %d of sip.conf.\n", v->lineno);
30844                continue;
30845             }
30846             peer->outboundproxy = proxy;
30847          } else if (!strcasecmp(v->name, "host")) {
30848             if (!strcasecmp(v->value, "dynamic")) {
30849                /* They'll register with us */
30850                if ((!found && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) || !peer->host_dynamic) {
30851                   /* Initialize stuff if this is a new peer, or if it used to
30852                    * not be dynamic before the reload. */
30853                   ast_sockaddr_setnull(&peer->addr);
30854                }
30855                peer->host_dynamic = TRUE;
30856             } else {
30857                /* Non-dynamic.  Make sure we become that way if we're not */
30858                AST_SCHED_DEL_UNREF(sched, peer->expire,
30859                      sip_unref_peer(peer, "removing register expire ref"));
30860                peer->host_dynamic = FALSE;
30861                srvlookup = v->value;
30862             }
30863          } else if (!strcasecmp(v->name, "defaultip")) {
30864             if (!ast_strlen_zero(v->value) && ast_get_ip(&peer->defaddr, v->value)) {
30865                sip_unref_peer(peer, "sip_unref_peer: from build_peer defaultip");
30866                return NULL;
30867             }
30868          } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny") || !strcasecmp(v->name, "acl")) {
30869             int ha_error = 0;
30870             if (!ast_strlen_zero(v->value)) {
30871                ast_append_acl(v->name, v->value, &peer->acl, &ha_error, &acl_change_subscription_needed);
30872             }
30873             if (ha_error) {
30874                ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
30875             }
30876          } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny") || !strcasecmp(v->name, "contactacl")) {
30877             int ha_error = 0;
30878             if (!ast_strlen_zero(v->value)) {
30879                ast_append_acl(v->name + 7, v->value, &peer->contactacl, &ha_error, &acl_change_subscription_needed);
30880             }
30881             if (ha_error) {
30882                ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
30883             }
30884          } else if (!strcasecmp(v->name, "directmediapermit") || !strcasecmp(v->name, "directmediadeny") || !strcasecmp(v->name, "directmediaacl")) {
30885             int ha_error = 0;
30886             ast_append_acl(v->name + 11, v->value, &peer->directmediaacl, &ha_error, &acl_change_subscription_needed);
30887             if (ha_error) {
30888                ast_log(LOG_ERROR, "Bad directmedia ACL entry in configuration line %d : %s\n", v->lineno, v->value);
30889             }
30890          } else if (!strcasecmp(v->name, "port")) {
30891             peer->portinuri = 1;
30892             if (!(port = port_str2int(v->value, 0))) {
30893                if (realtime) {
30894                   /* If stored as integer, could be 0 for some DBs (notably MySQL) */
30895                   peer->portinuri = 0;
30896                } else {
30897                   ast_log(LOG_WARNING, "Invalid peer port configuration at line %d : %s\n", v->lineno, v->value);
30898                }
30899             }
30900          } else if (!strcasecmp(v->name, "callingpres")) {
30901             peer->callingpres = ast_parse_caller_presentation(v->value);
30902             if (peer->callingpres == -1) {
30903                peer->callingpres = atoi(v->value);
30904             }
30905          } else if (!strcasecmp(v->name, "username") || !strcmp(v->name, "defaultuser")) {   /* "username" is deprecated */
30906             ast_string_field_set(peer, username, v->value);
30907             if (!strcasecmp(v->name, "username")) {
30908                if (deprecation_warning) {
30909                   ast_log(LOG_NOTICE, "The 'username' field for sip peers has been deprecated in favor of the term 'defaultuser'\n");
30910                   deprecation_warning = 0;
30911                }
30912                peer->deprecated_username = 1;
30913             }
30914          } else if (!strcasecmp(v->name, "tonezone")) {
30915             struct ast_tone_zone *new_zone;
30916             if (!(new_zone = ast_get_indication_zone(v->value))) {
30917                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);
30918             } else {
30919                ast_tone_zone_unref(new_zone);
30920                ast_string_field_set(peer, zone, v->value);
30921             }
30922          } else if (!strcasecmp(v->name, "language")) {
30923             ast_string_field_set(peer, language, v->value);
30924          } else if (!strcasecmp(v->name, "regexten")) {
30925             ast_string_field_set(peer, regexten, v->value);
30926          } else if (!strcasecmp(v->name, "callbackextension")) {
30927             ast_string_field_set(peer, callback, v->value);
30928          } else if (!strcasecmp(v->name, "amaflags")) {
30929             format = ast_cdr_amaflags2int(v->value);
30930             if (format < 0) {
30931                ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
30932             } else {
30933                peer->amaflags = format;
30934             }
30935          } else if (!strcasecmp(v->name, "maxforwards")) {
30936             if (sscanf(v->value, "%30d", &peer->maxforwards) != 1
30937                || peer->maxforwards < 1 || 255 < peer->maxforwards) {
30938                ast_log(LOG_WARNING, "'%s' is not a valid maxforwards value at line %d.  Using default.\n", v->value, v->lineno);
30939                peer->maxforwards = sip_cfg.default_max_forwards;
30940             }
30941          } else if (!strcasecmp(v->name, "accountcode")) {
30942             ast_string_field_set(peer, accountcode, v->value);
30943          } else if (!strcasecmp(v->name, "mohinterpret")) {
30944             ast_string_field_set(peer, mohinterpret, v->value);
30945          } else if (!strcasecmp(v->name, "mohsuggest")) {
30946             ast_string_field_set(peer, mohsuggest, v->value);
30947          } else if (!strcasecmp(v->name, "parkinglot")) {
30948             ast_string_field_set(peer, parkinglot, v->value);
30949          } else if (!strcasecmp(v->name, "rtp_engine")) {
30950             ast_string_field_set(peer, engine, v->value);
30951          } else if (!strcasecmp(v->name, "mailbox")) {
30952             add_peer_mailboxes(peer, v->value);
30953          } else if (!strcasecmp(v->name, "hasvoicemail")) {
30954             /* People expect that if 'hasvoicemail' is set, that the mailbox will
30955              * be also set, even if not explicitly specified. */
30956             if (ast_true(v->value) && AST_LIST_EMPTY(&peer->mailboxes)) {
30957                add_peer_mailboxes(peer, name);
30958             }
30959          } else if (!strcasecmp(v->name, "subscribemwi")) {
30960             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
30961          } else if (!strcasecmp(v->name, "vmexten")) {
30962             ast_string_field_set(peer, vmexten, v->value);
30963          } else if (!strcasecmp(v->name, "callgroup")) {
30964             peer->callgroup = ast_get_group(v->value);
30965          } else if (!strcasecmp(v->name, "allowtransfer")) {
30966             peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
30967          } else if (!strcasecmp(v->name, "pickupgroup")) {
30968             peer->pickupgroup = ast_get_group(v->value);
30969          } else if (!strcasecmp(v->name, "namedcallgroup")) {
30970             peer->named_callgroups = ast_get_namedgroups(v->value);
30971          } else if (!strcasecmp(v->name, "namedpickupgroup")) {
30972             peer->named_pickupgroups = ast_get_namedgroups(v->value);
30973          } else if (!strcasecmp(v->name, "allow")) {
30974             int error = ast_parse_allow_disallow(&peer->prefs, peer->caps, v->value, TRUE);
30975             if (error) {
30976                ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
30977             }
30978          } else if (!strcasecmp(v->name, "disallow")) {
30979             int error =  ast_parse_allow_disallow(&peer->prefs, peer->caps, v->value, FALSE);
30980             if (error) {
30981                ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
30982             }
30983          } else if (!strcasecmp(v->name, "preferred_codec_only")) {
30984             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_PREFERRED_CODEC);
30985          } else if (!strcasecmp(v->name, "autoframing")) {
30986             peer->autoframing = ast_true(v->value);
30987          } else if (!strcasecmp(v->name, "rtptimeout")) {
30988             if ((sscanf(v->value, "%30d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
30989                ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
30990                peer->rtptimeout = global_rtptimeout;
30991             }
30992          } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
30993             if ((sscanf(v->value, "%30d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
30994                ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
30995                peer->rtpholdtimeout = global_rtpholdtimeout;
30996             }
30997          } else if (!strcasecmp(v->name, "rtpkeepalive")) {
30998             if ((sscanf(v->value, "%30d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
30999                ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d.  Using default.\n", v->value, v->lineno);
31000                peer->rtpkeepalive = global_rtpkeepalive;
31001             }
31002          } else if (!strcasecmp(v->name, "timert1")) {
31003             if ((sscanf(v->value, "%30d", &peer->timer_t1) != 1) || (peer->timer_t1 < 200) || (peer->timer_t1 < global_t1min)) {
31004                ast_log(LOG_WARNING, "'%s' is not a valid T1 time at line %d.  Using default.\n", v->value, v->lineno);
31005                peer->timer_t1 = global_t1min;
31006             }
31007             timert1_set = 1;
31008          } else if (!strcasecmp(v->name, "timerb")) {
31009             if ((sscanf(v->value, "%30d", &peer->timer_b) != 1) || (peer->timer_b < 200)) {
31010                ast_log(LOG_WARNING, "'%s' is not a valid Timer B time at line %d.  Using default.\n", v->value, v->lineno);
31011                peer->timer_b = global_timer_b;
31012             }
31013             timerb_set = 1;
31014          } else if (!strcasecmp(v->name, "setvar")) {
31015             peer->chanvars = add_var(v->value, peer->chanvars);
31016          } else if (!strcasecmp(v->name, "header")) {
31017             char tmp[4096];
31018             snprintf(tmp, sizeof(tmp), "__SIPADDHEADERpre%2d=%s", ++headercount, v->value);
31019             peer->chanvars = add_var(tmp, peer->chanvars);
31020          } else if (!strcasecmp(v->name, "qualifyfreq")) {
31021             int i;
31022             if (sscanf(v->value, "%30d", &i) == 1) {
31023                peer->qualifyfreq = i * 1000;
31024             } else {
31025                ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
31026                peer->qualifyfreq = global_qualifyfreq;
31027             }
31028          } else if (!strcasecmp(v->name, "maxcallbitrate")) {
31029             peer->maxcallbitrate = atoi(v->value);
31030             if (peer->maxcallbitrate < 0) {
31031                peer->maxcallbitrate = default_maxcallbitrate;
31032             }
31033          } else if (!strcasecmp(v->name, "session-timers")) {
31034             int i = (int) str2stmode(v->value);
31035             if (i < 0) {
31036                ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
31037                peer->stimer.st_mode_oper = global_st_mode;
31038             } else {
31039                peer->stimer.st_mode_oper = i;
31040             }
31041          } else if (!strcasecmp(v->name, "session-expires")) {
31042             if (sscanf(v->value, "%30d", &peer->stimer.st_max_se) != 1) {
31043                ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
31044                peer->stimer.st_max_se = global_max_se;
31045             }
31046          } else if (!strcasecmp(v->name, "session-minse")) {
31047             if (sscanf(v->value, "%30d", &peer->stimer.st_min_se) != 1) {
31048                ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
31049                peer->stimer.st_min_se = global_min_se;
31050             }
31051             if (peer->stimer.st_min_se < DEFAULT_MIN_SE) {
31052                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);
31053                peer->stimer.st_min_se = global_min_se;
31054             }
31055          } else if (!strcasecmp(v->name, "session-refresher")) {
31056             int i = (int) str2strefresherparam(v->value);
31057             if (i < 0) {
31058                ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
31059                peer->stimer.st_ref = global_st_refresher;
31060             } else {
31061                peer->stimer.st_ref = i;
31062             }
31063          } else if (!strcasecmp(v->name, "disallowed_methods")) {
31064             char *disallow = ast_strdupa(v->value);
31065             mark_parsed_methods(&peer->disallowed_methods, disallow);
31066          } else if (!strcasecmp(v->name, "unsolicited_mailbox")) {
31067             ast_string_field_set(peer, unsolicited_mailbox, v->value);
31068          } else if (!strcasecmp(v->name, "use_q850_reason")) {
31069             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_Q850_REASON);
31070          } else if (!strcasecmp(v->name, "encryption")) {
31071             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_USE_SRTP);
31072          } else if (!strcasecmp(v->name, "encryption_taglen")) {
31073             ast_set2_flag(&peer->flags[2], !strcasecmp(v->value, "32"), SIP_PAGE3_SRTP_TAG_32);
31074          } else if (!strcasecmp(v->name, "snom_aoc_enabled")) {
31075             ast_set2_flag(&peer->flags[2], ast_true(v->value), SIP_PAGE3_SNOM_AOC);
31076          } else if (!strcasecmp(v->name, "avpf")) {
31077             ast_set2_flag(&peer->flags[2], ast_true(v->value), SIP_PAGE3_USE_AVPF);
31078          } else if (!strcasecmp(v->name, "icesupport")) {
31079             ast_set2_flag(&peer->flags[2], ast_true(v->value), SIP_PAGE3_ICE_SUPPORT);
31080          } else {
31081             ast_rtp_dtls_cfg_parse(&peer->dtls_cfg, v->name, v->value);
31082          }
31083       }
31084 
31085       /* Apply the encryption tag length to the DTLS configuration, in case DTLS is in use */
31086       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);
31087 
31088       /* These apply to devstate lookups */
31089       if (realtime && !strcasecmp(v->name, "lastms")) {
31090          sscanf(v->value, "%30d", &peer->lastms);
31091       } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
31092          ast_sockaddr_parse(&peer->addr, v->value, PARSE_PORT_FORBID);
31093       } else if (realtime && !strcasecmp(v->name, "fullcontact")) {
31094          if (alt_fullcontact && !alt) {
31095             /* Reset, because the alternate also has a fullcontact and we
31096              * do NOT want the field value to be doubled. It might be
31097              * tempting to skip this, but the first table might not have
31098              * fullcontact and since we're here, we know that the alternate
31099              * absolutely does. */
31100             alt_fullcontact = 0;
31101             ast_str_reset(fullcontact);
31102          }
31103          /* Reconstruct field, because realtime separates our value at the ';' */
31104          if (ast_str_strlen(fullcontact) > 0) {
31105             ast_str_append(&fullcontact, 0, ";%s", v->value);
31106          } else {
31107             ast_str_set(&fullcontact, 0, "%s", v->value);
31108          }
31109       } else if (!strcasecmp(v->name, "qualify")) {
31110          if (!strcasecmp(v->value, "no")) {
31111             peer->maxms = 0;
31112          } else if (!strcasecmp(v->value, "yes")) {
31113             peer->maxms = default_qualify ? default_qualify : DEFAULT_MAXMS;
31114          } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
31115             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);
31116             peer->maxms = 0;
31117          }
31118          if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->maxms > 0) {
31119             /* This would otherwise cause a network storm, where the
31120              * qualify response refreshes the peer from the database,
31121              * which in turn causes another qualify to be sent, ad
31122              * infinitum. */
31123             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);
31124             peer->maxms = 0;
31125          }
31126       } else if (!strcasecmp(v->name, "keepalive")) {
31127          if (!strcasecmp(v->value, "no")) {
31128             peer->keepalive = 0;
31129          } else if (!strcasecmp(v->value, "yes")) {
31130             peer->keepalive = DEFAULT_KEEPALIVE_INTERVAL;
31131          } else if (sscanf(v->value, "%30d", &peer->keepalive) != 1) {
31132             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);
31133             peer->keepalive = 0;
31134          }
31135       } else if (!strcasecmp(v->name, "callcounter")) {
31136          peer->call_limit = ast_true(v->value) ? INT_MAX : 0;
31137       } else if (!strcasecmp(v->name, "call-limit")) {
31138          peer->call_limit = atoi(v->value);
31139          if (peer->call_limit < 0) {
31140             peer->call_limit = 0;
31141          }
31142       } else if (!strcasecmp(v->name, "busylevel")) {
31143          peer->busy_level = atoi(v->value);
31144          if (peer->busy_level < 0) {
31145             peer->busy_level = 0;
31146          }
31147       } else if (ast_cc_is_config_param(v->name)) {
31148          ast_cc_set_param(peer->cc_params, v->name, v->value);
31149       }
31150    }
31151 
31152    if (!devstate_only) {
31153       struct sip_mailbox *mailbox;
31154       AST_LIST_TRAVERSE_SAFE_BEGIN(&peer->mailboxes, mailbox, entry) {
31155          if (mailbox->delme) {
31156             AST_LIST_REMOVE_CURRENT(entry);
31157             destroy_mailbox(mailbox);
31158          }
31159       }
31160       AST_LIST_TRAVERSE_SAFE_END;
31161    }
31162 
31163    if (!can_parse_xml && (ast_get_cc_agent_policy(peer->cc_params) == AST_CC_AGENT_NATIVE)) {
31164       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);
31165       ast_set_cc_agent_policy(peer->cc_params, AST_CC_AGENT_NEVER);
31166    }
31167 
31168    /* Note that Timer B is dependent upon T1 and MUST NOT be lower
31169     * than T1 * 64, according to RFC 3261, Section 17.1.1.2 */
31170    if (peer->timer_b < peer->timer_t1 * 64) {
31171       if (timerb_set && timert1_set) {
31172          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);
31173       } else if (timerb_set) {
31174          if ((peer->timer_t1 = peer->timer_b / 64) < global_t1min) {
31175             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);
31176             peer->timer_t1 = global_t1min;
31177             peer->timer_b = peer->timer_t1 * 64;
31178          }
31179          peer->timer_t1 = peer->timer_b / 64;
31180       } else {
31181          peer->timer_b = peer->timer_t1 * 64;
31182       }
31183    }
31184 
31185    if (!peer->default_outbound_transport) {
31186       /* Set default set of transports */
31187       peer->transports = default_transports;
31188       /* Set default primary transport */
31189       peer->default_outbound_transport = default_primary_transport;
31190    }
31191 
31192    /* The default transport type set during build_peer should only replace the socket.type when...
31193     * 1. Registration is not present and the socket.type and default transport types are different.
31194     * 2. The socket.type is not an acceptable transport type after rebuilding peer.
31195     * 3. The socket.type is not set yet. */
31196    if (((peer->socket.type != peer->default_outbound_transport) && (peer->expire == -1)) ||
31197       !(peer->socket.type & peer->transports) || !(peer->socket.type)) {
31198       set_socket_transport(&peer->socket, peer->default_outbound_transport);
31199    }
31200 
31201    ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
31202    ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
31203    ast_copy_flags(&peer->flags[2], &peerflags[2], mask[2].flags);
31204 
31205    if (ast_str_strlen(fullcontact)) {
31206       ast_string_field_set(peer, fullcontact, ast_str_buffer(fullcontact));
31207       peer->rt_fromcontact = TRUE;
31208       /* We have a hostname in the fullcontact, but if we don't have an
31209        * address listed on the entry (or if it's 'dynamic'), then we need to
31210        * parse the entry to obtain the IP address, so a dynamic host can be
31211        * contacted immediately after reload (as opposed to waiting for it to
31212        * register once again). But if we have an address for this peer and NAT was
31213        * specified, use that address instead. */
31214       /* XXX May need to revisit the final argument; does the realtime DB store whether
31215        * the original contact was over TLS or not? XXX */
31216       if ((!ast_test_flag(&peer->flags[2],  SIP_PAGE3_NAT_AUTO_RPORT) && !ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT))
31217           || ast_sockaddr_isnull(&peer->addr)) {
31218          __set_address_from_contact(ast_str_buffer(fullcontact), &peer->addr, 0);
31219       }
31220    }
31221 
31222    if (srvlookup && peer->dnsmgr == NULL) {
31223       char transport[MAXHOSTNAMELEN];
31224       char _srvlookup[MAXHOSTNAMELEN];
31225       char *params;
31226 
31227       ast_copy_string(_srvlookup, srvlookup, sizeof(_srvlookup));
31228       if ((params = strchr(_srvlookup, ';'))) {
31229          *params++ = '\0';
31230       }
31231 
31232       snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(peer->socket.type), get_srv_protocol(peer->socket.type));
31233 
31234       peer->addr.ss.ss_family = get_address_family_filter(peer->socket.type); /* Filter address family */
31235       if (ast_dnsmgr_lookup_cb(_srvlookup, &peer->addr, &peer->dnsmgr, sip_cfg.srvlookup && !peer->portinuri ? transport : NULL,
31236                on_dns_update_peer, sip_ref_peer(peer, "Store peer on dnsmgr"))) {
31237          ast_log(LOG_ERROR, "srvlookup failed for host: %s, on peer %s, removing peer\n", _srvlookup, peer->name);
31238          sip_unref_peer(peer, "dnsmgr lookup failed, getting rid of peer dnsmgr ref");
31239          sip_unref_peer(peer, "getting rid of a peer pointer");
31240          return NULL;
31241       }
31242       if (!peer->dnsmgr) {
31243          /* dnsmgr refresh disabeld, release reference */
31244          sip_unref_peer(peer, "dnsmgr disabled, unref peer");
31245       }
31246 
31247       ast_string_field_set(peer, tohost, srvlookup);
31248 
31249       if (global_dynamic_exclude_static && !ast_sockaddr_isnull(&peer->addr)) {
31250          int ha_error = 0;
31251 
31252          ast_append_acl("deny", ast_sockaddr_stringify_addr(&peer->addr), &sip_cfg.contact_acl, &ha_error, NULL);
31253          if (ha_error) {
31254             ast_log(LOG_ERROR, "Bad or unresolved host/IP entry in configuration for peer %s, cannot add to contact ACL\n", peer->name);
31255          }
31256       }
31257    } else if (peer->dnsmgr && !peer->host_dynamic) {
31258       /* force a refresh here on reload if dnsmgr already exists and host is set. */
31259       ast_dnsmgr_refresh(peer->dnsmgr);
31260    }
31261 
31262    if (port && !realtime && peer->host_dynamic) {
31263       ast_sockaddr_set_port(&peer->defaddr, port);
31264    } else if (port) {
31265       ast_sockaddr_set_port(&peer->addr, port);
31266    }
31267 
31268    if (ast_sockaddr_port(&peer->addr) == 0) {
31269       ast_sockaddr_set_port(&peer->addr,
31270                   (peer->socket.type & SIP_TRANSPORT_TLS) ?
31271                   STANDARD_TLS_PORT : STANDARD_SIP_PORT);
31272    }
31273    if (ast_sockaddr_port(&peer->defaddr) == 0) {
31274       ast_sockaddr_set_port(&peer->defaddr,
31275                   (peer->socket.type & SIP_TRANSPORT_TLS) ?
31276                   STANDARD_TLS_PORT : STANDARD_SIP_PORT);
31277    }
31278    if (!peer->socket.port) {
31279       peer->socket.port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
31280    }
31281 
31282    if (realtime) {
31283       int enablepoke = 1;
31284 
31285       if (!sip_cfg.ignore_regexpire && peer->host_dynamic) {
31286          time_t nowtime = time(NULL);
31287 
31288          if ((nowtime - regseconds) > 0) {
31289             destroy_association(peer);
31290             memset(&peer->addr, 0, sizeof(peer->addr));
31291             peer->lastms = -1;
31292             enablepoke = 0;
31293             ast_debug(1, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
31294          }
31295       }
31296 
31297       /* Startup regular pokes */
31298       if (!devstate_only && enablepoke) {
31299          sip_ref_peer(peer, "schedule qualify");
31300          sip_poke_peer(peer, 0);
31301       }
31302    }
31303 
31304    if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
31305       sip_cfg.allowsubscribe = TRUE;   /* No global ban any more */
31306    }
31307    /* If read-only RT backend, then refresh from local DB cache */
31308    if (peer->host_dynamic && (!peer->is_realtime || !sip_cfg.peer_rtupdate)) {
31309       reg_source_db(peer);
31310    }
31311 
31312    /* If they didn't request that MWI is sent *only* on subscribe, go ahead and
31313     * subscribe to it now. */
31314    if (!devstate_only && !ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
31315       !AST_LIST_EMPTY(&peer->mailboxes)) {
31316       add_peer_mwi_subs(peer);
31317       /* Send MWI from the event cache only.  This is so we can send initial
31318        * MWI if app_voicemail got loaded before chan_sip.  If it is the other
31319        * way, then we will get events when app_voicemail gets loaded. */
31320       sip_send_mwi_to_peer(peer, 1);
31321    }
31322 
31323    peer->the_mark = 0;
31324 
31325    oldacl = ast_free_acl_list(oldacl);
31326    olddirectmediaacl = ast_free_acl_list(olddirectmediaacl);
31327    if (!ast_strlen_zero(peer->callback)) { /* build string from peer info */
31328       char *reg_string;
31329       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) {
31330          sip_register(reg_string, 0); /* XXX TODO: count in registry_count */
31331          ast_free(reg_string);
31332       }
31333    }
31334 
31335    /* If an ACL change subscription is needed and doesn't exist, we need one. */
31336    if (acl_change_subscription_needed) {
31337       acl_change_event_subscribe();
31338    }
31339 
31340    return peer;
31341 }
31342 
31343 static int peer_markall_func(void *device, void *arg, int flags)
31344 {
31345    struct sip_peer *peer = device;
31346    if (!peer->selfdestruct) {
31347       peer->the_mark = 1;
31348    }
31349    return 0;
31350 }
31351 
31352 static int peer_markall_autopeers_func(void *device, void *arg, int flags)
31353 {
31354    struct sip_peer *peer = device;
31355    if (peer->selfdestruct) {
31356       peer->the_mark = 1;
31357    }
31358    return 0;
31359 }
31360 
31361 /*!
31362  * \internal
31363  * \brief If no default formats are set in config, these are used 
31364  */
31365 static void sip_set_default_format_capabilities(struct ast_format_cap *cap)
31366 {
31367    struct ast_format tmp_fmt;
31368 
31369    ast_format_cap_remove_all(cap);
31370    ast_format_cap_add(cap, ast_format_set(&tmp_fmt, AST_FORMAT_ULAW, 0));
31371    ast_format_cap_add(cap, ast_format_set(&tmp_fmt, AST_FORMAT_TESTLAW, 0));
31372    ast_format_cap_add(cap, ast_format_set(&tmp_fmt, AST_FORMAT_ALAW, 0));
31373    ast_format_cap_add(cap, ast_format_set(&tmp_fmt, AST_FORMAT_GSM, 0));
31374    ast_format_cap_add(cap, ast_format_set(&tmp_fmt, AST_FORMAT_H263, 0));
31375 }
31376 
31377 static void display_nat_warning(const char *cat, int reason, struct ast_flags *flags) {
31378    int global_nat, specific_nat;
31379 
31380    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))) {
31381       ast_log(LOG_WARNING, "!!! PLEASE NOTE: Setting 'nat' for a peer/user that differs from the  global setting can make\n");
31382       ast_log(LOG_WARNING, "!!! the name of that peer/user discoverable by an attacker. Replies for non-existent peers/users\n");
31383       ast_log(LOG_WARNING, "!!! will be sent to a different port than replies for an existing peer/user. If at all possible,\n");
31384       ast_log(LOG_WARNING, "!!! use the global 'nat' setting and do not set 'nat' per peer/user.\n");
31385       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));
31386    }
31387 }
31388 
31389 static void cleanup_all_regs(void)
31390 {
31391       /* First, destroy all outstanding registry calls */
31392       /* This is needed, since otherwise active registry entries will not be destroyed */
31393       ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {  /* regl is locked */
31394             ASTOBJ_WRLOCK(iterator); /* now regl is locked, and the object is also locked */
31395             if (iterator->call) {
31396                ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
31397                /* This will also remove references to the registry */
31398                dialog_unlink_all(iterator->call);
31399                iterator->call = dialog_unref(iterator->call, "remove iterator->call from registry traversal");
31400             }
31401             if (iterator->expire > -1) {
31402                AST_SCHED_DEL_UNREF(sched, iterator->expire, registry_unref(iterator, "reg ptr unref from reload config"));
31403             }
31404             if (iterator->timeout > -1) {
31405                AST_SCHED_DEL_UNREF(sched, iterator->timeout, registry_unref(iterator, "reg ptr unref from reload config"));
31406             }
31407             if (iterator->dnsmgr) {
31408                ast_dnsmgr_release(iterator->dnsmgr);
31409                iterator->dnsmgr = NULL;
31410                registry_unref(iterator, "reg ptr unref from dnsmgr");
31411             }
31412             ASTOBJ_UNLOCK(iterator);
31413       } while(0));
31414 }
31415 
31416 /*! \brief Re-read SIP.conf config file
31417 \note This function reloads all config data, except for
31418    active peers (with registrations). They will only
31419    change configuration data at restart, not at reload.
31420    SIP debug and recordhistory state will not change
31421  */
31422 static int reload_config(enum channelreloadreason reason)
31423 {
31424    struct ast_config *cfg, *ucfg;
31425    struct ast_variable *v;
31426    struct sip_peer *peer;
31427    char *cat, *stringp, *context, *oldregcontext;
31428    char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
31429    struct ast_flags mask[3] = {{0}};
31430    struct ast_flags setflags[3] = {{0}};
31431    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 };
31432    int auto_sip_domains = FALSE;
31433    struct ast_sockaddr old_bindaddr = bindaddr;
31434    int registry_count = 0, peer_count = 0, timerb_set = 0, timert1_set = 0;
31435    int subscribe_network_change = 1;
31436    time_t run_start, run_end;
31437    int bindport = 0;
31438    int acl_change_subscription_needed = 0;
31439    int min_subexpiry_set = 0, max_subexpiry_set = 0;
31440 
31441    run_start = time(0);
31442    ast_unload_realtime("sipregs");
31443    ast_unload_realtime("sippeers");
31444    cfg = ast_config_load(config, config_flags);
31445 
31446    /* We *must* have a config file otherwise stop immediately */
31447    if (!cfg) {
31448       ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
31449       return -1;
31450    } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
31451       ucfg = ast_config_load("users.conf", config_flags);
31452       if (ucfg == CONFIG_STATUS_FILEUNCHANGED) {
31453          return 1;
31454       } else if (ucfg == CONFIG_STATUS_FILEINVALID) {
31455          ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
31456          return 1;
31457       }
31458       /* Must reread both files, because one changed */
31459       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
31460       if ((cfg = ast_config_load(config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
31461          ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
31462          ast_config_destroy(ucfg);
31463          return 1;
31464       }
31465       if (!cfg) {
31466          /* should have been able to reload here */
31467          ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
31468          return -1;
31469       }
31470    } else if (cfg == CONFIG_STATUS_FILEINVALID) {
31471       ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
31472       return 1;
31473    } else {
31474       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
31475       if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEINVALID) {
31476          ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
31477          ast_config_destroy(cfg);
31478          return 1;
31479       }
31480    }
31481 
31482    sip_cfg.contact_acl = ast_free_acl_list(sip_cfg.contact_acl);
31483 
31484    default_tls_cfg.enabled = FALSE;    /* Default: Disable TLS */
31485 
31486    if (reason != CHANNEL_MODULE_LOAD) {
31487       ast_debug(4, "--------------- SIP reload started\n");
31488 
31489       clear_sip_domains();
31490       ast_mutex_lock(&authl_lock);
31491       if (authl) {
31492          ao2_t_ref(authl, -1, "Removing old global authentication");
31493          authl = NULL;
31494       }
31495       ast_mutex_unlock(&authl_lock);
31496 
31497       cleanup_all_regs();
31498 
31499       /* Then, actually destroy users and registry */
31500       ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
31501       ast_debug(4, "--------------- Done destroying registry list\n");
31502       ao2_t_callback(peers, OBJ_NODATA, peer_markall_func, NULL, "callback to mark all peers");
31503    }
31504 
31505    /* Reset certificate handling for TLS sessions */
31506    if (reason != CHANNEL_MODULE_LOAD) {
31507       ast_free(default_tls_cfg.certfile);
31508       ast_free(default_tls_cfg.pvtfile);
31509       ast_free(default_tls_cfg.cipher);
31510       ast_free(default_tls_cfg.cafile);
31511       ast_free(default_tls_cfg.capath);
31512    }
31513    default_tls_cfg.certfile = ast_strdup(AST_CERTFILE); /*XXX Not sure if this is useful */
31514    default_tls_cfg.pvtfile = ast_strdup("");
31515    default_tls_cfg.cipher = ast_strdup("");
31516    default_tls_cfg.cafile = ast_strdup("");
31517    default_tls_cfg.capath = ast_strdup("");
31518 
31519    /* Initialize copy of current sip_cfg.regcontext for later use in removing stale contexts */
31520    ast_copy_string(oldcontexts, sip_cfg.regcontext, sizeof(oldcontexts));
31521    oldregcontext = oldcontexts;
31522 
31523    /* Clear all flags before setting default values */
31524    /* Preserve debugging settings for console */
31525    sipdebug &= sip_debug_console;
31526    ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
31527    ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
31528    ast_clear_flag(&global_flags[2], AST_FLAGS_ALL);
31529 
31530    /* Reset IP addresses  */
31531    ast_sockaddr_parse(&bindaddr, "0.0.0.0:0", 0);
31532    memset(&internip, 0, sizeof(internip));
31533 
31534    /* Free memory for local network address mask */
31535    ast_free_ha(localaddr);
31536    memset(&localaddr, 0, sizeof(localaddr));
31537    memset(&externaddr, 0, sizeof(externaddr));
31538    memset(&media_address, 0, sizeof(media_address));
31539    memset(&default_prefs, 0 , sizeof(default_prefs));
31540    memset(&sip_cfg.outboundproxy, 0, sizeof(struct sip_proxy));
31541    sip_cfg.outboundproxy.force = FALSE;      /*!< Don't force proxy usage, use route: headers */
31542    default_transports = SIP_TRANSPORT_UDP;
31543    default_primary_transport = SIP_TRANSPORT_UDP;
31544    ourport_tcp = STANDARD_SIP_PORT;
31545    ourport_tls = STANDARD_TLS_PORT;
31546    externtcpport = STANDARD_SIP_PORT;
31547    externtlsport = STANDARD_TLS_PORT;
31548    sip_cfg.srvlookup = DEFAULT_SRVLOOKUP;
31549    global_tos_sip = DEFAULT_TOS_SIP;
31550    global_tos_audio = DEFAULT_TOS_AUDIO;
31551    global_tos_video = DEFAULT_TOS_VIDEO;
31552    global_tos_text = DEFAULT_TOS_TEXT;
31553    global_cos_sip = DEFAULT_COS_SIP;
31554    global_cos_audio = DEFAULT_COS_AUDIO;
31555    global_cos_video = DEFAULT_COS_VIDEO;
31556    global_cos_text = DEFAULT_COS_TEXT;
31557 
31558    externhost[0] = '\0';         /* External host name (for behind NAT DynDNS support) */
31559    externexpire = 0;       /* Expiration for DNS re-issuing */
31560    externrefresh = 10;
31561 
31562    /* Reset channel settings to default before re-configuring */
31563    sip_cfg.allow_external_domains = DEFAULT_ALLOW_EXT_DOM;           /* Allow external invites */
31564    sip_cfg.regcontext[0] = '\0';
31565    sip_set_default_format_capabilities(sip_cfg.caps);
31566    sip_cfg.regextenonqualify = DEFAULT_REGEXTENONQUALIFY;
31567    sip_cfg.legacy_useroption_parsing = DEFAULT_LEGACY_USEROPTION_PARSING;
31568    sip_cfg.send_diversion = DEFAULT_SEND_DIVERSION;
31569    sip_cfg.notifyringing = DEFAULT_NOTIFYRINGING;
31570    sip_cfg.notifycid = DEFAULT_NOTIFYCID;
31571    sip_cfg.notifyhold = FALSE;      /*!< Keep track of hold status for a peer */
31572    sip_cfg.directrtpsetup = FALSE;     /* Experimental feature, disabled by default */
31573    sip_cfg.alwaysauthreject = DEFAULT_ALWAYSAUTHREJECT;
31574    sip_cfg.auth_options_requests = DEFAULT_AUTH_OPTIONS;
31575    sip_cfg.auth_message_requests = DEFAULT_AUTH_MESSAGE;
31576    sip_cfg.messagecontext[0] = '\0';
31577    sip_cfg.accept_outofcall_message = DEFAULT_ACCEPT_OUTOFCALL_MESSAGE;
31578    sip_cfg.allowsubscribe = FALSE;
31579    sip_cfg.disallowed_methods = SIP_UNKNOWN;
31580    sip_cfg.contact_acl = NULL;      /* Reset the contact ACL */
31581    snprintf(global_useragent, sizeof(global_useragent), "%s %s", DEFAULT_USERAGENT, ast_get_version());
31582    snprintf(global_sdpsession, sizeof(global_sdpsession), "%s %s", DEFAULT_SDPSESSION, ast_get_version());
31583    snprintf(global_sdpowner, sizeof(global_sdpowner), "%s", DEFAULT_SDPOWNER);
31584    global_prematuremediafilter = TRUE;
31585    ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
31586    ast_copy_string(sip_cfg.realm, S_OR(ast_config_AST_SYSTEM_NAME, DEFAULT_REALM), sizeof(sip_cfg.realm));
31587    sip_cfg.domainsasrealm = DEFAULT_DOMAINSASREALM;
31588    ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
31589    ast_copy_string(default_mwi_from, DEFAULT_MWI_FROM, sizeof(default_mwi_from));
31590    sip_cfg.compactheaders = DEFAULT_COMPACTHEADERS;
31591    global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
31592    global_regattempts_max = 0;
31593    global_reg_retry_403 = 0;
31594    sip_cfg.pedanticsipchecking = DEFAULT_PEDANTIC;
31595    sip_cfg.autocreatepeer = DEFAULT_AUTOCREATEPEER;
31596    global_autoframing = 0;
31597    sip_cfg.allowguest = DEFAULT_ALLOWGUEST;
31598    global_callcounter = DEFAULT_CALLCOUNTER;
31599    global_match_auth_username = FALSE;    /*!< Match auth username if available instead of From: Default off. */
31600    global_rtptimeout = 0;
31601    global_rtpholdtimeout = 0;
31602    global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
31603    sip_cfg.allowtransfer = TRANSFER_OPENFORALL; /* Merrily accept all transfers by default */
31604    sip_cfg.rtautoclear = 120;
31605    ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE);   /* Default for all devices: TRUE */
31606    ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP_YES); /* Default for all devices: Yes */
31607    sip_cfg.peer_rtupdate = TRUE;
31608    global_dynamic_exclude_static = 0;  /* Exclude static peers */
31609    sip_cfg.tcp_enabled = FALSE;
31610 
31611    /* Session-Timers */
31612    global_st_mode = SESSION_TIMER_MODE_ACCEPT;
31613    global_st_refresher = SESSION_TIMER_REFRESHER_PARAM_UAS;
31614    global_min_se  = DEFAULT_MIN_SE;
31615    global_max_se  = DEFAULT_MAX_SE;
31616 
31617    /* Peer poking settings */
31618    global_qualify_gap = DEFAULT_QUALIFY_GAP;
31619    global_qualify_peers = DEFAULT_QUALIFY_PEERS;
31620 
31621    /* Initialize some reasonable defaults at SIP reload (used both for channel and as default for devices */
31622    ast_copy_string(sip_cfg.default_context, DEFAULT_CONTEXT, sizeof(sip_cfg.default_context));
31623    ast_copy_string(sip_cfg.default_record_on_feature, DEFAULT_RECORD_FEATURE, sizeof(sip_cfg.default_record_on_feature));
31624    ast_copy_string(sip_cfg.default_record_off_feature, DEFAULT_RECORD_FEATURE, sizeof(sip_cfg.default_record_off_feature));
31625    sip_cfg.default_subscribecontext[0] = '\0';
31626    sip_cfg.default_max_forwards = DEFAULT_MAX_FORWARDS;
31627    default_language[0] = '\0';
31628    default_fromdomain[0] = '\0';
31629    default_fromdomainport = 0;
31630    default_qualify = DEFAULT_QUALIFY;
31631    default_keepalive = DEFAULT_KEEPALIVE;
31632    default_zone[0] = '\0';
31633    default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
31634    ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
31635    ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
31636    ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
31637    ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833);    /*!< Default DTMF setting: RFC2833 */
31638    ast_set_flag(&global_flags[0], SIP_DIRECT_MEDIA);    /*!< Allow re-invites */
31639    ast_set_flag(&global_flags[2], SIP_PAGE3_NAT_AUTO_RPORT); /*!< Default to nat=auto_force_rport */
31640    ast_copy_string(default_engine, DEFAULT_ENGINE, sizeof(default_engine));
31641    ast_copy_string(default_parkinglot, DEFAULT_PARKINGLOT, sizeof(default_parkinglot));
31642 
31643    /* Debugging settings, always default to off */
31644    dumphistory = FALSE;
31645    recordhistory = FALSE;
31646    sipdebug &= ~sip_debug_config;
31647 
31648    /* Misc settings for the channel */
31649    global_relaxdtmf = FALSE;
31650    sip_cfg.callevents = DEFAULT_CALLEVENTS;
31651    global_authfailureevents = FALSE;
31652    global_t1 = DEFAULT_TIMER_T1;
31653    global_timer_b = 64 * DEFAULT_TIMER_T1;
31654    global_t1min = DEFAULT_T1MIN;
31655    global_qualifyfreq = DEFAULT_QUALIFYFREQ;
31656    global_t38_maxdatagram = -1;
31657    global_shrinkcallerid = 1;
31658    global_refer_addheaders = TRUE;
31659    authlimit = DEFAULT_AUTHLIMIT;
31660    authtimeout = DEFAULT_AUTHTIMEOUT;
31661    global_store_sip_cause = DEFAULT_STORE_SIP_CAUSE;
31662    min_expiry = DEFAULT_MIN_EXPIRY;
31663    max_expiry = DEFAULT_MAX_EXPIRY;
31664    default_expiry = DEFAULT_DEFAULT_EXPIRY;
31665 
31666    sip_cfg.matchexternaddrlocally = DEFAULT_MATCHEXTERNADDRLOCALLY;
31667 
31668    /* Copy the default jb config over global_jbconf */
31669    memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
31670 
31671    ast_clear_flag(&global_flags[1], SIP_PAGE2_FAX_DETECT);
31672    ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
31673    ast_clear_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT);
31674    ast_clear_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION);
31675 
31676    /* Read the [general] config section of sip.conf (or from realtime config) */
31677    for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
31678       if (handle_common_options(&setflags[0], &mask[0], v)) {
31679          continue;
31680       }
31681       if (handle_t38_options(&setflags[0], &mask[0], v, &global_t38_maxdatagram)) {
31682          continue;
31683       }
31684       /* handle jb conf */
31685       if (!ast_jb_read_conf(&global_jbconf, v->name, v->value)) {
31686          continue;
31687       }
31688 
31689       /* handle tls conf, don't allow setting of tlsverifyclient as it isn't supported by chan_sip */
31690       if (!strcasecmp(v->name, "tlsverifyclient")) {
31691          ast_log(LOG_WARNING, "Ignoring unsupported option 'tlsverifyclient'\n");
31692          continue;
31693       } else if (!ast_tls_read_conf(&default_tls_cfg, &sip_tls_desc, v->name, v->value)) {
31694          continue;
31695       }
31696 
31697       if (!strcasecmp(v->name, "context")) {
31698          ast_copy_string(sip_cfg.default_context, v->value, sizeof(sip_cfg.default_context));
31699       } else if (!strcasecmp(v->name, "recordonfeature")) {
31700          ast_copy_string(sip_cfg.default_record_on_feature, v->value, sizeof(sip_cfg.default_record_on_feature));
31701       } else if (!strcasecmp(v->name, "recordofffeature")) {
31702          ast_copy_string(sip_cfg.default_record_off_feature, v->value, sizeof(sip_cfg.default_record_off_feature));
31703       } else if (!strcasecmp(v->name, "subscribecontext")) {
31704          ast_copy_string(sip_cfg.default_subscribecontext, v->value, sizeof(sip_cfg.default_subscribecontext));
31705       } else if (!strcasecmp(v->name, "callcounter")) {
31706          global_callcounter = ast_true(v->value) ? 1 : 0;
31707       } else if (!strcasecmp(v->name, "allowguest")) {
31708          sip_cfg.allowguest = ast_true(v->value) ? 1 : 0;
31709       } else if (!strcasecmp(v->name, "realm")) {
31710          ast_copy_string(sip_cfg.realm, v->value, sizeof(sip_cfg.realm));
31711       } else if (!strcasecmp(v->name, "domainsasrealm")) {
31712          sip_cfg.domainsasrealm = ast_true(v->value);
31713       } else if (!strcasecmp(v->name, "useragent")) {
31714          ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
31715          ast_debug(1, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
31716       } else if (!strcasecmp(v->name, "sdpsession")) {
31717          ast_copy_string(global_sdpsession, v->value, sizeof(global_sdpsession));
31718       } else if (!strcasecmp(v->name, "sdpowner")) {
31719          /* Field cannot contain spaces */
31720          if (!strstr(v->value, " ")) {
31721             ast_copy_string(global_sdpowner, v->value, sizeof(global_sdpowner));
31722          } else {
31723             ast_log(LOG_WARNING, "'%s' must not contain spaces at line %d.  Using default.\n", v->value, v->lineno);
31724          }
31725       } else if (!strcasecmp(v->name, "allowtransfer")) {
31726          sip_cfg.allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
31727       } else if (!strcasecmp(v->name, "rtcachefriends")) {
31728          ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);
31729       } else if (!strcasecmp(v->name, "rtsavesysname")) {
31730          sip_cfg.rtsave_sysname = ast_true(v->value);
31731       } else if (!strcasecmp(v->name, "rtupdate")) {
31732          sip_cfg.peer_rtupdate = ast_true(v->value);
31733       } else if (!strcasecmp(v->name, "ignoreregexpire")) {
31734          sip_cfg.ignore_regexpire = ast_true(v->value);
31735       } else if (!strcasecmp(v->name, "timert1")) {
31736          /* Defaults to 500ms, but RFC 3261 states that it is recommended
31737           * for the value to be set higher, though a lower value is only
31738           * allowed on private networks unconnected to the Internet. */
31739          global_t1 = atoi(v->value);
31740       } else if (!strcasecmp(v->name, "timerb")) {
31741          int tmp = atoi(v->value);
31742          if (tmp < 500) {
31743             global_timer_b = global_t1 * 64;
31744             ast_log(LOG_WARNING, "Invalid value for timerb ('%s').  Setting to default ('%d').\n", v->value, global_timer_b);
31745          }
31746          timerb_set = 1;
31747       } else if (!strcasecmp(v->name, "t1min")) {
31748          global_t1min = atoi(v->value);
31749       } else if (!strcasecmp(v->name, "transport")) {
31750          char *val = ast_strdupa(v->value);
31751          char *trans;
31752 
31753          default_transports = default_primary_transport = 0;
31754          while ((trans = strsep(&val, ","))) {
31755             trans = ast_skip_blanks(trans);
31756 
31757             if (!strncasecmp(trans, "udp", 3)) {
31758                default_transports |= SIP_TRANSPORT_UDP;
31759             } else if (!strncasecmp(trans, "tcp", 3)) {
31760                default_transports |= SIP_TRANSPORT_TCP;
31761             } else if (!strncasecmp(trans, "tls", 3)) {
31762                default_transports |= SIP_TRANSPORT_TLS;
31763             } else if (!strncasecmp(trans, "wss", 3)) {
31764                default_transports |= SIP_TRANSPORT_WSS;
31765             } else if (!strncasecmp(trans, "ws", 2)) {
31766                default_transports |= SIP_TRANSPORT_WS;
31767             } else {
31768                ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
31769             }
31770             if (default_primary_transport == 0) {
31771                default_primary_transport = default_transports;
31772             }
31773          }
31774       } else if (!strcasecmp(v->name, "tcpenable")) {
31775          if (!ast_false(v->value)) {
31776             ast_debug(2, "Enabling TCP socket for listening\n");
31777             sip_cfg.tcp_enabled = TRUE;
31778          }
31779       } else if (!strcasecmp(v->name, "tcpbindaddr")) {
31780          if (ast_parse_arg(v->value, PARSE_ADDR,
31781                  &sip_tcp_desc.local_address)) {
31782             ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
31783                v->name, v->value, v->lineno, config);
31784          }
31785          ast_debug(2, "Setting TCP socket address to %s\n",
31786               ast_sockaddr_stringify(&sip_tcp_desc.local_address));
31787       } else if (!strcasecmp(v->name, "dynamic_exclude_static") || !strcasecmp(v->name, "dynamic_excludes_static")) {
31788          global_dynamic_exclude_static = ast_true(v->value);
31789       } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny") || !strcasecmp(v->name, "contactacl")) {
31790          int ha_error = 0;
31791          ast_append_acl(v->name + 7, v->value, &sip_cfg.contact_acl, &ha_error, &acl_change_subscription_needed);
31792          if (ha_error) {
31793             ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
31794          }
31795       } else if (!strcasecmp(v->name, "rtautoclear")) {
31796          int i = atoi(v->value);
31797          if (i > 0) {
31798             sip_cfg.rtautoclear = i;
31799          } else {
31800             i = 0;
31801          }
31802          ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
31803       } else if (!strcasecmp(v->name, "usereqphone")) {
31804          ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);
31805       } else if (!strcasecmp(v->name, "prematuremedia")) {
31806          global_prematuremediafilter = ast_true(v->value);
31807       } else if (!strcasecmp(v->name, "relaxdtmf")) {
31808          global_relaxdtmf = ast_true(v->value);
31809       } else if (!strcasecmp(v->name, "vmexten")) {
31810          ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
31811       } else if (!strcasecmp(v->name, "rtptimeout")) {
31812          if ((sscanf(v->value, "%30d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
31813             ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
31814             global_rtptimeout = 0;
31815          }
31816       } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
31817          if ((sscanf(v->value, "%30d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
31818             ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
31819             global_rtpholdtimeout = 0;
31820          }
31821       } else if (!strcasecmp(v->name, "rtpkeepalive")) {
31822          if ((sscanf(v->value, "%30d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
31823             ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d.  Using default.\n", v->value, v->lineno);
31824             global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
31825          }
31826       } else if (!strcasecmp(v->name, "compactheaders")) {
31827          sip_cfg.compactheaders = ast_true(v->value);
31828       } else if (!strcasecmp(v->name, "notifymimetype")) {
31829          ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
31830       } else if (!strcasecmp(v->name, "directrtpsetup")) {
31831          sip_cfg.directrtpsetup = ast_true(v->value);
31832       } else if (!strcasecmp(v->name, "notifyringing")) {
31833          sip_cfg.notifyringing = ast_true(v->value);
31834       } else if (!strcasecmp(v->name, "notifyhold")) {
31835          sip_cfg.notifyhold = ast_true(v->value);
31836       } else if (!strcasecmp(v->name, "notifycid")) {
31837          if (!strcasecmp(v->value, "ignore-context")) {
31838             sip_cfg.notifycid = IGNORE_CONTEXT;
31839          } else {
31840             sip_cfg.notifycid = ast_true(v->value) ? ENABLED : DISABLED;
31841          }
31842       } else if (!strcasecmp(v->name, "alwaysauthreject")) {
31843          sip_cfg.alwaysauthreject = ast_true(v->value);
31844       } else if (!strcasecmp(v->name, "auth_options_requests")) {
31845          if (ast_true(v->value)) {
31846             sip_cfg.auth_options_requests = 1;
31847          }
31848       } else if (!strcasecmp(v->name, "auth_message_requests")) {
31849          sip_cfg.auth_message_requests = ast_true(v->value) ? 1 : 0;
31850       } else if (!strcasecmp(v->name, "accept_outofcall_message")) {
31851          sip_cfg.accept_outofcall_message = ast_true(v->value) ? 1 : 0;
31852       } else if (!strcasecmp(v->name, "outofcall_message_context")) {
31853          ast_copy_string(sip_cfg.messagecontext, v->value, sizeof(sip_cfg.messagecontext));
31854       } else if (!strcasecmp(v->name, "mohinterpret")) {
31855          ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
31856       } else if (!strcasecmp(v->name, "mohsuggest")) {
31857          ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
31858       } else if (!strcasecmp(v->name, "tonezone")) {
31859          struct ast_tone_zone *new_zone;
31860          if (!(new_zone = ast_get_indication_zone(v->value))) {
31861             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);
31862          } else {
31863             ast_tone_zone_unref(new_zone);
31864             ast_copy_string(default_zone, v->value, sizeof(default_zone));
31865          }
31866       } else if (!strcasecmp(v->name, "language")) {
31867          ast_copy_string(default_language, v->value, sizeof(default_language));
31868       } else if (!strcasecmp(v->name, "regcontext")) {
31869          ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
31870          stringp = newcontexts;
31871          /* Let's remove any contexts that are no longer defined in regcontext */
31872          cleanup_stale_contexts(stringp, oldregcontext);
31873          /* Create contexts if they don't exist already */
31874          while ((context = strsep(&stringp, "&"))) {
31875             ast_copy_string(used_context, context, sizeof(used_context));
31876             ast_context_find_or_create(NULL, NULL, context, "SIP");
31877          }
31878          ast_copy_string(sip_cfg.regcontext, v->value, sizeof(sip_cfg.regcontext));
31879       } else if (!strcasecmp(v->name, "regextenonqualify")) {
31880          sip_cfg.regextenonqualify = ast_true(v->value);
31881       } else if (!strcasecmp(v->name, "legacy_useroption_parsing")) {
31882          sip_cfg.legacy_useroption_parsing = ast_true(v->value);
31883       } else if (!strcasecmp(v->name, "send_diversion")) {
31884          sip_cfg.send_diversion = ast_true(v->value);
31885       } else if (!strcasecmp(v->name, "callerid")) {
31886          ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
31887       } else if (!strcasecmp(v->name, "mwi_from")) {
31888          ast_copy_string(default_mwi_from, v->value, sizeof(default_mwi_from));
31889       } else if (!strcasecmp(v->name, "fromdomain")) {
31890          char *fromdomainport;
31891          ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
31892          if ((fromdomainport = strchr(default_fromdomain, ':'))) {
31893             *fromdomainport++ = '\0';
31894             if (!(default_fromdomainport = port_str2int(fromdomainport, 0))) {
31895                ast_log(LOG_NOTICE, "'%s' is not a valid port number for fromdomain.\n",fromdomainport);
31896             }
31897          } else {
31898             default_fromdomainport = STANDARD_SIP_PORT;
31899          }
31900       } else if (!strcasecmp(v->name, "outboundproxy")) {
31901          struct sip_proxy *proxy;
31902          if (ast_strlen_zero(v->value)) {
31903             ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf\n", v->lineno);
31904             continue;
31905          }
31906          proxy = proxy_from_config(v->value, v->lineno, &sip_cfg.outboundproxy);
31907          if (!proxy) {
31908             ast_log(LOG_WARNING, "failure parsing the outbound proxy on line %d of sip.conf.\n", v->lineno);
31909             continue;
31910          }
31911       } else if (!strcasecmp(v->name, "autocreatepeer")) {
31912          if (!strcasecmp(v->value, "persist")) {
31913             sip_cfg.autocreatepeer = AUTOPEERS_PERSIST;
31914          } else {
31915             sip_cfg.autocreatepeer = ast_true(v->value) ? AUTOPEERS_VOLATILE : AUTOPEERS_DISABLED;
31916          }
31917       } else if (!strcasecmp(v->name, "match_auth_username")) {
31918          global_match_auth_username = ast_true(v->value);
31919       } else if (!strcasecmp(v->name, "srvlookup")) {
31920          sip_cfg.srvlookup = ast_true(v->value);
31921       } else if (!strcasecmp(v->name, "pedantic")) {
31922          sip_cfg.pedanticsipchecking = ast_true(v->value);
31923       } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
31924          max_expiry = atoi(v->value);
31925          if (max_expiry < 1) {
31926             max_expiry = DEFAULT_MAX_EXPIRY;
31927          }
31928       } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
31929          min_expiry = atoi(v->value);
31930          if (min_expiry < 1) {
31931             min_expiry = DEFAULT_MIN_EXPIRY;
31932          }
31933       } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
31934          default_expiry = atoi(v->value);
31935          if (default_expiry < 1) {
31936             default_expiry = DEFAULT_DEFAULT_EXPIRY;
31937          }
31938       } else if (!strcasecmp(v->name, "submaxexpirey") || !strcasecmp(v->name, "submaxexpiry")) {
31939          max_subexpiry = atoi(v->value);
31940          if (max_subexpiry < 1) {
31941             max_subexpiry = DEFAULT_MAX_EXPIRY;
31942          }
31943          max_subexpiry_set = 1;
31944       } else if (!strcasecmp(v->name, "subminexpirey") || !strcasecmp(v->name, "subminexpiry")) {
31945          min_subexpiry = atoi(v->value);
31946          if (min_subexpiry < 1) {
31947             min_subexpiry = DEFAULT_MIN_EXPIRY;
31948          }
31949          min_subexpiry_set = 1;
31950       } else if (!strcasecmp(v->name, "mwiexpiry") || !strcasecmp(v->name, "mwiexpirey")) {
31951          mwi_expiry = atoi(v->value);
31952          if (mwi_expiry < 1) {
31953             mwi_expiry = DEFAULT_MWI_EXPIRY;
31954          }
31955       } else if (!strcasecmp(v->name, "tcpauthtimeout")) {
31956          if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
31957                  &authtimeout, DEFAULT_AUTHTIMEOUT, 1, INT_MAX)) {
31958             ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
31959                v->name, v->value, v->lineno, config);
31960          }
31961       } else if (!strcasecmp(v->name, "tcpauthlimit")) {
31962          if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
31963                  &authlimit, DEFAULT_AUTHLIMIT, 1, INT_MAX)) {
31964             ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
31965                v->name, v->value, v->lineno, config);
31966          }
31967       } else if (!strcasecmp(v->name, "sipdebug")) {
31968          if (ast_true(v->value))
31969             sipdebug |= sip_debug_config;
31970       } else if (!strcasecmp(v->name, "dumphistory")) {
31971          dumphistory = ast_true(v->value);
31972       } else if (!strcasecmp(v->name, "recordhistory")) {
31973          recordhistory = ast_true(v->value);
31974       } else if (!strcasecmp(v->name, "registertimeout")) {
31975          global_reg_timeout = atoi(v->value);
31976          if (global_reg_timeout < 1) {
31977             global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
31978          }
31979       } else if (!strcasecmp(v->name, "registerattempts")) {
31980          global_regattempts_max = atoi(v->value);
31981       } else if (!strcasecmp(v->name, "register_retry_403")) {
31982          global_reg_retry_403 = ast_true(v->value);
31983       } else if (!strcasecmp(v->name, "bindaddr") || !strcasecmp(v->name, "udpbindaddr")) {
31984          if (ast_parse_arg(v->value, PARSE_ADDR, &bindaddr)) {
31985             ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
31986          }
31987       } else if (!strcasecmp(v->name, "localnet")) {
31988          struct ast_ha *na;
31989          int ha_error = 0;
31990 
31991          if (!(na = ast_append_ha("d", v->value, localaddr, &ha_error))) {
31992             ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
31993          } else {
31994             localaddr = na;
31995          }
31996          if (ha_error) {
31997             ast_log(LOG_ERROR, "Bad localnet configuration value line %d : %s\n", v->lineno, v->value);
31998          }
31999       } else if (!strcasecmp(v->name, "media_address")) {
32000          if (ast_parse_arg(v->value, PARSE_ADDR, &media_address))
32001             ast_log(LOG_WARNING, "Invalid address for media_address keyword: %s\n", v->value);
32002       } else if (!strcasecmp(v->name, "externaddr") || !strcasecmp(v->name, "externip")) {
32003          if (ast_parse_arg(v->value, PARSE_ADDR, &externaddr)) {
32004             ast_log(LOG_WARNING,
32005                "Invalid address for externaddr keyword: %s\n",
32006                v->value);
32007          }
32008          externexpire = 0;
32009       } else if (!strcasecmp(v->name, "externhost")) {
32010          ast_copy_string(externhost, v->value, sizeof(externhost));
32011          if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
32012             ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
32013          }
32014          externexpire = time(NULL);
32015       } else if (!strcasecmp(v->name, "externrefresh")) {
32016          if (sscanf(v->value, "%30d", &externrefresh) != 1) {
32017             ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
32018             externrefresh = 10;
32019          }
32020       } else if (!strcasecmp(v->name, "externtcpport")) {
32021          if (!(externtcpport = port_str2int(v->value, 0))) {
32022             ast_log(LOG_WARNING, "Invalid externtcpport value, must be a positive integer between 1 and 65535 at line %d\n", v->lineno);
32023             externtcpport = 0;
32024          }
32025       } else if (!strcasecmp(v->name, "externtlsport")) {
32026          if (!(externtlsport = port_str2int(v->value, STANDARD_TLS_PORT))) {
32027             ast_log(LOG_WARNING, "Invalid externtlsport value, must be a positive integer between 1 and 65535 at line %d\n", v->lineno);
32028          }
32029       } else if (!strcasecmp(v->name, "allow")) {
32030          int error =  ast_parse_allow_disallow(&default_prefs, sip_cfg.caps, v->value, TRUE);
32031          if (error) {
32032             ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
32033          }
32034       } else if (!strcasecmp(v->name, "disallow")) {
32035          int error =  ast_parse_allow_disallow(&default_prefs, sip_cfg.caps, v->value, FALSE);
32036          if (error) {
32037             ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
32038          }
32039       } else if (!strcasecmp(v->name, "preferred_codec_only")) {
32040          ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_PREFERRED_CODEC);
32041       } else if (!strcasecmp(v->name, "autoframing")) {
32042          global_autoframing = ast_true(v->value);
32043       } else if (!strcasecmp(v->name, "allowexternaldomains")) {
32044          sip_cfg.allow_external_domains = ast_true(v->value);
32045       } else if (!strcasecmp(v->name, "autodomain")) {
32046          auto_sip_domains = ast_true(v->value);
32047       } else if (!strcasecmp(v->name, "domain")) {
32048          char *domain = ast_strdupa(v->value);
32049          char *cntx = strchr(domain, ',');
32050 
32051          if (cntx) {
32052             *cntx++ = '\0';
32053          }
32054 
32055          if (ast_strlen_zero(cntx)) {
32056             ast_debug(1, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
32057          }
32058          if (ast_strlen_zero(domain)) {
32059             ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
32060          } else {
32061             add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, cntx ? ast_strip(cntx) : "");
32062          }
32063       } else if (!strcasecmp(v->name, "register")) {
32064          if (sip_register(v->value, v->lineno) == 0) {
32065             registry_count++;
32066          }
32067       } else if (!strcasecmp(v->name, "mwi")) {
32068          sip_subscribe_mwi(v->value, v->lineno);
32069       } else if (!strcasecmp(v->name, "tos_sip")) {
32070          if (ast_str2tos(v->value, &global_tos_sip)) {
32071             ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, refer to QoS documentation\n", v->lineno);
32072          }
32073       } else if (!strcasecmp(v->name, "tos_audio")) {
32074          if (ast_str2tos(v->value, &global_tos_audio)) {
32075             ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, refer to QoS documentation\n", v->lineno);
32076          }
32077       } else if (!strcasecmp(v->name, "tos_video")) {
32078          if (ast_str2tos(v->value, &global_tos_video)) {
32079             ast_log(LOG_WARNING, "Invalid tos_video value at line %d, refer to QoS documentation\n", v->lineno);
32080          }
32081       } else if (!strcasecmp(v->name, "tos_text")) {
32082          if (ast_str2tos(v->value, &global_tos_text)) {
32083             ast_log(LOG_WARNING, "Invalid tos_text value at line %d, refer to QoS documentation\n", v->lineno);
32084          }
32085       } else if (!strcasecmp(v->name, "cos_sip")) {
32086          if (ast_str2cos(v->value, &global_cos_sip)) {
32087             ast_log(LOG_WARNING, "Invalid cos_sip value at line %d, refer to QoS documentation\n", v->lineno);
32088          }
32089       } else if (!strcasecmp(v->name, "cos_audio")) {
32090          if (ast_str2cos(v->value, &global_cos_audio)) {
32091             ast_log(LOG_WARNING, "Invalid cos_audio value at line %d, refer to QoS documentation\n", v->lineno);
32092          }
32093       } else if (!strcasecmp(v->name, "cos_video")) {
32094          if (ast_str2cos(v->value, &global_cos_video)) {
32095             ast_log(LOG_WARNING, "Invalid cos_video value at line %d, refer to QoS documentation\n", v->lineno);
32096          }
32097       } else if (!strcasecmp(v->name, "cos_text")) {
32098          if (ast_str2cos(v->value, &global_cos_text)) {
32099             ast_log(LOG_WARNING, "Invalid cos_text value at line %d, refer to QoS documentation\n", v->lineno);
32100          }
32101       } else if (!strcasecmp(v->name, "bindport")) {
32102          if (sscanf(v->value, "%5d", &bindport) != 1) {
32103             ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
32104          }
32105       } else if (!strcasecmp(v->name, "qualify")) {
32106          if (!strcasecmp(v->value, "no")) {
32107             default_qualify = 0;
32108          } else if (!strcasecmp(v->value, "yes")) {
32109             default_qualify = DEFAULT_MAXMS;
32110          } else if (sscanf(v->value, "%30d", &default_qualify) != 1) {
32111             ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
32112             default_qualify = 0;
32113          }
32114       } else if (!strcasecmp(v->name, "keepalive")) {
32115          if (!strcasecmp(v->value, "no")) {
32116             default_keepalive = 0;
32117          } else if (!strcasecmp(v->value, "yes")) {
32118             default_keepalive = DEFAULT_KEEPALIVE_INTERVAL;
32119          } else if (sscanf(v->value, "%30d", &default_keepalive) != 1) {
32120             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);
32121             default_keepalive = 0;
32122          }
32123       } else if (!strcasecmp(v->name, "qualifyfreq")) {
32124          int i;
32125          if (sscanf(v->value, "%30d", &i) == 1) {
32126             global_qualifyfreq = i * 1000;
32127          } else {
32128             ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
32129             global_qualifyfreq = DEFAULT_QUALIFYFREQ;
32130          }
32131       } else if (!strcasecmp(v->name, "callevents")) {
32132          sip_cfg.callevents = ast_true(v->value);
32133       } else if (!strcasecmp(v->name, "authfailureevents")) {
32134          global_authfailureevents = ast_true(v->value);
32135       } else if (!strcasecmp(v->name, "maxcallbitrate")) {
32136          default_maxcallbitrate = atoi(v->value);
32137          if (default_maxcallbitrate < 0) {
32138             default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
32139          }
32140       } else if (!strcasecmp(v->name, "matchexternaddrlocally") || !strcasecmp(v->name, "matchexterniplocally")) {
32141          sip_cfg.matchexternaddrlocally = ast_true(v->value);
32142       } else if (!strcasecmp(v->name, "session-timers")) {
32143          int i = (int) str2stmode(v->value);
32144          if (i < 0) {
32145             ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
32146             global_st_mode = SESSION_TIMER_MODE_ACCEPT;
32147          } else {
32148             global_st_mode = i;
32149          }
32150       } else if (!strcasecmp(v->name, "session-expires")) {
32151          if (sscanf(v->value, "%30d", &global_max_se) != 1) {
32152             ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
32153             global_max_se = DEFAULT_MAX_SE;
32154          }
32155       } else if (!strcasecmp(v->name, "session-minse")) {
32156          if (sscanf(v->value, "%30d", &global_min_se) != 1) {
32157             ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
32158             global_min_se = DEFAULT_MIN_SE;
32159          }
32160          if (global_min_se < DEFAULT_MIN_SE) {
32161             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);
32162             global_min_se = DEFAULT_MIN_SE;
32163          }
32164       } else if (!strcasecmp(v->name, "session-refresher")) {
32165          int i = (int) str2strefresherparam(v->value);
32166          if (i < 0) {
32167             ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
32168             global_st_refresher = SESSION_TIMER_REFRESHER_PARAM_UAS;
32169          } else {
32170             global_st_refresher = i;
32171          }
32172       } else if (!strcasecmp(v->name, "storesipcause")) {
32173          global_store_sip_cause = ast_true(v->value);
32174          if (global_store_sip_cause) {
32175             ast_log(LOG_WARNING, "Usage of SIP_CAUSE is deprecated.  Please use HANGUPCAUSE instead.\n");
32176          }
32177       } else if (!strcasecmp(v->name, "qualifygap")) {
32178          if (sscanf(v->value, "%30d", &global_qualify_gap) != 1) {
32179             ast_log(LOG_WARNING, "Invalid qualifygap '%s' at line %d of %s\n", v->value, v->lineno, config);
32180             global_qualify_gap = DEFAULT_QUALIFY_GAP;
32181          }
32182       } else if (!strcasecmp(v->name, "qualifypeers")) {
32183          if (sscanf(v->value, "%30d", &global_qualify_peers) != 1) {
32184             ast_log(LOG_WARNING, "Invalid pokepeers '%s' at line %d of %s\n", v->value, v->lineno, config);
32185             global_qualify_peers = DEFAULT_QUALIFY_PEERS;
32186          }
32187       } else if (!strcasecmp(v->name, "disallowed_methods")) {
32188          char *disallow = ast_strdupa(v->value);
32189          mark_parsed_methods(&sip_cfg.disallowed_methods, disallow);
32190       } else if (!strcasecmp(v->name, "shrinkcallerid")) {
32191          if (ast_true(v->value)) {
32192             global_shrinkcallerid = 1;
32193          } else if (ast_false(v->value)) {
32194             global_shrinkcallerid = 0;
32195          } else {
32196             ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
32197          }
32198       } else if (!strcasecmp(v->name, "use_q850_reason")) {
32199          ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_Q850_REASON);
32200       } else if (!strcasecmp(v->name, "maxforwards")) {
32201          if (sscanf(v->value, "%30d", &sip_cfg.default_max_forwards) != 1
32202             || sip_cfg.default_max_forwards < 1 || 255 < sip_cfg.default_max_forwards) {
32203             ast_log(LOG_WARNING, "'%s' is not a valid maxforwards value at line %d.  Using default.\n", v->value, v->lineno);
32204             sip_cfg.default_max_forwards = DEFAULT_MAX_FORWARDS;
32205          }
32206       } else if (!strcasecmp(v->name, "subscribe_network_change_event")) {
32207          if (ast_true(v->value)) {
32208             subscribe_network_change = 1;
32209          } else if (ast_false(v->value)) {
32210             subscribe_network_change = 0;
32211          } else {
32212             ast_log(LOG_WARNING, "subscribe_network_change_event value %s is not valid at line %d.\n", v->value, v->lineno);
32213          }
32214       } else if (!strcasecmp(v->name, "snom_aoc_enabled")) {
32215          ast_set2_flag(&global_flags[2], ast_true(v->value), SIP_PAGE3_SNOM_AOC);
32216       } else if (!strcasecmp(v->name, "icesupport")) {
32217          ast_set2_flag(&global_flags[2], ast_true(v->value), SIP_PAGE3_ICE_SUPPORT);
32218       } else if (!strcasecmp(v->name, "parkinglot")) {
32219          ast_copy_string(default_parkinglot, v->value, sizeof(default_parkinglot));
32220       } else if (!strcasecmp(v->name, "refer_addheaders")) {
32221          global_refer_addheaders = ast_true(v->value);
32222       }
32223    }
32224 
32225    /* Override global defaults if setting found in general section */
32226    ast_copy_flags(&global_flags[0], &setflags[0], mask[0].flags);
32227    ast_copy_flags(&global_flags[1], &setflags[1], mask[1].flags);
32228    ast_copy_flags(&global_flags[2], &setflags[2], mask[2].flags);
32229 
32230    /* For backwards compatibility the corresponding registration timer value is used if subscription timer value isn't set by configuration */
32231    if (!min_subexpiry_set) {
32232       min_subexpiry = min_expiry;
32233    }
32234    if (!max_subexpiry_set) {
32235       max_subexpiry = max_expiry;
32236    }
32237 
32238    if (reason != CHANNEL_MODULE_LOAD && sip_cfg.autocreatepeer != AUTOPEERS_PERSIST) {
32239       ao2_t_callback(peers, OBJ_NODATA, peer_markall_autopeers_func, NULL, "callback to mark autopeers for destruction");
32240    }
32241 
32242    if (subscribe_network_change) {
32243       network_change_event_subscribe();
32244    } else {
32245       network_change_event_unsubscribe();
32246    }
32247 
32248    if (global_t1 < global_t1min) {
32249       ast_log(LOG_WARNING, "'t1min' (%d) cannot be greater than 't1timer' (%d).  Resetting 't1timer' to the value of 't1min'\n", global_t1min, global_t1);
32250       global_t1 = global_t1min;
32251    }
32252 
32253    if (global_timer_b < global_t1 * 64) {
32254       if (timerb_set && timert1_set) {
32255          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);
32256       } else if (timerb_set) {
32257          if ((global_t1 = global_timer_b / 64) < global_t1min) {
32258             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);
32259             global_t1 = global_t1min;
32260             global_timer_b = global_t1 * 64;
32261          }
32262       } else {
32263          global_timer_b = global_t1 * 64;
32264       }
32265    }
32266    if (!sip_cfg.allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
32267       ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
32268       sip_cfg.allow_external_domains = 1;
32269    }
32270    /* If not or badly configured, set default transports */
32271    if (!sip_cfg.tcp_enabled && (default_transports & SIP_TRANSPORT_TCP)) {
32272       ast_log(LOG_WARNING, "Cannot use 'tcp' transport with tcpenable=no. Removing from available transports.\n");
32273       default_primary_transport &= ~SIP_TRANSPORT_TCP;
32274       default_transports &= ~SIP_TRANSPORT_TCP;
32275    }
32276    if (!default_tls_cfg.enabled && (default_transports & SIP_TRANSPORT_TLS)) {
32277       ast_log(LOG_WARNING, "Cannot use 'tls' transport with tlsenable=no. Removing from available transports.\n");
32278       default_primary_transport &= ~SIP_TRANSPORT_TLS;
32279       default_transports &= ~SIP_TRANSPORT_TLS;
32280    }
32281    if (!default_transports) {
32282       ast_log(LOG_WARNING, "No valid transports available, falling back to 'udp'.\n");
32283       default_transports = default_primary_transport = SIP_TRANSPORT_UDP;
32284    } else if (!default_primary_transport) {
32285       ast_log(LOG_WARNING, "No valid default transport. Selecting 'udp' as default.\n");
32286       default_primary_transport = SIP_TRANSPORT_UDP;
32287    }
32288 
32289    /* Build list of authentication to various SIP realms, i.e. service providers */
32290    for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
32291       /* Format for authentication is auth = username:password@realm */
32292       if (!strcasecmp(v->name, "auth")) {
32293          add_realm_authentication(&authl, v->value, v->lineno);
32294       }
32295    }
32296 
32297    if (bindport) {
32298       if (ast_sockaddr_port(&bindaddr)) {
32299          ast_log(LOG_WARNING, "bindport is also specified in bindaddr. "
32300             "Using %d.\n", bindport);
32301       }
32302       ast_sockaddr_set_port(&bindaddr, bindport);
32303    }
32304 
32305    if (!ast_sockaddr_port(&bindaddr)) {
32306       ast_sockaddr_set_port(&bindaddr, STANDARD_SIP_PORT);
32307    }
32308 
32309    /* Set UDP address and open socket */
32310    ast_sockaddr_copy(&internip, &bindaddr);
32311    if (ast_find_ourip(&internip, &bindaddr, 0)) {
32312       ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
32313       ast_config_destroy(cfg);
32314       return 0;
32315    }
32316 
32317    ast_mutex_lock(&netlock);
32318    if ((sipsock > -1) && (ast_sockaddr_cmp(&old_bindaddr, &bindaddr))) {
32319       close(sipsock);
32320       sipsock = -1;
32321    }
32322    if (sipsock < 0) {
32323       sipsock = socket(ast_sockaddr_is_ipv6(&bindaddr) ?
32324              AF_INET6 : AF_INET, SOCK_DGRAM, 0);
32325       if (sipsock < 0) {
32326          ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
32327          ast_config_destroy(cfg);
32328          ast_mutex_unlock(&netlock);
32329          return -1;
32330       } else {
32331          /* Allow SIP clients on the same host to access us: */
32332          const int reuseFlag = 1;
32333 
32334          setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
32335                (const char*)&reuseFlag,
32336                sizeof reuseFlag);
32337 
32338          ast_enable_packet_fragmentation(sipsock);
32339 
32340          if (ast_bind(sipsock, &bindaddr) < 0) {
32341             ast_log(LOG_WARNING, "Failed to bind to %s: %s\n",
32342                ast_sockaddr_stringify(&bindaddr), strerror(errno));
32343             close(sipsock);
32344             sipsock = -1;
32345          } else {
32346             ast_verb(2, "SIP Listening on %s\n", ast_sockaddr_stringify(&bindaddr));
32347             ast_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
32348          }
32349       }
32350    } else {
32351       ast_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
32352    }
32353    ast_mutex_unlock(&netlock);
32354 
32355    /* Start TCP server */
32356    if (sip_cfg.tcp_enabled) {
32357       if (ast_sockaddr_isnull(&sip_tcp_desc.local_address)) {
32358          ast_sockaddr_copy(&sip_tcp_desc.local_address, &bindaddr);
32359       }
32360       if (!ast_sockaddr_port(&sip_tcp_desc.local_address)) {
32361          ast_sockaddr_set_port(&sip_tcp_desc.local_address, STANDARD_SIP_PORT);
32362       }
32363    } else {
32364       ast_sockaddr_setnull(&sip_tcp_desc.local_address);
32365    }
32366    ast_tcptls_server_start(&sip_tcp_desc);
32367    if (sip_cfg.tcp_enabled && sip_tcp_desc.accept_fd == -1) {
32368       /* TCP server start failed. Tell the admin */
32369       ast_log(LOG_ERROR, "SIP TCP Server start failed. Not listening on TCP socket.\n");
32370    } else {
32371       ast_debug(2, "SIP TCP server started\n");
32372    }
32373 
32374    /* Start TLS server if needed */
32375    memcpy(sip_tls_desc.tls_cfg, &default_tls_cfg, sizeof(default_tls_cfg));
32376 
32377    if (ast_ssl_setup(sip_tls_desc.tls_cfg)) {
32378       if (ast_sockaddr_isnull(&sip_tls_desc.local_address)) {
32379          ast_sockaddr_copy(&sip_tls_desc.local_address, &bindaddr);
32380          ast_sockaddr_set_port(&sip_tls_desc.local_address,
32381                      STANDARD_TLS_PORT);
32382       }
32383       if (!ast_sockaddr_port(&sip_tls_desc.local_address)) {
32384          ast_sockaddr_set_port(&sip_tls_desc.local_address,
32385                      STANDARD_TLS_PORT);
32386       }
32387       ast_tcptls_server_start(&sip_tls_desc);
32388       if (default_tls_cfg.enabled && sip_tls_desc.accept_fd == -1) {
32389          ast_log(LOG_ERROR, "TLS Server start failed. Not listening on TLS socket.\n");
32390          sip_tls_desc.tls_cfg = NULL;
32391       }
32392    } else if (sip_tls_desc.tls_cfg->enabled) {
32393       sip_tls_desc.tls_cfg = NULL;
32394       ast_log(LOG_WARNING, "SIP TLS server did not load because of errors.\n");
32395    }
32396 
32397    if (ucfg) {
32398       struct ast_variable *gen;
32399       int genhassip, genregistersip;
32400       const char *hassip, *registersip;
32401       
32402       genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
32403       genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
32404       gen = ast_variable_browse(ucfg, "general");
32405       cat = ast_category_browse(ucfg, NULL);
32406       while (cat) {
32407          if (strcasecmp(cat, "general")) {
32408             hassip = ast_variable_retrieve(ucfg, cat, "hassip");
32409             registersip = ast_variable_retrieve(ucfg, cat, "registersip");
32410             if (ast_true(hassip) || (!hassip && genhassip)) {
32411                peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0, 0);
32412                if (peer) {
32413                   /* user.conf entries are always of type friend */
32414                   peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
32415                   ao2_t_link(peers, peer, "link peer into peer table");
32416                   if ((peer->type & SIP_TYPE_PEER) && !ast_sockaddr_isnull(&peer->addr)) {
32417                      ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
32418                   }
32419                   
32420                   sip_unref_peer(peer, "sip_unref_peer: from reload_config");
32421                   peer_count++;
32422                }
32423             }
32424             if (ast_true(registersip) || (!registersip && genregistersip)) {
32425                char tmp[256];
32426                const char *host = ast_variable_retrieve(ucfg, cat, "host");
32427                const char *username = ast_variable_retrieve(ucfg, cat, "username");
32428                const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
32429                const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
32430                const char *authuser = ast_variable_retrieve(ucfg, cat, "authuser");
32431                if (!host) {
32432                   host = ast_variable_retrieve(ucfg, "general", "host");
32433                }
32434                if (!username) {
32435                   username = ast_variable_retrieve(ucfg, "general", "username");
32436                }
32437                if (!secret) {
32438                   secret = ast_variable_retrieve(ucfg, "general", "secret");
32439                }
32440                if (!contact) {
32441                   contact = "s";
32442                }
32443                if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
32444                   if (!ast_strlen_zero(secret)) {
32445                      if (!ast_strlen_zero(authuser)) {
32446                         snprintf(tmp, sizeof(tmp), "%s?%s:%s:%s@%s/%s", cat, username, secret, authuser, host, contact);
32447                      } else {
32448                         snprintf(tmp, sizeof(tmp), "%s?%s:%s@%s/%s", cat, username, secret, host, contact);
32449                      }
32450                   } else if (!ast_strlen_zero(authuser)) {
32451                      snprintf(tmp, sizeof(tmp), "%s?%s::%s@%s/%s", cat, username, authuser, host, contact);
32452                   } else {
32453                      snprintf(tmp, sizeof(tmp), "%s?%s@%s/%s", cat, username, host, contact);
32454                   }
32455                   if (sip_register(tmp, 0) == 0) {
32456                      registry_count++;
32457                   }
32458                }
32459             }
32460          }
32461          cat = ast_category_browse(ucfg, cat);
32462       }
32463       ast_config_destroy(ucfg);
32464    }
32465 
32466    /* Load peers, users and friends */
32467    cat = NULL;
32468    while ( (cat = ast_category_browse(cfg, cat)) ) {
32469       const char *utype;
32470       if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
32471          continue;
32472       utype = ast_variable_retrieve(cfg, cat, "type");
32473       if (!utype) {
32474          ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
32475          continue;
32476       } else {
32477          if (!strcasecmp(utype, "user")) {
32478             ;
32479          } else if (!strcasecmp(utype, "friend")) {
32480             ;
32481          } else if (!strcasecmp(utype, "peer")) {
32482             ;
32483          } else {
32484             ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
32485             continue;
32486          }
32487          peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0, 0);
32488          if (peer) {
32489             display_nat_warning(cat, reason, &peer->flags[0]);
32490             ao2_t_link(peers, peer, "link peer into peers table");
32491             if ((peer->type & SIP_TYPE_PEER) && !ast_sockaddr_isnull(&peer->addr)) {
32492                ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
32493             }
32494             sip_unref_peer(peer, "unref the result of the build_peer call. Now, the links from the tables are the only ones left.");
32495             peer_count++;
32496          }
32497       }
32498    }
32499 
32500    /* Add default domains - host name, IP address and IP:port
32501     * Only do this if user added any sip domain with "localdomains"
32502     * In order to *not* break backwards compatibility
32503     *    Some phones address us at IP only, some with additional port number
32504     */
32505    if (auto_sip_domains) {
32506       char temp[MAXHOSTNAMELEN];
32507 
32508       /* First our default IP address */
32509       if (!ast_sockaddr_isnull(&bindaddr) && !ast_sockaddr_is_any(&bindaddr)) {
32510          add_sip_domain(ast_sockaddr_stringify_addr(&bindaddr),
32511                    SIP_DOMAIN_AUTO, NULL);
32512       } else if (!ast_sockaddr_isnull(&internip) && !ast_sockaddr_is_any(&internip)) {
32513       /* Our internal IP address, if configured */
32514          add_sip_domain(ast_sockaddr_stringify_addr(&internip),
32515                    SIP_DOMAIN_AUTO, NULL);
32516       } else {
32517          ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
32518       }
32519 
32520       /* If TCP is running on a different IP than UDP, then add it too */
32521       if (!ast_sockaddr_isnull(&sip_tcp_desc.local_address) &&
32522           !ast_sockaddr_cmp(&bindaddr, &sip_tcp_desc.local_address)) {
32523          add_sip_domain(ast_sockaddr_stringify_addr(&sip_tcp_desc.local_address),
32524                    SIP_DOMAIN_AUTO, NULL);
32525       }
32526 
32527       /* If TLS is running on a different IP than UDP and TCP, then add that too */
32528       if (!ast_sockaddr_isnull(&sip_tls_desc.local_address) &&
32529           !ast_sockaddr_cmp(&bindaddr, &sip_tls_desc.local_address) &&
32530           !ast_sockaddr_cmp(&sip_tcp_desc.local_address,
32531                   &sip_tls_desc.local_address)) {
32532          add_sip_domain(ast_sockaddr_stringify_addr(&sip_tcp_desc.local_address),
32533                    SIP_DOMAIN_AUTO, NULL);
32534       }
32535 
32536       /* Our extern IP address, if configured */
32537       if (!ast_sockaddr_isnull(&externaddr)) {
32538          add_sip_domain(ast_sockaddr_stringify_addr(&externaddr),
32539                    SIP_DOMAIN_AUTO, NULL);
32540       }
32541 
32542       /* Extern host name (NAT traversal support) */
32543       if (!ast_strlen_zero(externhost)) {
32544          add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
32545       }
32546       
32547       /* Our host name */
32548       if (!gethostname(temp, sizeof(temp))) {
32549          add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
32550       }
32551    }
32552 
32553    /* Release configuration from memory */
32554    ast_config_destroy(cfg);
32555 
32556    register_realtime_peers_with_callbackextens();
32557 
32558    /* Load the list of manual NOTIFY types to support */
32559    if (notify_types) {
32560       ast_config_destroy(notify_types);
32561    }
32562    if ((notify_types = ast_config_load(notify_config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
32563       ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed.\n", notify_config);
32564       notify_types = NULL;
32565    }
32566 
32567    /* Done, tell the manager */
32568    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);
32569    run_end = time(0);
32570    ast_debug(4, "SIP reload_config done...Runtime= %d sec\n", (int)(run_end-run_start));
32571 
32572    /* If an ACL change subscription is needed and doesn't exist, we need one. */
32573    if (acl_change_subscription_needed) {
32574       acl_change_event_subscribe();
32575    }
32576 
32577    return 0;
32578 }
32579 
32580 static int apply_directmedia_acl(struct sip_pvt *p, struct ast_acl_list *directmediaacl, const char *op)
32581 {
32582    struct ast_sockaddr us = { { 0, }, }, them = { { 0, }, };
32583    int res = AST_SENSE_ALLOW;
32584 
32585    ast_rtp_instance_get_remote_address(p->rtp, &them);
32586    ast_rtp_instance_get_local_address(p->rtp, &us);
32587 
32588    if ((res = ast_apply_acl(directmediaacl, &them, "SIP Direct Media ACL: ")) == AST_SENSE_DENY) {
32589       const char *us_addr = ast_strdupa(ast_sockaddr_stringify(&us));
32590       const char *them_addr = ast_strdupa(ast_sockaddr_stringify(&them));
32591 
32592       ast_debug(3, "Reinvite %s to %s denied by directmedia ACL on %s\n",
32593          op, them_addr, us_addr);
32594    }
32595 
32596    return res;
32597 }
32598 
32599 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan)
32600 {
32601    struct sip_pvt *p;
32602    struct ast_udptl *udptl = NULL;
32603    
32604    p = ast_channel_tech_pvt(chan);
32605    if (!p) {
32606       return NULL;
32607    }
32608 
32609    sip_pvt_lock(p);
32610    if (p->udptl && ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
32611       udptl = p->udptl;
32612    }
32613    sip_pvt_unlock(p);
32614    return udptl;
32615 }
32616 
32617 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl)
32618 {
32619    struct sip_pvt *p;
32620 
32621    /* Lock the channel and the private safely. */
32622    ast_channel_lock(chan);
32623    p = ast_channel_tech_pvt(chan);
32624    if (!p) {
32625       ast_channel_unlock(chan);
32626       return -1;
32627    }
32628    sip_pvt_lock(p);
32629    if (p->owner != chan) {
32630       /* I suppose it could be argued that if this happens it is a bug. */
32631       ast_debug(1, "The private is not owned by channel %s anymore.\n", ast_channel_name(chan));
32632       sip_pvt_unlock(p);
32633       ast_channel_unlock(chan);
32634       return 0;
32635    }
32636 
32637    if (udptl) {
32638       ast_udptl_get_peer(udptl, &p->udptlredirip);
32639    } else {
32640       memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
32641    }
32642    if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
32643       if (!p->pendinginvite) {
32644          ast_debug(3, "Sending reinvite on SIP '%s' - It's UDPTL soon redirected to IP %s\n",
32645                p->callid, ast_sockaddr_stringify(udptl ? &p->udptlredirip : &p->ourip));
32646          transmit_reinvite_with_sdp(p, TRUE, FALSE);
32647       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
32648          ast_debug(3, "Deferring reinvite on SIP '%s' - It's UDPTL will be redirected to IP %s\n",
32649                p->callid, ast_sockaddr_stringify(udptl ? &p->udptlredirip : &p->ourip));
32650          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
32651       }
32652    }
32653    /* Reset lastrtprx timer */
32654    p->lastrtprx = p->lastrtptx = time(NULL);
32655    sip_pvt_unlock(p);
32656    ast_channel_unlock(chan);
32657    return 0;
32658 }
32659 
32660 static int sip_allow_anyrtp_remote(struct ast_channel *chan1, struct ast_channel *chan2, char *rtptype)
32661 {
32662    struct sip_pvt *p1 = NULL, *p2 = NULL;
32663    struct ast_acl_list *p2_directmediaacl = NULL; /* opposed directmediaha for comparing against first channel host address */
32664    struct ast_acl_list *p1_directmediaacl = NULL; /* opposed directmediaha for comparing against second channel host address */
32665    int res = 1;
32666 
32667    if (!(p1 = ast_channel_tech_pvt(chan1))) {
32668       return 0;
32669    }
32670 
32671    if (!(p2 = ast_channel_tech_pvt(chan2))) {
32672       return 0;
32673    }
32674 
32675    sip_pvt_lock(p2);
32676    if (p2->relatedpeer && p2->relatedpeer->directmediaacl) {
32677       p2_directmediaacl = ast_duplicate_acl_list(p2->relatedpeer->directmediaacl);
32678    }
32679    sip_pvt_unlock(p2);
32680 
32681    sip_pvt_lock(p1);
32682    if (p1->relatedpeer && p1->relatedpeer->directmediaacl) {
32683       p1_directmediaacl = ast_duplicate_acl_list(p1->relatedpeer->directmediaacl);
32684    }
32685 
32686    if (p2_directmediaacl && ast_test_flag(&p1->flags[0], SIP_DIRECT_MEDIA)) {
32687       if (!apply_directmedia_acl(p1, p2_directmediaacl, rtptype)) {
32688          res = 0;
32689       }
32690    }
32691    sip_pvt_unlock(p1);
32692 
32693    if (res == 0) {
32694       goto allow_anyrtp_remote_end;
32695    }
32696 
32697    sip_pvt_lock(p2);
32698    if (p1_directmediaacl && ast_test_flag(&p2->flags[0], SIP_DIRECT_MEDIA)) {
32699       if (!apply_directmedia_acl(p2, p1_directmediaacl, rtptype)) {
32700          res = 0;
32701       }
32702    }
32703    sip_pvt_unlock(p2);
32704 
32705 allow_anyrtp_remote_end:
32706 
32707    if (p2_directmediaacl) {
32708       p2_directmediaacl = ast_free_acl_list(p2_directmediaacl);
32709    }
32710 
32711    if (p1_directmediaacl) {
32712       p1_directmediaacl = ast_free_acl_list(p1_directmediaacl);
32713    }
32714 
32715    return res;
32716 }
32717 
32718 static int sip_allow_rtp_remote(struct ast_channel *chan1, struct ast_channel *chan2)
32719 {
32720    return sip_allow_anyrtp_remote(chan1, chan2, "audio");
32721 }
32722 
32723 static int sip_allow_vrtp_remote(struct ast_channel *chan1, struct ast_channel *chan2)
32724 {
32725    return sip_allow_anyrtp_remote(chan1, chan2, "video");
32726 }
32727 
32728 static enum ast_rtp_glue_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
32729 {
32730    struct sip_pvt *p = NULL;
32731    enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_LOCAL;
32732 
32733    if (!(p = ast_channel_tech_pvt(chan))) {
32734       return AST_RTP_GLUE_RESULT_FORBID;
32735    }
32736 
32737    sip_pvt_lock(p);
32738    if (!(p->rtp)) {
32739       sip_pvt_unlock(p);
32740       return AST_RTP_GLUE_RESULT_FORBID;
32741    }
32742 
32743    ao2_ref(p->rtp, +1);
32744    *instance = p->rtp;
32745 
32746    if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
32747       res = AST_RTP_GLUE_RESULT_REMOTE;
32748    } else if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT)) {
32749       res = AST_RTP_GLUE_RESULT_REMOTE;
32750    } else if (ast_test_flag(&global_jbconf, AST_JB_FORCED)) {
32751       res = AST_RTP_GLUE_RESULT_FORBID;
32752    }
32753 
32754    if (p->srtp) {
32755       res = AST_RTP_GLUE_RESULT_FORBID;
32756    }
32757 
32758    sip_pvt_unlock(p);
32759 
32760    return res;
32761 }
32762 
32763 static enum ast_rtp_glue_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
32764 {
32765    struct sip_pvt *p = NULL;
32766    enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_FORBID;
32767 
32768    if (!(p = ast_channel_tech_pvt(chan))) {
32769       return AST_RTP_GLUE_RESULT_FORBID;
32770    }
32771 
32772    sip_pvt_lock(p);
32773    if (!(p->vrtp)) {
32774       sip_pvt_unlock(p);
32775       return AST_RTP_GLUE_RESULT_FORBID;
32776    }
32777 
32778    ao2_ref(p->vrtp, +1);
32779    *instance = p->vrtp;
32780 
32781    if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
32782       res = AST_RTP_GLUE_RESULT_REMOTE;
32783    }
32784 
32785    sip_pvt_unlock(p);
32786 
32787    return res;
32788 }
32789 
32790 static enum ast_rtp_glue_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
32791 {
32792    struct sip_pvt *p = NULL;
32793    enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_FORBID;
32794 
32795    if (!(p = ast_channel_tech_pvt(chan))) {
32796       return AST_RTP_GLUE_RESULT_FORBID;
32797    }
32798 
32799    sip_pvt_lock(p);
32800    if (!(p->trtp)) {
32801       sip_pvt_unlock(p);
32802       return AST_RTP_GLUE_RESULT_FORBID;
32803    }
32804 
32805    ao2_ref(p->trtp, +1);
32806    *instance = p->trtp;
32807 
32808    if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
32809       res = AST_RTP_GLUE_RESULT_REMOTE;
32810    }
32811 
32812    sip_pvt_unlock(p);
32813 
32814    return res;
32815 }
32816 
32817 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)
32818 {
32819    struct sip_pvt *p;
32820    int changed = 0;
32821 
32822    /* Lock the channel and the private safely. */
32823    ast_channel_lock(chan);
32824    p = ast_channel_tech_pvt(chan);
32825    if (!p) {
32826       ast_channel_unlock(chan);
32827       return -1;
32828    }
32829    sip_pvt_lock(p);
32830    if (p->owner != chan) {
32831       /* I suppose it could be argued that if this happens it is a bug. */
32832       ast_debug(1, "The private is not owned by channel %s anymore.\n", ast_channel_name(chan));
32833       sip_pvt_unlock(p);
32834       ast_channel_unlock(chan);
32835       return 0;
32836    }
32837 
32838    /* Disable early RTP bridge  */
32839    if ((instance || vinstance || tinstance) &&
32840       !ast_bridged_channel(chan) &&
32841       !sip_cfg.directrtpsetup) {
32842       sip_pvt_unlock(p);
32843       ast_channel_unlock(chan);
32844       return 0;
32845    }
32846 
32847    if (p->alreadygone) {
32848       /* If we're destroyed, don't bother */
32849       sip_pvt_unlock(p);
32850       ast_channel_unlock(chan);
32851       return 0;
32852    }
32853 
32854    /* if this peer cannot handle reinvites of the media stream to devices
32855       that are known to be behind a NAT, then stop the process now
32856    */
32857    if (nat_active && !ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT)) {
32858       sip_pvt_unlock(p);
32859       ast_channel_unlock(chan);
32860       return 0;
32861    }
32862 
32863    if (instance) {
32864       changed |= ast_rtp_instance_get_and_cmp_remote_address(instance, &p->redirip);
32865 
32866       if (p->rtp) {
32867          /* Prevent audio RTCP reads */
32868          ast_channel_set_fd(chan, 1, -1);
32869          /* Silence RTCP while audio RTP is inactive */
32870          ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 0);
32871       }
32872    } else if (!ast_sockaddr_isnull(&p->redirip)) {
32873       memset(&p->redirip, 0, sizeof(p->redirip));
32874       changed = 1;
32875 
32876       if (p->rtp) {
32877          /* Enable RTCP since it will be inactive if we're coming back
32878           * from a reinvite */
32879          ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 1);
32880          /* Enable audio RTCP reads */
32881          ast_channel_set_fd(chan, 1, ast_rtp_instance_fd(p->rtp, 1));
32882       }
32883    }
32884 
32885    if (vinstance) {
32886       changed |= ast_rtp_instance_get_and_cmp_remote_address(vinstance, &p->vredirip);
32887 
32888       if (p->vrtp) {
32889          /* Prevent video RTCP reads */
32890          ast_channel_set_fd(chan, 3, -1);
32891          /* Silence RTCP while video RTP is inactive */
32892          ast_rtp_instance_set_prop(p->vrtp, AST_RTP_PROPERTY_RTCP, 0);
32893       }
32894    } else if (!ast_sockaddr_isnull(&p->vredirip)) {
32895       memset(&p->vredirip, 0, sizeof(p->vredirip));
32896       changed = 1;
32897 
32898       if (p->vrtp) {
32899          /* Enable RTCP since it will be inactive if we're coming back
32900           * from a reinvite */
32901          ast_rtp_instance_set_prop(p->vrtp, AST_RTP_PROPERTY_RTCP, 1);
32902          /* Enable video RTCP reads */
32903          ast_channel_set_fd(chan, 3, ast_rtp_instance_fd(p->vrtp, 1));
32904       }
32905    }
32906 
32907    if (tinstance) {
32908       changed |= ast_rtp_instance_get_and_cmp_remote_address(tinstance, &p->tredirip);
32909    } else if (!ast_sockaddr_isnull(&p->tredirip)) {
32910       memset(&p->tredirip, 0, sizeof(p->tredirip));
32911       changed = 1;
32912    }
32913    if (cap && !ast_format_cap_is_empty(cap) && !ast_format_cap_identical(p->redircaps, cap)) {
32914       ast_format_cap_copy(p->redircaps, cap);
32915       changed = 1;
32916    }
32917 
32918    if (ast_test_flag(&p->flags[2], SIP_PAGE3_DIRECT_MEDIA_OUTGOING) && !p->outgoing_call) {
32919       /* We only wish to withhold sending the initial direct media reinvite on the incoming dialog.
32920        * Further direct media reinvites beyond the initial should be sent. In order to allow further
32921        * direct media reinvites to be sent, we clear this flag.
32922        */
32923       ast_clear_flag(&p->flags[2], SIP_PAGE3_DIRECT_MEDIA_OUTGOING);
32924       sip_pvt_unlock(p);
32925       ast_channel_unlock(chan);
32926       return 0;
32927    }
32928 
32929    if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER) && !ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
32930       if (ast_channel_state(chan) != AST_STATE_UP) {     /* We are in early state */
32931          if (p->do_history)
32932             append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
32933          ast_debug(1, "Early remote bridge setting SIP '%s' - Sending media to %s\n", p->callid, ast_sockaddr_stringify(instance ? &p->redirip : &p->ourip));
32934       } else if (!p->pendinginvite) {   /* We are up, and have no outstanding invite */
32935          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));
32936          transmit_reinvite_with_sdp(p, FALSE, FALSE);
32937       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
32938          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));
32939          /* We have a pending Invite. Send re-invite when we're done with the invite */
32940          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
32941       }
32942    }
32943    /* Reset lastrtprx timer */
32944    p->lastrtprx = p->lastrtptx = time(NULL);
32945    sip_pvt_unlock(p);
32946    ast_channel_unlock(chan);
32947    return 0;
32948 }
32949 
32950 static void sip_get_codec(struct ast_channel *chan, struct ast_format_cap *result)
32951 {
32952    struct sip_pvt *p = ast_channel_tech_pvt(chan);
32953    ast_format_cap_append(result, ast_format_cap_is_empty(p->peercaps) ? p->caps : p->peercaps);
32954 }
32955 
32956 static struct ast_rtp_glue sip_rtp_glue = {
32957    .type = "SIP",
32958    .get_rtp_info = sip_get_rtp_peer,
32959    .allow_rtp_remote = sip_allow_rtp_remote,
32960    .get_vrtp_info = sip_get_vrtp_peer,
32961    .allow_vrtp_remote = sip_allow_vrtp_remote,
32962    .get_trtp_info = sip_get_trtp_peer,
32963    .update_peer = sip_set_rtp_peer,
32964    .get_codec = sip_get_codec,
32965 };
32966 
32967 static char *app_dtmfmode = "SIPDtmfMode";
32968 static char *app_sipaddheader = "SIPAddHeader";
32969 static char *app_sipremoveheader = "SIPRemoveHeader";
32970 #ifdef TEST_FRAMEWORK
32971 static char *app_sipsendcustominfo = "SIPSendCustomINFO";
32972 #endif
32973 
32974 /*! \brief Set the DTMFmode for an outbound SIP call (application) */
32975 static int sip_dtmfmode(struct ast_channel *chan, const char *data)
32976 {
32977    struct sip_pvt *p;
32978    const char *mode = data;
32979 
32980    if (!data) {
32981       ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
32982       return 0;
32983    }
32984    ast_channel_lock(chan);
32985    if (!IS_SIP_TECH(ast_channel_tech(chan))) {
32986       ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
32987       ast_channel_unlock(chan);
32988       return 0;
32989    }
32990    p = ast_channel_tech_pvt(chan);
32991    if (!p) {
32992       ast_channel_unlock(chan);
32993       return 0;
32994    }
32995    sip_pvt_lock(p);
32996    if (!strcasecmp(mode, "info")) {
32997       ast_clear_flag(&p->flags[0], SIP_DTMF);
32998       ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
32999       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
33000    } else if (!strcasecmp(mode, "shortinfo")) {
33001       ast_clear_flag(&p->flags[0], SIP_DTMF);
33002       ast_set_flag(&p->flags[0], SIP_DTMF_SHORTINFO);
33003       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
33004    } else if (!strcasecmp(mode, "rfc2833")) {
33005       ast_clear_flag(&p->flags[0], SIP_DTMF);
33006       ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
33007       p->jointnoncodeccapability |= AST_RTP_DTMF;
33008    } else if (!strcasecmp(mode, "inband")) {
33009       ast_clear_flag(&p->flags[0], SIP_DTMF);
33010       ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
33011       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
33012    } else {
33013       ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n", mode);
33014    }
33015    if (p->rtp)
33016       ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
33017    if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
33018        (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
33019       enable_dsp_detect(p);
33020    } else {
33021       disable_dsp_detect(p);
33022    }
33023    sip_pvt_unlock(p);
33024    ast_channel_unlock(chan);
33025    return 0;
33026 }
33027 
33028 /*! \brief Add a SIP header to an outbound INVITE */
33029 static int sip_addheader(struct ast_channel *chan, const char *data)
33030 {
33031    int no = 0;
33032    int ok = FALSE;
33033    char varbuf[30];
33034    const char *inbuf = data;
33035    char *subbuf;
33036    
33037    if (ast_strlen_zero(inbuf)) {
33038       ast_log(LOG_WARNING, "This application requires the argument: Header\n");
33039       return 0;
33040    }
33041    ast_channel_lock(chan);
33042 
33043    /* Check for headers */
33044    while (!ok && no <= 50) {
33045       no++;
33046       snprintf(varbuf, sizeof(varbuf), "__SIPADDHEADER%.2d", no);
33047 
33048       /* Compare without the leading underscores */
33049       if ((pbx_builtin_getvar_helper(chan, (const char *) varbuf + 2) == (const char *) NULL)) {
33050          ok = TRUE;
33051       }
33052    }
33053    if (ok) {
33054       size_t len = strlen(inbuf);
33055       subbuf = ast_alloca(len + 1);
33056       ast_get_encoded_str(inbuf, subbuf, len + 1);
33057       pbx_builtin_setvar_helper(chan, varbuf, subbuf);
33058       if (sipdebug) {
33059          ast_debug(1, "SIP Header added \"%s\" as %s\n", inbuf, varbuf);
33060       }
33061    } else {
33062       ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
33063    }
33064    ast_channel_unlock(chan);
33065    return 0;
33066 }
33067 
33068 /*! \brief Remove SIP headers added previously with SipAddHeader application */
33069 static int sip_removeheader(struct ast_channel *chan, const char *data)
33070 {
33071    struct ast_var_t *newvariable;
33072    struct varshead *headp;
33073    int removeall = 0;
33074    char *inbuf = (char *) data;
33075 
33076    if (ast_strlen_zero(inbuf)) {
33077       removeall = 1;
33078    }
33079    ast_channel_lock(chan);
33080 
33081    headp=ast_channel_varshead(chan);
33082    AST_LIST_TRAVERSE_SAFE_BEGIN (headp, newvariable, entries) {
33083       if (strncasecmp(ast_var_name(newvariable), "SIPADDHEADER", strlen("SIPADDHEADER")) == 0) {
33084          if (removeall || (!strncasecmp(ast_var_value(newvariable),inbuf,strlen(inbuf)))) {
33085             if (sipdebug) {
33086                ast_debug(1,"removing SIP Header \"%s\" as %s\n",
33087                   ast_var_value(newvariable),
33088                   ast_var_name(newvariable));
33089             }
33090             AST_LIST_REMOVE_CURRENT(entries);
33091             ast_var_delete(newvariable);
33092          }
33093       }
33094    }
33095    AST_LIST_TRAVERSE_SAFE_END;
33096 
33097    ast_channel_unlock(chan);
33098    return 0;
33099 }
33100 
33101 #ifdef TEST_FRAMEWORK
33102 /*! \brief Send a custom INFO message via AST_CONTROL_CUSTOM indication */
33103 static int sip_sendcustominfo(struct ast_channel *chan, const char *data)
33104 {
33105    char *info_data, *useragent;
33106 
33107    if (ast_strlen_zero(data)) {
33108       ast_log(LOG_WARNING, "You must provide data to be sent\n");
33109       return 0;
33110    }
33111 
33112    useragent = ast_strdupa(data);
33113    info_data = strsep(&useragent, ",");
33114 
33115    if (ast_sipinfo_send(chan, NULL, "text/plain", info_data, useragent)) {
33116       ast_log(LOG_WARNING, "Failed to create payload for custom SIP INFO\n");
33117       return 0;
33118    }
33119    return 0;
33120 }
33121 #endif
33122 
33123 /*! \brief Transfer call before connect with a 302 redirect
33124 \note Called by the transfer() dialplan application through the sip_transfer()
33125    pbx interface function if the call is in ringing state
33126 \todo Fix this function so that we wait for reply to the REFER and
33127    react to errors, denials or other issues the other end might have.
33128  */
33129 static int sip_sipredirect(struct sip_pvt *p, const char *dest)
33130 {
33131    char *cdest;
33132    char *extension, *domain;
33133 
33134    cdest = ast_strdupa(dest);
33135 
33136    extension = strsep(&cdest, "@");
33137    domain = cdest;
33138    if (ast_strlen_zero(extension)) {
33139       ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
33140       return 0;
33141    }
33142 
33143    /* we'll issue the redirect message here */
33144    if (!domain) {
33145       char *local_to_header;
33146       char to_header[256];
33147 
33148       ast_copy_string(to_header, sip_get_header(&p->initreq, "To"), sizeof(to_header));
33149       if (ast_strlen_zero(to_header)) {
33150          ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
33151          return 0;
33152       }
33153       if (((local_to_header = strcasestr(to_header, "sip:")) || (local_to_header = strcasestr(to_header, "sips:")))
33154          && (local_to_header = strchr(local_to_header, '@'))) {
33155          char ldomain[256];
33156 
33157          memset(ldomain, 0, sizeof(ldomain));
33158          local_to_header++;
33159          /* This is okey because lhost and lport are as big as tmp */
33160          sscanf(local_to_header, "%256[^<>; ]", ldomain);
33161          if (ast_strlen_zero(ldomain)) {
33162             ast_log(LOG_ERROR, "Can't find the host address\n");
33163             return 0;
33164          }
33165          domain = ast_strdupa(ldomain);
33166       }
33167    }
33168 
33169    ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s>", extension, domain);
33170    transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);
33171 
33172    sip_scheddestroy(p, SIP_TRANS_TIMEOUT);   /* Make sure we stop send this reply. */
33173    sip_alreadygone(p);
33174 
33175    if (p->owner) {
33176       enum ast_control_transfer message = AST_TRANSFER_SUCCESS;
33177       ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
33178    }
33179    /* hangup here */
33180    return 0;
33181 }
33182 
33183 static int sip_is_xml_parsable(void)
33184 {
33185 #ifdef HAVE_LIBXML2
33186    return TRUE;
33187 #else
33188    return FALSE;
33189 #endif
33190 }
33191 
33192 /*! \brief Send a poke to all known peers */
33193 static void sip_poke_all_peers(void)
33194 {
33195    int ms = 0, num = 0;
33196    struct ao2_iterator i;
33197    struct sip_peer *peer;
33198 
33199    if (!speerobjs) { /* No peers, just give up */
33200       return;
33201    }
33202 
33203    i = ao2_iterator_init(peers, 0);
33204    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
33205       ao2_lock(peer);
33206       /* Don't schedule poking on a peer without qualify */
33207       if (peer->maxms) {
33208          if (num == global_qualify_peers) {
33209             ms += global_qualify_gap;
33210             num = 0;
33211          } else {
33212             num++;
33213          }
33214          AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ms, sip_poke_peer_s, peer,
33215                sip_unref_peer(_data, "removing poke peer ref"),
33216                sip_unref_peer(peer, "removing poke peer ref"),
33217                sip_ref_peer(peer, "adding poke peer ref"));
33218       }
33219       ao2_unlock(peer);
33220       sip_unref_peer(peer, "toss iterator peer ptr");
33221    }
33222    ao2_iterator_destroy(&i);
33223 }
33224 
33225 /*! \brief Send a keepalive to all known peers */
33226 static void sip_keepalive_all_peers(void)
33227 {
33228    struct ao2_iterator i;
33229    struct sip_peer *peer;
33230 
33231    if (!speerobjs) {       /* No peers, just give up */
33232       return;
33233    }
33234 
33235    i = ao2_iterator_init(peers, 0);
33236    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
33237       ao2_lock(peer);
33238       AST_SCHED_REPLACE_UNREF(peer->keepalivesend, sched, 0, sip_send_keepalive, peer,
33239                sip_unref_peer(_data, "removing poke peer ref"),
33240                sip_unref_peer(peer, "removing poke peer ref"),
33241                sip_ref_peer(peer, "adding poke peer ref"));
33242       ao2_unlock(peer);
33243       sip_unref_peer(peer, "toss iterator peer ptr");
33244    }
33245    ao2_iterator_destroy(&i);
33246 }
33247 
33248 /*! \brief Send all known registrations */
33249 static void sip_send_all_registers(void)
33250 {
33251    int ms;
33252    int regspacing;
33253    if (!regobjs) {
33254       return;
33255    }
33256    regspacing = default_expiry * 1000/regobjs;
33257    if (regspacing > 100) {
33258       regspacing = 100;
33259    }
33260    ms = regspacing;
33261    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
33262       ASTOBJ_WRLOCK(iterator);
33263       ms += regspacing;
33264       AST_SCHED_REPLACE_UNREF(iterator->expire, sched, ms, sip_reregister, iterator,
33265                         registry_unref(_data, "REPLACE sched del decs the refcount"),
33266                         registry_unref(iterator, "REPLACE sched add failure decs the refcount"),
33267                         registry_addref(iterator, "REPLACE sched add incs the refcount"));
33268       ASTOBJ_UNLOCK(iterator);
33269    } while (0)
33270    );
33271 }
33272 
33273 /*! \brief Send all MWI subscriptions */
33274 static void sip_send_all_mwi_subscriptions(void)
33275 {
33276    ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
33277       struct sip_subscription_mwi *saved;
33278       ASTOBJ_WRLOCK(iterator);
33279       AST_SCHED_DEL(sched, iterator->resub);
33280       saved = ASTOBJ_REF(iterator);
33281       if ((iterator->resub = ast_sched_add(sched, 1, sip_subscribe_mwi_do, saved)) < 0) {
33282          ASTOBJ_UNREF(saved, sip_subscribe_mwi_destroy);
33283       }
33284       ASTOBJ_UNLOCK(iterator);
33285    } while (0));
33286 }
33287 
33288 /* SRTP */
33289 static int setup_srtp(struct sip_srtp **srtp)
33290 {
33291    if (!ast_rtp_engine_srtp_is_registered()) {
33292       ast_log(LOG_ERROR, "No SRTP module loaded, can't setup SRTP session.\n");
33293       return -1;
33294    }
33295 
33296    if (!(*srtp = sip_srtp_alloc())) { /* Allocate SRTP data structure */
33297       return -1;
33298    }
33299 
33300    return 0;
33301 }
33302 
33303 static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct sip_srtp **srtp, const char *a)
33304 {
33305    struct ast_rtp_engine_dtls *dtls;
33306 
33307    /* If no RTP instance exists for this media stream don't bother processing the crypto line */
33308    if (!rtp) {
33309       ast_debug(3, "Received offer with crypto line for media stream that is not enabled\n");
33310       return FALSE;
33311    }
33312 
33313    if (strncasecmp(a, "crypto:", 7)) {
33314       return FALSE;
33315    }
33316    if (!*srtp) {
33317       if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
33318          ast_log(LOG_WARNING, "Ignoring unexpected crypto attribute in SDP answer\n");
33319          return FALSE;
33320       }
33321 
33322       if (setup_srtp(srtp) < 0) {
33323          return FALSE;
33324       }
33325    }
33326 
33327    if (!(*srtp)->crypto && !((*srtp)->crypto = sdp_crypto_setup())) {
33328       return FALSE;
33329    }
33330 
33331    if (sdp_crypto_process((*srtp)->crypto, a, rtp, *srtp) < 0) {
33332       return FALSE;
33333    }
33334 
33335    ast_set_flag(*srtp, SRTP_CRYPTO_OFFER_OK);
33336 
33337    if ((dtls = ast_rtp_instance_get_dtls(rtp))) {
33338       dtls->stop(rtp);
33339       p->dtls_cfg.enabled = 0;
33340    }
33341 
33342    return TRUE;
33343 }
33344 
33345 /*! \brief Reload module */
33346 static int sip_do_reload(enum channelreloadreason reason)
33347 {
33348    time_t start_poke, end_poke;
33349 
33350    reload_config(reason);
33351    ast_sched_dump(sched);
33352 
33353    start_poke = time(0);
33354    /* Prune peers who still are supposed to be deleted */
33355    unlink_marked_peers_from_tables();
33356 
33357    ast_debug(4, "--------------- Done destroying pruned peers\n");
33358 
33359    /* Send qualify (OPTIONS) to all peers */
33360    sip_poke_all_peers();
33361 
33362    /* Send keepalive to all peers */
33363    sip_keepalive_all_peers();
33364 
33365    /* Register with all services */
33366    sip_send_all_registers();
33367 
33368    sip_send_all_mwi_subscriptions();
33369 
33370    end_poke = time(0);
33371 
33372    ast_debug(4, "do_reload finished. peer poke/prune reg contact time = %d sec.\n", (int)(end_poke-start_poke));
33373 
33374    ast_debug(4, "--------------- SIP reload done\n");
33375 
33376    return 0;
33377 }
33378 
33379 /*! \brief Force reload of module from cli */
33380 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
33381 {
33382    static struct sip_peer *tmp_peer, *new_peer;
33383 
33384    switch (cmd) {
33385    case CLI_INIT:
33386       e->command = "sip reload";
33387       e->usage =
33388          "Usage: sip reload\n"
33389          "       Reloads SIP configuration from sip.conf\n";
33390       return NULL;
33391    case CLI_GENERATE:
33392       return NULL;
33393    }
33394 
33395    ast_mutex_lock(&sip_reload_lock);
33396    if (sip_reloading) {
33397       ast_verbose("Previous SIP reload not yet done\n");
33398    } else {
33399       sip_reloading = TRUE;
33400       sip_reloadreason = (a && a->fd) ? CHANNEL_CLI_RELOAD : CHANNEL_MODULE_RELOAD;
33401    }
33402    ast_mutex_unlock(&sip_reload_lock);
33403    restart_monitor();
33404 
33405    tmp_peer = bogus_peer;
33406    /* Create new bogus peer possibly with new global settings. */
33407    if ((new_peer = temp_peer("(bogus_peer)"))) {
33408       ast_string_field_set(new_peer, md5secret, BOGUS_PEER_MD5SECRET);
33409       ast_clear_flag(&new_peer->flags[0], SIP_INSECURE);
33410       bogus_peer = new_peer;
33411       ao2_t_ref(tmp_peer, -1, "unref the old bogus_peer during reload");
33412    } else {
33413       ast_log(LOG_ERROR, "Could not update the fake authentication peer.\n");
33414       /* You probably have bigger (memory?) issues to worry about though.. */
33415    }
33416 
33417    return CLI_SUCCESS;
33418 }
33419 
33420 /*! \brief  Part of Asterisk module interface */
33421 static int reload(void)
33422 {
33423    if (sip_reload(0, 0, NULL)) {
33424       return 0;
33425    }
33426    return 1;
33427 }
33428 
33429 /*! \brief  Return the first entry from ast_sockaddr_resolve filtered by address family
33430  *
33431  * \warn Using this function probably means you have a faulty design.
33432  */
33433 static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
33434                   const char* name, int flag, int family)
33435 {
33436    struct ast_sockaddr *addrs;
33437    int addrs_cnt;
33438 
33439    addrs_cnt = ast_sockaddr_resolve(&addrs, name, flag, family);
33440    if (addrs_cnt <= 0) {
33441       return 1;
33442    }
33443    if (addrs_cnt > 1) {
33444       ast_debug(1, "Multiple addresses, using the first one only\n");
33445    }
33446 
33447    ast_sockaddr_copy(addr, &addrs[0]);
33448 
33449    ast_free(addrs);
33450    return 0;
33451 }
33452 
33453 /*! \brief  Return the first entry from ast_sockaddr_resolve filtered by family of binddaddr
33454  *
33455  * \warn Using this function probably means you have a faulty design.
33456  */
33457 static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
33458                   const char* name, int flag)
33459 {
33460    return ast_sockaddr_resolve_first_af(addr, name, flag, get_address_family_filter(SIP_TRANSPORT_UDP));
33461 }
33462 
33463 /*! \brief  Return the first entry from ast_sockaddr_resolve filtered by family of binddaddr
33464  *
33465  * \warn Using this function probably means you have a faulty design.
33466  */
33467 static int ast_sockaddr_resolve_first_transport(struct ast_sockaddr *addr,
33468                   const char* name, int flag, unsigned int transport)
33469 {
33470         return ast_sockaddr_resolve_first_af(addr, name, flag, get_address_family_filter(transport));
33471 }
33472 
33473 /*! \brief
33474  * \note The only member of the peer used here is the name field
33475  */
33476 static int peer_hash_cb(const void *obj, const int flags)
33477 {
33478    const struct sip_peer *peer = obj;
33479 
33480    return ast_str_case_hash(peer->name);
33481 }
33482 
33483 /*!
33484  * \note The only member of the peer used here is the name field
33485  */
33486 static int peer_cmp_cb(void *obj, void *arg, int flags)
33487 {
33488    struct sip_peer *peer = obj, *peer2 = arg;
33489 
33490    return !strcasecmp(peer->name, peer2->name) ? CMP_MATCH | CMP_STOP : 0;
33491 }
33492 
33493 /*!
33494  * Hash function based on the the peer's ip address.  For IPv6, we use the end
33495  * of the address.
33496  * \todo Find a better hashing function
33497  */
33498 static int peer_iphash_cb(const void *obj, const int flags)
33499 {
33500    const struct sip_peer *peer = obj;
33501    int ret = 0;
33502 
33503    if (ast_sockaddr_isnull(&peer->addr)) {
33504       ast_log(LOG_ERROR, "Empty address\n");
33505    }
33506 
33507    ret = ast_sockaddr_hash(&peer->addr);
33508 
33509    if (ret < 0) {
33510       ret = -ret;
33511    }
33512 
33513    return ret;
33514 }
33515 
33516 /*!
33517  * Match Peers by IP and Port number.
33518  *
33519  * This function has two modes.
33520  *  - If the peer arg does not have INSECURE_PORT set, then we will only return
33521  *    a match for a peer that matches both the IP and port.
33522  *  - If the peer arg does have the INSECURE_PORT flag set, then we will only
33523  *    return a match for a peer that matches the IP and has insecure=port
33524  *    in its configuration.
33525  *
33526  * This callback will be used twice when doing peer matching.  There is a first
33527  * pass for full IP+port matching, and a second pass in case there is a match
33528  * that meets the insecure=port criteria.
33529  *
33530  * \note Connections coming in over TCP or TLS should never be matched by port.
33531  *
33532  * \note the peer's addr struct provides to fields combined to make a key: the sin_addr.s_addr and sin_port fields.
33533  */
33534 static int peer_ipcmp_cb_full(void *obj, void *arg, void *data, int flags)
33535 {
33536    struct sip_peer *peer = obj, *peer2 = arg;
33537    char *callback = data;
33538 
33539    if (!ast_strlen_zero(callback) && strcasecmp(peer->callback, callback)) {
33540       /* We require a callback extension match, but don't have one */
33541       return 0;
33542    }
33543 
33544    /* At this point, we match the callback extension if we need to. Carry on. */
33545 
33546    if (ast_sockaddr_cmp_addr(&peer->addr, &peer2->addr)) {
33547       /* IP doesn't match */
33548       return 0;
33549    }
33550 
33551    /* We matched the IP, check to see if we need to match by port as well. */
33552    if ((peer->transports & peer2->transports) & (SIP_TRANSPORT_TLS | SIP_TRANSPORT_TCP)) {
33553       /* peer matching on port is not possible with TCP/TLS */
33554       return CMP_MATCH | CMP_STOP;
33555    } else if (ast_test_flag(&peer2->flags[0], SIP_INSECURE_PORT)) {
33556       /* We are allowing match without port for peers configured that
33557        * way in this pass through the peers. */
33558       return ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT) ?
33559             (CMP_MATCH | CMP_STOP) : 0;
33560    }
33561 
33562    /* Now only return a match if the port matches, as well. */
33563    return ast_sockaddr_port(&peer->addr) == ast_sockaddr_port(&peer2->addr) ?
33564          (CMP_MATCH | CMP_STOP) : 0;
33565 }
33566 
33567 static int peer_ipcmp_cb(void *obj, void *arg, int flags)
33568 {
33569    return peer_ipcmp_cb_full(obj, arg, NULL, flags);
33570 }
33571 
33572 static int threadt_hash_cb(const void *obj, const int flags)
33573 {
33574    const struct sip_threadinfo *th = obj;
33575 
33576    return ast_sockaddr_hash(&th->tcptls_session->remote_address);
33577 }
33578 
33579 static int threadt_cmp_cb(void *obj, void *arg, int flags)
33580 {
33581    struct sip_threadinfo *th = obj, *th2 = arg;
33582 
33583    return (th->tcptls_session == th2->tcptls_session) ? CMP_MATCH | CMP_STOP : 0;
33584 }
33585 
33586 /*!
33587  * \note The only member of the dialog used here callid string
33588  */
33589 static int dialog_hash_cb(const void *obj, const int flags)
33590 {
33591    const struct sip_pvt *pvt = obj;
33592 
33593    return ast_str_case_hash(pvt->callid);
33594 }
33595 
33596 /*!
33597  * \note Same as dialog_cmp_cb, except without the CMP_STOP on match
33598  */
33599 static int dialog_find_multiple(void *obj, void *arg, int flags)
33600 {
33601    struct sip_pvt *pvt = obj, *pvt2 = arg;
33602 
33603    return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH : 0;
33604 }
33605 
33606 /*!
33607  * \note The only member of the dialog used here callid string
33608  */
33609 static int dialog_cmp_cb(void *obj, void *arg, int flags)
33610 {
33611    struct sip_pvt *pvt = obj, *pvt2 = arg;
33612 
33613    return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH | CMP_STOP : 0;
33614 }
33615 
33616 /*! \brief SIP Cli commands definition */
33617 static struct ast_cli_entry cli_sip[] = {
33618    AST_CLI_DEFINE(sip_show_channels, "List active SIP channels or subscriptions"),
33619    AST_CLI_DEFINE(sip_show_channelstats, "List statistics for active SIP channels"),
33620    AST_CLI_DEFINE(sip_show_domains, "List our local SIP domains"),
33621    AST_CLI_DEFINE(sip_show_inuse, "List all inuse/limits"),
33622    AST_CLI_DEFINE(sip_show_objects, "List all SIP object allocations"),
33623    AST_CLI_DEFINE(sip_show_peers, "List defined SIP peers"),
33624    AST_CLI_DEFINE(sip_show_registry, "List SIP registration status"),
33625    AST_CLI_DEFINE(sip_unregister, "Unregister (force expiration) a SIP peer from the registry"),
33626    AST_CLI_DEFINE(sip_show_settings, "Show SIP global settings"),
33627    AST_CLI_DEFINE(sip_show_mwi, "Show MWI subscriptions"),
33628    AST_CLI_DEFINE(sip_cli_notify, "Send a notify packet to a SIP peer"),
33629    AST_CLI_DEFINE(sip_show_channel, "Show detailed SIP channel info"),
33630    AST_CLI_DEFINE(sip_show_history, "Show SIP dialog history"),
33631    AST_CLI_DEFINE(sip_show_peer, "Show details on specific SIP peer"),
33632    AST_CLI_DEFINE(sip_show_users, "List defined SIP users"),
33633    AST_CLI_DEFINE(sip_show_user, "Show details on specific SIP user"),
33634    AST_CLI_DEFINE(sip_qualify_peer, "Send an OPTIONS packet to a peer"),
33635    AST_CLI_DEFINE(sip_show_sched, "Present a report on the status of the scheduler queue"),
33636    AST_CLI_DEFINE(sip_prune_realtime, "Prune cached Realtime users/peers"),
33637    AST_CLI_DEFINE(sip_do_debug, "Enable/Disable SIP debugging"),
33638    AST_CLI_DEFINE(sip_set_history, "Enable/Disable SIP history"),
33639    AST_CLI_DEFINE(sip_reload, "Reload SIP configuration"),
33640    AST_CLI_DEFINE(sip_show_tcp, "List TCP Connections")
33641 };
33642 
33643 /*! \brief SIP test registration */
33644 static void sip_register_tests(void)
33645 {
33646    sip_config_parser_register_tests();
33647    sip_request_parser_register_tests();
33648    sip_dialplan_function_register_tests();
33649 }
33650 
33651 /*! \brief SIP test registration */
33652 static void sip_unregister_tests(void)
33653 {
33654    sip_config_parser_unregister_tests();
33655    sip_request_parser_unregister_tests();
33656    sip_dialplan_function_unregister_tests();
33657 }
33658 
33659 #ifdef TEST_FRAMEWORK
33660 AST_TEST_DEFINE(test_sip_mwi_subscribe_parse)
33661 {
33662    int found = 0;
33663    enum ast_test_result_state res = AST_TEST_PASS;
33664    const char *mwi1 = "1234@mysipprovider.com/1234";
33665    const char *mwi2 = "1234:password@mysipprovider.com/1234";
33666    const char *mwi3 = "1234:password@mysipprovider.com:5061/1234";
33667    const char *mwi4 = "1234:password:authuser@mysipprovider.com/1234";
33668    const char *mwi5 = "1234:password:authuser@mysipprovider.com:5061/1234";
33669    const char *mwi6 = "1234:password";
33670 
33671    switch (cmd) {
33672    case TEST_INIT:
33673       info->name = "sip_mwi_subscribe_parse_test";
33674       info->category = "/channels/chan_sip/";
33675       info->summary = "SIP MWI subscribe line parse unit test";
33676       info->description =
33677          "Tests the parsing of mwi subscription lines (e.g., mwi => from sip.conf)";
33678       return AST_TEST_NOT_RUN;
33679    case TEST_EXECUTE:
33680       break;
33681    }
33682 
33683    if (sip_subscribe_mwi(mwi1, 1)) {
33684       res = AST_TEST_FAIL;
33685    } else {
33686       found = 0;
33687       res = AST_TEST_FAIL;
33688       ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
33689          ASTOBJ_WRLOCK(iterator);
33690          if (
33691             !strcmp(iterator->hostname, "mysipprovider.com") &&
33692             !strcmp(iterator->username, "1234") &&
33693             !strcmp(iterator->secret, "") &&
33694             !strcmp(iterator->authuser, "") &&
33695             !strcmp(iterator->mailbox, "1234") &&
33696             iterator->portno == 0) {
33697             found = 1;
33698             res = AST_TEST_PASS;
33699          }
33700          ASTOBJ_UNLOCK(iterator);
33701       } while(0));
33702       if (!found) {
33703          ast_test_status_update(test, "sip_subscribe_mwi test 1 failed\n");
33704       }
33705    }
33706 
33707    if (sip_subscribe_mwi(mwi2, 1)) {
33708       res = AST_TEST_FAIL;
33709    } else {
33710       found = 0;
33711       res = AST_TEST_FAIL;
33712       ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
33713          ASTOBJ_WRLOCK(iterator);
33714          if (
33715             !strcmp(iterator->hostname, "mysipprovider.com") &&
33716             !strcmp(iterator->username, "1234") &&
33717             !strcmp(iterator->secret, "password") &&
33718             !strcmp(iterator->authuser, "") &&
33719             !strcmp(iterator->mailbox, "1234") &&
33720             iterator->portno == 0) {
33721             found = 1;
33722             res = AST_TEST_PASS;
33723          }
33724          ASTOBJ_UNLOCK(iterator);
33725       } while(0));
33726       if (!found) {
33727          ast_test_status_update(test, "sip_subscribe_mwi test 2 failed\n");
33728       }
33729    }
33730 
33731    if (sip_subscribe_mwi(mwi3, 1)) {
33732       res = AST_TEST_FAIL;
33733    } else {
33734       found = 0;
33735       res = AST_TEST_FAIL;
33736       ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
33737          ASTOBJ_WRLOCK(iterator);
33738          if (
33739             !strcmp(iterator->hostname, "mysipprovider.com") &&
33740             !strcmp(iterator->username, "1234") &&
33741             !strcmp(iterator->secret, "password") &&
33742             !strcmp(iterator->authuser, "") &&
33743             !strcmp(iterator->mailbox, "1234") &&
33744             iterator->portno == 5061) {
33745             found = 1;
33746             res = AST_TEST_PASS;
33747          }
33748          ASTOBJ_UNLOCK(iterator);
33749       } while(0));
33750       if (!found) {
33751          ast_test_status_update(test, "sip_subscribe_mwi test 3 failed\n");
33752       }
33753    }
33754 
33755    if (sip_subscribe_mwi(mwi4, 1)) {
33756       res = AST_TEST_FAIL;
33757    } else {
33758       found = 0;
33759       res = AST_TEST_FAIL;
33760       ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
33761          ASTOBJ_WRLOCK(iterator);
33762          if (
33763             !strcmp(iterator->hostname, "mysipprovider.com") &&
33764             !strcmp(iterator->username, "1234") &&
33765             !strcmp(iterator->secret, "password") &&
33766             !strcmp(iterator->authuser, "authuser") &&
33767             !strcmp(iterator->mailbox, "1234") &&
33768             iterator->portno == 0) {
33769             found = 1;
33770             res = AST_TEST_PASS;
33771          }
33772          ASTOBJ_UNLOCK(iterator);
33773       } while(0));
33774       if (!found) {
33775          ast_test_status_update(test, "sip_subscribe_mwi test 4 failed\n");
33776       }
33777    }
33778 
33779    if (sip_subscribe_mwi(mwi5, 1)) {
33780       res = AST_TEST_FAIL;
33781    } else {
33782       found = 0;
33783       res = AST_TEST_FAIL;
33784       ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
33785          ASTOBJ_WRLOCK(iterator);
33786          if (
33787             !strcmp(iterator->hostname, "mysipprovider.com") &&
33788             !strcmp(iterator->username, "1234") &&
33789             !strcmp(iterator->secret, "password") &&
33790             !strcmp(iterator->authuser, "authuser") &&
33791             !strcmp(iterator->mailbox, "1234") &&
33792             iterator->portno == 5061) {
33793             found = 1;
33794             res = AST_TEST_PASS;
33795          }
33796          ASTOBJ_UNLOCK(iterator);
33797       } while(0));
33798       if (!found) {
33799          ast_test_status_update(test, "sip_subscribe_mwi test 5 failed\n");
33800       }
33801    }
33802    
33803    if (sip_subscribe_mwi(mwi6, 1)) {
33804       res = AST_TEST_PASS;
33805    } else {
33806       res = AST_TEST_FAIL;
33807    }
33808    return res;
33809 }
33810 
33811 AST_TEST_DEFINE(test_sip_peers_get)
33812 {
33813    struct sip_peer *peer;
33814    struct ast_data *node;
33815    struct ast_data_query query = {
33816       .path = "/asterisk/channel/sip/peers",
33817       .search = "peers/peer/name=test_peer_data_provider"
33818    };
33819 
33820    switch (cmd) {
33821       case TEST_INIT:
33822          info->name = "sip_peers_get_data_test";
33823          info->category = "/main/data/sip/peers/";
33824          info->summary = "SIP peers data providers unit test";
33825          info->description =
33826             "Tests whether the SIP peers data provider implementation works as expected.";
33827          return AST_TEST_NOT_RUN;
33828       case TEST_EXECUTE:
33829          break;
33830    }
33831 
33832    /* Create the peer that we will retrieve. */
33833    peer = build_peer("test_peer_data_provider", NULL, NULL, 0, 0);
33834    if (!peer) {
33835       return AST_TEST_FAIL;
33836    }
33837    peer->type = SIP_TYPE_USER;
33838    peer->call_limit = 10;
33839    ao2_link(peers, peer);
33840 
33841    /* retrieve the chan_sip/peers tree and check the created peer. */
33842    node = ast_data_get(&query);
33843    if (!node) {
33844       ao2_unlink(peers, peer);
33845       ao2_ref(peer, -1);
33846       return AST_TEST_FAIL;
33847    }
33848 
33849    /* compare item. */
33850    if (strcmp(ast_data_retrieve_string(node, "peer/name"), "test_peer_data_provider")) {
33851       ao2_unlink(peers, peer);
33852       ao2_ref(peer, -1);
33853       ast_data_free(node);
33854       return AST_TEST_FAIL;
33855    }
33856 
33857    if (strcmp(ast_data_retrieve_string(node, "peer/type"), "user")) {
33858       ao2_unlink(peers, peer);
33859       ao2_ref(peer, -1);
33860       ast_data_free(node);
33861       return AST_TEST_FAIL;
33862    }
33863 
33864    if (ast_data_retrieve_int(node, "peer/call_limit") != 10) {
33865       ao2_unlink(peers, peer);
33866       ao2_ref(peer, -1);
33867       ast_data_free(node);
33868       return AST_TEST_FAIL;
33869    }
33870 
33871    /* release resources */
33872    ast_data_free(node);
33873 
33874    ao2_unlink(peers, peer);
33875    ao2_ref(peer, -1);
33876 
33877    return AST_TEST_PASS;
33878 }
33879 
33880 /*!
33881  * \brief Imitation TCP reception loop
33882  *
33883  * This imitates the logic used by SIP's TCP code. Its purpose
33884  * is to either
33885  * 1) Combine fragments into a single message
33886  * 2) Break up combined messages into single messages
33887  *
33888  * \param fragments The message fragments. This simulates the data received on a TCP socket.
33889  * \param num_fragments This indicates the number of fragments to receive
33890  * \param overflow This is a place to stash extra data if more than one message is received
33891  *        in a single fragment
33892  * \param[out] messages The parsed messages are placed in this array
33893  * \param[out] num_messages The number of messages that were parsed
33894  * \param test Used for printing messages
33895  * \retval 0 Success
33896  * \retval -1 Failure
33897  */
33898 static int mock_tcp_loop(char *fragments[], size_t num_fragments,
33899       struct ast_str **overflow, char **messages, int *num_messages, struct ast_test* test)
33900 {
33901    struct ast_str *req_data;
33902    int i = 0;
33903    int res = 0;
33904 
33905    req_data = ast_str_create(128);
33906    ast_str_reset(*overflow);
33907 
33908    while (i < num_fragments || ast_str_strlen(*overflow) > 0) {
33909       enum message_integrity message_integrity = MESSAGE_FRAGMENT;
33910       ast_str_reset(req_data);
33911       while (message_integrity == MESSAGE_FRAGMENT) {
33912          if (ast_str_strlen(*overflow) > 0) {
33913             ast_str_append(&req_data, 0, "%s", ast_str_buffer(*overflow));
33914             ast_str_reset(*overflow);
33915          } else {
33916             ast_str_append(&req_data, 0, "%s", fragments[i++]);
33917          }
33918          message_integrity = check_message_integrity(&req_data, overflow);
33919       }
33920       if (strcmp(ast_str_buffer(req_data), messages[*num_messages])) {
33921          ast_test_status_update(test, "Mismatch in SIP messages.\n");
33922          ast_test_status_update(test, "Expected message:\n%s", messages[*num_messages]);
33923          ast_test_status_update(test, "Parsed message:\n%s", ast_str_buffer(req_data));
33924          res = -1;
33925          goto end;
33926       } else {
33927          ast_test_status_update(test, "Successfully read message:\n%s", ast_str_buffer(req_data));
33928       }
33929       (*num_messages)++;
33930    }
33931 
33932 end:
33933    ast_free(req_data);
33934    return res;
33935 };
33936 
33937 AST_TEST_DEFINE(test_tcp_message_fragmentation)
33938 {
33939    /* Normal single message in one fragment */
33940    char *normal[] = {
33941       "INVITE sip:bob@example.org SIP/2.0\r\n"
33942       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
33943       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
33944       "To: <sip:bob@example.org:5060>\r\n"
33945       "Call-ID: 12345\r\n"
33946       "CSeq: 1 INVITE\r\n"
33947       "Contact: sip:127.0.0.1:5061\r\n"
33948       "Max-Forwards: 70\r\n"
33949       "Content-Type: application/sdp\r\n"
33950       "Content-Length: 130\r\n"
33951       "\r\n"
33952       "v=0\r\n"
33953       "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
33954       "s=-\r\n"
33955       "c=IN IP4 127.0.0.1\r\n"
33956       "t=0 0\r\n"
33957       "m=audio 10000 RTP/AVP 0\r\n"
33958       "a=rtpmap:0 PCMU/8000\r\n"
33959    };
33960 
33961    /* Single message in two fragments.
33962     * Fragments combine to make "normal"
33963     */
33964    char *fragmented[] = {
33965       "INVITE sip:bob@example.org SIP/2.0\r\n"
33966       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
33967       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
33968       "To: <sip:bob@example.org:5060>\r\n"
33969       "Call-ID: 12345\r\n"
33970       "CSeq: 1 INVITE\r\n"
33971       "Contact: sip:127.0.0.1:5061\r\n"
33972       "Max-Forwards: ",
33973 
33974       "70\r\n"
33975       "Content-Type: application/sdp\r\n"
33976       "Content-Length: 130\r\n"
33977       "\r\n"
33978       "v=0\r\n"
33979       "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
33980       "s=-\r\n"
33981       "c=IN IP4 127.0.0.1\r\n"
33982       "t=0 0\r\n"
33983       "m=audio 10000 RTP/AVP 0\r\n"
33984       "a=rtpmap:0 PCMU/8000\r\n"
33985    };
33986    /* Single message in two fragments, divided precisely at the body
33987     * Fragments combine to make "normal"
33988     */
33989    char *fragmented_body[] = {
33990       "INVITE sip:bob@example.org SIP/2.0\r\n"
33991       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
33992       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
33993       "To: <sip:bob@example.org:5060>\r\n"
33994       "Call-ID: 12345\r\n"
33995       "CSeq: 1 INVITE\r\n"
33996       "Contact: sip:127.0.0.1:5061\r\n"
33997       "Max-Forwards: 70\r\n"
33998       "Content-Type: application/sdp\r\n"
33999       "Content-Length: 130\r\n"
34000       "\r\n",
34001 
34002       "v=0\r\n"
34003       "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
34004       "s=-\r\n"
34005       "c=IN IP4 127.0.0.1\r\n"
34006       "t=0 0\r\n"
34007       "m=audio 10000 RTP/AVP 0\r\n"
34008       "a=rtpmap:0 PCMU/8000\r\n"
34009    };
34010 
34011    /* Single message in three fragments
34012     * Fragments combine to make "normal"
34013     */
34014    char *multi_fragment[] = {
34015       "INVITE sip:bob@example.org SIP/2.0\r\n"
34016       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34017       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34018       "To: <sip:bob@example.org:5060>\r\n"
34019       "Call-ID: 12345\r\n"
34020       "CSeq: 1 INVITE\r\n",
34021 
34022       "Contact: sip:127.0.0.1:5061\r\n"
34023       "Max-Forwards: 70\r\n"
34024       "Content-Type: application/sdp\r\n"
34025       "Content-Length: 130\r\n"
34026       "\r\n"
34027       "v=0\r\n"
34028       "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
34029       "s=-\r\n"
34030       "c=IN IP4",
34031 
34032       " 127.0.0.1\r\n"
34033       "t=0 0\r\n"
34034       "m=audio 10000 RTP/AVP 0\r\n"
34035       "a=rtpmap:0 PCMU/8000\r\n"
34036    };
34037 
34038    /* Two messages in a single fragment
34039     * Fragments split into "multi_message_divided"
34040     */
34041    char *multi_message[] = {
34042       "SIP/2.0 100 Trying\r\n"
34043       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34044       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34045       "To: <sip:bob@example.org:5060>\r\n"
34046       "Call-ID: 12345\r\n"
34047       "CSeq: 1 INVITE\r\n"
34048       "Contact: <sip:bob@example.org:5060>\r\n"
34049       "Content-Length: 0\r\n"
34050       "\r\n"
34051       "SIP/2.0 180 Ringing\r\n"
34052       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34053       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34054       "To: <sip:bob@example.org:5060>\r\n"
34055       "Call-ID: 12345\r\n"
34056       "CSeq: 1 INVITE\r\n"
34057       "Contact: <sip:bob@example.org:5060>\r\n"
34058       "Content-Length: 0\r\n"
34059       "\r\n"
34060    };
34061    char *multi_message_divided[] = {
34062       "SIP/2.0 100 Trying\r\n"
34063       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34064       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34065       "To: <sip:bob@example.org:5060>\r\n"
34066       "Call-ID: 12345\r\n"
34067       "CSeq: 1 INVITE\r\n"
34068       "Contact: <sip:bob@example.org:5060>\r\n"
34069       "Content-Length: 0\r\n"
34070       "\r\n",
34071 
34072       "SIP/2.0 180 Ringing\r\n"
34073       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34074       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34075       "To: <sip:bob@example.org:5060>\r\n"
34076       "Call-ID: 12345\r\n"
34077       "CSeq: 1 INVITE\r\n"
34078       "Contact: <sip:bob@example.org:5060>\r\n"
34079       "Content-Length: 0\r\n"
34080       "\r\n"
34081    };
34082    /* Two messages with bodies combined into one fragment
34083     * Fragments split into "multi_message_body_divided"
34084     */
34085    char *multi_message_body[] = {
34086       "INVITE sip:bob@example.org SIP/2.0\r\n"
34087       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34088       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34089       "To: <sip:bob@example.org:5060>\r\n"
34090       "Call-ID: 12345\r\n"
34091       "CSeq: 1 INVITE\r\n"
34092       "Contact: sip:127.0.0.1:5061\r\n"
34093       "Max-Forwards: 70\r\n"
34094       "Content-Type: application/sdp\r\n"
34095       "Content-Length: 130\r\n"
34096       "\r\n"
34097       "v=0\r\n"
34098       "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
34099       "s=-\r\n"
34100       "c=IN IP4 127.0.0.1\r\n"
34101       "t=0 0\r\n"
34102       "m=audio 10000 RTP/AVP 0\r\n"
34103       "a=rtpmap:0 PCMU/8000\r\n"
34104       "INVITE sip:bob@example.org SIP/2.0\r\n"
34105       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34106       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34107       "To: <sip:bob@example.org:5060>\r\n"
34108       "Call-ID: 12345\r\n"
34109       "CSeq: 2 INVITE\r\n"
34110       "Contact: sip:127.0.0.1:5061\r\n"
34111       "Max-Forwards: 70\r\n"
34112       "Content-Type: application/sdp\r\n"
34113       "Content-Length: 130\r\n"
34114       "\r\n"
34115       "v=0\r\n"
34116       "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
34117       "s=-\r\n"
34118       "c=IN IP4 127.0.0.1\r\n"
34119       "t=0 0\r\n"
34120       "m=audio 10000 RTP/AVP 0\r\n"
34121       "a=rtpmap:0 PCMU/8000\r\n"
34122    };
34123    char *multi_message_body_divided[] = {
34124       "INVITE sip:bob@example.org SIP/2.0\r\n"
34125       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34126       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34127       "To: <sip:bob@example.org:5060>\r\n"
34128       "Call-ID: 12345\r\n"
34129       "CSeq: 1 INVITE\r\n"
34130       "Contact: sip:127.0.0.1:5061\r\n"
34131       "Max-Forwards: 70\r\n"
34132       "Content-Type: application/sdp\r\n"
34133       "Content-Length: 130\r\n"
34134       "\r\n"
34135       "v=0\r\n"
34136       "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
34137       "s=-\r\n"
34138       "c=IN IP4 127.0.0.1\r\n"
34139       "t=0 0\r\n"
34140       "m=audio 10000 RTP/AVP 0\r\n"
34141       "a=rtpmap:0 PCMU/8000\r\n",
34142 
34143       "INVITE sip:bob@example.org SIP/2.0\r\n"
34144       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34145       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34146       "To: <sip:bob@example.org:5060>\r\n"
34147       "Call-ID: 12345\r\n"
34148       "CSeq: 2 INVITE\r\n"
34149       "Contact: sip:127.0.0.1:5061\r\n"
34150       "Max-Forwards: 70\r\n"
34151       "Content-Type: application/sdp\r\n"
34152       "Content-Length: 130\r\n"
34153       "\r\n"
34154       "v=0\r\n"
34155       "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
34156       "s=-\r\n"
34157       "c=IN IP4 127.0.0.1\r\n"
34158       "t=0 0\r\n"
34159       "m=audio 10000 RTP/AVP 0\r\n"
34160       "a=rtpmap:0 PCMU/8000\r\n"
34161    };
34162 
34163    /* Two messages that appear in two fragments. Fragment
34164     * boundaries do not align with message boundaries.
34165     * Fragments combine to make "multi_message_divided"
34166     */
34167    char *multi_message_in_fragments[] = {
34168       "SIP/2.0 100 Trying\r\n"
34169       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34170       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34171       "To: <sip:bob@example.org:5060>\r\n"
34172       "Call-ID: 12345\r\n"
34173       "CSeq: 1 INVI",
34174 
34175       "TE\r\n"
34176       "Contact: <sip:bob@example.org:5060>\r\n"
34177       "Content-Length: 0\r\n"
34178       "\r\n"
34179       "SIP/2.0 180 Ringing\r\n"
34180       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34181       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34182       "To: <sip:bob@example.org:5060>\r\n"
34183       "Call-ID: 12345\r\n"
34184       "CSeq: 1 INVITE\r\n"
34185       "Contact: <sip:bob@example.org:5060>\r\n"
34186       "Content-Length: 0\r\n"
34187       "\r\n"
34188    };
34189 
34190    /* Message with compact content-length header
34191     * Same as "normal" but with compact content-length header
34192     */
34193    char *compact[] = {
34194       "INVITE sip:bob@example.org SIP/2.0\r\n"
34195       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34196       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34197       "To: <sip:bob@example.org:5060>\r\n"
34198       "Call-ID: 12345\r\n"
34199       "CSeq: 1 INVITE\r\n"
34200       "Contact: sip:127.0.0.1:5061\r\n"
34201       "Max-Forwards: 70\r\n"
34202       "Content-Type: application/sdp\r\n"
34203       "l:130\r\n" /* intentionally no space */
34204       "\r\n"
34205       "v=0\r\n"
34206       "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
34207       "s=-\r\n"
34208       "c=IN IP4 127.0.0.1\r\n"
34209       "t=0 0\r\n"
34210       "m=audio 10000 RTP/AVP 0\r\n"
34211       "a=rtpmap:0 PCMU/8000\r\n"
34212    };
34213 
34214    /* Message with faux content-length headers
34215     * Same as "normal" but with extra fake content-length headers
34216     */
34217    char *faux[] = {
34218       "INVITE sip:bob@example.org SIP/2.0\r\n"
34219       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34220       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34221       "To: <sip:bob@example.org:5060>\r\n"
34222       "Call-ID: 12345\r\n"
34223       "CSeq: 1 INVITE\r\n"
34224       "Contact: sip:127.0.0.1:5061\r\n"
34225       "Max-Forwards: 70\r\n"
34226       "Content-Type: application/sdp\r\n"
34227       "DisContent-Length: 0\r\n"
34228       "MalContent-Length: 60\r\n"
34229       "Content-Length:130\r\n" /* intentionally no space */
34230       "\r\n"
34231       "v=0\r\n"
34232       "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
34233       "s=-\r\n"
34234       "c=IN IP4 127.0.0.1\r\n"
34235       "t=0 0\r\n"
34236       "m=audio 10000 RTP/AVP 0\r\n"
34237       "a=rtpmap:0 PCMU/8000\r\n"
34238    };
34239 
34240    /* Message with folded Content-Length header
34241     * Message is "normal" with Content-Length spread across three lines
34242     *
34243     * This is the test that requires pedantic=yes in order to pass
34244     */
34245    char *folded[] = {
34246       "INVITE sip:bob@example.org SIP/2.0\r\n"
34247       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34248       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34249       "To: <sip:bob@example.org:5060>\r\n"
34250       "Call-ID: 12345\r\n"
34251       "CSeq: 1 INVITE\r\n"
34252       "Contact: sip:127.0.0.1:5061\r\n"
34253       "Max-Forwards: 70\r\n"
34254       "Content-Type: application/sdp\r\n"
34255       "Content-Length: \t\r\n"
34256       "\t \r\n"
34257       " 130\t \r\n"
34258       "\r\n"
34259       "v=0\r\n"
34260       "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
34261       "s=-\r\n"
34262       "c=IN IP4 127.0.0.1\r\n"
34263       "t=0 0\r\n"
34264       "m=audio 10000 RTP/AVP 0\r\n"
34265       "a=rtpmap:0 PCMU/8000\r\n"
34266    };
34267 
34268    /* Message with compact Content-length header in message and
34269     * full Content-Length header in the body. Ensure that the header
34270     * in the message is read and that the one in the body is ignored
34271     */
34272    char *cl_in_body[] = {
34273       "INVITE sip:bob@example.org SIP/2.0\r\n"
34274       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
34275       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
34276       "To: <sip:bob@example.org:5060>\r\n"
34277       "Call-ID: 12345\r\n"
34278       "CSeq: 1 INVITE\r\n"
34279       "Contact: sip:127.0.0.1:5061\r\n"
34280       "Max-Forwards: 70\r\n"
34281       "Content-Type: application/sdp\r\n"
34282       "l: 149\r\n"
34283       "\r\n"
34284       "v=0\r\n"
34285       "Content-Length: 0\r\n"
34286       "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
34287       "s=-\r\n"
34288       "c=IN IP4 127.0.0.1\r\n"
34289       "t=0 0\r\n"
34290       "m=audio 10000 RTP/AVP 0\r\n"
34291       "a=rtpmap:0 PCMU/8000\r\n"
34292    };
34293 
34294    struct ast_str *overflow;
34295    struct {
34296       char **fragments;
34297       char **expected;
34298       int num_expected;
34299       const char *description;
34300    } tests[] = {
34301       { normal, normal, 1, "normal" },
34302       { fragmented, normal, 1, "fragmented" },
34303       { fragmented_body, normal, 1, "fragmented_body" },
34304       { multi_fragment, normal, 1, "multi_fragment" },
34305       { multi_message, multi_message_divided, 2, "multi_message" },
34306       { multi_message_body, multi_message_body_divided, 2, "multi_message_body" },
34307       { multi_message_in_fragments, multi_message_divided, 2, "multi_message_in_fragments" },
34308       { compact, compact, 1, "compact" },
34309       { faux, faux, 1, "faux" },
34310       { folded, folded, 1, "folded" },
34311       { cl_in_body, cl_in_body, 1, "cl_in_body" },
34312    };
34313    int i;
34314    enum ast_test_result_state res = AST_TEST_PASS;
34315 
34316    switch (cmd) {
34317       case TEST_INIT:
34318          info->name = "sip_tcp_message_fragmentation";
34319          info->category = "/main/sip/transport/";
34320          info->summary = "SIP TCP message fragmentation test";
34321          info->description =
34322             "Tests reception of different TCP messages that have been fragmented or"
34323             "run together. This test mimicks the code that TCP reception uses.";
34324          return AST_TEST_NOT_RUN;
34325       case TEST_EXECUTE:
34326          break;
34327    }
34328    if (!sip_cfg.pedanticsipchecking) {
34329       ast_log(LOG_WARNING, "Not running test. Pedantic SIP checking is not enabled, so it is guaranteed to fail\n");
34330       return AST_TEST_NOT_RUN;
34331    }
34332 
34333    overflow = ast_str_create(128);
34334    if (!overflow) {
34335       return AST_TEST_FAIL;
34336    }
34337    for (i = 0; i < ARRAY_LEN(tests); ++i) {
34338       int num_messages = 0;
34339       if (mock_tcp_loop(tests[i].fragments, ARRAY_LEN(tests[i].fragments),
34340                &overflow, tests[i].expected, &num_messages, test)) {
34341          ast_test_status_update(test, "Failed to parse message '%s'\n", tests[i].description);
34342          res = AST_TEST_FAIL;
34343          break;
34344       }
34345       if (num_messages != tests[i].num_expected) {
34346          ast_test_status_update(test, "Did not receive the expected number of messages. "
34347                "Expected %d but received %d\n", tests[i].num_expected, num_messages);
34348          res = AST_TEST_FAIL;
34349          break;
34350       }
34351    }
34352    ast_free(overflow);
34353    return res;
34354 }
34355 
34356 AST_TEST_DEFINE(get_in_brackets_const_test)
34357 {
34358    const char *input;
34359    const char *start = NULL;
34360    int len = 0;
34361    int res;
34362 
34363 #define CHECK_RESULTS(in, expected_res, expected_start, expected_len)   do {  \
34364       input = (in);                 \
34365       res = get_in_brackets_const(input, &start, &len);  \
34366       if ((expected_res) != res) {           \
34367          ast_test_status_update(test, "Unexpected result: %d != %d\n", expected_res, res); \
34368          return AST_TEST_FAIL;            \
34369       }                    \
34370       if ((expected_start) != start) {       \
34371          const char *e = expected_start ? expected_start : "(null)"; \
34372          const char *a = start ? start : "(null)"; \
34373          ast_test_status_update(test, "Unexpected start: %s != %s\n", e, a); \
34374          return AST_TEST_FAIL;            \
34375       }                    \
34376       if ((expected_len) != len) {           \
34377          ast_test_status_update(test, "Unexpected len: %d != %d\n", expected_len, len); \
34378          return AST_TEST_FAIL;            \
34379       }                    \
34380    } while(0)
34381 
34382    switch (cmd) {
34383    case TEST_INIT:
34384       info->name = __func__;
34385       info->category = "/channels/chan_sip/";
34386       info->summary = "get_in_brackets_const test";
34387       info->description =
34388          "Tests the get_in_brackets_const function";
34389       return AST_TEST_NOT_RUN;
34390    case TEST_EXECUTE:
34391       break;
34392    }
34393 
34394    CHECK_RESULTS("", 1, NULL, -1);
34395    CHECK_RESULTS("normal <test>", 0, input + 8, 4);
34396    CHECK_RESULTS("\"normal\" <test>", 0, input + 10, 4);
34397    CHECK_RESULTS("not normal <test", -1, NULL, -1);
34398    CHECK_RESULTS("\"yes < really\" <test>", 0, input + 16, 4);
34399    CHECK_RESULTS("\"even > this\" <test>", 0, input + 15, 4);
34400    CHECK_RESULTS("<sip:id1@10.10.10.10;lr>", 0, input + 1, 22);
34401    CHECK_RESULTS("<sip:id1@10.10.10.10;lr>, <sip:id1@10.10.10.20;lr>", 0, input + 1, 22);
34402    CHECK_RESULTS("<sip:id1,id2@10.10.10.10;lr>", 0, input + 1, 26);
34403    CHECK_RESULTS("<sip:id1@10., <sip:id2@10.10.10.10;lr>", 0, input + 1, 36);
34404    CHECK_RESULTS("\"quoted text\" <sip:dlg1@10.10.10.10;lr>", 0, input + 15, 23);
34405 
34406    return AST_TEST_PASS;
34407 }
34408 
34409 #endif
34410 
34411 #define DATA_EXPORT_SIP_PEER(MEMBER)            \
34412    MEMBER(sip_peer, name, AST_DATA_STRING)         \
34413    MEMBER(sip_peer, secret, AST_DATA_PASSWORD)     \
34414    MEMBER(sip_peer, md5secret, AST_DATA_PASSWORD)     \
34415    MEMBER(sip_peer, remotesecret, AST_DATA_PASSWORD)  \
34416    MEMBER(sip_peer, context, AST_DATA_STRING)      \
34417    MEMBER(sip_peer, subscribecontext, AST_DATA_STRING)   \
34418    MEMBER(sip_peer, username, AST_DATA_STRING)     \
34419    MEMBER(sip_peer, accountcode, AST_DATA_STRING)     \
34420    MEMBER(sip_peer, tohost, AST_DATA_STRING)    \
34421    MEMBER(sip_peer, regexten, AST_DATA_STRING)     \
34422    MEMBER(sip_peer, fromuser, AST_DATA_STRING)     \
34423    MEMBER(sip_peer, fromdomain, AST_DATA_STRING)      \
34424    MEMBER(sip_peer, fullcontact, AST_DATA_STRING)     \
34425    MEMBER(sip_peer, cid_num, AST_DATA_STRING)      \
34426    MEMBER(sip_peer, cid_name, AST_DATA_STRING)     \
34427    MEMBER(sip_peer, vmexten, AST_DATA_STRING)      \
34428    MEMBER(sip_peer, language, AST_DATA_STRING)     \
34429    MEMBER(sip_peer, mohinterpret, AST_DATA_STRING)    \
34430    MEMBER(sip_peer, mohsuggest, AST_DATA_STRING)      \
34431    MEMBER(sip_peer, parkinglot, AST_DATA_STRING)      \
34432    MEMBER(sip_peer, useragent, AST_DATA_STRING)    \
34433    MEMBER(sip_peer, mwi_from, AST_DATA_STRING)     \
34434    MEMBER(sip_peer, engine, AST_DATA_STRING)    \
34435    MEMBER(sip_peer, unsolicited_mailbox, AST_DATA_STRING)   \
34436    MEMBER(sip_peer, is_realtime, AST_DATA_BOOLEAN)    \
34437    MEMBER(sip_peer, host_dynamic, AST_DATA_BOOLEAN)   \
34438    MEMBER(sip_peer, autoframing, AST_DATA_BOOLEAN)    \
34439    MEMBER(sip_peer, inuse, AST_DATA_INTEGER)    \
34440    MEMBER(sip_peer, ringing, AST_DATA_INTEGER)     \
34441    MEMBER(sip_peer, onhold, AST_DATA_INTEGER)      \
34442    MEMBER(sip_peer, call_limit, AST_DATA_INTEGER)     \
34443    MEMBER(sip_peer, t38_maxdatagram, AST_DATA_INTEGER)   \
34444    MEMBER(sip_peer, maxcallbitrate, AST_DATA_INTEGER) \
34445    MEMBER(sip_peer, rtptimeout, AST_DATA_SECONDS)     \
34446    MEMBER(sip_peer, rtpholdtimeout, AST_DATA_SECONDS) \
34447    MEMBER(sip_peer, rtpkeepalive, AST_DATA_SECONDS)   \
34448    MEMBER(sip_peer, lastms, AST_DATA_MILLISECONDS)    \
34449    MEMBER(sip_peer, maxms, AST_DATA_MILLISECONDS)     \
34450    MEMBER(sip_peer, qualifyfreq, AST_DATA_MILLISECONDS)  \
34451    MEMBER(sip_peer, timer_t1, AST_DATA_MILLISECONDS)  \
34452    MEMBER(sip_peer, timer_b, AST_DATA_MILLISECONDS)   \
34453    MEMBER(sip_peer, description, AST_DATA_STRING)
34454 
34455 AST_DATA_STRUCTURE(sip_peer, DATA_EXPORT_SIP_PEER);
34456 
34457 static int peers_data_provider_get(const struct ast_data_search *search,
34458    struct ast_data *data_root)
34459 {
34460    struct sip_peer *peer;
34461    struct ao2_iterator i;
34462    struct ast_data *data_peer, *data_peer_mailboxes = NULL, *data_peer_mailbox, *enum_node;
34463    struct ast_data *data_sip_options;
34464    int total_mailboxes, x;
34465    struct sip_mailbox *mailbox;
34466 
34467    i = ao2_iterator_init(peers, 0);
34468    while ((peer = ao2_iterator_next(&i))) {
34469       ao2_lock(peer);
34470 
34471       data_peer = ast_data_add_node(data_root, "peer");
34472       if (!data_peer) {
34473          ao2_unlock(peer);
34474          ao2_ref(peer, -1);
34475          continue;
34476       }
34477 
34478       ast_data_add_structure(sip_peer, data_peer, peer);
34479 
34480       /* transfer mode */
34481       enum_node = ast_data_add_node(data_peer, "allowtransfer");
34482       if (!enum_node) {
34483          ao2_unlock(peer);
34484          ao2_ref(peer, -1);
34485          continue;
34486       }
34487       ast_data_add_str(enum_node, "text", transfermode2str(peer->allowtransfer));
34488       ast_data_add_int(enum_node, "value", peer->allowtransfer);
34489 
34490       /* transports */
34491       ast_data_add_str(data_peer, "transports", get_transport_list(peer->transports));
34492 
34493       /* peer type */
34494       if ((peer->type & SIP_TYPE_USER) && (peer->type & SIP_TYPE_PEER)) {
34495          ast_data_add_str(data_peer, "type", "friend");
34496       } else if (peer->type & SIP_TYPE_PEER) {
34497          ast_data_add_str(data_peer, "type", "peer");
34498       } else if (peer->type & SIP_TYPE_USER) {
34499          ast_data_add_str(data_peer, "type", "user");
34500       }
34501 
34502       /* mailboxes */
34503       total_mailboxes = 0;
34504       AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
34505          if (!total_mailboxes) {
34506             data_peer_mailboxes = ast_data_add_node(data_peer, "mailboxes");
34507             if (!data_peer_mailboxes) {
34508                break;
34509             }
34510             total_mailboxes++;
34511          }
34512 
34513          data_peer_mailbox = ast_data_add_node(data_peer_mailboxes, "mailbox");
34514          if (!data_peer_mailbox) {
34515             continue;
34516          }
34517          ast_data_add_str(data_peer_mailbox, "mailbox", mailbox->mailbox);
34518          ast_data_add_str(data_peer_mailbox, "context", mailbox->context);
34519       }
34520 
34521       /* amaflags */
34522       enum_node = ast_data_add_node(data_peer, "amaflags");
34523       if (!enum_node) {
34524          ao2_unlock(peer);
34525          ao2_ref(peer, -1);
34526          continue;
34527       }
34528       ast_data_add_int(enum_node, "value", peer->amaflags);
34529       ast_data_add_str(enum_node, "text", ast_cdr_flags2str(peer->amaflags));
34530 
34531       /* sip options */
34532       data_sip_options = ast_data_add_node(data_peer, "sipoptions");
34533       if (!data_sip_options) {
34534          ao2_unlock(peer);
34535          ao2_ref(peer, -1);
34536          continue;
34537       }
34538       for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
34539          ast_data_add_bool(data_sip_options, sip_options[x].text, peer->sipoptions & sip_options[x].id);
34540       }
34541 
34542       /* callingpres */
34543       enum_node = ast_data_add_node(data_peer, "callingpres");
34544       if (!enum_node) {
34545          ao2_unlock(peer);
34546          ao2_ref(peer, -1);
34547          continue;
34548       }
34549       ast_data_add_int(enum_node, "value", peer->callingpres);
34550       ast_data_add_str(enum_node, "text", ast_describe_caller_presentation(peer->callingpres));
34551 
34552       /* codecs */
34553       ast_data_add_codecs(data_peer, "codecs", peer->caps);
34554 
34555       if (!ast_data_search_match(search, data_peer)) {
34556          ast_data_remove_node(data_root, data_peer);
34557       }
34558 
34559       ao2_unlock(peer);
34560       ao2_ref(peer, -1);
34561    }
34562    ao2_iterator_destroy(&i);
34563 
34564    return 0;
34565 }
34566 
34567 static const struct ast_data_handler peers_data_provider = {
34568    .version = AST_DATA_HANDLER_VERSION,
34569    .get = peers_data_provider_get
34570 };
34571 
34572 static const struct ast_data_entry sip_data_providers[] = {
34573    AST_DATA_ENTRY("asterisk/channel/sip/peers", &peers_data_provider),
34574 };
34575 
34576 static const struct ast_sip_api_tech chan_sip_api_provider = {
34577    .version = AST_SIP_API_VERSION,
34578    .name = "chan_sip",
34579    .sipinfo_send = sipinfo_send,
34580 };
34581 
34582 /*! \brief PBX load module - initialization */
34583 static int load_module(void)
34584 {
34585    ast_verbose("SIP channel loading...\n");
34586 
34587    if (!(sip_tech.capabilities = ast_format_cap_alloc())) {
34588       return AST_MODULE_LOAD_FAILURE;
34589    }
34590 
34591    if (ast_sip_api_provider_register(&chan_sip_api_provider)) {
34592       return AST_MODULE_LOAD_FAILURE;
34593    }
34594 
34595    /* the fact that ao2_containers can't resize automatically is a major worry! */
34596    /* if the number of objects gets above MAX_XXX_BUCKETS, things will slow down */
34597    peers = ao2_t_container_alloc(HASH_PEER_SIZE, peer_hash_cb, peer_cmp_cb, "allocate peers");
34598    peers_by_ip = ao2_t_container_alloc(HASH_PEER_SIZE, peer_iphash_cb, peer_ipcmp_cb, "allocate peers_by_ip");
34599    dialogs = ao2_t_container_alloc(HASH_DIALOG_SIZE, dialog_hash_cb, dialog_cmp_cb, "allocate dialogs");
34600    dialogs_needdestroy = ao2_t_container_alloc(1, NULL, NULL, "allocate dialogs_needdestroy");
34601    dialogs_rtpcheck = ao2_t_container_alloc(HASH_DIALOG_SIZE, dialog_hash_cb, dialog_cmp_cb, "allocate dialogs for rtpchecks");
34602    threadt = ao2_t_container_alloc(HASH_DIALOG_SIZE, threadt_hash_cb, threadt_cmp_cb, "allocate threadt table");
34603    if (!peers || !peers_by_ip || !dialogs || !dialogs_needdestroy || !dialogs_rtpcheck
34604       || !threadt) {
34605       ast_log(LOG_ERROR, "Unable to create primary SIP container(s)\n");
34606       return AST_MODULE_LOAD_FAILURE;
34607    }
34608 
34609    if (!(sip_cfg.caps = ast_format_cap_alloc())) {
34610       return AST_MODULE_LOAD_FAILURE;
34611    }
34612    ast_format_cap_add_all_by_type(sip_tech.capabilities, AST_FORMAT_TYPE_AUDIO);
34613 
34614    ASTOBJ_CONTAINER_INIT(&regl); /* Registry object list -- not searched for anything */
34615    ASTOBJ_CONTAINER_INIT(&submwil); /* MWI subscription object list */
34616 
34617    if (!(sched = ast_sched_context_create())) {
34618       ast_log(LOG_ERROR, "Unable to create scheduler context\n");
34619       return AST_MODULE_LOAD_FAILURE;
34620    }
34621 
34622    if (!(io = io_context_create())) {
34623       ast_log(LOG_ERROR, "Unable to create I/O context\n");
34624       return AST_MODULE_LOAD_FAILURE;
34625    }
34626 
34627    sip_reloadreason = CHANNEL_MODULE_LOAD;
34628 
34629    can_parse_xml = sip_is_xml_parsable();
34630    if (reload_config(sip_reloadreason)) { /* Load the configuration from sip.conf */
34631       ast_sip_api_provider_unregister();
34632       return AST_MODULE_LOAD_DECLINE;
34633    }
34634 
34635    /* Initialize bogus peer. Can be done first after reload_config() */
34636    if (!(bogus_peer = temp_peer("(bogus_peer)"))) {
34637       ast_log(LOG_ERROR, "Unable to create bogus_peer for authentication\n");
34638       io_context_destroy(io);
34639       ast_sched_context_destroy(sched);
34640       return AST_MODULE_LOAD_FAILURE;
34641    }
34642    /* Make sure the auth will always fail. */
34643    ast_string_field_set(bogus_peer, md5secret, BOGUS_PEER_MD5SECRET);
34644    ast_clear_flag(&bogus_peer->flags[0], SIP_INSECURE);
34645 
34646    /* Prepare the version that does not require DTMF BEGIN frames.
34647     * We need to use tricks such as memcpy and casts because the variable
34648     * has const fields.
34649     */
34650    memcpy(&sip_tech_info, &sip_tech, sizeof(sip_tech));
34651    memset((void *) &sip_tech_info.send_digit_begin, 0, sizeof(sip_tech_info.send_digit_begin));
34652 
34653    if (ast_msg_tech_register(&sip_msg_tech)) {
34654       /* LOAD_FAILURE stops Asterisk, so cleanup is a moot point. */
34655       return AST_MODULE_LOAD_FAILURE;
34656    }
34657 
34658    /* Make sure we can register our sip channel type */
34659    if (ast_channel_register(&sip_tech)) {
34660       ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
34661       ao2_t_ref(bogus_peer, -1, "unref the bogus_peer");
34662       io_context_destroy(io);
34663       ast_sched_context_destroy(sched);
34664       return AST_MODULE_LOAD_FAILURE;
34665    }
34666 
34667 #ifdef TEST_FRAMEWORK
34668    AST_TEST_REGISTER(test_sip_peers_get);
34669    AST_TEST_REGISTER(test_sip_mwi_subscribe_parse);
34670    AST_TEST_REGISTER(test_tcp_message_fragmentation);
34671    AST_TEST_REGISTER(get_in_brackets_const_test);
34672 #endif
34673 
34674    /* Register AstData providers */
34675    ast_data_register_multiple(sip_data_providers, ARRAY_LEN(sip_data_providers));
34676 
34677    /* Register all CLI functions for SIP */
34678    ast_cli_register_multiple(cli_sip, ARRAY_LEN(cli_sip));
34679 
34680    /* Tell the UDPTL subdriver that we're here */
34681    ast_udptl_proto_register(&sip_udptl);
34682 
34683    /* Tell the RTP engine about our RTP glue */
34684    ast_rtp_glue_register(&sip_rtp_glue);
34685 
34686    /* Register dialplan applications */
34687    ast_register_application_xml(app_dtmfmode, sip_dtmfmode);
34688    ast_register_application_xml(app_sipaddheader, sip_addheader);
34689    ast_register_application_xml(app_sipremoveheader, sip_removeheader);
34690 #ifdef TEST_FRAMEWORK
34691    ast_register_application_xml(app_sipsendcustominfo, sip_sendcustominfo);
34692 #endif
34693 
34694    /* Register dialplan functions */
34695    ast_custom_function_register(&sip_header_function);
34696    ast_custom_function_register(&sippeer_function);
34697    ast_custom_function_register(&sipchaninfo_function);
34698    ast_custom_function_register(&checksipdomain_function);
34699 
34700    /* Register manager commands */
34701    ast_manager_register_xml("SIPpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peers);
34702    ast_manager_register_xml("SIPshowpeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peer);
34703    ast_manager_register_xml("SIPqualifypeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_qualify_peer);
34704    ast_manager_register_xml("SIPshowregistry", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_show_registry);
34705    ast_manager_register_xml("SIPnotify", EVENT_FLAG_SYSTEM, manager_sipnotify);
34706    ast_manager_register_xml("SIPpeerstatus", EVENT_FLAG_SYSTEM, manager_sip_peer_status);
34707    sip_poke_all_peers();
34708    sip_keepalive_all_peers();
34709    sip_send_all_registers();
34710    sip_send_all_mwi_subscriptions();
34711    initialize_escs();
34712 
34713    if (sip_epa_register(&cc_epa_static_data)) {
34714       ast_sip_api_provider_unregister();
34715       return AST_MODULE_LOAD_DECLINE;
34716    }
34717 
34718    if (sip_reqresp_parser_init() == -1) {
34719       ast_log(LOG_ERROR, "Unable to initialize the SIP request and response parser\n");
34720       ast_sip_api_provider_unregister();
34721       return AST_MODULE_LOAD_DECLINE;
34722    }
34723 
34724    if (can_parse_xml) {
34725       /* SIP CC agents require the ability to parse XML PIDF bodies
34726        * in incoming PUBLISH requests
34727        */
34728       if (ast_cc_agent_register(&sip_cc_agent_callbacks)) {
34729          ast_sip_api_provider_unregister();
34730          return AST_MODULE_LOAD_DECLINE;
34731       }
34732    }
34733    if (ast_cc_monitor_register(&sip_cc_monitor_callbacks)) {
34734       ast_sip_api_provider_unregister();
34735       return AST_MODULE_LOAD_DECLINE;
34736    }
34737    if (!(sip_monitor_instances = ao2_container_alloc(37, sip_monitor_instance_hash_fn, sip_monitor_instance_cmp_fn))) {
34738       ast_sip_api_provider_unregister();
34739       return AST_MODULE_LOAD_DECLINE;
34740    }
34741 
34742    /* And start the monitor for the first time */
34743    restart_monitor();
34744 
34745    ast_realtime_require_field(ast_check_realtime("sipregs") ? "sipregs" : "sippeers",
34746       "name", RQ_CHAR, 10,
34747       "ipaddr", RQ_CHAR, INET6_ADDRSTRLEN - 1,
34748       "port", RQ_UINTEGER2, 5,
34749       "regseconds", RQ_INTEGER4, 11,
34750       "defaultuser", RQ_CHAR, 10,
34751       "fullcontact", RQ_CHAR, 35,
34752       "regserver", RQ_CHAR, 20,
34753       "useragent", RQ_CHAR, 20,
34754       "lastms", RQ_INTEGER4, 11,
34755       SENTINEL);
34756 
34757 
34758    sip_register_tests();
34759    network_change_event_subscribe();
34760 
34761    ast_websocket_add_protocol("sip", sip_websocket_callback);
34762 
34763    return AST_MODULE_LOAD_SUCCESS;
34764 }
34765 
34766 /*! \brief PBX unload module API */
34767 static int unload_module(void)
34768 {
34769    struct sip_pvt *p;
34770    struct sip_threadinfo *th;
34771    struct ast_context *con;
34772    struct ao2_iterator i;
34773    int wait_count;
34774 
34775    ast_sip_api_provider_unregister();
34776 
34777    ast_websocket_remove_protocol("sip", sip_websocket_callback);
34778 
34779    network_change_event_unsubscribe();
34780    acl_change_event_unsubscribe();
34781 
34782    ast_sched_dump(sched);
34783    
34784    /* First, take us out of the channel type list */
34785    ast_channel_unregister(&sip_tech);
34786 
34787    ast_msg_tech_unregister(&sip_msg_tech);
34788 
34789    /* Unregister dial plan functions */
34790    ast_custom_function_unregister(&sipchaninfo_function);
34791    ast_custom_function_unregister(&sippeer_function);
34792    ast_custom_function_unregister(&sip_header_function);
34793    ast_custom_function_unregister(&checksipdomain_function);
34794 
34795    /* Unregister dial plan applications */
34796    ast_unregister_application(app_dtmfmode);
34797    ast_unregister_application(app_sipaddheader);
34798    ast_unregister_application(app_sipremoveheader);
34799 #ifdef TEST_FRAMEWORK
34800    ast_unregister_application(app_sipsendcustominfo);
34801 
34802    AST_TEST_UNREGISTER(test_sip_peers_get);
34803    AST_TEST_UNREGISTER(test_sip_mwi_subscribe_parse);
34804    AST_TEST_UNREGISTER(test_tcp_message_fragmentation);
34805    AST_TEST_UNREGISTER(get_in_brackets_const_test);
34806 #endif
34807    /* Unregister all the AstData providers */
34808    ast_data_unregister(NULL);
34809 
34810    /* Unregister CLI commands */
34811    ast_cli_unregister_multiple(cli_sip, ARRAY_LEN(cli_sip));
34812 
34813    /* Disconnect from UDPTL */
34814    ast_udptl_proto_unregister(&sip_udptl);
34815 
34816    /* Disconnect from RTP engine */
34817    ast_rtp_glue_unregister(&sip_rtp_glue);
34818 
34819    /* Unregister AMI actions */
34820    ast_manager_unregister("SIPpeers");
34821    ast_manager_unregister("SIPshowpeer");
34822    ast_manager_unregister("SIPqualifypeer");
34823    ast_manager_unregister("SIPshowregistry");
34824    ast_manager_unregister("SIPnotify");
34825    ast_manager_unregister("SIPpeerstatus");
34826    
34827    /* Kill TCP/TLS server threads */
34828    if (sip_tcp_desc.master) {
34829       ast_tcptls_server_stop(&sip_tcp_desc);
34830    }
34831    if (sip_tls_desc.master) {
34832       ast_tcptls_server_stop(&sip_tls_desc);
34833    }
34834    ast_ssl_teardown(sip_tls_desc.tls_cfg);
34835 
34836    /* Kill all existing TCP/TLS threads */
34837    i = ao2_iterator_init(threadt, 0);
34838    while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
34839       pthread_t thread = th->threadid;
34840       th->stop = 1;
34841       pthread_kill(thread, SIGURG);
34842       ao2_t_ref(th, -1, "decrement ref from iterator");
34843    }
34844    ao2_iterator_destroy(&i);
34845 
34846    /* Hangup all dialogs if they have an owner */
34847    i = ao2_iterator_init(dialogs, 0);
34848    while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
34849       if (p->owner)
34850          ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
34851       ao2_t_ref(p, -1, "toss dialog ptr from iterator_next");
34852    }
34853    ao2_iterator_destroy(&i);
34854 
34855    unlink_all_peers_from_tables();
34856 
34857    ast_mutex_lock(&monlock);
34858    if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
34859       pthread_t th = monitor_thread;
34860       monitor_thread = AST_PTHREADT_STOP;
34861       pthread_cancel(th);
34862       pthread_kill(th, SIGURG);
34863       ast_mutex_unlock(&monlock);
34864       pthread_join(th, NULL);
34865    } else {
34866       monitor_thread = AST_PTHREADT_STOP;
34867       ast_mutex_unlock(&monlock);
34868    }
34869 
34870    /* Destroy all the dialogs and free their memory */
34871    i = ao2_iterator_init(dialogs, 0);
34872    while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
34873       dialog_unlink_all(p);
34874       ao2_t_ref(p, -1, "throw away iterator result");
34875    }
34876    ao2_iterator_destroy(&i);
34877 
34878    /* Free memory for local network address mask */
34879    ast_free_ha(localaddr);
34880 
34881    ast_mutex_lock(&authl_lock);
34882    if (authl) {
34883       ao2_t_ref(authl, -1, "Removing global authentication");
34884       authl = NULL;
34885    }
34886    ast_mutex_unlock(&authl_lock);
34887 
34888    sip_epa_unregister_all();
34889    destroy_escs();
34890 
34891    ast_free(default_tls_cfg.certfile);
34892    ast_free(default_tls_cfg.pvtfile);
34893    ast_free(default_tls_cfg.cipher);
34894    ast_free(default_tls_cfg.cafile);
34895    ast_free(default_tls_cfg.capath);
34896 
34897    cleanup_all_regs();
34898    ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
34899    ASTOBJ_CONTAINER_DESTROY(&regl);
34900 
34901    ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
34902       ASTOBJ_WRLOCK(iterator);
34903       if (iterator->dnsmgr) {
34904          ast_dnsmgr_release(iterator->dnsmgr);
34905          iterator->dnsmgr = NULL;
34906          ASTOBJ_UNREF(iterator, sip_subscribe_mwi_destroy);
34907       }
34908       ASTOBJ_UNLOCK(iterator);
34909    } while(0));
34910    ASTOBJ_CONTAINER_DESTROYALL(&submwil, sip_subscribe_mwi_destroy);
34911    ASTOBJ_CONTAINER_DESTROY(&submwil);
34912 
34913    /*
34914     * Wait awhile for the TCP/TLS thread container to become empty.
34915     *
34916     * XXX This is a hack, but the worker threads cannot be created
34917     * joinable.  They can die on their own and remove themselves
34918     * from the container thus resulting in a huge memory leak.
34919     */
34920    wait_count = 1000;
34921    while (ao2_container_count(threadt) && --wait_count) {
34922       sched_yield();
34923    }
34924    if (!wait_count) {
34925       ast_debug(2, "TCP/TLS thread container did not become empty :(\n");
34926    }
34927 
34928    ao2_t_ref(bogus_peer, -1, "unref the bogus_peer");
34929 
34930    ao2_t_ref(peers, -1, "unref the peers table");
34931    ao2_t_ref(peers_by_ip, -1, "unref the peers_by_ip table");
34932    ao2_t_ref(dialogs, -1, "unref the dialogs table");
34933    ao2_t_ref(dialogs_needdestroy, -1, "unref dialogs_needdestroy");
34934    ao2_t_ref(dialogs_rtpcheck, -1, "unref dialogs_rtpcheck");
34935    ao2_t_ref(threadt, -1, "unref the thread table");
34936    ao2_t_ref(sip_monitor_instances, -1, "unref the sip_monitor_instances table");
34937 
34938    clear_sip_domains();
34939    sip_cfg.contact_acl = ast_free_acl_list(sip_cfg.contact_acl);
34940    if (sipsock_read_id) {
34941       ast_io_remove(io, sipsock_read_id);
34942       sipsock_read_id = NULL;
34943    }
34944    close(sipsock);
34945    io_context_destroy(io);
34946    ast_sched_context_destroy(sched);
34947    con = ast_context_find(used_context);
34948    if (con) {
34949       ast_context_destroy(con, "SIP");
34950    }
34951    ast_unload_realtime("sipregs");
34952    ast_unload_realtime("sippeers");
34953    ast_cc_monitor_unregister(&sip_cc_monitor_callbacks);
34954    ast_cc_agent_unregister(&sip_cc_agent_callbacks);
34955 
34956    sip_reqresp_parser_exit();
34957    sip_unregister_tests();
34958 
34959    if (notify_types) {
34960       ast_config_destroy(notify_types);
34961       notify_types = NULL;
34962    }
34963 
34964    ast_format_cap_destroy(sip_tech.capabilities);
34965    sip_cfg.caps = ast_format_cap_destroy(sip_cfg.caps);
34966 
34967    return 0;
34968 }
34969 
34970 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Session Initiation Protocol (SIP)",
34971       .load = load_module,
34972       .unload = unload_module,
34973       .reload = reload,
34974       .load_pri = AST_MODPRI_CHANNEL_DRIVER,
34975       .nonoptreq = "res_crypto,chan_local,res_http_websocket",
34976           );