Thu Sep 7 01:02:57 2017

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>res_crypto</use>
00166    <depend>chan_local</depend>
00167    <support_level>core</support_level>
00168  ***/
00169 
00170 /*!  \page sip_session_timers SIP Session Timers in Asterisk Chan_sip
00171 
00172    The SIP Session-Timers is an extension of the SIP protocol that allows end-points and proxies to
00173    refresh a session periodically. The sessions are kept alive by sending a RE-INVITE or UPDATE
00174    request at a negotiated interval. If a session refresh fails then all the entities that support Session-
00175    Timers clear their internal session state. In addition, UAs generate a BYE request in order to clear
00176    the state in the proxies and the remote UA (this is done for the benefit of SIP entities in the path
00177    that do not support Session-Timers).
00178 
00179    The Session-Timers can be configured on a system-wide, per-user, or per-peer basis. The peruser/
00180    per-peer settings override the global settings. The following new parameters have been
00181    added to the sip.conf file.
00182       session-timers=["accept", "originate", "refuse"]
00183       session-expires=[integer]
00184       session-minse=[integer]
00185       session-refresher=["uas", "uac"]
00186 
00187    The session-timers parameter in sip.conf defines the mode of operation of SIP session-timers feature in
00188    Asterisk. The Asterisk can be configured in one of the following three modes:
00189 
00190    1. Accept :: In the "accept" mode, the Asterisk server honors session-timers requests
00191       made by remote end-points. A remote end-point can request Asterisk to engage
00192       session-timers by either sending it an INVITE request with a "Supported: timer"
00193       header in it or by responding to Asterisk's INVITE with a 200 OK that contains
00194       Session-Expires: header in it. In this mode, the Asterisk server does not
00195       request session-timers from remote end-points. This is the default mode.
00196    2. Originate :: In the "originate" mode, the Asterisk server requests the remote
00197       end-points to activate session-timers in addition to honoring such requests
00198       made by the remote end-pints. In order to get as much protection as possible
00199       against hanging SIP channels due to network or end-point failures, Asterisk
00200       resends periodic re-INVITEs even if a remote end-point does not support
00201       the session-timers feature.
00202    3. Refuse :: In the "refuse" mode, Asterisk acts as if it does not support session-
00203       timers for inbound or outbound requests. If a remote end-point requests
00204       session-timers in a dialog, then Asterisk ignores that request unless it's
00205       noted as a requirement (Require: header), in which case the INVITE is
00206       rejected with a 420 Bad Extension response.
00207 
00208 */
00209 
00210 #include "asterisk.h"
00211 
00212 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 426599 $")
00213 
00214 #include <signal.h>
00215 #include <sys/signal.h>
00216 #include <regex.h>
00217 #include <inttypes.h>
00218 
00219 #include "asterisk/network.h"
00220 #include "asterisk/paths.h"   /* need ast_config_AST_SYSTEM_NAME */
00221 #include "asterisk/lock.h"
00222 #include "asterisk/config.h"
00223 #include "asterisk/module.h"
00224 #include "asterisk/pbx.h"
00225 #include "asterisk/sched.h"
00226 #include "asterisk/io.h"
00227 #include "asterisk/rtp_engine.h"
00228 #include "asterisk/udptl.h"
00229 #include "asterisk/acl.h"
00230 #include "asterisk/manager.h"
00231 #include "asterisk/callerid.h"
00232 #include "asterisk/cli.h"
00233 #include "asterisk/musiconhold.h"
00234 #include "asterisk/dsp.h"
00235 #include "asterisk/features.h"
00236 #include "asterisk/srv.h"
00237 #include "asterisk/astdb.h"
00238 #include "asterisk/causes.h"
00239 #include "asterisk/utils.h"
00240 #include "asterisk/file.h"
00241 #include "asterisk/astobj2.h"
00242 #include "asterisk/dnsmgr.h"
00243 #include "asterisk/devicestate.h"
00244 #include "asterisk/monitor.h"
00245 #include "asterisk/netsock2.h"
00246 #include "asterisk/localtime.h"
00247 #include "asterisk/abstract_jb.h"
00248 #include "asterisk/threadstorage.h"
00249 #include "asterisk/translate.h"
00250 #include "asterisk/ast_version.h"
00251 #include "asterisk/event.h"
00252 #include "asterisk/cel.h"
00253 #include "asterisk/data.h"
00254 #include "asterisk/aoc.h"
00255 #include "sip/include/sip.h"
00256 #include "sip/include/globals.h"
00257 #include "sip/include/config_parser.h"
00258 #include "sip/include/reqresp_parser.h"
00259 #include "sip/include/sip_utils.h"
00260 #include "sip/include/srtp.h"
00261 #include "sip/include/sdp_crypto.h"
00262 #include "asterisk/ccss.h"
00263 #include "asterisk/xml.h"
00264 #include "sip/include/dialog.h"
00265 #include "sip/include/dialplan_functions.h"
00266 
00267 
00268 /*** DOCUMENTATION
00269    <application name="SIPDtmfMode" language="en_US">
00270       <synopsis>
00271          Change the dtmfmode for a SIP call.
00272       </synopsis>
00273       <syntax>
00274          <parameter name="mode" required="true">
00275             <enumlist>
00276                <enum name="inband" />
00277                <enum name="info" />
00278                <enum name="rfc2833" />
00279             </enumlist>
00280          </parameter>
00281       </syntax>
00282       <description>
00283          <para>Changes the dtmfmode for a SIP call.</para>
00284       </description>
00285    </application>
00286    <application name="SIPAddHeader" language="en_US">
00287       <synopsis>
00288          Add a SIP header to the outbound call.
00289       </synopsis>
00290       <syntax argsep=":">
00291          <parameter name="Header" required="true" />
00292          <parameter name="Content" required="true" />
00293       </syntax>
00294       <description>
00295          <para>Adds a header to a SIP call placed with DIAL.</para>
00296          <para>Remember to use the X-header if you are adding non-standard SIP
00297          headers, like <literal>X-Asterisk-Accountcode:</literal>. Use this with care.
00298          Adding the wrong headers may jeopardize the SIP dialog.</para>
00299          <para>Always returns <literal>0</literal>.</para>
00300       </description>
00301    </application>
00302    <application name="SIPRemoveHeader" language="en_US">
00303       <synopsis>
00304          Remove SIP headers previously added with SIPAddHeader
00305       </synopsis>
00306       <syntax>
00307          <parameter name="Header" required="false" />
00308       </syntax>
00309       <description>
00310          <para>SIPRemoveHeader() allows you to remove headers which were previously
00311          added with SIPAddHeader(). If no parameter is supplied, all previously added
00312          headers will be removed. If a parameter is supplied, only the matching headers
00313          will be removed.</para>
00314          <para>For example you have added these 2 headers:</para>
00315          <para>SIPAddHeader(P-Asserted-Identity: sip:foo@bar);</para>
00316          <para>SIPAddHeader(P-Preferred-Identity: sip:bar@foo);</para>
00317          <para></para>
00318          <para>// remove all headers</para>
00319          <para>SIPRemoveHeader();</para>
00320          <para>// remove all P- headers</para>
00321          <para>SIPRemoveHeader(P-);</para>
00322          <para>// remove only the PAI header (note the : at the end)</para>
00323          <para>SIPRemoveHeader(P-Asserted-Identity:);</para>
00324          <para></para>
00325          <para>Always returns <literal>0</literal>.</para>
00326       </description>
00327    </application>
00328    <function name="SIP_HEADER" language="en_US">
00329       <synopsis>
00330          Gets the specified SIP header from an incoming INVITE message.
00331       </synopsis>
00332       <syntax>
00333          <parameter name="name" required="true" />
00334          <parameter name="number">
00335             <para>If not specified, defaults to <literal>1</literal>.</para>
00336          </parameter>
00337       </syntax>
00338       <description>
00339          <para>Since there are several headers (such as Via) which can occur multiple
00340          times, SIP_HEADER takes an optional second argument to specify which header with
00341          that name to retrieve. Headers start at offset <literal>1</literal>.</para>
00342       </description>
00343    </function>
00344    <function name="SIPPEER" language="en_US">
00345       <synopsis>
00346          Gets SIP peer information.
00347       </synopsis>
00348       <syntax>
00349          <parameter name="peername" required="true" />
00350          <parameter name="item">
00351             <enumlist>
00352                <enum name="ip">
00353                   <para>(default) The ip address.</para>
00354                </enum>
00355                <enum name="port">
00356                   <para>The port number.</para>
00357                </enum>
00358                <enum name="mailbox">
00359                   <para>The configured mailbox.</para>
00360                </enum>
00361                <enum name="context">
00362                   <para>The configured context.</para>
00363                </enum>
00364                <enum name="expire">
00365                   <para>The epoch time of the next expire.</para>
00366                </enum>
00367                <enum name="dynamic">
00368                   <para>Is it dynamic? (yes/no).</para>
00369                </enum>
00370                <enum name="callerid_name">
00371                   <para>The configured Caller ID name.</para>
00372                </enum>
00373                <enum name="callerid_num">
00374                   <para>The configured Caller ID number.</para>
00375                </enum>
00376                <enum name="callgroup">
00377                   <para>The configured Callgroup.</para>
00378                </enum>
00379                <enum name="pickupgroup">
00380                   <para>The configured Pickupgroup.</para>
00381                </enum>
00382                <enum name="codecs">
00383                   <para>The configured codecs.</para>
00384                </enum>
00385                <enum name="status">
00386                   <para>Status (if qualify=yes).</para>
00387                </enum>
00388                <enum name="regexten">
00389                   <para>Registration extension.</para>
00390                </enum>
00391                <enum name="limit">
00392                   <para>Call limit (call-limit).</para>
00393                </enum>
00394                <enum name="busylevel">
00395                   <para>Configured call level for signalling busy.</para>
00396                </enum>
00397                <enum name="curcalls">
00398                   <para>Current amount of calls. Only available if call-limit is set.</para>
00399                </enum>
00400                <enum name="language">
00401                   <para>Default language for peer.</para>
00402                </enum>
00403                <enum name="accountcode">
00404                   <para>Account code for this peer.</para>
00405                </enum>
00406                <enum name="useragent">
00407                   <para>Current user agent id for peer.</para>
00408                </enum>
00409                <enum name="maxforwards">
00410                   <para>The value used for SIP loop prevention in outbound requests</para>
00411                </enum>
00412                <enum name="chanvar[name]">
00413                   <para>A channel variable configured with setvar for this peer.</para>
00414                </enum>
00415                <enum name="codec[x]">
00416                   <para>Preferred codec index number <replaceable>x</replaceable> (beginning with zero).</para>
00417                </enum>
00418             </enumlist>
00419          </parameter>
00420       </syntax>
00421       <description></description>
00422    </function>
00423    <function name="SIPCHANINFO" language="en_US">
00424       <synopsis>
00425          Gets the specified SIP parameter from the current channel.
00426       </synopsis>
00427       <syntax>
00428          <parameter name="item" required="true">
00429             <enumlist>
00430                <enum name="peerip">
00431                   <para>The IP address of the peer.</para>
00432                </enum>
00433                <enum name="recvip">
00434                   <para>The source IP address of the peer.</para>
00435                </enum>
00436                <enum name="from">
00437                   <para>The URI from the <literal>From:</literal> header.</para>
00438                </enum>
00439                <enum name="uri">
00440                   <para>The URI from the <literal>Contact:</literal> header.</para>
00441                </enum>
00442                <enum name="useragent">
00443                   <para>The useragent.</para>
00444                </enum>
00445                <enum name="peername">
00446                   <para>The name of the peer.</para>
00447                </enum>
00448                <enum name="t38passthrough">
00449                   <para><literal>1</literal> if T38 is offered or enabled in this channel,
00450                   otherwise <literal>0</literal>.</para>
00451                </enum>
00452             </enumlist>
00453          </parameter>
00454       </syntax>
00455       <description></description>
00456    </function>
00457    <function name="CHECKSIPDOMAIN" language="en_US">
00458       <synopsis>
00459          Checks if domain is a local domain.
00460       </synopsis>
00461       <syntax>
00462          <parameter name="domain" required="true" />
00463       </syntax>
00464       <description>
00465          <para>This function checks if the <replaceable>domain</replaceable> in the argument is configured
00466          as a local SIP domain that this Asterisk server is configured to handle.
00467          Returns the domain name if it is locally handled, otherwise an empty string.
00468          Check the <literal>domain=</literal> configuration in <filename>sip.conf</filename>.</para>
00469       </description>
00470    </function>
00471    <manager name="SIPpeers" language="en_US">
00472       <synopsis>
00473          List SIP peers (text format).
00474       </synopsis>
00475       <syntax>
00476          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00477       </syntax>
00478       <description>
00479          <para>Lists SIP peers in text format with details on current status.
00480          Peerlist will follow as separate events, followed by a final event called
00481          PeerlistComplete.</para>
00482       </description>
00483    </manager>
00484    <manager name="SIPshowpeer" language="en_US">
00485       <synopsis>
00486          show SIP peer (text format).
00487       </synopsis>
00488       <syntax>
00489          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00490          <parameter name="Peer" required="true">
00491             <para>The peer name you want to check.</para>
00492          </parameter>
00493       </syntax>
00494       <description>
00495          <para>Show one SIP peer with details on current status.</para>
00496       </description>
00497    </manager>
00498    <manager name="SIPqualifypeer" language="en_US">
00499       <synopsis>
00500          Qualify SIP peers.
00501       </synopsis>
00502       <syntax>
00503          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00504          <parameter name="Peer" required="true">
00505             <para>The peer name you want to qualify.</para>
00506          </parameter>
00507       </syntax>
00508       <description>
00509          <para>Qualify a SIP peer.</para>
00510       </description>
00511    </manager>
00512    <manager name="SIPshowregistry" language="en_US">
00513       <synopsis>
00514          Show SIP registrations (text format).
00515       </synopsis>
00516       <syntax>
00517          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00518       </syntax>
00519       <description>
00520          <para>Lists all registration requests and status. Registrations will follow as separate
00521          events. followed by a final event called RegistrationsComplete.</para>
00522       </description>
00523    </manager>
00524    <manager name="SIPnotify" language="en_US">
00525       <synopsis>
00526          Send a SIP notify.
00527       </synopsis>
00528       <syntax>
00529          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00530          <parameter name="Channel" required="true">
00531             <para>Peer to receive the notify.</para>
00532          </parameter>
00533          <parameter name="Variable" required="true">
00534             <para>At least one variable pair must be specified.
00535             <replaceable>name</replaceable>=<replaceable>value</replaceable></para>
00536          </parameter>
00537       </syntax>
00538       <description>
00539          <para>Sends a SIP Notify event.</para>
00540          <para>All parameters for this event must be specified in the body of this request
00541          via multiple Variable: name=value sequences.</para>
00542       </description>
00543    </manager>
00544  ***/
00545 
00546 static int min_expiry = DEFAULT_MIN_EXPIRY;        /*!< Minimum accepted registration time */
00547 static int max_expiry = DEFAULT_MAX_EXPIRY;        /*!< Maximum accepted registration time */
00548 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
00549 static int mwi_expiry = DEFAULT_MWI_EXPIRY;
00550 
00551 static int unauth_sessions = 0;
00552 static int authlimit = DEFAULT_AUTHLIMIT;
00553 static int authtimeout = DEFAULT_AUTHTIMEOUT;
00554 
00555 /*! \brief Global jitterbuffer configuration - by default, jb is disabled
00556  *  \note Values shown here match the defaults shown in sip.conf.sample */
00557 static struct ast_jb_conf default_jbconf =
00558 {
00559    .flags = 0,
00560    .max_size = 200,
00561    .resync_threshold = 1000,
00562    .impl = "fixed",
00563    .target_extra = 40,
00564 };
00565 static struct ast_jb_conf global_jbconf;                /*!< Global jitterbuffer configuration */
00566 
00567 static const char config[] = "sip.conf";                /*!< Main configuration file */
00568 static const char notify_config[] = "sip_notify.conf";  /*!< Configuration file for sending Notify with CLI commands to reconfigure or reboot phones */
00569 
00570 /*! \brief Readable descriptions of device states.
00571  *  \note Should be aligned to above table as index */
00572 static const struct invstate2stringtable {
00573    const enum invitestates state;
00574    const char *desc;
00575 } invitestate2string[] = {
00576    {INV_NONE,              "None"  },
00577    {INV_CALLING,           "Calling (Trying)"},
00578    {INV_PROCEEDING,        "Proceeding "},
00579    {INV_EARLY_MEDIA,       "Early media"},
00580    {INV_COMPLETED,         "Completed (done)"},
00581    {INV_CONFIRMED,         "Confirmed (up)"},
00582    {INV_TERMINATED,        "Done"},
00583    {INV_CANCELLED,         "Cancelled"}
00584 };
00585 
00586 /*! \brief Subscription types that we support. We support
00587  * - dialoginfo updates (really device status, not dialog info as was the original intent of the standard)
00588  * - SIMPLE presence used for device status
00589  * - Voicemail notification subscriptions
00590  */
00591 static const struct cfsubscription_types {
00592    enum subscriptiontype type;
00593    const char * const event;
00594    const char * const mediatype;
00595    const char * const text;
00596 } subscription_types[] = {
00597    { NONE,        "-",        "unknown",               "unknown" },
00598    /* RFC 4235: SIP Dialog event package */
00599    { DIALOG_INFO_XML, "dialog",   "application/dialog-info+xml", "dialog-info+xml" },
00600    { CPIM_PIDF_XML,   "presence", "application/cpim-pidf+xml",   "cpim-pidf+xml" },  /* RFC 3863 */
00601    { PIDF_XML,        "presence", "application/pidf+xml",        "pidf+xml" },       /* RFC 3863 */
00602    { XPIDF_XML,       "presence", "application/xpidf+xml",       "xpidf+xml" },       /* Pre-RFC 3863 with MS additions */
00603    { MWI_NOTIFICATION,  "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
00604 };
00605 
00606 /*! \brief The core structure to setup dialogs. We parse incoming messages by using
00607  *  structure and then route the messages according to the type.
00608  *
00609  *  \note Note that sip_methods[i].id == i must hold or the code breaks
00610  */
00611 static const struct  cfsip_methods {
00612    enum sipmethod id;
00613    int need_rtp;     /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
00614    char * const text;
00615    enum can_create_dialog can_create;
00616 } sip_methods[] = {
00617    { SIP_UNKNOWN,   RTP,    "-UNKNOWN-",CAN_CREATE_DIALOG },
00618    { SIP_RESPONSE,  NO_RTP, "SIP/2.0",  CAN_NOT_CREATE_DIALOG },
00619    { SIP_REGISTER,  NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
00620    { SIP_OPTIONS,   NO_RTP, "OPTIONS",  CAN_CREATE_DIALOG },
00621    { SIP_NOTIFY,    NO_RTP, "NOTIFY",   CAN_CREATE_DIALOG },
00622    { SIP_INVITE,    RTP,    "INVITE",   CAN_CREATE_DIALOG },
00623    { SIP_ACK,       NO_RTP, "ACK",      CAN_NOT_CREATE_DIALOG },
00624    { SIP_PRACK,     NO_RTP, "PRACK",    CAN_NOT_CREATE_DIALOG },
00625    { SIP_BYE,       NO_RTP, "BYE",      CAN_NOT_CREATE_DIALOG },
00626    { SIP_REFER,     NO_RTP, "REFER",    CAN_CREATE_DIALOG },
00627    { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE",CAN_CREATE_DIALOG },
00628    { SIP_MESSAGE,   NO_RTP, "MESSAGE",  CAN_CREATE_DIALOG },
00629    { SIP_UPDATE,    NO_RTP, "UPDATE",   CAN_NOT_CREATE_DIALOG },
00630    { SIP_INFO,      NO_RTP, "INFO",     CAN_NOT_CREATE_DIALOG },
00631    { SIP_CANCEL,    NO_RTP, "CANCEL",   CAN_NOT_CREATE_DIALOG },
00632    { SIP_PUBLISH,   NO_RTP, "PUBLISH",  CAN_CREATE_DIALOG },
00633    { SIP_PING,      NO_RTP, "PING",     CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
00634 };
00635 
00636 /*! \brief Diversion header reasons
00637  *
00638  * The core defines a bunch of constants used to define
00639  * redirecting reasons. This provides a translation table
00640  * between those and the strings which may be present in
00641  * a SIP Diversion header
00642  */
00643 static const struct sip_reasons {
00644    enum AST_REDIRECTING_REASON code;
00645    char * const text;
00646 } sip_reason_table[] = {
00647    { AST_REDIRECTING_REASON_UNKNOWN, "unknown" },
00648    { AST_REDIRECTING_REASON_USER_BUSY, "user-busy" },
00649    { AST_REDIRECTING_REASON_NO_ANSWER, "no-answer" },
00650    { AST_REDIRECTING_REASON_UNAVAILABLE, "unavailable" },
00651    { AST_REDIRECTING_REASON_UNCONDITIONAL, "unconditional" },
00652    { AST_REDIRECTING_REASON_TIME_OF_DAY, "time-of-day" },
00653    { AST_REDIRECTING_REASON_DO_NOT_DISTURB, "do-not-disturb" },
00654    { AST_REDIRECTING_REASON_DEFLECTION, "deflection" },
00655    { AST_REDIRECTING_REASON_FOLLOW_ME, "follow-me" },
00656    { AST_REDIRECTING_REASON_OUT_OF_ORDER, "out-of-service" },
00657    { AST_REDIRECTING_REASON_AWAY, "away" },
00658    { AST_REDIRECTING_REASON_CALL_FWD_DTE, "unknown"}
00659 };
00660 
00661 
00662 /*! \name DefaultSettings
00663    Default setttings are used as a channel setting and as a default when
00664    configuring devices
00665 */
00666 /*@{*/
00667 static char default_language[MAX_LANGUAGE];      /*!< Default language setting for new channels */
00668 static char default_callerid[AST_MAX_EXTENSION]; /*!< Default caller ID for sip messages */
00669 static char default_mwi_from[80];                /*!< Default caller ID for MWI updates */
00670 static char default_fromdomain[AST_MAX_EXTENSION]; /*!< Default domain on outound messages */
00671 static int default_fromdomainport;                 /*!< Default domain port on outbound messages */
00672 static char default_notifymime[AST_MAX_EXTENSION]; /*!< Default MIME media type for MWI notify messages */
00673 static char default_vmexten[AST_MAX_EXTENSION];    /*!< Default From Username on MWI updates */
00674 static int default_qualify;                        /*!< Default Qualify= setting */
00675 static char default_mohinterpret[MAX_MUSICCLASS];  /*!< Global setting for moh class to use when put on hold */
00676 static char default_mohsuggest[MAX_MUSICCLASS];    /*!< Global setting for moh class to suggest when putting
00677                                                     *   a bridged channel on hold */
00678 static char default_parkinglot[AST_MAX_CONTEXT];   /*!< Parkinglot */
00679 static char default_engine[256];                   /*!< Default RTP engine */
00680 static int default_maxcallbitrate;                 /*!< Maximum bitrate for call */
00681 static struct ast_codec_pref default_prefs;        /*!< Default codec prefs */
00682 static unsigned int default_transports;            /*!< Default Transports (enum sip_transport) that are acceptable */
00683 static unsigned int default_primary_transport;     /*!< Default primary Transport (enum sip_transport) for outbound connections to devices */
00684 /*@}*/
00685 
00686 static struct sip_settings sip_cfg;    /*!< SIP configuration data.
00687                \note in the future we could have multiple of these (per domain, per device group etc) */
00688 
00689 /*!< use this macro when ast_uri_decode is dependent on pedantic checking to be on. */
00690 #define SIP_PEDANTIC_DECODE(str) \
00691    if (sip_cfg.pedanticsipchecking && !ast_strlen_zero(str)) { \
00692       ast_uri_decode(str); \
00693    }  \
00694 
00695 static unsigned int chan_idx;       /*!< used in naming sip channel */
00696 static int global_match_auth_username;    /*!< Match auth username if available instead of From: Default off. */
00697 
00698 static int global_relaxdtmf;        /*!< Relax DTMF */
00699 static int global_prematuremediafilter;   /*!< Enable/disable premature frames in a call (causing 183 early media) */
00700 static int global_rtptimeout;       /*!< Time out call if no RTP */
00701 static int global_rtpholdtimeout;   /*!< Time out call if no RTP during hold */
00702 static int global_rtpkeepalive;     /*!< Send RTP keepalives */
00703 static int global_reg_timeout;      /*!< Global time between attempts for outbound registrations */
00704 static int global_regattempts_max;  /*!< Registration attempts before giving up */
00705 static int global_reg_retry_403;    /*!< Treat 403 responses to registrations as 401 responses */
00706 static int global_shrinkcallerid;   /*!< enable or disable shrinking of caller id  */
00707 static int global_callcounter;      /*!< Enable call counters for all devices. This is currently enabled by setting the peer
00708                                      *   call-limit to INT_MAX. When we remove the call-limit from the code, we can make it
00709                                      *   with just a boolean flag in the device structure */
00710 static unsigned int global_tos_sip;      /*!< IP type of service for SIP packets */
00711 static unsigned int global_tos_audio;    /*!< IP type of service for audio RTP packets */
00712 static unsigned int global_tos_video;    /*!< IP type of service for video RTP packets */
00713 static unsigned int global_tos_text;     /*!< IP type of service for text RTP packets */
00714 static unsigned int global_cos_sip;      /*!< 802.1p class of service for SIP packets */
00715 static unsigned int global_cos_audio;    /*!< 802.1p class of service for audio RTP packets */
00716 static unsigned int global_cos_video;    /*!< 802.1p class of service for video RTP packets */
00717 static unsigned int global_cos_text;     /*!< 802.1p class of service for text RTP packets */
00718 static unsigned int recordhistory;       /*!< Record SIP history. Off by default */
00719 static unsigned int dumphistory;         /*!< Dump history to verbose before destroying SIP dialog */
00720 static char global_useragent[AST_MAX_EXTENSION];    /*!< Useragent for the SIP channel */
00721 static char global_sdpsession[AST_MAX_EXTENSION];   /*!< SDP session name for the SIP channel */
00722 static char global_sdpowner[AST_MAX_EXTENSION];     /*!< SDP owner name for the SIP channel */
00723 static int global_authfailureevents;     /*!< Whether we send authentication failure manager events or not. Default no. */
00724 static int global_t1;           /*!< T1 time */
00725 static int global_t1min;        /*!< T1 roundtrip time minimum */
00726 static int global_timer_b;      /*!< Timer B - RFC 3261 Section 17.1.1.2 */
00727 static unsigned int global_autoframing; /*!< Turn autoframing on or off. */
00728 static int global_qualifyfreq;          /*!< Qualify frequency */
00729 static int global_qualify_gap;          /*!< Time between our group of peer pokes */
00730 static int global_qualify_peers;        /*!< Number of peers to poke at a given time */
00731 
00732 static enum st_mode global_st_mode;           /*!< Mode of operation for Session-Timers           */
00733 static enum st_refresher_param global_st_refresher; /*!< Session-Timer refresher                        */
00734 static int global_min_se;                     /*!< Lowest threshold for session refresh interval  */
00735 static int global_max_se;                     /*!< Highest threshold for session refresh interval */
00736 
00737 static int global_store_sip_cause;    /*!< Whether the MASTER_CHANNEL(HASH(SIP_CAUSE,[chan_name])) var should be set */
00738 
00739 static int global_dynamic_exclude_static = 0; /*!< Exclude static peers from contact registrations */
00740 /*@}*/
00741 
00742 /*!
00743  * We use libxml2 in order to parse XML that may appear in the body of a SIP message. Currently,
00744  * the only usage is for parsing PIDF bodies of incoming PUBLISH requests in the call-completion
00745  * event package. This variable is set at module load time and may be checked at runtime to determine
00746  * if XML parsing support was found.
00747  */
00748 static int can_parse_xml;
00749 
00750 /*! \name Object counters @{
00751  *  \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
00752  *  should be used to modify these values. */
00753 static int speerobjs = 0;     /*!< Static peers */
00754 static int rpeerobjs = 0;     /*!< Realtime peers */
00755 static int apeerobjs = 0;     /*!< Autocreated peer objects */
00756 static int regobjs = 0;       /*!< Registry objects */
00757 /* }@ */
00758 
00759 static struct ast_flags global_flags[3] = {{0}};  /*!< global SIP_ flags */
00760 static unsigned int global_t38_maxdatagram;                /*!< global T.38 FaxMaxDatagram override */
00761 
00762 static struct ast_event_sub *network_change_event_subscription; /*!< subscription id for network change events */
00763 static int network_change_event_sched_id = -1;
00764 
00765 static char used_context[AST_MAX_CONTEXT];        /*!< name of automatically created context for unloading */
00766 
00767 AST_MUTEX_DEFINE_STATIC(netlock);
00768 
00769 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
00770    when it's doing something critical. */
00771 AST_MUTEX_DEFINE_STATIC(monlock);
00772 
00773 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
00774 
00775 /*! \brief This is the thread for the monitor which checks for input on the channels
00776    which are not currently in use.  */
00777 static pthread_t monitor_thread = AST_PTHREADT_NULL;
00778 
00779 static int sip_reloading = FALSE;                       /*!< Flag for avoiding multiple reloads at the same time */
00780 static enum channelreloadreason sip_reloadreason;       /*!< Reason for last reload/load of configuration */
00781 
00782 struct sched_context *sched;     /*!< The scheduling context */
00783 static struct io_context *io;           /*!< The IO context */
00784 static int *sipsock_read_id;            /*!< ID of IO entry for sipsock FD */
00785 struct sip_pkt;
00786 static AST_LIST_HEAD_STATIC(domain_list, domain);    /*!< The SIP domain list */
00787 
00788 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
00789 
00790 static enum sip_debug_e sipdebug;
00791 
00792 /*! \brief extra debugging for 'text' related events.
00793  *  At the moment this is set together with sip_debug_console.
00794  *  \note It should either go away or be implemented properly.
00795  */
00796 static int sipdebug_text;
00797 
00798 static const struct _map_x_s referstatusstrings[] = {
00799    { REFER_IDLE,      "<none>" },
00800    { REFER_SENT,      "Request sent" },
00801    { REFER_RECEIVED,  "Request received" },
00802    { REFER_CONFIRMED, "Confirmed" },
00803    { REFER_ACCEPTED,  "Accepted" },
00804    { REFER_RINGING,   "Target ringing" },
00805    { REFER_200OK,     "Done" },
00806    { REFER_FAILED,    "Failed" },
00807    { REFER_NOAUTH,    "Failed - auth failure" },
00808    { -1,               NULL} /* terminator */
00809 };
00810 
00811 /* --- Hash tables of various objects --------*/
00812 #ifdef LOW_MEMORY
00813 static const int HASH_PEER_SIZE = 17;
00814 static const int HASH_DIALOG_SIZE = 17;
00815 #else
00816 static const int HASH_PEER_SIZE = 563; /*!< Size of peer hash table, prime number preferred! */
00817 static const int HASH_DIALOG_SIZE = 563;
00818 #endif
00819 
00820 static const struct {
00821    enum ast_cc_service_type service;
00822    const char *service_string;
00823 } sip_cc_service_map [] = {
00824    [AST_CC_NONE] = { AST_CC_NONE, "" },
00825    [AST_CC_CCBS] = { AST_CC_CCBS, "BS" },
00826    [AST_CC_CCNR] = { AST_CC_CCNR, "NR" },
00827    [AST_CC_CCNL] = { AST_CC_CCNL, "NL" },
00828 };
00829 
00830 static enum ast_cc_service_type service_string_to_service_type(const char * const service_string)
00831 {
00832    enum ast_cc_service_type service;
00833    for (service = AST_CC_CCBS; service <= AST_CC_CCNL; ++service) {
00834       if (!strcasecmp(service_string, sip_cc_service_map[service].service_string)) {
00835          return service;
00836       }
00837    }
00838    return AST_CC_NONE;
00839 }
00840 
00841 static const struct {
00842    enum sip_cc_notify_state state;
00843    const char *state_string;
00844 } sip_cc_notify_state_map [] = {
00845    [CC_QUEUED] = {CC_QUEUED, "cc-state: queued"},
00846    [CC_READY] = {CC_READY, "cc-state: ready"},
00847 };
00848 
00849 AST_LIST_HEAD_STATIC(epa_static_data_list, epa_backend);
00850 
00851 static int sip_epa_register(const struct epa_static_data *static_data)
00852 {
00853    struct epa_backend *backend = ast_calloc(1, sizeof(*backend));
00854 
00855    if (!backend) {
00856       return -1;
00857    }
00858 
00859    backend->static_data = static_data;
00860 
00861    AST_LIST_LOCK(&epa_static_data_list);
00862    AST_LIST_INSERT_TAIL(&epa_static_data_list, backend, next);
00863    AST_LIST_UNLOCK(&epa_static_data_list);
00864    return 0;
00865 }
00866 
00867 static void sip_epa_unregister_all(void)
00868 {
00869    struct epa_backend *backend;
00870 
00871    AST_LIST_LOCK(&epa_static_data_list);
00872    while ((backend = AST_LIST_REMOVE_HEAD(&epa_static_data_list, next))) {
00873       ast_free(backend);
00874    }
00875    AST_LIST_UNLOCK(&epa_static_data_list);
00876 }
00877 
00878 static void cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry);
00879 
00880 static void cc_epa_destructor(void *data)
00881 {
00882    struct sip_epa_entry *epa_entry = data;
00883    struct cc_epa_entry *cc_entry = epa_entry->instance_data;
00884    ast_free(cc_entry);
00885 }
00886 
00887 static const struct epa_static_data cc_epa_static_data  = {
00888    .event = CALL_COMPLETION,
00889    .name = "call-completion",
00890    .handle_error = cc_handle_publish_error,
00891    .destructor = cc_epa_destructor,
00892 };
00893 
00894 static const struct epa_static_data *find_static_data(const char * const event_package)
00895 {
00896    const struct epa_backend *backend = NULL;
00897 
00898    AST_LIST_LOCK(&epa_static_data_list);
00899    AST_LIST_TRAVERSE(&epa_static_data_list, backend, next) {
00900       if (!strcmp(backend->static_data->name, event_package)) {
00901          break;
00902       }
00903    }
00904    AST_LIST_UNLOCK(&epa_static_data_list);
00905    return backend ? backend->static_data : NULL;
00906 }
00907 
00908 static struct sip_epa_entry *create_epa_entry (const char * const event_package, const char * const destination)
00909 {
00910    struct sip_epa_entry *epa_entry;
00911    const struct epa_static_data *static_data;
00912 
00913    if (!(static_data = find_static_data(event_package))) {
00914       return NULL;
00915    }
00916 
00917    if (!(epa_entry = ao2_t_alloc(sizeof(*epa_entry), static_data->destructor, "Allocate new EPA entry"))) {
00918       return NULL;
00919    }
00920 
00921    epa_entry->static_data = static_data;
00922    ast_copy_string(epa_entry->destination, destination, sizeof(epa_entry->destination));
00923    return epa_entry;
00924 }
00925 
00926 /*!
00927  * Used to create new entity IDs by ESCs.
00928  */
00929 static int esc_etag_counter;
00930 static const int DEFAULT_PUBLISH_EXPIRES = 3600;
00931 
00932 #ifdef HAVE_LIBXML2
00933 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);
00934 
00935 static const struct sip_esc_publish_callbacks cc_esc_publish_callbacks = {
00936    .initial_handler = cc_esc_publish_handler,
00937    .modify_handler = cc_esc_publish_handler,
00938 };
00939 #endif
00940 
00941 /*!
00942  * \brief The Event State Compositors
00943  *
00944  * An Event State Compositor is an entity which
00945  * accepts PUBLISH requests and acts appropriately
00946  * based on these requests.
00947  *
00948  * The actual event_state_compositor structure is simply
00949  * an ao2_container of sip_esc_entrys. When an incoming
00950  * PUBLISH is received, we can match the appropriate sip_esc_entry
00951  * using the entity ID of the incoming PUBLISH.
00952  */
00953 static struct event_state_compositor {
00954    enum subscriptiontype event;
00955    const char * name;
00956    const struct sip_esc_publish_callbacks *callbacks;
00957    struct ao2_container *compositor;
00958 } event_state_compositors [] = {
00959 #ifdef HAVE_LIBXML2
00960    {CALL_COMPLETION, "call-completion", &cc_esc_publish_callbacks},
00961 #endif
00962 };
00963 
00964 static const int ESC_MAX_BUCKETS = 37;
00965 
00966 static void esc_entry_destructor(void *obj)
00967 {
00968    struct sip_esc_entry *esc_entry = obj;
00969    if (esc_entry->sched_id > -1) {
00970       AST_SCHED_DEL(sched, esc_entry->sched_id);
00971    }
00972 }
00973 
00974 static int esc_hash_fn(const void *obj, const int flags)
00975 {
00976    const struct sip_esc_entry *entry = obj;
00977    return ast_str_hash(entry->entity_tag);
00978 }
00979 
00980 static int esc_cmp_fn(void *obj, void *arg, int flags)
00981 {
00982    struct sip_esc_entry *entry1 = obj;
00983    struct sip_esc_entry *entry2 = arg;
00984 
00985    return (!strcmp(entry1->entity_tag, entry2->entity_tag)) ? (CMP_MATCH | CMP_STOP) : 0;
00986 }
00987 
00988 static struct event_state_compositor *get_esc(const char * const event_package) {
00989    int i;
00990    for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
00991       if (!strcasecmp(event_package, event_state_compositors[i].name)) {
00992          return &event_state_compositors[i];
00993       }
00994    }
00995    return NULL;
00996 }
00997 
00998 static struct sip_esc_entry *get_esc_entry(const char * entity_tag, struct event_state_compositor *esc) {
00999    struct sip_esc_entry *entry;
01000    struct sip_esc_entry finder;
01001 
01002    ast_copy_string(finder.entity_tag, entity_tag, sizeof(finder.entity_tag));
01003 
01004    entry = ao2_find(esc->compositor, &finder, OBJ_POINTER);
01005 
01006    return entry;
01007 }
01008 
01009 static int publish_expire(const void *data)
01010 {
01011    struct sip_esc_entry *esc_entry = (struct sip_esc_entry *) data;
01012    struct event_state_compositor *esc = get_esc(esc_entry->event);
01013 
01014    ast_assert(esc != NULL);
01015 
01016    ao2_unlink(esc->compositor, esc_entry);
01017    ao2_ref(esc_entry, -1);
01018    return 0;
01019 }
01020 
01021 static void create_new_sip_etag(struct sip_esc_entry *esc_entry, int is_linked)
01022 {
01023    int new_etag = ast_atomic_fetchadd_int(&esc_etag_counter, +1);
01024    struct event_state_compositor *esc = get_esc(esc_entry->event);
01025 
01026    ast_assert(esc != NULL);
01027    if (is_linked) {
01028       ao2_unlink(esc->compositor, esc_entry);
01029    }
01030    snprintf(esc_entry->entity_tag, sizeof(esc_entry->entity_tag), "%d", new_etag);
01031    ao2_link(esc->compositor, esc_entry);
01032 }
01033 
01034 static struct sip_esc_entry *create_esc_entry(struct event_state_compositor *esc, struct sip_request *req, const int expires)
01035 {
01036    struct sip_esc_entry *esc_entry;
01037    int expires_ms;
01038 
01039    if (!(esc_entry = ao2_alloc(sizeof(*esc_entry), esc_entry_destructor))) {
01040       return NULL;
01041    }
01042 
01043    esc_entry->event = esc->name;
01044 
01045    expires_ms = expires * 1000;
01046    /* Bump refcount for scheduler */
01047    ao2_ref(esc_entry, +1);
01048    esc_entry->sched_id = ast_sched_add(sched, expires_ms, publish_expire, esc_entry);
01049 
01050    /* Note: This links the esc_entry into the ESC properly */
01051    create_new_sip_etag(esc_entry, 0);
01052 
01053    return esc_entry;
01054 }
01055 
01056 static int initialize_escs(void)
01057 {
01058    int i, res = 0;
01059    for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
01060       if (!((event_state_compositors[i].compositor) =
01061                ao2_container_alloc(ESC_MAX_BUCKETS, esc_hash_fn, esc_cmp_fn))) {
01062          res = -1;
01063       }
01064    }
01065    return res;
01066 }
01067 
01068 static void destroy_escs(void)
01069 {
01070    int i;
01071    for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
01072       ao2_ref(event_state_compositors[i].compositor, -1);
01073    }
01074 }
01075 
01076 /*!
01077  * \details
01078  * This container holds the dialogs that will be destroyed immediately.
01079  */
01080 struct ao2_container *dialogs_to_destroy;
01081 
01082 /*! \brief
01083  * Here we implement the container for dialogs (sip_pvt), defining
01084  * generic wrapper functions to ease the transition from the current
01085  * implementation (a single linked list) to a different container.
01086  * In addition to a reference to the container, we need functions to lock/unlock
01087  * the container and individual items, and functions to add/remove
01088  * references to the individual items.
01089  */
01090 static struct ao2_container *dialogs;
01091 #define sip_pvt_lock(x) ao2_lock(x)
01092 #define sip_pvt_trylock(x) ao2_trylock(x)
01093 #define sip_pvt_unlock(x) ao2_unlock(x)
01094 
01095 /*! \brief  The table of TCP threads */
01096 static struct ao2_container *threadt;
01097 
01098 /*! \brief  The peer list: Users, Peers and Friends */
01099 static struct ao2_container *peers;
01100 static struct ao2_container *peers_by_ip;
01101 
01102 /*! \brief  A bogus peer, to be used when authentication should fail */
01103 static struct sip_peer *bogus_peer;
01104 /*! \brief  We can recognise the bogus peer by this invalid MD5 hash */
01105 #define BOGUS_PEER_MD5SECRET "intentionally_invalid_md5_string"
01106 
01107 /*! \brief  The register list: Other SIP proxies we register with and receive calls from */
01108 static struct ast_register_list {
01109    ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
01110    int recheck;
01111 } regl;
01112 
01113 /*! \brief  The MWI subscription list */
01114 static struct ast_subscription_mwi_list {
01115    ASTOBJ_CONTAINER_COMPONENTS(struct sip_subscription_mwi);
01116 } submwil;
01117 static int temp_pvt_init(void *);
01118 static void temp_pvt_cleanup(void *);
01119 
01120 /*! \brief A per-thread temporary pvt structure */
01121 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
01122 
01123 /*! \brief Authentication container for realm authentication */
01124 static struct sip_auth_container *authl = NULL;
01125 /*! \brief Global authentication container protection while adjusting the references. */
01126 AST_MUTEX_DEFINE_STATIC(authl_lock);
01127 
01128 /* --- Sockets and networking --------------*/
01129 
01130 /*! \brief Main socket for UDP SIP communication.
01131  *
01132  * sipsock is shared between the SIP manager thread (which handles reload
01133  * requests), the udp io handler (sipsock_read()) and the user routines that
01134  * issue udp writes (using __sip_xmit()).
01135  * The socket is -1 only when opening fails (this is a permanent condition),
01136  * or when we are handling a reload() that changes its address (this is
01137  * a transient situation during which we might have a harmless race, see
01138  * below). Because the conditions for the race to be possible are extremely
01139  * rare, we don't want to pay the cost of locking on every I/O.
01140  * Rather, we remember that when the race may occur, communication is
01141  * bound to fail anyways, so we just live with this event and let
01142  * the protocol handle this above us.
01143  */
01144 static int sipsock  = -1;
01145 
01146 struct ast_sockaddr bindaddr; /*!< UDP: The address we bind to */
01147 
01148 /*! \brief our (internal) default address/port to put in SIP/SDP messages
01149  *  internip is initialized picking a suitable address from one of the
01150  * interfaces, and the same port number we bind to. It is used as the
01151  * default address/port in SIP messages, and as the default address
01152  * (but not port) in SDP messages.
01153  */
01154 static struct ast_sockaddr internip;
01155 
01156 /*! \brief our external IP address/port for SIP sessions.
01157  * externaddr.sin_addr is only set when we know we might be behind
01158  * a NAT, and this is done using a variety of (mutually exclusive)
01159  * ways from the config file:
01160  *
01161  * + with "externaddr = host[:port]" we specify the address/port explicitly.
01162  *   The address is looked up only once when (re)loading the config file;
01163  *
01164  * + with "externhost = host[:port]" we do a similar thing, but the
01165  *   hostname is stored in externhost, and the hostname->IP mapping
01166  *   is refreshed every 'externrefresh' seconds;
01167  *
01168  * Other variables (externhost, externexpire, externrefresh) are used
01169  * to support the above functions.
01170  */
01171 static struct ast_sockaddr externaddr;      /*!< External IP address if we are behind NAT */
01172 static struct ast_sockaddr media_address; /*!< External RTP IP address if we are behind NAT */
01173 
01174 static char externhost[MAXHOSTNAMELEN];   /*!< External host name */
01175 static time_t externexpire;             /*!< Expiration counter for re-resolving external host name in dynamic DNS */
01176 static int externrefresh = 10;          /*!< Refresh timer for DNS-based external address (dyndns) */
01177 static uint16_t externtcpport;          /*!< external tcp port */ 
01178 static uint16_t externtlsport;          /*!< external tls port */
01179 
01180 /*! \brief  List of local networks
01181  * We store "localnet" addresses from the config file into an access list,
01182  * marked as 'DENY', so the call to ast_apply_ha() will return
01183  * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
01184  * (i.e. presumably public) addresses.
01185  */
01186 static struct ast_ha *localaddr;    /*!< List of local networks, on the same side of NAT as this Asterisk */
01187 
01188 static int ourport_tcp;             /*!< The port used for TCP connections */
01189 static int ourport_tls;             /*!< The port used for TCP/TLS connections */
01190 static struct ast_sockaddr debugaddr;
01191 
01192 static struct ast_config *notify_types = NULL;    /*!< The list of manual NOTIFY types we know how to send */
01193 
01194 /*! some list management macros. */
01195 
01196 #define UNLINK(element, head, prev) do {  \
01197    if (prev)            \
01198       (prev)->next = (element)->next;  \
01199    else              \
01200       (head) = (element)->next;  \
01201    } while (0)
01202 
01203 struct show_peers_context;
01204 
01205 /*---------------------------- Forward declarations of functions in chan_sip.c */
01206 /* Note: This is added to help splitting up chan_sip.c into several files
01207    in coming releases. */
01208 
01209 /*--- PBX interface functions */
01210 static struct ast_channel *sip_request_call(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause);
01211 static int sip_devicestate(void *data);
01212 static int sip_sendtext(struct ast_channel *ast, const char *text);
01213 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
01214 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
01215 static int sip_hangup(struct ast_channel *ast);
01216 static int sip_answer(struct ast_channel *ast);
01217 static struct ast_frame *sip_read(struct ast_channel *ast);
01218 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
01219 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
01220 static int sip_transfer(struct ast_channel *ast, const char *dest);
01221 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
01222 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
01223 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
01224 static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen);
01225 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
01226 static const char *sip_get_callid(struct ast_channel *chan);
01227 
01228 static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr);
01229 static int sip_standard_port(enum sip_transport type, int port);
01230 static int sip_prepare_socket(struct sip_pvt *p);
01231 static int get_address_family_filter(unsigned int transport);
01232 
01233 /*--- Transmitting responses and requests */
01234 static int sipsock_read(int *id, int fd, short events, void *ignore);
01235 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data);
01236 static int __sip_reliable_xmit(struct sip_pvt *p, uint32_t seqno, int resp, struct ast_str *data, int fatal, int sipmethod);
01237 static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp);
01238 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
01239 static int retrans_pkt(const void *data);
01240 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);
01241 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01242 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01243 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01244 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);
01245 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
01246 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);
01247 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
01248 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
01249 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable);
01250 static int transmit_request(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch);
01251 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch);
01252 static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri);
01253 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri);
01254 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
01255 static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded);
01256 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
01257 static int transmit_info_with_vidupdate(struct sip_pvt *p);
01258 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
01259 static int transmit_refer(struct sip_pvt *p, const char *dest);
01260 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
01261 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
01262 static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state);
01263 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
01264 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno);
01265 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno);
01266 static void copy_request(struct sip_request *dst, const struct sip_request *src);
01267 static void receive_message(struct sip_pvt *p, struct sip_request *req);
01268 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward);
01269 static int sip_send_mwi_to_peer(struct sip_peer *peer, int cache_only);
01270 
01271 /* Misc dialog routines */
01272 static int __sip_autodestruct(const void *data);
01273 static void *registry_unref(struct sip_registry *reg, char *tag);
01274 static int update_call_counter(struct sip_pvt *fup, int event);
01275 static int auto_congest(const void *arg);
01276 static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method);
01277 static void free_old_route(struct sip_route *route);
01278 static void list_route(struct sip_route *route);
01279 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards, int resp);
01280 static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
01281                      struct sip_request *req, const char *uri);
01282 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
01283 static void check_pendings(struct sip_pvt *p);
01284 static void *sip_park_thread(void *stuff);
01285 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);
01286 
01287 static void *sip_pickup_thread(void *stuff);
01288 static int sip_pickup(struct ast_channel *chan);
01289 
01290 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
01291 static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method);
01292 
01293 /*--- Codec handling / SDP */
01294 static void try_suggested_sip_codec(struct sip_pvt *p);
01295 static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
01296 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
01297 static int find_sdp(struct sip_request *req);
01298 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
01299 static int process_sdp_o(const char *o, struct sip_pvt *p);
01300 static int process_sdp_c(const char *c, struct ast_sockaddr *addr);
01301 static int process_sdp_a_sendonly(const char *a, int *sendonly);
01302 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec);
01303 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec);
01304 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);
01305 static int process_sdp_a_image(const char *a, struct sip_pvt *p);
01306 static void add_codec_to_sdp(const struct sip_pvt *p, format_t codec,
01307               struct ast_str **m_buf, struct ast_str **a_buf,
01308               int debug, int *min_packet_size);
01309 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
01310             struct ast_str **m_buf, struct ast_str **a_buf,
01311             int debug);
01312 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
01313 static void do_setnat(struct sip_pvt *p);
01314 static void stop_media_flows(struct sip_pvt *p);
01315 
01316 /*--- Authentication stuff */
01317 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
01318 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
01319 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
01320                 const char *secret, const char *md5secret, int sipmethod,
01321                 const char *uri, enum xmittype reliable, int ignore);
01322 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
01323                      int sipmethod, const char *uri, enum xmittype reliable,
01324                      struct ast_sockaddr *addr, struct sip_peer **authpeer);
01325 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr);
01326 
01327 /*--- Domain handling */
01328 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
01329 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
01330 static void clear_sip_domains(void);
01331 
01332 /*--- SIP realm authentication */
01333 static void add_realm_authentication(struct sip_auth_container **credentials, const char *configuration, int lineno);
01334 static struct sip_auth *find_realm_authentication(struct sip_auth_container *credentials, const char *realm);
01335 
01336 /*--- Misc functions */
01337 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t);
01338 static int reload_config(enum channelreloadreason reason);
01339 static void add_diversion_header(struct sip_request *req, struct sip_pvt *pvt);
01340 static int expire_register(const void *data);
01341 static void *do_monitor(void *data);
01342 static int restart_monitor(void);
01343 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
01344 static struct ast_variable *copy_vars(struct ast_variable *src);
01345 static int dialog_find_multiple(void *obj, void *arg, int flags);
01346 static struct ast_channel *sip_pvt_lock_full(struct sip_pvt *pvt);
01347 /* static int sip_addrcmp(char *name, struct sockaddr_in *sin);   Support for peer matching */
01348 static int sip_refer_allocate(struct sip_pvt *p);
01349 static int sip_notify_allocate(struct sip_pvt *p);
01350 static void ast_quiet_chan(struct ast_channel *chan);
01351 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
01352 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
01353 
01354 /*--- Device monitoring and Device/extension state/event handling */
01355 static int cb_extensionstate(char *context, char* exten, int state, void *data);
01356 static int sip_devicestate(void *data);
01357 static int sip_poke_noanswer(const void *data);
01358 static int sip_poke_peer(struct sip_peer *peer, int force);
01359 static void sip_poke_all_peers(void);
01360 static void sip_peer_hold(struct sip_pvt *p, int hold);
01361 static void mwi_event_cb(const struct ast_event *, void *);
01362 static void network_change_event_cb(const struct ast_event *, void *);
01363 
01364 /*--- Applications, functions, CLI and manager command helpers */
01365 static const char *sip_nat_mode(const struct sip_pvt *p);
01366 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01367 static char *transfermode2str(enum transfermodes mode) attribute_const;
01368 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
01369 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01370 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01371 static struct sip_peer *_sip_show_peers_one(int fd, struct mansession *s, struct show_peers_context *cont, struct sip_peer *peer);
01372 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01373 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01374 static void  print_group(int fd, ast_group_t group, int crlf);
01375 static const char *dtmfmode2str(int mode) attribute_const;
01376 static int str2dtmfmode(const char *str) attribute_unused;
01377 static const char *insecure2str(int mode) attribute_const;
01378 static const char *allowoverlap2str(int mode) attribute_const;
01379 static void cleanup_stale_contexts(char *new, char *old);
01380 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
01381 static const char *domain_mode_to_text(const enum domain_mode mode);
01382 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01383 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01384 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01385 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01386 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01387 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01388 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01389 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01390 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01391 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
01392 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
01393 static char *complete_sip_peer(const char *word, int state, int flags2);
01394 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
01395 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
01396 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
01397 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
01398 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
01399 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01400 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01401 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01402 static char *sip_do_debug_ip(int fd, const char *arg);
01403 static char *sip_do_debug_peer(int fd, const char *arg);
01404 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01405 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01406 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01407 static int sip_dtmfmode(struct ast_channel *chan, const char *data);
01408 static int sip_addheader(struct ast_channel *chan, const char *data);
01409 static int sip_do_reload(enum channelreloadreason reason);
01410 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01411 static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
01412                   const char *name, int flag, int family);
01413 static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
01414                   const char *name, int flag);
01415 static int ast_sockaddr_resolve_first_transport(struct ast_sockaddr *addr,
01416                   const char *name, int flag, unsigned int transport);
01417 
01418 /*--- Debugging
01419    Functions for enabling debug per IP or fully, or enabling history logging for
01420    a SIP dialog
01421 */
01422 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to debuglog at end of dialog, before destroying data */
01423 static inline int sip_debug_test_addr(const struct ast_sockaddr *addr);
01424 static inline int sip_debug_test_pvt(struct sip_pvt *p);
01425 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
01426 static void sip_dump_history(struct sip_pvt *dialog);
01427 
01428 /*--- Device object handling */
01429 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
01430 static int update_call_counter(struct sip_pvt *fup, int event);
01431 static void sip_destroy_peer(struct sip_peer *peer);
01432 static void sip_destroy_peer_fn(void *peer);
01433 static void set_peer_defaults(struct sip_peer *peer);
01434 static struct sip_peer *temp_peer(const char *name);
01435 static void register_peer_exten(struct sip_peer *peer, int onoff);
01436 static struct sip_peer *find_peer(const char *peer, struct ast_sockaddr *addr, int realtime, int forcenamematch, int devstate_only, int transport);
01437 static int sip_poke_peer_s(const void *data);
01438 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
01439 static void reg_source_db(struct sip_peer *peer);
01440 static void destroy_association(struct sip_peer *peer);
01441 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
01442 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
01443 static void set_socket_transport(struct sip_socket *socket, int transport);
01444 
01445 /* Realtime device support */
01446 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);
01447 static void update_peer(struct sip_peer *p, int expire);
01448 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
01449 static const char *get_name_from_variable(const struct ast_variable *var);
01450 static struct sip_peer *realtime_peer(const char *peername, struct ast_sockaddr *sin, int devstate_only, int which_objects);
01451 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01452 
01453 /*--- Internal UA client handling (outbound registrations) */
01454 static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p);
01455 static void sip_registry_destroy(struct sip_registry *reg);
01456 static int sip_register(const char *value, int lineno);
01457 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
01458 static int sip_reregister(const void *data);
01459 static int __sip_do_register(struct sip_registry *r);
01460 static int sip_reg_timeout(const void *data);
01461 static void sip_send_all_registers(void);
01462 static int sip_reinvite_retry(const void *data);
01463 
01464 /*--- Parsing SIP requests and responses */
01465 static void append_date(struct sip_request *req);  /* Append date to SIP packet */
01466 static int determine_firstline_parts(struct sip_request *req);
01467 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
01468 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
01469 static int find_sip_method(const char *msg);
01470 static unsigned int parse_allowed_methods(struct sip_request *req);
01471 static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req);
01472 static int parse_request(struct sip_request *req);
01473 static const char *get_header(const struct sip_request *req, const char *name);
01474 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
01475 static int method_match(enum sipmethod id, const char *name);
01476 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
01477 static const char *find_alias(const char *name, const char *_default);
01478 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
01479 static void lws2sws(struct ast_str *msgbuf);
01480 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
01481 static char *remove_uri_parameters(char *uri);
01482 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
01483 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
01484 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
01485 static int set_address_from_contact(struct sip_pvt *pvt);
01486 static void check_via(struct sip_pvt *p, const struct sip_request *req);
01487 static int get_rpid(struct sip_pvt *p, struct sip_request *oreq);
01488 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason);
01489 static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id);
01490 static int get_msg_text(char *buf, int len, struct sip_request *req);
01491 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
01492 static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen);
01493 static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen);
01494 static int get_domain(const char *str, char *domain, int len);
01495 static void get_realm(struct sip_pvt *p, const struct sip_request *req);
01496 
01497 /*-- TCP connection handling ---*/
01498 static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session);
01499 static void *sip_tcp_worker_fn(void *);
01500 
01501 /*--- Constructing requests and responses */
01502 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
01503 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
01504 static void deinit_req(struct sip_request *req);
01505 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, uint32_t seqno, int newbranch);
01506 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri);
01507 static int init_resp(struct sip_request *resp, const char *msg);
01508 static inline int resp_needs_contact(const char *msg, enum sipmethod method);
01509 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
01510 static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p);
01511 static void build_via(struct sip_pvt *p);
01512 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
01513 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog);
01514 static char *generate_random_string(char *buf, size_t size);
01515 static void build_callid_pvt(struct sip_pvt *pvt);
01516 static void change_callid_pvt(struct sip_pvt *pvt, const char *callid);
01517 static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain);
01518 static void build_localtag_registry(struct sip_registry *reg);
01519 static void make_our_tag(struct sip_pvt *pvt);
01520 static int add_header(struct sip_request *req, const char *var, const char *value);
01521 static int add_header_max_forwards(struct sip_pvt *dialog, struct sip_request *req);
01522 static int add_content(struct sip_request *req, const char *line);
01523 static int finalize_content(struct sip_request *req);
01524 static int add_text(struct sip_request *req, const char *text);
01525 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
01526 static int add_rpid(struct sip_request *req, struct sip_pvt *p);
01527 static int add_vidupdate(struct sip_request *req);
01528 static void add_route(struct sip_request *req, struct sip_route *route);
01529 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
01530 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
01531 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
01532 static void set_destination(struct sip_pvt *p, char *uri);
01533 static void append_date(struct sip_request *req);
01534 static void build_contact(struct sip_pvt *p);
01535 
01536 /*------Request handling functions */
01537 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock);
01538 static int handle_request_update(struct sip_pvt *p, struct sip_request *req);
01539 static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, struct ast_sockaddr *addr, int *recount, const char *e, int *nounlock);
01540 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, int *nounlock);
01541 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
01542 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *sin, const char *e);
01543 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
01544 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
01545 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
01546 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
01547 static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
01548 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, struct ast_sockaddr *addr, int *nounlock);
01549 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
01550 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, uint32_t seqno, int *nounlock);
01551 
01552 /*------Response handling functions */
01553 static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01554 static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01555 static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01556 static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01557 static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01558 static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01559 static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01560 
01561 /*------ SRTP Support -------- */
01562 static int setup_srtp(struct sip_srtp **srtp);
01563 static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct sip_srtp **srtp, const char *a);
01564 
01565 /*------ T38 Support --------- */
01566 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
01567 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
01568 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
01569 static void change_t38_state(struct sip_pvt *p, int state);
01570 
01571 /*------ Session-Timers functions --------- */
01572 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
01573 static int  proc_session_timer(const void *vp);
01574 static void stop_session_timer(struct sip_pvt *p);
01575 static void start_session_timer(struct sip_pvt *p);
01576 static void restart_session_timer(struct sip_pvt *p);
01577 static const char *strefresherparam2str(enum st_refresher r);
01578 static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher_param *const p_ref);
01579 static int parse_minse(const char *p_hdrval, int *const p_interval);
01580 static int st_get_se(struct sip_pvt *, int max);
01581 static enum st_refresher st_get_refresher(struct sip_pvt *);
01582 static enum st_mode st_get_mode(struct sip_pvt *, int no_cached);
01583 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
01584 
01585 /*------- RTP Glue functions -------- */
01586 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, format_t codecs, int nat_active);
01587 
01588 /*!--- SIP MWI Subscription support */
01589 static int sip_subscribe_mwi(const char *value, int lineno);
01590 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi);
01591 static void sip_send_all_mwi_subscriptions(void);
01592 static int sip_subscribe_mwi_do(const void *data);
01593 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
01594 
01595 /*! \brief Definition of this channel for PBX channel registration */
01596 const struct ast_channel_tech sip_tech = {
01597    .type = "SIP",
01598    .description = "Session Initiation Protocol (SIP)",
01599    .capabilities = AST_FORMAT_AUDIO_MASK, /* all audio formats */
01600    .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
01601    .requester = sip_request_call,         /* called with chan unlocked */
01602    .devicestate = sip_devicestate,        /* called with chan unlocked (not chan-specific) */
01603    .call = sip_call,       /* called with chan locked */
01604    .send_html = sip_sendhtml,
01605    .hangup = sip_hangup,         /* called with chan locked */
01606    .answer = sip_answer,         /* called with chan locked */
01607    .read = sip_read,       /* called with chan locked */
01608    .write = sip_write,        /* called with chan locked */
01609    .write_video = sip_write,     /* called with chan locked */
01610    .write_text = sip_write,
01611    .indicate = sip_indicate,     /* called with chan locked */
01612    .transfer = sip_transfer,     /* called with chan locked */
01613    .fixup = sip_fixup,        /* called with chan locked */
01614    .send_digit_begin = sip_senddigit_begin,  /* called with chan unlocked */
01615    .send_digit_end = sip_senddigit_end,
01616    .bridge = ast_rtp_instance_bridge,        /* XXX chan unlocked ? */
01617    .early_bridge = ast_rtp_instance_early_bridge,
01618    .send_text = sip_sendtext,    /* called with chan locked */
01619    .func_channel_read = sip_acf_channel_read,
01620    .setoption = sip_setoption,
01621    .queryoption = sip_queryoption,
01622    .get_pvt_uniqueid = sip_get_callid,
01623 };
01624 
01625 /*! \brief This version of the sip channel tech has no send_digit_begin
01626  * callback so that the core knows that the channel does not want
01627  * DTMF BEGIN frames.
01628  * The struct is initialized just before registering the channel driver,
01629  * and is for use with channels using SIP INFO DTMF.
01630  */
01631 struct ast_channel_tech sip_tech_info;
01632 
01633 static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan);
01634 static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent);
01635 static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent);
01636 static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason);
01637 static int sip_cc_agent_status_request(struct ast_cc_agent *agent);
01638 static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent);
01639 static int sip_cc_agent_recall(struct ast_cc_agent *agent);
01640 static void sip_cc_agent_destructor(struct ast_cc_agent *agent);
01641 
01642 static struct ast_cc_agent_callbacks sip_cc_agent_callbacks = {
01643    .type = "SIP",
01644    .init = sip_cc_agent_init,
01645    .start_offer_timer = sip_cc_agent_start_offer_timer,
01646    .stop_offer_timer = sip_cc_agent_stop_offer_timer,
01647    .respond = sip_cc_agent_respond,
01648    .status_request = sip_cc_agent_status_request,
01649    .start_monitoring = sip_cc_agent_start_monitoring,
01650    .callee_available = sip_cc_agent_recall,
01651    .destructor = sip_cc_agent_destructor,
01652 };
01653 
01654 static int find_by_notify_uri_helper(void *obj, void *arg, int flags)
01655 {
01656    struct ast_cc_agent *agent = obj;
01657    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01658    const char *uri = arg;
01659 
01660    return !sip_uri_cmp(agent_pvt->notify_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
01661 }
01662 
01663 static struct ast_cc_agent *find_sip_cc_agent_by_notify_uri(const char * const uri)
01664 {
01665    struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_notify_uri_helper, (char *)uri, "SIP");
01666    return agent;
01667 }
01668 
01669 static int find_by_subscribe_uri_helper(void *obj, void *arg, int flags)
01670 {
01671    struct ast_cc_agent *agent = obj;
01672    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01673    const char *uri = arg;
01674 
01675    return !sip_uri_cmp(agent_pvt->subscribe_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
01676 }
01677 
01678 static struct ast_cc_agent *find_sip_cc_agent_by_subscribe_uri(const char * const uri)
01679 {
01680    struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_subscribe_uri_helper, (char *)uri, "SIP");
01681    return agent;
01682 }
01683 
01684 static int find_by_callid_helper(void *obj, void *arg, int flags)
01685 {
01686    struct ast_cc_agent *agent = obj;
01687    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01688    struct sip_pvt *call_pvt = arg;
01689 
01690    return !strcmp(agent_pvt->original_callid, call_pvt->callid) ? CMP_MATCH | CMP_STOP : 0;
01691 }
01692 
01693 static struct ast_cc_agent *find_sip_cc_agent_by_original_callid(struct sip_pvt *pvt)
01694 {
01695    struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_callid_helper, pvt, "SIP");
01696    return agent;
01697 }
01698 
01699 static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan)
01700 {
01701    struct sip_cc_agent_pvt *agent_pvt = ast_calloc(1, sizeof(*agent_pvt));
01702    struct sip_pvt *call_pvt = chan->tech_pvt;
01703 
01704    if (!agent_pvt) {
01705       return -1;
01706    }
01707 
01708    ast_assert(!strcmp(chan->tech->type, "SIP"));
01709 
01710    ast_copy_string(agent_pvt->original_callid, call_pvt->callid, sizeof(agent_pvt->original_callid));
01711    ast_copy_string(agent_pvt->original_exten, call_pvt->exten, sizeof(agent_pvt->original_exten));
01712    agent_pvt->offer_timer_id = -1;
01713    agent->private_data = agent_pvt;
01714    sip_pvt_lock(call_pvt);
01715    ast_set_flag(&call_pvt->flags[0], SIP_OFFER_CC);
01716    sip_pvt_unlock(call_pvt);
01717    return 0;
01718 }
01719 
01720 static int sip_offer_timer_expire(const void *data)
01721 {
01722    struct ast_cc_agent *agent = (struct ast_cc_agent *) data;
01723    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01724 
01725    agent_pvt->offer_timer_id = -1;
01726 
01727    return ast_cc_failed(agent->core_id, "SIP agent %s's offer timer expired", agent->device_name);
01728 }
01729 
01730 static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent)
01731 {
01732    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01733    int when;
01734 
01735    when = ast_get_cc_offer_timer(agent->cc_params) * 1000;
01736    agent_pvt->offer_timer_id = ast_sched_add(sched, when, sip_offer_timer_expire, agent);
01737    return 0;
01738 }
01739 
01740 static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent)
01741 {
01742    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01743 
01744    AST_SCHED_DEL(sched, agent_pvt->offer_timer_id);
01745    return 0;
01746 }
01747 
01748 static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason)
01749 {
01750    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01751 
01752    sip_pvt_lock(agent_pvt->subscribe_pvt);
01753    ast_set_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
01754    if (reason == AST_CC_AGENT_RESPONSE_SUCCESS || !ast_strlen_zero(agent_pvt->notify_uri)) {
01755       /* The second half of this if statement may be a bit hard to grasp,
01756        * so here's an explanation. When a subscription comes into
01757        * chan_sip, as long as it is not malformed, it will be passed
01758        * to the CC core. If the core senses an out-of-order state transition,
01759        * then the core will call this callback with the "reason" set to a
01760        * failure condition.
01761        * However, an out-of-order state transition will occur during a resubscription
01762        * for CC. In such a case, we can see that we have already generated a notify_uri
01763        * and so we can detect that this isn't a *real* failure. Rather, it is just
01764        * something the core doesn't recognize as a legitimate SIP state transition.
01765        * Thus we respond with happiness and flowers.
01766        */
01767       transmit_response(agent_pvt->subscribe_pvt, "200 OK", &agent_pvt->subscribe_pvt->initreq);
01768       transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_QUEUED);
01769    } else {
01770       transmit_response(agent_pvt->subscribe_pvt, "500 Internal Error", &agent_pvt->subscribe_pvt->initreq);
01771    }
01772    sip_pvt_unlock(agent_pvt->subscribe_pvt);
01773    agent_pvt->is_available = TRUE;
01774 }
01775 
01776 static int sip_cc_agent_status_request(struct ast_cc_agent *agent)
01777 {
01778    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01779    enum ast_device_state state = agent_pvt->is_available ? AST_DEVICE_NOT_INUSE : AST_DEVICE_INUSE;
01780    return ast_cc_agent_status_response(agent->core_id, state);
01781 }
01782 
01783 static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent)
01784 {
01785    /* To start monitoring just means to wait for an incoming PUBLISH
01786     * to tell us that the caller has become available again. No special
01787     * action is needed
01788     */
01789    return 0;
01790 }
01791 
01792 static int sip_cc_agent_recall(struct ast_cc_agent *agent)
01793 {
01794    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01795    /* If we have received a PUBLISH beforehand stating that the caller in question
01796     * is not available, we can save ourself a bit of effort here and just report
01797     * the caller as busy
01798     */
01799    if (!agent_pvt->is_available) {
01800       return ast_cc_agent_caller_busy(agent->core_id, "Caller %s is busy, reporting to the core",
01801             agent->device_name);
01802    }
01803    /* Otherwise, we transmit a NOTIFY to the caller and await either
01804     * a PUBLISH or an INVITE
01805     */
01806    sip_pvt_lock(agent_pvt->subscribe_pvt);
01807    transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_READY);
01808    sip_pvt_unlock(agent_pvt->subscribe_pvt);
01809    return 0;
01810 }
01811 
01812 static void sip_cc_agent_destructor(struct ast_cc_agent *agent)
01813 {
01814    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01815 
01816    if (!agent_pvt) {
01817       /* The agent constructor probably failed. */
01818       return;
01819    }
01820 
01821    sip_cc_agent_stop_offer_timer(agent);
01822    if (agent_pvt->subscribe_pvt) {
01823       sip_pvt_lock(agent_pvt->subscribe_pvt);
01824       if (!ast_test_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
01825          /* If we haven't sent a 200 OK for the SUBSCRIBE dialog yet, then we need to send a response letting
01826           * the subscriber know something went wrong
01827           */
01828          transmit_response(agent_pvt->subscribe_pvt, "500 Internal Server Error", &agent_pvt->subscribe_pvt->initreq);
01829       }
01830       sip_pvt_unlock(agent_pvt->subscribe_pvt);
01831       agent_pvt->subscribe_pvt = dialog_unref(agent_pvt->subscribe_pvt, "SIP CC agent destructor: Remove ref to subscription");
01832    }
01833    ast_free(agent_pvt);
01834 }
01835 
01836 struct ao2_container *sip_monitor_instances;
01837 
01838 static int sip_monitor_instance_hash_fn(const void *obj, const int flags)
01839 {
01840    const struct sip_monitor_instance *monitor_instance = obj;
01841    return monitor_instance->core_id;
01842 }
01843 
01844 static int sip_monitor_instance_cmp_fn(void *obj, void *arg, int flags)
01845 {
01846    struct sip_monitor_instance *monitor_instance1 = obj;
01847    struct sip_monitor_instance *monitor_instance2 = arg;
01848 
01849    return monitor_instance1->core_id == monitor_instance2->core_id ? CMP_MATCH | CMP_STOP : 0;
01850 }
01851 
01852 static void sip_monitor_instance_destructor(void *data)
01853 {
01854    struct sip_monitor_instance *monitor_instance = data;
01855    if (monitor_instance->subscription_pvt) {
01856       sip_pvt_lock(monitor_instance->subscription_pvt);
01857       monitor_instance->subscription_pvt->expiry = 0;
01858       transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 0, monitor_instance->subscribe_uri);
01859       sip_pvt_unlock(monitor_instance->subscription_pvt);
01860       dialog_unref(monitor_instance->subscription_pvt, "Unref monitor instance ref of subscription pvt");
01861    }
01862    if (monitor_instance->suspension_entry) {
01863       monitor_instance->suspension_entry->body[0] = '\0';
01864       transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_REMOVE ,monitor_instance->notify_uri);
01865       ao2_t_ref(monitor_instance->suspension_entry, -1, "Decrementing suspension entry refcount in sip_monitor_instance_destructor");
01866    }
01867    ast_string_field_free_memory(monitor_instance);
01868 }
01869 
01870 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)
01871 {
01872    struct sip_monitor_instance *monitor_instance = ao2_alloc(sizeof(*monitor_instance), sip_monitor_instance_destructor);
01873 
01874    if (!monitor_instance) {
01875       return NULL;
01876    }
01877 
01878    if (ast_string_field_init(monitor_instance, 256)) {
01879       ao2_ref(monitor_instance, -1);
01880       return NULL;
01881    }
01882 
01883    ast_string_field_set(monitor_instance, subscribe_uri, subscribe_uri);
01884    ast_string_field_set(monitor_instance, peername, peername);
01885    ast_string_field_set(monitor_instance, device_name, device_name);
01886    monitor_instance->core_id = core_id;
01887    ao2_link(sip_monitor_instances, monitor_instance);
01888    return monitor_instance;
01889 }
01890 
01891 static int find_sip_monitor_instance_by_subscription_pvt(void *obj, void *arg, int flags)
01892 {
01893    struct sip_monitor_instance *monitor_instance = obj;
01894    return monitor_instance->subscription_pvt == arg ? CMP_MATCH | CMP_STOP : 0;
01895 }
01896 
01897 static int find_sip_monitor_instance_by_suspension_entry(void *obj, void *arg, int flags)
01898 {
01899    struct sip_monitor_instance *monitor_instance = obj;
01900    return monitor_instance->suspension_entry == arg ? CMP_MATCH | CMP_STOP : 0;
01901 }
01902 
01903 static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id);
01904 static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor);
01905 static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor);
01906 static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id);
01907 static void sip_cc_monitor_destructor(void *private_data);
01908 
01909 static struct ast_cc_monitor_callbacks sip_cc_monitor_callbacks = {
01910    .type = "SIP",
01911    .request_cc = sip_cc_monitor_request_cc,
01912    .suspend = sip_cc_monitor_suspend,
01913    .unsuspend = sip_cc_monitor_unsuspend,
01914    .cancel_available_timer = sip_cc_monitor_cancel_available_timer,
01915    .destructor = sip_cc_monitor_destructor,
01916 };
01917 
01918 static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id)
01919 {
01920    struct sip_monitor_instance *monitor_instance = monitor->private_data;
01921    enum ast_cc_service_type service = monitor->service_offered;
01922    int when;
01923 
01924    if (!monitor_instance) {
01925       return -1;
01926    }
01927 
01928    if (!(monitor_instance->subscription_pvt = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
01929       return -1;
01930    }
01931 
01932    when = service == AST_CC_CCBS ? ast_get_ccbs_available_timer(monitor->interface->config_params) :
01933       ast_get_ccnr_available_timer(monitor->interface->config_params);
01934 
01935    sip_pvt_lock(monitor_instance->subscription_pvt);
01936    ast_set_flag(&monitor_instance->subscription_pvt->flags[0], SIP_OUTGOING);
01937    create_addr(monitor_instance->subscription_pvt, monitor_instance->peername, 0, 1);
01938    ast_sip_ouraddrfor(&monitor_instance->subscription_pvt->sa, &monitor_instance->subscription_pvt->ourip, monitor_instance->subscription_pvt);
01939    monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
01940    monitor_instance->subscription_pvt->expiry = when;
01941 
01942    transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 2, monitor_instance->subscribe_uri);
01943    sip_pvt_unlock(monitor_instance->subscription_pvt);
01944 
01945    ao2_t_ref(monitor, +1, "Adding a ref to the monitor for the scheduler");
01946    *available_timer_id = ast_sched_add(sched, when * 1000, ast_cc_available_timer_expire, monitor);
01947    return 0;
01948 }
01949 
01950 static int construct_pidf_body(enum sip_cc_publish_state state, char *pidf_body, size_t size, const char *presentity)
01951 {
01952    struct ast_str *body = ast_str_alloca(size);
01953    char tuple_id[32];
01954 
01955    generate_random_string(tuple_id, sizeof(tuple_id));
01956 
01957    /* We'll make this a bare-bones pidf body. In state_notify_build_xml, the PIDF
01958     * body gets a lot more extra junk that isn't necessary, so we'll leave it out here.
01959     */
01960    ast_str_append(&body, 0, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
01961    /* XXX The entity attribute is currently set to the peer name associated with the
01962     * dialog. This is because we currently only call this function for call-completion
01963     * PUBLISH bodies. In such cases, the entity is completely disregarded. For other
01964     * event packages, it may be crucial to have a proper URI as the presentity so this
01965     * should be revisited as support is expanded.
01966     */
01967    ast_str_append(&body, 0, "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" entity=\"%s\">\n", presentity);
01968    ast_str_append(&body, 0, "<tuple id=\"%s\">\n", tuple_id);
01969    ast_str_append(&body, 0, "<status><basic>%s</basic></status>\n", state == CC_OPEN ? "open" : "closed");
01970    ast_str_append(&body, 0, "</tuple>\n");
01971    ast_str_append(&body, 0, "</presence>\n");
01972    ast_copy_string(pidf_body, ast_str_buffer(body), size);
01973    return 0;
01974 }
01975 
01976 static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor)
01977 {
01978    struct sip_monitor_instance *monitor_instance = monitor->private_data;
01979    enum sip_publish_type publish_type;
01980    struct cc_epa_entry *cc_entry;
01981 
01982    if (!monitor_instance) {
01983       return -1;
01984    }
01985 
01986    if (!monitor_instance->suspension_entry) {
01987       /* We haven't yet allocated the suspension entry, so let's give it a shot */
01988       if (!(monitor_instance->suspension_entry = create_epa_entry("call-completion", monitor_instance->peername))) {
01989          ast_log(LOG_WARNING, "Unable to allocate sip EPA entry for call-completion\n");
01990          ao2_ref(monitor_instance, -1);
01991          return -1;
01992       }
01993       if (!(cc_entry = ast_calloc(1, sizeof(*cc_entry)))) {
01994          ast_log(LOG_WARNING, "Unable to allocate space for instance data of EPA entry for call-completion\n");
01995          ao2_ref(monitor_instance, -1);
01996          return -1;
01997       }
01998       cc_entry->core_id = monitor->core_id;
01999       monitor_instance->suspension_entry->instance_data = cc_entry;
02000       publish_type = SIP_PUBLISH_INITIAL;
02001    } else {
02002       publish_type = SIP_PUBLISH_MODIFY;
02003       cc_entry = monitor_instance->suspension_entry->instance_data;
02004    }
02005 
02006    cc_entry->current_state = CC_CLOSED;
02007 
02008    if (ast_strlen_zero(monitor_instance->notify_uri)) {
02009       /* If we have no set notify_uri, then what this means is that we have
02010        * not received a NOTIFY from this destination stating that he is
02011        * currently available.
02012        *
02013        * This situation can arise when the core calls the suspend callbacks
02014        * of multiple destinations. If one of the other destinations aside
02015        * from this one notified Asterisk that he is available, then there
02016        * is no reason to take any suspension action on this device. Rather,
02017        * we should return now and if we receive a NOTIFY while monitoring
02018        * is still "suspended" then we can immediately respond with the
02019        * proper PUBLISH to let this endpoint know what is going on.
02020        */
02021       return 0;
02022    }
02023    construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
02024    return transmit_publish(monitor_instance->suspension_entry, publish_type, monitor_instance->notify_uri);
02025 }
02026 
02027 static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor)
02028 {
02029    struct sip_monitor_instance *monitor_instance = monitor->private_data;
02030    struct cc_epa_entry *cc_entry;
02031 
02032    if (!monitor_instance) {
02033       return -1;
02034    }
02035 
02036    ast_assert(monitor_instance->suspension_entry != NULL);
02037 
02038    cc_entry = monitor_instance->suspension_entry->instance_data;
02039    cc_entry->current_state = CC_OPEN;
02040    if (ast_strlen_zero(monitor_instance->notify_uri)) {
02041       /* This means we are being asked to unsuspend a call leg we never
02042        * sent a PUBLISH on. As such, there is no reason to send another
02043        * PUBLISH at this point either. We can just return instead.
02044        */
02045       return 0;
02046    }
02047    construct_pidf_body(CC_OPEN, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
02048    return transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_MODIFY, monitor_instance->notify_uri);
02049 }
02050 
02051 static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id)
02052 {
02053    if (*sched_id != -1) {
02054       AST_SCHED_DEL(sched, *sched_id);
02055       ao2_t_ref(monitor, -1, "Removing scheduler's reference to the monitor");
02056    }
02057    return 0;
02058 }
02059 
02060 static void sip_cc_monitor_destructor(void *private_data)
02061 {
02062    struct sip_monitor_instance *monitor_instance = private_data;
02063    ao2_unlink(sip_monitor_instances, monitor_instance);
02064    ast_module_unref(ast_module_info->self);
02065 }
02066 
02067 static int sip_get_cc_information(struct sip_request *req, char *subscribe_uri, size_t size, enum ast_cc_service_type *service)
02068 {
02069    char *call_info = ast_strdupa(get_header(req, "Call-Info"));
02070    char *uri;
02071    char *purpose;
02072    char *service_str;
02073    static const char cc_purpose[] = "purpose=call-completion";
02074    static const int cc_purpose_len = sizeof(cc_purpose) - 1;
02075 
02076    if (ast_strlen_zero(call_info)) {
02077       /* No Call-Info present. Definitely no CC offer */
02078       return -1;
02079    }
02080 
02081    uri = strsep(&call_info, ";");
02082 
02083    while ((purpose = strsep(&call_info, ";"))) {
02084       if (!strncmp(purpose, cc_purpose, cc_purpose_len)) {
02085          break;
02086       }
02087    }
02088    if (!purpose) {
02089       /* We didn't find the appropriate purpose= parameter. Oh well */
02090       return -1;
02091    }
02092 
02093    /* Okay, call-completion has been offered. Let's figure out what type of service this is */
02094    while ((service_str = strsep(&call_info, ";"))) {
02095       if (!strncmp(service_str, "m=", 2)) {
02096          break;
02097       }
02098    }
02099    if (!service_str) {
02100       /* So they didn't offer a particular service, We'll just go with CCBS since it really
02101        * doesn't matter anyway
02102        */
02103       service_str = "BS";
02104    } else {
02105       /* We already determined that there is an "m=" so no need to check
02106        * the result of this strsep
02107        */
02108       strsep(&service_str, "=");
02109    }
02110 
02111    if ((*service = service_string_to_service_type(service_str)) == AST_CC_NONE) {
02112       /* Invalid service offered */
02113       return -1;
02114    }
02115 
02116    ast_copy_string(subscribe_uri, get_in_brackets(uri), size);
02117 
02118    return 0;
02119 }
02120 
02121 /*
02122  * \brief Determine what, if any, CC has been offered and queue a CC frame if possible
02123  *
02124  * After taking care of some formalities to be sure that this call is eligible for CC,
02125  * we first try to see if we can make use of native CC. We grab the information from
02126  * the passed-in sip_request (which is always a response to an INVITE). If we can
02127  * use native CC monitoring for the call, then so be it.
02128  *
02129  * If native cc monitoring is not possible or not supported, then we will instead attempt
02130  * to use generic monitoring. Falling back to generic from a failed attempt at using native
02131  * monitoring will only work if the monitor policy of the endpoint is "always"
02132  *
02133  * \param pvt The current dialog. Contains CC parameters for the endpoint
02134  * \param req The response to the INVITE we want to inspect
02135  * \param service The service to use if generic monitoring is to be used. For native
02136  * monitoring, we get the service from the SIP response itself
02137  */
02138 static void sip_handle_cc(struct sip_pvt *pvt, struct sip_request *req, enum ast_cc_service_type service)
02139 {
02140    enum ast_cc_monitor_policies monitor_policy = ast_get_cc_monitor_policy(pvt->cc_params);
02141    int core_id;
02142    char interface_name[AST_CHANNEL_NAME];
02143 
02144    if (monitor_policy == AST_CC_MONITOR_NEVER) {
02145       /* Don't bother, just return */
02146       return;
02147    }
02148 
02149    if ((core_id = ast_cc_get_current_core_id(pvt->owner)) == -1) {
02150       /* For some reason, CC is invalid, so don't try it! */
02151       return;
02152    }
02153 
02154    ast_channel_get_device_name(pvt->owner, interface_name, sizeof(interface_name));
02155 
02156    if (monitor_policy == AST_CC_MONITOR_ALWAYS || monitor_policy == AST_CC_MONITOR_NATIVE) {
02157       char subscribe_uri[SIPBUFSIZE];
02158       char device_name[AST_CHANNEL_NAME];
02159       enum ast_cc_service_type offered_service;
02160       struct sip_monitor_instance *monitor_instance;
02161       if (sip_get_cc_information(req, subscribe_uri, sizeof(subscribe_uri), &offered_service)) {
02162          /* If CC isn't being offered to us, or for some reason the CC offer is
02163           * not formatted correctly, then it may still be possible to use generic
02164           * call completion since the monitor policy may be "always"
02165           */
02166          goto generic;
02167       }
02168       ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
02169       if (!(monitor_instance = sip_monitor_instance_init(core_id, subscribe_uri, pvt->peername, device_name))) {
02170          /* Same deal. We can try using generic still */
02171          goto generic;
02172       }
02173       /* We bump the refcount of chan_sip because once we queue this frame, the CC core
02174        * will have a reference to callbacks in this module. We decrement the module
02175        * refcount once the monitor destructor is called
02176        */
02177       ast_module_ref(ast_module_info->self);
02178       ast_queue_cc_frame(pvt->owner, "SIP", pvt->dialstring, offered_service, monitor_instance);
02179       ao2_ref(monitor_instance, -1);
02180       return;
02181    }
02182 
02183 generic:
02184    if (monitor_policy == AST_CC_MONITOR_GENERIC || monitor_policy == AST_CC_MONITOR_ALWAYS) {
02185       ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE, interface_name, service, NULL);
02186    }
02187 }
02188 
02189 /*! \brief Working TLS connection configuration */
02190 static struct ast_tls_config sip_tls_cfg;
02191 
02192 /*! \brief Default TLS connection configuration */
02193 static struct ast_tls_config default_tls_cfg;
02194 
02195 /*! \brief The TCP server definition */
02196 static struct ast_tcptls_session_args sip_tcp_desc = {
02197    .accept_fd = -1,
02198    .master = AST_PTHREADT_NULL,
02199    .tls_cfg = NULL,
02200    .poll_timeout = -1,
02201    .name = "SIP TCP server",
02202    .accept_fn = ast_tcptls_server_root,
02203    .worker_fn = sip_tcp_worker_fn,
02204 };
02205 
02206 /*! \brief The TCP/TLS server definition */
02207 static struct ast_tcptls_session_args sip_tls_desc = {
02208    .accept_fd = -1,
02209    .master = AST_PTHREADT_NULL,
02210    .tls_cfg = &sip_tls_cfg,
02211    .poll_timeout = -1,
02212    .name = "SIP TLS server",
02213    .accept_fn = ast_tcptls_server_root,
02214    .worker_fn = sip_tcp_worker_fn,
02215 };
02216 
02217 /*! \brief Append to SIP dialog history
02218    \return Always returns 0 */
02219 #define append_history(p, event, fmt , args... )   append_history_full(p, "%-15s " fmt, event, ## args)
02220 
02221 struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
02222 {
02223    if (p)
02224 #ifdef REF_DEBUG
02225       __ao2_ref_debug(p, 1, tag, file, line, func);
02226 #else
02227       ao2_ref(p, 1);
02228 #endif
02229    else
02230       ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
02231    return p;
02232 }
02233 
02234 struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
02235 {
02236    if (p)
02237 #ifdef REF_DEBUG
02238       __ao2_ref_debug(p, -1, tag, file, line, func);
02239 #else
02240       ao2_ref(p, -1);
02241 #endif
02242    return NULL;
02243 }
02244 
02245 /*! \brief map from an integer value to a string.
02246  * If no match is found, return errorstring
02247  */
02248 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
02249 {
02250    const struct _map_x_s *cur;
02251 
02252    for (cur = table; cur->s; cur++)
02253       if (cur->x == x)
02254          return cur->s;
02255    return errorstring;
02256 }
02257 
02258 /*! \brief map from a string to an integer value, case insensitive.
02259  * If no match is found, return errorvalue.
02260  */
02261 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
02262 {
02263    const struct _map_x_s *cur;
02264 
02265    for (cur = table; cur->s; cur++)
02266       if (!strcasecmp(cur->s, s))
02267          return cur->x;
02268    return errorvalue;
02269 }
02270 
02271 static enum AST_REDIRECTING_REASON sip_reason_str_to_code(const char *text)
02272 {
02273    enum AST_REDIRECTING_REASON ast = AST_REDIRECTING_REASON_UNKNOWN;
02274    int i;
02275 
02276    for (i = 0; i < ARRAY_LEN(sip_reason_table); ++i) {
02277       if (!strcasecmp(text, sip_reason_table[i].text)) {
02278          ast = sip_reason_table[i].code;
02279          break;
02280       }
02281    }
02282 
02283    return ast;
02284 }
02285 
02286 static const char *sip_reason_code_to_str(enum AST_REDIRECTING_REASON code)
02287 {
02288    if (code >= 0 && code < ARRAY_LEN(sip_reason_table)) {
02289       return sip_reason_table[code].text;
02290    }
02291 
02292    return "unknown";
02293 }
02294 
02295 /*!
02296  * \brief generic function for determining if a correct transport is being
02297  * used to contact a peer
02298  *
02299  * this is done as a macro so that the "tmpl" var can be passed either a
02300  * sip_request or a sip_peer
02301  */
02302 #define check_request_transport(peer, tmpl) ({ \
02303    int ret = 0; \
02304    if (peer->socket.type == tmpl->socket.type) \
02305       ; \
02306    else if (!(peer->transports & tmpl->socket.type)) {\
02307       ast_log(LOG_ERROR, \
02308          "'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
02309          get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
02310          ); \
02311       ret = 1; \
02312    } else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
02313       ast_log(LOG_WARNING, \
02314          "peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
02315          peer->name, get_transport(tmpl->socket.type) \
02316       ); \
02317    } else { \
02318       ast_debug(1, \
02319          "peer '%s' has contacted us over %s even though we prefer %s.\n", \
02320          peer->name, get_transport(tmpl->socket.type), get_transport(peer->socket.type) \
02321       ); \
02322    }\
02323    (ret); \
02324 })
02325 
02326 /*! \brief
02327  * duplicate a list of channel variables, \return the copy.
02328  */
02329 static struct ast_variable *copy_vars(struct ast_variable *src)
02330 {
02331    struct ast_variable *res = NULL, *tmp, *v = NULL;
02332 
02333    for (v = src ; v ; v = v->next) {
02334       if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
02335          tmp->next = res;
02336          res = tmp;
02337       }
02338    }
02339    return res;
02340 }
02341 
02342 static void tcptls_packet_destructor(void *obj)
02343 {
02344    struct tcptls_packet *packet = obj;
02345 
02346    ast_free(packet->data);
02347 }
02348 
02349 static void sip_tcptls_client_args_destructor(void *obj)
02350 {
02351    struct ast_tcptls_session_args *args = obj;
02352    if (args->tls_cfg) {
02353       ast_free(args->tls_cfg->certfile);
02354       ast_free(args->tls_cfg->pvtfile);
02355       ast_free(args->tls_cfg->cipher);
02356       ast_free(args->tls_cfg->cafile);
02357       ast_free(args->tls_cfg->capath);
02358 
02359       ast_ssl_teardown(args->tls_cfg);
02360    }
02361    ast_free(args->tls_cfg);
02362    ast_free((char *) args->name);
02363 }
02364 
02365 static void sip_threadinfo_destructor(void *obj)
02366 {
02367    struct sip_threadinfo *th = obj;
02368    struct tcptls_packet *packet;
02369    if (th->alert_pipe[1] > -1) {
02370       close(th->alert_pipe[0]);
02371    }
02372    if (th->alert_pipe[1] > -1) {
02373       close(th->alert_pipe[1]);
02374    }
02375    th->alert_pipe[0] = th->alert_pipe[1] = -1;
02376 
02377    while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
02378       ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
02379    }
02380 
02381    if (th->tcptls_session) {
02382       ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
02383    }
02384 }
02385 
02386 /*! \brief creates a sip_threadinfo object and links it into the threadt table. */
02387 static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
02388 {
02389    struct sip_threadinfo *th;
02390 
02391    if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
02392       return NULL;
02393    }
02394 
02395    th->alert_pipe[0] = th->alert_pipe[1] = -1;
02396 
02397    if (pipe(th->alert_pipe) == -1) {
02398       ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
02399       ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
02400       return NULL;
02401    }
02402    ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
02403    th->tcptls_session = tcptls_session;
02404    th->type = transport ? transport : (tcptls_session->ssl ? SIP_TRANSPORT_TLS: SIP_TRANSPORT_TCP);
02405    ao2_t_link(threadt, th, "Adding new tcptls helper thread");
02406    ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
02407    return th;
02408 }
02409 
02410 /*! \brief used to indicate to a tcptls thread that data is ready to be written */
02411 static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
02412 {
02413    int res = len;
02414    struct sip_threadinfo *th = NULL;
02415    struct tcptls_packet *packet = NULL;
02416    struct sip_threadinfo tmp = {
02417       .tcptls_session = tcptls_session,
02418    };
02419    enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
02420 
02421    if (!tcptls_session) {
02422       return XMIT_ERROR;
02423    }
02424 
02425    ast_mutex_lock(&tcptls_session->lock);
02426 
02427    if ((tcptls_session->fd == -1) ||
02428       !(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
02429       !(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
02430       !(packet->data = ast_str_create(len))) {
02431       goto tcptls_write_setup_error;
02432    }
02433 
02434    /* goto tcptls_write_error should _NOT_ be used beyond this point */
02435    ast_str_set(&packet->data, 0, "%s", (char *) buf);
02436    packet->len = len;
02437 
02438    /* alert tcptls thread handler that there is a packet to be sent.
02439     * must lock the thread info object to guarantee control of the
02440     * packet queue */
02441    ao2_lock(th);
02442    if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
02443       ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
02444       ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
02445       packet = NULL;
02446       res = XMIT_ERROR;
02447    } else { /* it is safe to queue the frame after issuing the alert when we hold the threadinfo lock */
02448       AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
02449    }
02450    ao2_unlock(th);
02451 
02452    ast_mutex_unlock(&tcptls_session->lock);
02453    ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
02454    return res;
02455 
02456 tcptls_write_setup_error:
02457    if (th) {
02458       ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
02459    }
02460    if (packet) {
02461       ao2_t_ref(packet, -1, "could not allocate packet's data");
02462    }
02463    ast_mutex_unlock(&tcptls_session->lock);
02464 
02465    return XMIT_ERROR;
02466 }
02467 
02468 /*! \brief SIP TCP connection handler */
02469 static void *sip_tcp_worker_fn(void *data)
02470 {
02471    struct ast_tcptls_session_instance *tcptls_session = data;
02472 
02473    return _sip_tcp_helper_thread(tcptls_session);
02474 }
02475 
02476 /*! \brief Check if the authtimeout has expired.
02477  * \param start the time when the session started
02478  *
02479  * \retval 0 the timeout has expired
02480  * \retval -1 error
02481  * \return the number of milliseconds until the timeout will expire
02482  */
02483 static int sip_check_authtimeout(time_t start)
02484 {
02485    int timeout;
02486    time_t now;
02487    if(time(&now) == -1) {
02488       ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
02489       return -1;
02490    }
02491 
02492    timeout = (authtimeout - (now - start)) * 1000;
02493    if (timeout < 0) {
02494       /* we have timed out */
02495       return 0;
02496    }
02497 
02498    return timeout;
02499 }
02500 
02501 /*!
02502  * \brief Indication of a TCP message's integrity
02503  */
02504 enum message_integrity {
02505    /*!
02506     * The message has an error in it with
02507     * regards to its Content-Length header
02508     */
02509    MESSAGE_INVALID,
02510    /*!
02511     * The message is incomplete
02512     */
02513    MESSAGE_FRAGMENT,
02514    /*!
02515     * The data contains a complete message
02516     * plus a fragment of another.
02517     */
02518    MESSAGE_FRAGMENT_COMPLETE,
02519    /*!
02520     * The message is complete
02521     */
02522    MESSAGE_COMPLETE,
02523 };
02524 
02525 /*!
02526  * \brief
02527  * Get the content length from an unparsed SIP message
02528  *
02529  * \param message The unparsed SIP message headers
02530  * \return The value of the Content-Length header or -1 if message is invalid
02531  */
02532 static int read_raw_content_length(const char *message)
02533 {
02534    char *content_length_str;
02535    int content_length = -1;
02536 
02537    struct ast_str *msg_copy;
02538    char *msg;
02539 
02540    /* Using a ast_str because lws2sws takes one of those */
02541    if (!(msg_copy = ast_str_create(strlen(message) + 1))) {
02542       return -1;
02543    }
02544    ast_str_set(&msg_copy, 0, "%s", message);
02545 
02546    if (sip_cfg.pedanticsipchecking) {
02547       lws2sws(msg_copy);
02548    }
02549 
02550    msg = ast_str_buffer(msg_copy);
02551 
02552    /* Let's find a Content-Length header */
02553    if ((content_length_str = strcasestr(msg, "\nContent-Length:"))) {
02554       content_length_str += sizeof("\nContent-Length:") - 1;
02555    } else if ((content_length_str = strcasestr(msg, "\nl:"))) {
02556       content_length_str += sizeof("\nl:") - 1;
02557    } else {
02558       /* RFC 3261 18.3
02559        * "In the case of stream-oriented transports such as TCP, the Content-
02560        *  Length header field indicates the size of the body.  The Content-
02561        *  Length header field MUST be used with stream oriented transports."
02562        */
02563       goto done;
02564    }
02565 
02566    /* Double-check that this is a complete header */
02567    if (!strchr(content_length_str, '\n')) {
02568       goto done;
02569    }
02570 
02571    if (sscanf(content_length_str, "%30d", &content_length) != 1) {
02572       content_length = -1;
02573    }
02574 
02575 done:
02576    ast_free(msg_copy);
02577    return content_length;
02578 }
02579 
02580 /*!
02581  * \brief Check that a message received over TCP is a full message
02582  *
02583  * This will take the information read in and then determine if
02584  * 1) The message is a full SIP request
02585  * 2) The message is a partial SIP request
02586  * 3) The message contains a full SIP request along with another partial request
02587  * \param data The unparsed incoming SIP message.
02588  * \param request The resulting request with extra fragments removed.
02589  * \param overflow If the message contains more than a full request, this is the remainder of the message
02590  * \return The resulting integrity of the message
02591  */
02592 static enum message_integrity check_message_integrity(struct ast_str **request, struct ast_str **overflow)
02593 {
02594    char *message = ast_str_buffer(*request);
02595    char *body;
02596    int content_length;
02597    int message_len = ast_str_strlen(*request);
02598    int body_len;
02599 
02600    /* Important pieces to search for in a SIP request are \r\n\r\n. This
02601     * marks either
02602     * 1) The division between the headers and body
02603     * 2) The end of the SIP request
02604     */
02605    body = strstr(message, "\r\n\r\n");
02606    if (!body) {
02607       /* This is clearly a partial message since we haven't reached an end
02608        * yet.
02609        */
02610       return MESSAGE_FRAGMENT;
02611    }
02612    body += sizeof("\r\n\r\n") - 1;
02613    body_len = message_len - (body - message);
02614 
02615    body[-1] = '\0';
02616    content_length = read_raw_content_length(message);
02617    body[-1] = '\n';
02618 
02619    if (content_length < 0) {
02620       return MESSAGE_INVALID;
02621    } else if (content_length == 0) {
02622       /* We've definitely received an entire message. We need
02623        * to check if there's also a fragment of another message
02624        * in addition.
02625        */
02626       if (body_len == 0) {
02627          return MESSAGE_COMPLETE;
02628       } else {
02629          ast_str_append(overflow, 0, "%s", body);
02630          ast_str_truncate(*request, message_len - body_len);
02631          return MESSAGE_FRAGMENT_COMPLETE;
02632       }
02633    }
02634    /* Positive content length. Let's see what sort of
02635     * message body we're dealing with.
02636     */
02637    if (body_len < content_length) {
02638       /* We don't have the full message body yet */
02639       return MESSAGE_FRAGMENT;
02640    } else if (body_len > content_length) {
02641       /* We have the full message plus a fragment of a further
02642        * message
02643        */
02644       ast_str_append(overflow, 0, "%s", body + content_length);
02645       ast_str_truncate(*request, message_len - (body_len - content_length));
02646       return MESSAGE_FRAGMENT_COMPLETE;
02647    } else {
02648       /* Yay! Full message with no extra content */
02649       return MESSAGE_COMPLETE;
02650    }
02651 }
02652 
02653 /*!
02654  * \brief Read SIP request or response from a TCP/TLS connection
02655  *
02656  * \param req The request structure to be filled in
02657  * \param tcptls_session The TCP/TLS connection from which to read
02658  * \retval -1 Failed to read data
02659  * \retval 0 Successfully read data
02660  */
02661 static int sip_tcptls_read(struct sip_request *req, struct ast_tcptls_session_instance *tcptls_session,
02662       int authenticated, time_t start)
02663 {
02664    enum message_integrity message_integrity = MESSAGE_FRAGMENT;
02665 
02666    while (message_integrity == MESSAGE_FRAGMENT) {
02667       size_t datalen;
02668 
02669       if (ast_str_strlen(tcptls_session->overflow_buf) == 0) {
02670          char readbuf[4097];
02671          int timeout;
02672          int res;
02673          if (!tcptls_session->client && !authenticated) {
02674             if ((timeout = sip_check_authtimeout(start)) < 0) {
02675                return -1;
02676             }
02677 
02678             if (timeout == 0) {
02679                ast_debug(2, "SIP TCP/TLS server timed out\n");
02680                return -1;
02681             }
02682          } else {
02683             timeout = -1;
02684          }
02685          res = ast_wait_for_input(tcptls_session->fd, timeout);
02686          if (res < 0) {
02687             ast_debug(2, "SIP TCP/TLS server :: ast_wait_for_input returned %d\n", res);
02688             return -1;
02689          } else if (res == 0) {
02690             ast_debug(2, "SIP TCP/TLS server timed out\n");
02691             return -1;
02692          }
02693 
02694          res = ast_tcptls_server_read(tcptls_session, readbuf, sizeof(readbuf) - 1);
02695          if (res < 0) {
02696             if (errno == EAGAIN || errno == EINTR) {
02697                continue;
02698             }
02699             ast_debug(2, "SIP TCP/TLS server error when receiving data\n");
02700             return -1;
02701          } else if (res == 0) {
02702             ast_debug(2, "SIP TCP/TLS server has shut down\n");
02703             return -1;
02704          }
02705          readbuf[res] = '\0';
02706          ast_str_append(&req->data, 0, "%s", readbuf);
02707       } else {
02708          ast_str_append(&req->data, 0, "%s", ast_str_buffer(tcptls_session->overflow_buf));
02709          ast_str_reset(tcptls_session->overflow_buf);
02710       }
02711 
02712       datalen = ast_str_strlen(req->data);
02713       if (datalen > SIP_MAX_PACKET_SIZE) {
02714          ast_log(LOG_WARNING, "Rejecting TCP/TLS packet from '%s' because way too large: %zu\n",
02715             ast_sockaddr_stringify(&tcptls_session->remote_address), datalen);
02716          return -1;
02717       }
02718 
02719       message_integrity = check_message_integrity(&req->data, &tcptls_session->overflow_buf);
02720    }
02721 
02722    return 0;
02723 }
02724 
02725 /*! \brief SIP TCP thread management function
02726    This function reads from the socket, parses the packet into a request
02727 */
02728 static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session)
02729 {
02730    int res, timeout = -1, authenticated = 0, flags;
02731    time_t start;
02732    struct sip_request req = { 0, } , reqcpy = { 0, };
02733    struct sip_threadinfo *me = NULL;
02734    char buf[1024] = "";
02735    struct pollfd fds[2] = { { 0 }, { 0 }, };
02736    struct ast_tcptls_session_args *ca = NULL;
02737 
02738    /* If this is a server session, then the connection has already been
02739     * setup. Check if the authlimit has been reached and if not create the
02740     * threadinfo object so we can access this thread for writing.
02741     *
02742     * if this is a client connection more work must be done.
02743     * 1. We own the parent session args for a client connection.  This pointer needs
02744     *    to be held on to so we can decrement it's ref count on thread destruction.
02745     * 2. The threadinfo object was created before this thread was launched, however
02746     *    it must be found within the threadt table.
02747     * 3. Last, the tcptls_session must be started.
02748     */
02749    if (!tcptls_session->client) {
02750       if (ast_atomic_fetchadd_int(&unauth_sessions, +1) >= authlimit) {
02751          /* unauth_sessions is decremented in the cleanup code */
02752          goto cleanup;
02753       }
02754 
02755       if ((flags = fcntl(tcptls_session->fd, F_GETFL)) == -1) {
02756          ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
02757          goto cleanup;
02758       }
02759 
02760       flags |= O_NONBLOCK;
02761       if (fcntl(tcptls_session->fd, F_SETFL, flags) == -1) {
02762          ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
02763          goto cleanup;
02764       }
02765 
02766       if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? SIP_TRANSPORT_TLS : SIP_TRANSPORT_TCP))) {
02767          goto cleanup;
02768       }
02769       ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
02770    } else {
02771       struct sip_threadinfo tmp = {
02772          .tcptls_session = tcptls_session,
02773       };
02774 
02775       if ((!(ca = tcptls_session->parent)) ||
02776          (!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
02777          (!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
02778          goto cleanup;
02779       }
02780    }
02781 
02782    flags = 1;
02783    if (setsockopt(tcptls_session->fd, SOL_SOCKET, SO_KEEPALIVE, &flags, sizeof(flags))) {
02784       ast_log(LOG_ERROR, "error enabling TCP keep-alives on sip socket: %s\n", strerror(errno));
02785       goto cleanup;
02786    }
02787 
02788    me->threadid = pthread_self();
02789    ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "TLS" : "TCP");
02790 
02791    /* set up pollfd to watch for reads on both the socket and the alert_pipe */
02792    fds[0].fd = tcptls_session->fd;
02793    fds[1].fd = me->alert_pipe[0];
02794    fds[0].events = fds[1].events = POLLIN | POLLPRI;
02795 
02796    if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
02797       goto cleanup;
02798    }
02799    if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET))) {
02800       goto cleanup;
02801    }
02802 
02803    if(time(&start) == -1) {
02804       ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
02805       goto cleanup;
02806    }
02807 
02808    /*
02809     * We cannot let the stream exclusively wait for data to arrive.
02810     * We have to wake up the task to send outgoing messages.
02811     */
02812    ast_tcptls_stream_set_exclusive_input(tcptls_session->stream_cookie, 0);
02813 
02814    ast_tcptls_stream_set_timeout_sequence(tcptls_session->stream_cookie, ast_tvnow(),
02815       tcptls_session->client ? -1 : (authtimeout * 1000));
02816 
02817    for (;;) {
02818       struct ast_str *str_save;
02819 
02820       if (!tcptls_session->client && req.authenticated && !authenticated) {
02821          authenticated = 1;
02822          ast_tcptls_stream_set_timeout_disable(tcptls_session->stream_cookie);
02823          ast_atomic_fetchadd_int(&unauth_sessions, -1);
02824       }
02825 
02826       /* calculate the timeout for unauthenticated server sessions */
02827       if (!tcptls_session->client && !authenticated ) {
02828          if ((timeout = sip_check_authtimeout(start)) < 0) {
02829             goto cleanup;
02830          }
02831 
02832          if (timeout == 0) {
02833             ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "TLS": "TCP");
02834             goto cleanup;
02835          }
02836       } else {
02837          timeout = -1;
02838       }
02839 
02840       if (ast_str_strlen(tcptls_session->overflow_buf) == 0) {
02841          res = ast_poll(fds, 2, timeout); /* polls for both socket and alert_pipe */
02842          if (res < 0) {
02843             ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "TLS": "TCP", res);
02844             goto cleanup;
02845          } else if (res == 0) {
02846             /* timeout */
02847             ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "TLS": "TCP");
02848             goto cleanup;
02849          }
02850       }
02851 
02852       /* 
02853        * handle the socket event, check for both reads from the socket fd or TCP overflow buffer,
02854        * and writes from alert_pipe fd.
02855        */
02856       if (fds[0].revents || (ast_str_strlen(tcptls_session->overflow_buf) > 0)) { /* there is data on the socket to be read */
02857          fds[0].revents = 0;
02858 
02859          /* clear request structure */
02860          str_save = req.data;
02861          memset(&req, 0, sizeof(req));
02862          req.data = str_save;
02863          ast_str_reset(req.data);
02864 
02865          str_save = reqcpy.data;
02866          memset(&reqcpy, 0, sizeof(reqcpy));
02867          reqcpy.data = str_save;
02868          ast_str_reset(reqcpy.data);
02869 
02870          memset(buf, 0, sizeof(buf));
02871 
02872          if (tcptls_session->ssl) {
02873             set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
02874             req.socket.port = htons(ourport_tls);
02875          } else {
02876             set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
02877             req.socket.port = htons(ourport_tcp);
02878          }
02879          req.socket.fd = tcptls_session->fd;
02880 
02881          res = sip_tcptls_read(&req, tcptls_session, authenticated, start);
02882          if (res < 0) {
02883             goto cleanup;
02884          }
02885 
02886          req.socket.tcptls_session = tcptls_session;
02887          handle_request_do(&req, &tcptls_session->remote_address);
02888       }
02889 
02890       if (fds[1].revents) { /* alert_pipe indicates there is data in the send queue to be sent */
02891          enum sip_tcptls_alert alert;
02892          struct tcptls_packet *packet;
02893 
02894          fds[1].revents = 0;
02895 
02896          if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
02897             ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
02898             continue;
02899          }
02900 
02901          switch (alert) {
02902          case TCPTLS_ALERT_STOP:
02903             goto cleanup;
02904          case TCPTLS_ALERT_DATA:
02905             ao2_lock(me);
02906             if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
02907                ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty\n");
02908             }
02909             ao2_unlock(me);
02910 
02911             if (packet) {
02912                if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
02913                   ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
02914                }
02915                ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
02916             }
02917             break;
02918          default:
02919             ast_log(LOG_ERROR, "Unknown tcptls thread alert '%u'\n", alert);
02920          }
02921       }
02922    }
02923 
02924    ast_debug(2, "Shutting down thread for %s server\n", tcptls_session->ssl ? "TLS" : "TCP");
02925 
02926 cleanup:
02927    if (tcptls_session && !tcptls_session->client && !authenticated) {
02928       ast_atomic_fetchadd_int(&unauth_sessions, -1);
02929    }
02930 
02931    if (me) {
02932       ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
02933       ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
02934    }
02935    deinit_req(&reqcpy);
02936    deinit_req(&req);
02937 
02938    /* if client, we own the parent session arguments and must decrement ref */
02939    if (ca) {
02940       ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
02941    }
02942 
02943    if (tcptls_session) {
02944       ast_mutex_lock(&tcptls_session->lock);
02945       ast_tcptls_close_session_file(tcptls_session);
02946       tcptls_session->parent = NULL;
02947       ast_mutex_unlock(&tcptls_session->lock);
02948 
02949       ao2_ref(tcptls_session, -1);
02950       tcptls_session = NULL;
02951    }
02952    return NULL;
02953 }
02954 
02955 #ifdef REF_DEBUG
02956 #define ref_peer(arg1,arg2) _ref_peer((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
02957 #define unref_peer(arg1,arg2) _unref_peer((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
02958 static struct sip_peer *_ref_peer(struct sip_peer *peer, char *tag, char *file, int line, const char *func)
02959 {
02960    if (peer)
02961       __ao2_ref_debug(peer, 1, tag, file, line, func);
02962    else
02963       ast_log(LOG_ERROR, "Attempt to Ref a null peer pointer\n");
02964    return peer;
02965 }
02966 
02967 static struct sip_peer *_unref_peer(struct sip_peer *peer, char *tag, char *file, int line, const char *func)
02968 {
02969    if (peer)
02970       __ao2_ref_debug(peer, -1, tag, file, line, func);
02971    return NULL;
02972 }
02973 #else
02974 /*!
02975  * helper functions to unreference various types of objects.
02976  * By handling them this way, we don't have to declare the
02977  * destructor on each call, which removes the chance of errors.
02978  */
02979 static void *unref_peer(struct sip_peer *peer, char *tag)
02980 {
02981    ao2_t_ref(peer, -1, tag);
02982    return NULL;
02983 }
02984 
02985 static struct sip_peer *ref_peer(struct sip_peer *peer, char *tag)
02986 {
02987    ao2_t_ref(peer, 1, tag);
02988    return peer;
02989 }
02990 #endif /* REF_DEBUG */
02991 
02992 static void peer_sched_cleanup(struct sip_peer *peer)
02993 {
02994    if (peer->pokeexpire != -1) {
02995       AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
02996             unref_peer(peer, "removing poke peer ref"));
02997    }
02998    if (peer->expire != -1) {
02999       AST_SCHED_DEL_UNREF(sched, peer->expire,
03000             unref_peer(peer, "remove register expire ref"));
03001    }
03002 }
03003 
03004 typedef enum {
03005    SIP_PEERS_MARKED,
03006    SIP_PEERS_ALL,
03007 } peer_unlink_flag_t;
03008 
03009 /* this func is used with ao2_callback to unlink/delete all marked or linked
03010    peers, depending on arg */
03011 static int match_and_cleanup_peer_sched(void *peerobj, void *arg, int flags)
03012 {
03013    struct sip_peer *peer = peerobj;
03014    peer_unlink_flag_t which = *(peer_unlink_flag_t *)arg;
03015 
03016    if (which == SIP_PEERS_ALL || peer->the_mark) {
03017       peer_sched_cleanup(peer);
03018       if (peer->dnsmgr) {
03019          ast_dnsmgr_release(peer->dnsmgr);
03020          peer->dnsmgr = NULL;
03021          unref_peer(peer, "Release peer from dnsmgr");
03022       }
03023       return CMP_MATCH;
03024    }
03025    return 0;
03026 }
03027 
03028 static void unlink_peers_from_tables(peer_unlink_flag_t flag)
03029 {
03030    ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
03031       match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
03032    ao2_t_callback(peers_by_ip, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
03033       match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
03034 }
03035 
03036 /* \brief Unlink all marked peers from ao2 containers */
03037 static void unlink_marked_peers_from_tables(void)
03038 {
03039    unlink_peers_from_tables(SIP_PEERS_MARKED);
03040 }
03041 
03042 static void unlink_all_peers_from_tables(void)
03043 {
03044    unlink_peers_from_tables(SIP_PEERS_ALL);
03045 }
03046 
03047 /*! \brief maintain proper refcounts for a sip_pvt's outboundproxy
03048  *
03049  * This function sets pvt's outboundproxy pointer to the one referenced
03050  * by the proxy parameter. Because proxy may be a refcounted object, and
03051  * because pvt's old outboundproxy may also be a refcounted object, we need
03052  * to maintain the proper refcounts.
03053  *
03054  * \param pvt The sip_pvt for which we wish to set the outboundproxy
03055  * \param proxy The sip_proxy which we will point pvt towards.
03056  * \return Returns void
03057  */
03058 static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
03059 {
03060    struct sip_proxy *old_obproxy = pvt->outboundproxy;
03061    /* The sip_cfg.outboundproxy is statically allocated, and so
03062     * we don't ever need to adjust refcounts for it
03063     */
03064    if (proxy && proxy != &sip_cfg.outboundproxy) {
03065       ao2_ref(proxy, +1);
03066    }
03067    pvt->outboundproxy = proxy;
03068    if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
03069       ao2_ref(old_obproxy, -1);
03070    }
03071 }
03072 
03073 /*!
03074  * \brief Unlink a dialog from the dialogs container, as well as any other places
03075  * that it may be currently stored.
03076  *
03077  * \note A reference to the dialog must be held before calling this function, and this
03078  * function does not release that reference.
03079  */
03080 void dialog_unlink_all(struct sip_pvt *dialog)
03081 {
03082    struct sip_pkt *cp;
03083    struct ast_channel *owner;
03084 
03085    dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
03086 
03087    ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
03088 
03089    /* Unlink us from the owner (channel) if we have one */
03090    owner = sip_pvt_lock_full(dialog);
03091    if (owner) {
03092       ast_debug(1, "Detaching from channel %s\n", owner->name);
03093       owner->tech_pvt = dialog_unref(owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
03094       ast_channel_unlock(owner);
03095       ast_channel_unref(owner);
03096       dialog->owner = NULL;
03097    }
03098    sip_pvt_unlock(dialog);
03099 
03100    if (dialog->registry) {
03101       if (dialog->registry->call == dialog) {
03102          dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
03103       }
03104       dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
03105    }
03106    if (dialog->stateid != -1) {
03107       ast_extension_state_del(dialog->stateid, cb_extensionstate);
03108       dialog->stateid = -1;
03109    }
03110    /* Remove link from peer to subscription of MWI */
03111    if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog) {
03112       dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
03113    }
03114    if (dialog->relatedpeer && dialog->relatedpeer->call == dialog) {
03115       dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
03116    }
03117 
03118    /* remove all current packets in this dialog */
03119    while((cp = dialog->packets)) {
03120       dialog->packets = dialog->packets->next;
03121       AST_SCHED_DEL(sched, cp->retransid);
03122       dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
03123       if (cp->data) {
03124          ast_free(cp->data);
03125       }
03126       ast_free(cp);
03127    }
03128 
03129    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"));
03130 
03131    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"));
03132    
03133    if (dialog->autokillid > -1) {
03134       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"));
03135    }
03136 
03137    if (dialog->request_queue_sched_id > -1) {
03138       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"));
03139    }
03140 
03141    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"));
03142 
03143    if (dialog->t38id > -1) {
03144       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"));
03145    }
03146 
03147    if (dialog->stimer) {
03148       stop_session_timer(dialog);
03149    }
03150 
03151    dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
03152 }
03153 
03154 void *registry_unref(struct sip_registry *reg, char *tag)
03155 {
03156    ast_debug(3, "SIP Registry %s: refcount now %u\n", reg->hostname, reg->refcount - 1);
03157    ASTOBJ_UNREF(reg, sip_registry_destroy);
03158    return NULL;
03159 }
03160 
03161 /*! \brief Add object reference to SIP registry */
03162 static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
03163 {
03164    ast_debug(3, "SIP Registry %s: refcount now %u\n", reg->hostname, reg->refcount + 1);
03165    return ASTOBJ_REF(reg); /* Add pointer to registry in packet */
03166 }
03167 
03168 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
03169 static struct ast_udptl_protocol sip_udptl = {
03170    .type = "SIP",
03171    .get_udptl_info = sip_get_udptl_peer,
03172    .set_udptl_peer = sip_set_udptl_peer,
03173 };
03174 
03175 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03176    __attribute__((format(printf, 2, 3)));
03177 
03178 
03179 /*! \brief Convert transfer status to string */
03180 static const char *referstatus2str(enum referstatus rstatus)
03181 {
03182    return map_x_s(referstatusstrings, rstatus, "");
03183 }
03184 
03185 static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
03186 {
03187    if (pvt->final_destruction_scheduled) {
03188       return; /* This is already scheduled for final destruction, let the scheduler take care of it. */
03189    }
03190    append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
03191    pvt->needdestroy = 1;
03192 }
03193 
03194 /*! \brief Initialize the initital request packet in the pvt structure.
03195    This packet is used for creating replies and future requests in
03196    a dialog */
03197 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
03198 {
03199    if (p->initreq.headers) {
03200       ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
03201    } else {
03202       ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
03203    }
03204    /* Use this as the basis */
03205    copy_request(&p->initreq, req);
03206    parse_request(&p->initreq);
03207    if (req->debug) {
03208       ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
03209    }
03210 }
03211 
03212 /*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
03213 static void sip_alreadygone(struct sip_pvt *dialog)
03214 {
03215    ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
03216    dialog->alreadygone = 1;
03217 }
03218 
03219 /*! Resolve DNS srv name or host name in a sip_proxy structure */
03220 static int proxy_update(struct sip_proxy *proxy)
03221 {
03222    /* if it's actually an IP address and not a name,
03223            there's no need for a managed lookup */
03224    if (!ast_sockaddr_parse(&proxy->ip, proxy->name, 0)) {
03225       /* Ok, not an IP address, then let's check if it's a domain or host */
03226       /* XXX Todo - if we have proxy port, don't do SRV */
03227       proxy->ip.ss.ss_family = get_address_family_filter(SIP_TRANSPORT_UDP); /* Filter address family */
03228       if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
03229             ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
03230             return FALSE;
03231       }
03232 
03233    }
03234 
03235    ast_sockaddr_set_port(&proxy->ip, proxy->port);
03236 
03237    proxy->last_dnsupdate = time(NULL);
03238    return TRUE;
03239 }
03240 
03241 /*! \brief Parse proxy string and return an ao2_alloc'd proxy. If dest is
03242  *         non-NULL, no allocation is performed and dest is used instead.
03243  *         On error NULL is returned. */
03244 static struct sip_proxy *proxy_from_config(const char *proxy, int sipconf_lineno, struct sip_proxy *dest)
03245 {
03246    char *mutable_proxy, *sep, *name;
03247    int allocated = 0;
03248 
03249    if (!dest) {
03250       dest = ao2_alloc(sizeof(struct sip_proxy), NULL);
03251       if (!dest) {
03252          ast_log(LOG_WARNING, "Unable to allocate config storage for proxy\n");
03253          return NULL;
03254       }
03255       allocated = 1;
03256    }
03257 
03258    /* Format is: [transport://]name[:port][,force] */
03259    mutable_proxy = ast_skip_blanks(ast_strdupa(proxy));
03260    sep = strchr(mutable_proxy, ',');
03261    if (sep) {
03262       *sep++ = '\0';
03263       dest->force = !strncasecmp(ast_skip_blanks(sep), "force", 5);
03264    } else {
03265       dest->force = FALSE;
03266    }
03267 
03268    sip_parse_host(mutable_proxy, sipconf_lineno, &name, &dest->port, &dest->transport);
03269 
03270    /* Check that there is a name at all */
03271    if (ast_strlen_zero(name)) {
03272       if (allocated) {
03273          ao2_ref(dest, -1);
03274       } else {
03275          dest->name[0] = '\0';
03276       }
03277       return NULL;
03278    }
03279    ast_copy_string(dest->name, name, sizeof(dest->name));
03280 
03281    /* Resolve host immediately */
03282    proxy_update(dest);
03283 
03284    return dest;
03285 }
03286 
03287 /*! \brief converts ascii port to int representation. If no
03288  *  pt buffer is provided or the pt has errors when being converted
03289  *  to an int value, the port provided as the standard is used.
03290  */
03291 unsigned int port_str2int(const char *pt, unsigned int standard)
03292 {
03293    int port = standard;
03294    if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
03295       port = standard;
03296    }
03297 
03298    return port;
03299 }
03300 
03301 /*! \brief Get default outbound proxy or global proxy */
03302 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
03303 {
03304    if (dialog && dialog->options && dialog->options->outboundproxy) {
03305       if (sipdebug) {
03306          ast_debug(1, "OBPROXY: Applying dialplan set OBproxy to this call\n");
03307       }
03308       append_history(dialog, "OBproxy", "Using dialplan obproxy %s", dialog->options->outboundproxy->name);
03309       return dialog->options->outboundproxy;
03310    }
03311    if (peer && peer->outboundproxy) {
03312       if (sipdebug) {
03313          ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
03314       }
03315       append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
03316       return peer->outboundproxy;
03317    }
03318    if (sip_cfg.outboundproxy.name[0]) {
03319       if (sipdebug) {
03320          ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
03321       }
03322       append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
03323       return &sip_cfg.outboundproxy;
03324    }
03325    if (sipdebug) {
03326       ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
03327    }
03328    return NULL;
03329 }
03330 
03331 /*! \brief returns true if 'name' (with optional trailing whitespace)
03332  * matches the sip method 'id'.
03333  * Strictly speaking, SIP methods are case SENSITIVE, but we do
03334  * a case-insensitive comparison to be more tolerant.
03335  * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
03336  */
03337 static int method_match(enum sipmethod id, const char *name)
03338 {
03339    int len = strlen(sip_methods[id].text);
03340    int l_name = name ? strlen(name) : 0;
03341    /* true if the string is long enough, and ends with whitespace, and matches */
03342    return (l_name >= len && name && name[len] < 33 &&
03343       !strncasecmp(sip_methods[id].text, name, len));
03344 }
03345 
03346 /*! \brief  find_sip_method: Find SIP method from header */
03347 static int find_sip_method(const char *msg)
03348 {
03349    int i, res = 0;
03350    
03351    if (ast_strlen_zero(msg)) {
03352       return 0;
03353    }
03354    for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
03355       if (method_match(i, msg)) {
03356          res = sip_methods[i].id;
03357       }
03358    }
03359    return res;
03360 }
03361 
03362 /*! \brief See if we pass debug IP filter */
03363 static inline int sip_debug_test_addr(const struct ast_sockaddr *addr)
03364 {
03365    /* Can't debug if sipdebug is not enabled */
03366    if (!sipdebug) {
03367       return 0;
03368    }
03369 
03370    /* A null debug_addr means we'll debug any address */
03371    if (ast_sockaddr_isnull(&debugaddr)) {
03372       return 1;
03373    }
03374 
03375    /* If no port was specified for a debug address, just compare the
03376     * addresses, otherwise compare the address and port
03377     */
03378    if (ast_sockaddr_port(&debugaddr)) {
03379       return !ast_sockaddr_cmp(&debugaddr, addr);
03380    } else {
03381       return !ast_sockaddr_cmp_addr(&debugaddr, addr);
03382    }
03383 }
03384 
03385 /*! \brief The real destination address for a write */
03386 static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p)
03387 {
03388    if (p->outboundproxy) {
03389       return &p->outboundproxy->ip;
03390    }
03391 
03392    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;
03393 }
03394 
03395 /*! \brief Display SIP nat mode */
03396 static const char *sip_nat_mode(const struct sip_pvt *p)
03397 {
03398    return ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) ? "NAT" : "no NAT";
03399 }
03400 
03401 /*! \brief Test PVT for debugging output */
03402 static inline int sip_debug_test_pvt(struct sip_pvt *p)
03403 {
03404    if (!sipdebug) {
03405       return 0;
03406    }
03407    return sip_debug_test_addr(sip_real_dst(p));
03408 }
03409 
03410 /*! \brief Return int representing a bit field of transport types found in const char *transport */
03411 static int get_transport_str2enum(const char *transport)
03412 {
03413    int res = 0;
03414 
03415    if (ast_strlen_zero(transport)) {
03416       return res;
03417    }
03418 
03419    if (!strcasecmp(transport, "udp")) {
03420       res |= SIP_TRANSPORT_UDP;
03421    }
03422    if (!strcasecmp(transport, "tcp")) {
03423       res |= SIP_TRANSPORT_TCP;
03424    }
03425    if (!strcasecmp(transport, "tls")) {
03426       res |= SIP_TRANSPORT_TLS;
03427    }
03428 
03429    return res;
03430 }
03431 
03432 /*! \brief Return configuration of transports for a device */
03433 static inline const char *get_transport_list(unsigned int transports) {
03434    switch (transports) {
03435       case SIP_TRANSPORT_UDP:
03436          return "UDP";
03437       case SIP_TRANSPORT_TCP:
03438          return "TCP";
03439       case SIP_TRANSPORT_TLS:
03440          return "TLS";
03441       case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TCP:
03442          return "TCP,UDP";
03443       case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TLS:
03444          return "TLS,UDP";
03445       case SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS:
03446          return "TLS,TCP";
03447       default:
03448          return transports ?
03449             "TLS,TCP,UDP" : "UNKNOWN"; 
03450    }
03451 }
03452 
03453 /*! \brief Return transport as string */
03454 static inline const char *get_transport(enum sip_transport t)
03455 {
03456    switch (t) {
03457    case SIP_TRANSPORT_UDP:
03458       return "UDP";
03459    case SIP_TRANSPORT_TCP:
03460       return "TCP";
03461    case SIP_TRANSPORT_TLS:
03462       return "TLS";
03463    }
03464 
03465    return "UNKNOWN";
03466 }
03467 
03468 /*! \brief Return protocol string for srv dns query */
03469 static inline const char *get_srv_protocol(enum sip_transport t)
03470 {
03471    switch (t) {
03472    case SIP_TRANSPORT_UDP:
03473       return "udp";
03474    case SIP_TRANSPORT_TLS:
03475    case SIP_TRANSPORT_TCP:
03476       return "tcp";
03477    }
03478 
03479    return "udp";
03480 }
03481 
03482 /*! \brief Return service string for srv dns query */
03483 static inline const char *get_srv_service(enum sip_transport t)
03484 {
03485    switch (t) {
03486    case SIP_TRANSPORT_TCP:
03487    case SIP_TRANSPORT_UDP:
03488       return "sip";
03489    case SIP_TRANSPORT_TLS:
03490       return "sips";
03491    }
03492    return "sip";
03493 }
03494 
03495 /*! \brief Return transport of dialog.
03496    \note this is based on a false assumption. We don't always use the
03497    outbound proxy for all requests in a dialog. It depends on the
03498    "force" parameter. The FIRST request is always sent to the ob proxy.
03499    \todo Fix this function to work correctly
03500 */
03501 static inline const char *get_transport_pvt(struct sip_pvt *p)
03502 {
03503    if (p->outboundproxy && p->outboundproxy->transport) {
03504       set_socket_transport(&p->socket, p->outboundproxy->transport);
03505    }
03506 
03507    return get_transport(p->socket.type);
03508 }
03509 
03510 /*!
03511  * \internal
03512  * \brief Transmit SIP message
03513  *
03514  * \details
03515  * Sends a SIP request or response on a given socket (in the pvt)
03516  * \note
03517  * Called by retrans_pkt, send_request, send_response and __sip_reliable_xmit
03518  *
03519  * \return length of transmitted message, XMIT_ERROR on known network failures -1 on other failures.
03520  */
03521 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data)
03522 {
03523    int res = 0;
03524    const struct ast_sockaddr *dst = sip_real_dst(p);
03525 
03526    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));
03527 
03528    if (sip_prepare_socket(p) < 0) {
03529       return XMIT_ERROR;
03530    }
03531 
03532    if (p->socket.type == SIP_TRANSPORT_UDP) {
03533       res = ast_sendto(p->socket.fd, ast_str_buffer(data), ast_str_strlen(data), 0, dst);
03534    } else if (p->socket.tcptls_session) {
03535       res = sip_tcptls_write(p->socket.tcptls_session, ast_str_buffer(data), ast_str_strlen(data));
03536    } else {
03537       ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
03538       return XMIT_ERROR;
03539    }
03540 
03541    if (res == -1) {
03542       switch (errno) {
03543       case EBADF:       /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
03544       case EHOSTUNREACH:   /* Host can't be reached */
03545       case ENETDOWN:       /* Interface down */
03546       case ENETUNREACH: /* Network failure */
03547       case ECONNREFUSED:      /* ICMP port unreachable */
03548          res = XMIT_ERROR; /* Don't bother with trying to transmit again */
03549       }
03550    }
03551    if (res != ast_str_strlen(data)) {
03552       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));
03553    }
03554 
03555    return res;
03556 }
03557 
03558 /*! \brief Build a Via header for a request */
03559 static void build_via(struct sip_pvt *p)
03560 {
03561    /* Work around buggy UNIDEN UIP200 firmware */
03562    const char *rport = (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) || ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)) ? ";rport" : "";
03563 
03564    /* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
03565    snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s;branch=z9hG4bK%08x%s",
03566        get_transport_pvt(p),
03567        ast_sockaddr_stringify_remote(&p->ourip),
03568        (unsigned)p->branch, rport);
03569 }
03570 
03571 /*! \brief NAT fix - decide which IP address to use for Asterisk server?
03572  *
03573  * Using the localaddr structure built up with localnet statements in sip.conf
03574  * apply it to their address to see if we need to substitute our
03575  * externaddr or can get away with our internal bindaddr
03576  * 'us' is always overwritten.
03577  */
03578 static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p)
03579 {
03580    struct ast_sockaddr theirs;
03581 
03582    /* Set want_remap to non-zero if we want to remap 'us' to an externally
03583     * reachable IP address and port. This is done if:
03584     * 1. we have a localaddr list (containing 'internal' addresses marked
03585     *    as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
03586     *    and AST_SENSE_ALLOW on 'external' ones);
03587     * 2. externaddr is set, so we know what to use as the
03588     *    externally visible address;
03589     * 3. the remote address, 'them', is external;
03590     * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
03591     *    when passed to ast_apply_ha() so it does need to be remapped.
03592     *    This fourth condition is checked later.
03593     */
03594    int want_remap = 0;
03595 
03596    ast_sockaddr_copy(us, &internip); /* starting guess for the internal address */
03597    /* now ask the system what would it use to talk to 'them' */
03598    ast_ouraddrfor(them, us);
03599    ast_sockaddr_copy(&theirs, them);
03600 
03601    if (ast_sockaddr_is_ipv6(&theirs)) {
03602       if (localaddr && !ast_sockaddr_isnull(&externaddr) && !ast_sockaddr_is_any(&bindaddr)) {
03603          ast_log(LOG_WARNING, "Address remapping activated in sip.conf "
03604             "but we're using IPv6, which doesn't need it. Please "
03605             "remove \"localnet\" and/or \"externaddr\" settings.\n");
03606       }
03607    } else {
03608       want_remap = localaddr &&
03609          !ast_sockaddr_isnull(&externaddr) &&
03610          ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
03611    }
03612 
03613    if (want_remap &&
03614        (!sip_cfg.matchexternaddrlocally || !ast_apply_ha(localaddr, us)) ) {
03615       /* if we used externhost, see if it is time to refresh the info */
03616       if (externexpire && time(NULL) >= externexpire) {
03617          if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
03618             ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
03619          }
03620          externexpire = time(NULL) + externrefresh;
03621       }
03622       if (!ast_sockaddr_isnull(&externaddr)) {
03623          ast_sockaddr_copy(us, &externaddr);
03624          switch (p->socket.type) {
03625          case SIP_TRANSPORT_TCP:
03626             if (!externtcpport && ast_sockaddr_port(&externaddr)) {
03627                /* for consistency, default to the externaddr port */
03628                externtcpport = ast_sockaddr_port(&externaddr);
03629             }
03630             ast_sockaddr_set_port(us, externtcpport);
03631             break;
03632          case SIP_TRANSPORT_TLS:
03633             ast_sockaddr_set_port(us, externtlsport);
03634             break;
03635          case SIP_TRANSPORT_UDP:
03636             if (!ast_sockaddr_port(&externaddr)) {
03637                ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
03638             }
03639             break;
03640          default:
03641             break;
03642          }
03643       }
03644       ast_debug(1, "Target address %s is not local, substituting externaddr\n",
03645            ast_sockaddr_stringify(them));
03646    } else {
03647       /* no remapping, but we bind to a specific address, so use it. */
03648       switch (p->socket.type) {
03649       case SIP_TRANSPORT_TCP:
03650          if (!ast_sockaddr_is_any(&sip_tcp_desc.local_address)) {
03651             ast_sockaddr_copy(us,
03652                     &sip_tcp_desc.local_address);
03653          } else {
03654             ast_sockaddr_set_port(us,
03655                         ast_sockaddr_port(&sip_tcp_desc.local_address));
03656          }
03657          break;
03658       case SIP_TRANSPORT_TLS:
03659          if (!ast_sockaddr_is_any(&sip_tls_desc.local_address)) {
03660             ast_sockaddr_copy(us,
03661                     &sip_tls_desc.local_address);
03662          } else {
03663             ast_sockaddr_set_port(us,
03664                         ast_sockaddr_port(&sip_tls_desc.local_address));
03665          }
03666          break;
03667       case SIP_TRANSPORT_UDP:
03668          /* fall through on purpose */
03669       default:
03670          if (!ast_sockaddr_is_any(&bindaddr)) {
03671             ast_sockaddr_copy(us, &bindaddr);
03672          }
03673          if (!ast_sockaddr_port(us)) {
03674             ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
03675          }
03676       }
03677    }
03678    ast_debug(3, "Setting SIP_TRANSPORT_%s with address %s\n", get_transport(p->socket.type), ast_sockaddr_stringify(us));
03679 }
03680 
03681 /*! \brief Append to SIP dialog history with arg list  */
03682 static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
03683 {
03684    char buf[80], *c = buf; /* max history length */
03685    struct sip_history *hist;
03686    int l;
03687 
03688    vsnprintf(buf, sizeof(buf), fmt, ap);
03689    strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
03690    l = strlen(buf) + 1;
03691    if (!(hist = ast_calloc(1, sizeof(*hist) + l))) {
03692       return;
03693    }
03694    if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
03695       ast_free(hist);
03696       return;
03697    }
03698    memcpy(hist->event, buf, l);
03699    if (p->history_entries == MAX_HISTORY_ENTRIES) {
03700       struct sip_history *oldest;
03701       oldest = AST_LIST_REMOVE_HEAD(p->history, list);
03702       p->history_entries--;
03703       ast_free(oldest);
03704    }
03705    AST_LIST_INSERT_TAIL(p->history, hist, list);
03706    p->history_entries++;
03707 }
03708 
03709 /*! \brief Append to SIP dialog history with arg list  */
03710 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03711 {
03712    va_list ap;
03713 
03714    if (!p) {
03715       return;
03716    }
03717 
03718    if (!p->do_history && !recordhistory && !dumphistory) {
03719       return;
03720    }
03721 
03722    va_start(ap, fmt);
03723    append_history_va(p, fmt, ap);
03724    va_end(ap);
03725 
03726    return;
03727 }
03728 
03729 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
03730 static int retrans_pkt(const void *data)
03731 {
03732    struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
03733    int reschedule = DEFAULT_RETRANS;
03734    int xmitres = 0;
03735    /* how many ms until retrans timeout is reached */
03736    int64_t diff = pkt->retrans_stop_time - ast_tvdiff_ms(ast_tvnow(), pkt->time_sent);
03737 
03738    /* Do not retransmit if time out is reached. This will be negative if the time between
03739     * the first transmission and now is larger than our timeout period. This is a fail safe
03740     * check in case the scheduler gets behind or the clock is changed. */
03741    if ((diff <= 0) || (diff > pkt->retrans_stop_time)) {
03742       pkt->retrans_stop = 1;
03743    }
03744 
03745    /* Lock channel PVT */
03746    sip_pvt_lock(pkt->owner);
03747 
03748    if (!pkt->retrans_stop) {
03749       pkt->retrans++;
03750       if (!pkt->timer_t1) {   /* Re-schedule using timer_a and timer_t1 */
03751          if (sipdebug) {
03752             ast_debug(4, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n",
03753                pkt->retransid,
03754                sip_methods[pkt->method].text,
03755                pkt->method);
03756          }
03757       } else {
03758          int siptimer_a;
03759 
03760          if (sipdebug) {
03761             ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n",
03762                pkt->retransid,
03763                pkt->retrans,
03764                sip_methods[pkt->method].text,
03765                pkt->method);
03766          }
03767          if (!pkt->timer_a) {
03768             pkt->timer_a = 2 ;
03769          } else {
03770             pkt->timer_a = 2 * pkt->timer_a;
03771          }
03772 
03773          /* For non-invites, a maximum of 4 secs */
03774          siptimer_a = pkt->timer_t1 * pkt->timer_a;   /* Double each time */
03775          if (pkt->method != SIP_INVITE && siptimer_a > 4000) {
03776             siptimer_a = 4000;
03777          }
03778 
03779          /* Reschedule re-transmit */
03780          reschedule = siptimer_a;
03781          ast_debug(4, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n",
03782             pkt->retrans + 1,
03783             siptimer_a,
03784             pkt->timer_t1,
03785             pkt->retransid);
03786       }
03787 
03788       if (sip_debug_test_pvt(pkt->owner)) {
03789          const struct ast_sockaddr *dst = sip_real_dst(pkt->owner);
03790          ast_verbose("Retransmitting #%d (%s) to %s:\n%s\n---\n",
03791             pkt->retrans, sip_nat_mode(pkt->owner),
03792             ast_sockaddr_stringify(dst),
03793             ast_str_buffer(pkt->data));
03794       }
03795 
03796       append_history(pkt->owner, "ReTx", "%d %s", reschedule, ast_str_buffer(pkt->data));
03797       xmitres = __sip_xmit(pkt->owner, pkt->data);
03798 
03799       /* If there was no error during the network transmission, schedule the next retransmission,
03800        * but if the next retransmission is going to be beyond our timeout period, mark the packet's
03801        * stop_retrans value and set the next retransmit to be the exact time of timeout.  This will
03802        * allow any responses to the packet to be processed before the packet is destroyed on the next
03803        * call to this function by the scheduler. */
03804       if (xmitres != XMIT_ERROR) {
03805          if (reschedule >= diff) {
03806             pkt->retrans_stop = 1;
03807             reschedule = diff;
03808          }
03809          sip_pvt_unlock(pkt->owner);
03810          return  reschedule;
03811       }
03812    }
03813 
03814    /* At this point, either the packet's retransmission timed out, or there was a
03815     * transmission error, either way destroy the scheduler item and this packet. */
03816 
03817    pkt->retransid = -1; /* Kill this scheduler item */
03818 
03819    if (pkt->method != SIP_OPTIONS && xmitres == 0) {
03820       if (pkt->is_fatal || sipdebug) { /* Tell us if it's critical or if we're debugging */
03821          ast_log(LOG_WARNING, "Retransmission timeout reached on transmission %s from %s for seqno %u (%s %s) -- See https://wiki.asterisk.org/wiki/display/AST/SIP+Retransmissions\n"
03822             "Packet timed out after %dms with no response\n",
03823             pkt->owner->callid,
03824             pkt->owner->from,
03825             pkt->seqno,
03826             pkt->is_fatal ? "Critical" : "Non-critical",
03827             pkt->is_resp ? "Response" : "Request",
03828             (int) ast_tvdiff_ms(ast_tvnow(), pkt->time_sent));
03829       }
03830    } else if (pkt->method == SIP_OPTIONS && sipdebug) {
03831       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);
03832    }
03833 
03834    if (xmitres == XMIT_ERROR) {
03835       ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
03836       append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03837    } else {
03838       append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03839    }
03840 
03841    if (pkt->is_fatal) {
03842       while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
03843          sip_pvt_unlock(pkt->owner);   /* SIP_PVT, not channel */
03844          usleep(1);
03845          sip_pvt_lock(pkt->owner);
03846       }
03847       if (pkt->owner->owner && !pkt->owner->owner->hangupcause) {
03848          pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
03849       }
03850       if (pkt->owner->owner) {
03851          ast_log(LOG_WARNING, "Hanging up call %s from channel %s - no reply to our critical packet (see https://wiki.asterisk.org/wiki/display/AST/SIP+Retransmissions).\n", pkt->owner->callid, pkt->owner->owner->name);
03852 
03853          if (pkt->is_resp &&
03854             (pkt->response_code >= 200) &&
03855             (pkt->response_code < 300) &&
03856             pkt->owner->pendinginvite &&
03857             ast_test_flag(&pkt->owner->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
03858             /* This is a timeout of the 2XX response to a pending INVITE.  In this case terminate the INVITE
03859              * transaction just as if we received the ACK, but immediately hangup with a BYE (sip_hangup
03860              * will send the BYE as long as the dialog is not set as "alreadygone")
03861              * RFC 3261 section 13.3.1.4.
03862              * "If the server retransmits the 2xx response for 64*T1 seconds without receiving
03863              * an ACK, the dialog is confirmed, but the session SHOULD be terminated.  This is
03864              * accomplished with a BYE, as described in Section 15." */
03865             pkt->owner->invitestate = INV_TERMINATED;
03866             pkt->owner->pendinginvite = 0;
03867          } else {
03868             /* there is nothing left to do, mark the dialog as gone */
03869             sip_alreadygone(pkt->owner);
03870          }
03871          ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_NO_USER_RESPONSE);
03872          ast_channel_unlock(pkt->owner->owner);
03873       } else {
03874          /* If no channel owner, destroy now */
03875 
03876          /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
03877          if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
03878             pvt_set_needdestroy(pkt->owner, "no response to critical packet");
03879             sip_alreadygone(pkt->owner);
03880             append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
03881          }
03882       }
03883    } else if (pkt->owner->pendinginvite == pkt->seqno) {
03884           ast_log(LOG_WARNING, "Timeout on %s on non-critical invite transaction.\n", pkt->owner->callid);
03885           pkt->owner->invitestate = INV_TERMINATED;
03886           pkt->owner->pendinginvite = 0;
03887           check_pendings(pkt->owner);
03888    }
03889 
03890    if (pkt->method == SIP_BYE) {
03891       /* We're not getting answers on SIP BYE's.  Tear down the call anyway. */
03892       sip_alreadygone(pkt->owner);
03893       if (pkt->owner->owner) {
03894          ast_channel_unlock(pkt->owner->owner);
03895       }
03896       append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
03897       pvt_set_needdestroy(pkt->owner, "no response to BYE");
03898    }
03899 
03900    /* Remove the packet */
03901    for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
03902       if (cur == pkt) {
03903          UNLINK(cur, pkt->owner->packets, prev);
03904          sip_pvt_unlock(pkt->owner);
03905          if (pkt->owner) {
03906             pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
03907          }
03908          if (pkt->data) {
03909             ast_free(pkt->data);
03910          }
03911          pkt->data = NULL;
03912          ast_free(pkt);
03913          return 0;
03914       }
03915    }
03916    /* error case */
03917    ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
03918    sip_pvt_unlock(pkt->owner);
03919    return 0;
03920 }
03921 
03922 /*!
03923  * \internal
03924  * \brief Transmit packet with retransmits
03925  * \return 0 on success, -1 on failure to allocate packet
03926  */
03927 static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, uint32_t seqno, int resp, struct ast_str *data, int fatal, int sipmethod)
03928 {
03929    struct sip_pkt *pkt = NULL;
03930    int siptimer_a = DEFAULT_RETRANS;
03931    int xmitres = 0;
03932    unsigned respid;
03933 
03934    if (sipmethod == SIP_INVITE) {
03935       /* Note this is a pending invite */
03936       p->pendinginvite = seqno;
03937    }
03938 
03939    /* If the transport is something reliable (TCP or TLS) then don't really send this reliably */
03940    /* I removed the code from retrans_pkt that does the same thing so it doesn't get loaded into the scheduler */
03941    /*! \todo According to the RFC some packets need to be retransmitted even if its TCP, so this needs to get revisited */
03942    if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
03943       xmitres = __sip_xmit(p, data);   /* Send packet */
03944       if (xmitres == XMIT_ERROR) {  /* Serious network trouble, no need to try again */
03945          append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
03946          return AST_FAILURE;
03947       } else {
03948          return AST_SUCCESS;
03949       }
03950    }
03951 
03952    if (!(pkt = ast_calloc(1, sizeof(*pkt)))) {
03953       return AST_FAILURE;
03954    }
03955    /* copy data, add a terminator and save length */
03956    if (!(pkt->data = ast_str_create(ast_str_strlen(data)))) {
03957       ast_free(pkt);
03958       return AST_FAILURE;
03959    }
03960    ast_str_set(&pkt->data, 0, "%s%s", ast_str_buffer(data), "\0");
03961    /* copy other parameters from the caller */
03962    pkt->method = sipmethod;
03963    pkt->seqno = seqno;
03964    pkt->is_resp = resp;
03965    pkt->is_fatal = fatal;
03966    pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
03967    pkt->next = p->packets;
03968    p->packets = pkt; /* Add it to the queue */
03969    if (resp) {
03970       /* Parse out the response code */
03971       if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
03972          pkt->response_code = respid;
03973       }
03974    }
03975    pkt->timer_t1 = p->timer_t1;  /* Set SIP timer T1 */
03976    pkt->retransid = -1;
03977    if (pkt->timer_t1) {
03978       siptimer_a = pkt->timer_t1;
03979    }
03980 
03981    pkt->time_sent = ast_tvnow(); /* time packet was sent */
03982    pkt->retrans_stop_time = 64 * (pkt->timer_t1 ? pkt->timer_t1 : DEFAULT_TIMER_T1); /* time in ms after pkt->time_sent to stop retransmission */
03983 
03984    /* Schedule retransmission */
03985    AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
03986    if (sipdebug) {
03987       ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id  #%d\n", pkt->retransid);
03988    }
03989 
03990    xmitres = __sip_xmit(pkt->owner, pkt->data); /* Send packet */
03991 
03992    if (xmitres == XMIT_ERROR) {  /* Serious network trouble, no need to try again */
03993       append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03994       ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
03995       AST_SCHED_DEL(sched, pkt->retransid);
03996       p->packets = pkt->next;
03997       pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
03998       ast_free(pkt->data);
03999       ast_free(pkt);
04000       return AST_FAILURE;
04001    } else {
04002       /* This is odd, but since the retrans timer starts at 500ms and the do_monitor thread
04003        * only wakes up every 1000ms by default, we have to poke the thread here to make
04004        * sure it successfully detects this must be retransmitted in less time than
04005        * it usually sleeps for. Otherwise it might not retransmit this packet for 1000ms. */
04006       if (monitor_thread != AST_PTHREADT_NULL) {
04007          pthread_kill(monitor_thread, SIGURG);
04008       }
04009       return AST_SUCCESS;
04010    }
04011 }
04012 
04013 /*! \brief Kill a SIP dialog (called only by the scheduler)
04014  * The scheduler has a reference to this dialog when p->autokillid != -1,
04015  * and we are called using that reference. So if the event is not
04016  * rescheduled, we need to call dialog_unref().
04017  */
04018 static int __sip_autodestruct(const void *data)
04019 {
04020    struct sip_pvt *p = (struct sip_pvt *)data;
04021    struct ast_channel *owner;
04022 
04023    /* If this is a subscription, tell the phone that we got a timeout */
04024    if (p->subscribed && p->subscribed != MWI_NOTIFICATION && p->subscribed != CALL_COMPLETION) {
04025       transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);  /* Send last notification */
04026       p->subscribed = NONE;
04027       append_history(p, "Subscribestatus", "timeout");
04028       ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
04029       return 10000;  /* Reschedule this destruction so that we know that it's gone */
04030    }
04031 
04032    /* If there are packets still waiting for delivery, delay the destruction */
04033    if (p->packets) {
04034       if (!p->needdestroy) {
04035          char method_str[31];
04036          ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
04037          append_history(p, "ReliableXmit", "timeout");
04038          if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
04039             if (p->ongoing_reinvite || method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
04040                pvt_set_needdestroy(p, "autodestruct");
04041             }
04042          }
04043          return 10000;
04044       } else {
04045          /* They've had their chance to respond. Time to bail */
04046          __sip_pretend_ack(p);
04047       }
04048    }
04049 
04050    /* Reset schedule ID */
04051    p->autokillid = -1;
04052 
04053    /*
04054     * Lock both the pvt and the channel safely so that we can queue up a frame.
04055     */
04056    owner = sip_pvt_lock_full(p);
04057    if (owner) {
04058       ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner %s in place (Method: %s). Rescheduling destruction for 10000 ms\n", p->callid, owner->name, sip_methods[p->method].text);
04059       ast_queue_hangup_with_cause(owner, AST_CAUSE_PROTOCOL_ERROR);
04060       ast_channel_unlock(owner);
04061       ast_channel_unref(owner);
04062       sip_pvt_unlock(p);
04063       return 10000;
04064    } else if (p->refer && !p->alreadygone) {
04065       ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
04066       stop_media_flows(p);
04067       transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
04068       append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
04069       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
04070    } else {
04071       append_history(p, "AutoDestroy", "%s", p->callid);
04072       ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
04073       sip_pvt_unlock(p);
04074       dialog_unlink_all(p); /* once it's unlinked and unrefd everywhere, it'll be freed automagically */
04075       sip_pvt_lock(p);
04076       /* dialog_unref(p, "unref dialog-- no other matching conditions"); -- unlink all now should finish off the dialog's references and free it. */
04077       /* sip_destroy(p); */      /* Go ahead and destroy dialog. All attempts to recover is done */
04078       /* sip_destroy also absorbs the reference */
04079    }
04080 
04081    sip_pvt_unlock(p);
04082 
04083    dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
04084 
04085    return 0;
04086 }
04087 
04088 /*! \brief Schedule final destruction of SIP dialog.  This can not be canceled.
04089  *  This function is used to keep a dialog around for a period of time in order
04090  *  to properly respond to any retransmits. */
04091 void sip_scheddestroy_final(struct sip_pvt *p, int ms)
04092 {
04093    if (p->final_destruction_scheduled) {
04094       return; /* already set final destruction */
04095    }
04096 
04097    sip_scheddestroy(p, ms);
04098    if (p->autokillid != -1) {
04099       p->final_destruction_scheduled = 1;
04100    }
04101 }
04102 
04103 /*! \brief Schedule destruction of SIP dialog */
04104 void sip_scheddestroy(struct sip_pvt *p, int ms)
04105 {
04106    if (p->final_destruction_scheduled) {
04107       return; /* already set final destruction */
04108    }
04109 
04110    if (ms < 0) {
04111       if (p->timer_t1 == 0) {
04112          p->timer_t1 = global_t1;   /* Set timer T1 if not set (RFC 3261) */
04113       }
04114       if (p->timer_b == 0) {
04115          p->timer_b = global_timer_b;  /* Set timer B if not set (RFC 3261) */
04116       }
04117       ms = p->timer_t1 * 64;
04118    }
04119    if (sip_debug_test_pvt(p)) {
04120       ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
04121    }
04122    if (sip_cancel_destroy(p)) {
04123       ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
04124    }
04125 
04126    if (p->do_history) {
04127       append_history(p, "SchedDestroy", "%d ms", ms);
04128    }
04129    p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
04130 
04131    if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0) {
04132       stop_session_timer(p);
04133    }
04134 }
04135 
04136 /*! \brief Cancel destruction of SIP dialog.
04137  * Be careful as this also absorbs the reference - if you call it
04138  * from within the scheduler, this might be the last reference.
04139  */
04140 int sip_cancel_destroy(struct sip_pvt *p)
04141 {
04142    if (p->final_destruction_scheduled) {
04143       return 0;
04144    }
04145 
04146    if (p->autokillid > -1) {
04147       append_history(p, "CancelDestroy", "");
04148       AST_SCHED_DEL_UNREF(sched, p->autokillid, dialog_unref(p, "remove ref for autokillid"));
04149    }
04150    return 0;
04151 }
04152 
04153 /*! \brief Acknowledges receipt of a packet and stops retransmission
04154  * called with p locked*/
04155 int __sip_ack(struct sip_pvt *p, uint32_t seqno, int resp, int sipmethod)
04156 {
04157    struct sip_pkt *cur, *prev = NULL;
04158    const char *msg = "Not Found";   /* used only for debugging */
04159    int res = FALSE;
04160 
04161    /* If we have an outbound proxy for this dialog, then delete it now since
04162      the rest of the requests in this dialog needs to follow the routing.
04163      If obforcing is set, we will keep the outbound proxy during the whole
04164      dialog, regardless of what the SIP rfc says
04165    */
04166    if (p->outboundproxy && !p->outboundproxy->force) {
04167       ref_proxy(p, NULL);
04168    }
04169 
04170    for (cur = p->packets; cur; prev = cur, cur = cur->next) {
04171       if (cur->seqno != seqno || cur->is_resp != resp) {
04172          continue;
04173       }
04174       if (cur->is_resp || cur->method == sipmethod) {
04175          res = TRUE;
04176          msg = "Found";
04177          if (!resp && (seqno == p->pendinginvite)) {
04178             ast_debug(1, "Acked pending invite %u\n", p->pendinginvite);
04179             p->pendinginvite = 0;
04180          }
04181          if (cur->retransid > -1) {
04182             if (sipdebug)
04183                ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
04184          }
04185          /* This odd section is designed to thwart a
04186           * race condition in the packet scheduler. There are
04187           * two conditions under which deleting the packet from the
04188           * scheduler can fail.
04189           *
04190           * 1. The packet has been removed from the scheduler because retransmission
04191           * is being attempted. The problem is that if the packet is currently attempting
04192           * retransmission and we are at this point in the code, then that MUST mean
04193           * that retrans_pkt is waiting on p's lock. Therefore we will relinquish the
04194           * lock temporarily to allow retransmission.
04195           *
04196           * 2. The packet has reached its maximum number of retransmissions and has
04197           * been permanently removed from the packet scheduler. If this is the case, then
04198           * the packet's retransid will be set to -1. The atomicity of the setting and checking
04199           * of the retransid to -1 is ensured since in both cases p's lock is held.
04200           */
04201          while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
04202             sip_pvt_unlock(p);
04203             usleep(1);
04204             sip_pvt_lock(p);
04205          }
04206          UNLINK(cur, p->packets, prev);
04207          dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
04208          if (cur->data) {
04209             ast_free(cur->data);
04210          }
04211          ast_free(cur);
04212          break;
04213       }
04214    }
04215    ast_debug(1, "Stopping retransmission on '%s' of %s %u: Match %s\n",
04216       p->callid, resp ? "Response" : "Request", seqno, msg);
04217    return res;
04218 }
04219 
04220 /*! \brief Pretend to ack all packets
04221  * called with p locked */
04222 void __sip_pretend_ack(struct sip_pvt *p)
04223 {
04224    struct sip_pkt *cur = NULL;
04225 
04226    while (p->packets) {
04227       int method;
04228       if (cur == p->packets) {
04229          ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
04230          return;
04231       }
04232       cur = p->packets;
04233       method = (cur->method) ? cur->method : find_sip_method(ast_str_buffer(cur->data));
04234       __sip_ack(p, cur->seqno, cur->is_resp, method);
04235    }
04236 }
04237 
04238 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
04239 int __sip_semi_ack(struct sip_pvt *p, uint32_t seqno, int resp, int sipmethod)
04240 {
04241    struct sip_pkt *cur;
04242    int res = FALSE;
04243 
04244    for (cur = p->packets; cur; cur = cur->next) {
04245       if (cur->seqno == seqno && cur->is_resp == resp &&
04246          (cur->is_resp || method_match(sipmethod, ast_str_buffer(cur->data)))) {
04247          /* this is our baby */
04248          if (cur->retransid > -1) {
04249             if (sipdebug)
04250                ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
04251          }
04252          AST_SCHED_DEL(sched, cur->retransid);
04253          res = TRUE;
04254          break;
04255       }
04256    }
04257    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");
04258    return res;
04259 }
04260 
04261 
04262 /*! \brief Copy SIP request, parse it */
04263 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
04264 {
04265    copy_request(dst, src);
04266    parse_request(dst);
04267 }
04268 
04269 /*! \brief add a blank line if no body */
04270 static void add_blank(struct sip_request *req)
04271 {
04272    if (!req->lines) {
04273       /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
04274       ast_str_append(&req->data, 0, "\r\n");
04275    }
04276 }
04277 
04278 static int send_provisional_keepalive_full(struct sip_pvt *pvt, int with_sdp)
04279 {
04280    const char *msg = NULL;
04281    struct ast_channel *chan;
04282    int res = 0;
04283    int old_sched_id = pvt->provisional_keepalive_sched_id;
04284 
04285    chan = sip_pvt_lock_full(pvt);
04286    /* Check that nothing has changed while we were waiting for the lock */
04287    if (old_sched_id != pvt->provisional_keepalive_sched_id) {
04288       /* Keepalive has been cancelled or rescheduled, clean up and leave */
04289       if (chan) {
04290          ast_channel_unlock(chan);
04291          chan = ast_channel_unref(chan);
04292       }
04293       sip_pvt_unlock(pvt);
04294       dialog_unref(pvt, "dialog ref for provisional keepalive");
04295       return 0;
04296    }
04297 
04298    if (!pvt->last_provisional || !strncasecmp(pvt->last_provisional, "100", 3)) {
04299       msg = "183 Session Progress";
04300    }
04301 
04302    if (pvt->invitestate < INV_COMPLETED) {
04303       if (with_sdp) {
04304          transmit_response_with_sdp(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq, XMIT_UNRELIABLE, FALSE, FALSE);
04305       } else {
04306          transmit_response(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq);
04307       }
04308       res = PROVIS_KEEPALIVE_TIMEOUT;
04309    }
04310 
04311    if (chan) {
04312       ast_channel_unlock(chan);
04313       chan = ast_channel_unref(chan);
04314    }
04315 
04316    if (!res) {
04317       pvt->provisional_keepalive_sched_id = -1;
04318    }
04319 
04320    sip_pvt_unlock(pvt);
04321 
04322    if (!res) {
04323       dialog_unref(pvt, "dialog ref for provisional keepalive");
04324    }
04325    return res;
04326 }
04327 
04328 static int send_provisional_keepalive(const void *data) {
04329    struct sip_pvt *pvt = (struct sip_pvt *) data;
04330 
04331    return send_provisional_keepalive_full(pvt, 0);
04332 }
04333 
04334 static int send_provisional_keepalive_with_sdp(const void *data) {
04335    struct sip_pvt *pvt = (void *)data;
04336 
04337    return send_provisional_keepalive_full(pvt, 1);
04338 }
04339 
04340 static void update_provisional_keepalive(struct sip_pvt *pvt, int with_sdp)
04341 {
04342    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"));
04343 
04344    pvt->provisional_keepalive_sched_id = ast_sched_add(sched, PROVIS_KEEPALIVE_TIMEOUT,
04345       with_sdp ? send_provisional_keepalive_with_sdp : send_provisional_keepalive, dialog_ref(pvt, "Increment refcount to pass dialog pointer to sched callback"));
04346 }
04347 
04348 static void add_required_respheader(struct sip_request *req)
04349 {
04350    struct ast_str *str;
04351    int i;
04352 
04353    if (!req->reqsipoptions) {
04354       return;
04355    }
04356 
04357    str = ast_str_create(32);
04358 
04359    for (i = 0; i < ARRAY_LEN(sip_options); ++i) {
04360       if (!(req->reqsipoptions & sip_options[i].id)) {
04361          continue;
04362       }
04363       if (ast_str_strlen(str) > 0) {
04364          ast_str_append(&str, 0, ", ");
04365       }
04366       ast_str_append(&str, 0, "%s", sip_options[i].text);
04367    }
04368 
04369    if (ast_str_strlen(str) > 0) {
04370       add_header(req, "Require", ast_str_buffer(str));
04371    }
04372 
04373    ast_free(str);
04374 }
04375 
04376 /*! \brief Transmit response on SIP request*/
04377 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno)
04378 {
04379    int res;
04380 
04381    finalize_content(req);
04382    add_blank(req);
04383    if (sip_debug_test_pvt(p)) {
04384       const struct ast_sockaddr *dst = sip_real_dst(p);
04385 
04386       ast_verbose("\n<--- %sTransmitting (%s) to %s --->\n%s\n<------------>\n",
04387          reliable ? "Reliably " : "", sip_nat_mode(p),
04388          ast_sockaddr_stringify(dst),
04389          ast_str_buffer(req->data));
04390    }
04391    if (p->do_history) {
04392       struct sip_request tmp = { .rlPart1 = 0, };
04393       parse_copy(&tmp, req);
04394       append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", ast_str_buffer(tmp.data), get_header(&tmp, "CSeq"),
04395          (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? REQ_OFFSET_TO_STR(&tmp, rlPart2) : sip_methods[tmp.method].text);
04396       deinit_req(&tmp);
04397    }
04398 
04399    /* If we are sending a final response to an INVITE, stop retransmitting provisional responses */
04400    if (p->initreq.method == SIP_INVITE && reliable == XMIT_CRITICAL) {
04401       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"));
04402    }
04403 
04404    res = (reliable) ?
04405        __sip_reliable_xmit(p, seqno, 1, req->data, (reliable == XMIT_CRITICAL), req->method) :
04406       __sip_xmit(p, req->data);
04407    deinit_req(req);
04408    if (res > 0) {
04409       return 0;
04410    }
04411    return res;
04412 }
04413 
04414 /*!
04415  * \internal
04416  * \brief Send SIP Request to the other part of the dialogue
04417  * \return see \ref __sip_xmit
04418  */
04419 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno)
04420 {
04421    int res;
04422 
04423    /* If we have an outbound proxy, reset peer address
04424       Only do this once.
04425    */
04426    if (p->outboundproxy) {
04427       p->sa = p->outboundproxy->ip;
04428    }
04429 
04430    finalize_content(req);
04431    add_blank(req);
04432    if (sip_debug_test_pvt(p)) {
04433       if (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT)) {
04434          ast_verbose("%sTransmitting (NAT) to %s:\n%s\n---\n", reliable ? "Reliably " : "", ast_sockaddr_stringify(&p->recv), ast_str_buffer(req->data));
04435       } else {
04436          ast_verbose("%sTransmitting (no NAT) to %s:\n%s\n---\n", reliable ? "Reliably " : "", ast_sockaddr_stringify(&p->sa), ast_str_buffer(req->data));
04437       }
04438    }
04439    if (p->do_history) {
04440       struct sip_request tmp = { .rlPart1 = 0, };
04441       parse_copy(&tmp, req);
04442       append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", ast_str_buffer(tmp.data), get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
04443       deinit_req(&tmp);
04444    }
04445    res = (reliable) ?
04446       __sip_reliable_xmit(p, seqno, 0, req->data, (reliable == XMIT_CRITICAL), req->method) :
04447       __sip_xmit(p, req->data);
04448    deinit_req(req);
04449    return res;
04450 }
04451 
04452 static void enable_dsp_detect(struct sip_pvt *p)
04453 {
04454    int features = 0;
04455 
04456    if (p->dsp) {
04457       return;
04458    }
04459 
04460    if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
04461        (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
04462       if (p->rtp) {
04463          ast_rtp_instance_dtmf_mode_set(p->rtp, AST_RTP_DTMF_MODE_INBAND);
04464       }
04465       features |= DSP_FEATURE_DIGIT_DETECT;
04466    }
04467 
04468    if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
04469       features |= DSP_FEATURE_FAX_DETECT;
04470    }
04471 
04472    if (!features) {
04473       return;
04474    }
04475 
04476    if (!(p->dsp = ast_dsp_new())) {
04477       return;
04478    }
04479 
04480    ast_dsp_set_features(p->dsp, features);
04481    if (global_relaxdtmf) {
04482       ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
04483    }
04484 }
04485 
04486 static void disable_dsp_detect(struct sip_pvt *p)
04487 {
04488    if (p->dsp) {
04489       ast_dsp_free(p->dsp);
04490       p->dsp = NULL;
04491    }
04492 }
04493 
04494 /*! \brief Set an option on a SIP dialog */
04495 static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen)
04496 {
04497    int res = -1;
04498    struct sip_pvt *p = chan->tech_pvt;
04499 
04500         if (!p) {
04501          ast_log(LOG_ERROR, "Attempt to Ref a null pointer.  sip private structure is gone!\n");
04502          return -1;
04503         }
04504 
04505    sip_pvt_lock(p);
04506 
04507    switch (option) {
04508    case AST_OPTION_FORMAT_READ:
04509       if (p->rtp) {
04510          res = ast_rtp_instance_set_read_format(p->rtp, *(int *) data);
04511       }
04512       break;
04513    case AST_OPTION_FORMAT_WRITE:
04514       if (p->rtp) {
04515          res = ast_rtp_instance_set_write_format(p->rtp, *(int *) data);
04516       }
04517       break;
04518    case AST_OPTION_MAKE_COMPATIBLE:
04519       if (p->rtp) {
04520          res = ast_rtp_instance_make_compatible(chan, p->rtp, (struct ast_channel *) data);
04521       }
04522       break;
04523    case AST_OPTION_DIGIT_DETECT:
04524       if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
04525           (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
04526          char *cp = (char *) data;
04527 
04528          ast_debug(1, "%sabling digit detection on %s\n", *cp ? "En" : "Dis", chan->name);
04529          if (*cp) {
04530             enable_dsp_detect(p);
04531          } else {
04532             disable_dsp_detect(p);
04533          }
04534          res = 0;
04535       }
04536       break;
04537    case AST_OPTION_SECURE_SIGNALING:
04538       p->req_secure_signaling = *(unsigned int *) data;
04539       res = 0;
04540       break;
04541    case AST_OPTION_SECURE_MEDIA:
04542       ast_set2_flag(&p->flags[1], *(unsigned int *) data, SIP_PAGE2_USE_SRTP);
04543       res = 0;
04544       break;
04545    default:
04546       break;
04547    }
04548 
04549    sip_pvt_unlock(p);
04550 
04551    return res;
04552 }
04553 
04554 /*! \brief Query an option on a SIP dialog */
04555 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
04556 {
04557    int res = -1;
04558    enum ast_t38_state state = T38_STATE_UNAVAILABLE;
04559    struct sip_pvt *p = (struct sip_pvt *) chan->tech_pvt;
04560    char *cp;
04561 
04562    sip_pvt_lock(p);
04563 
04564    switch (option) {
04565    case AST_OPTION_T38_STATE:
04566       /* Make sure we got an ast_t38_state enum passed in */
04567       if (*datalen != sizeof(enum ast_t38_state)) {
04568          ast_log(LOG_ERROR, "Invalid datalen for AST_OPTION_T38_STATE option. Expected %d, got %d\n", (int)sizeof(enum ast_t38_state), *datalen);
04569          break;
04570       }
04571 
04572       /* 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 */
04573       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
04574          switch (p->t38.state) {
04575          case T38_LOCAL_REINVITE:
04576          case T38_PEER_REINVITE:
04577             state = T38_STATE_NEGOTIATING;
04578             break;
04579          case T38_ENABLED:
04580             state = T38_STATE_NEGOTIATED;
04581             break;
04582          default:
04583             state = T38_STATE_UNKNOWN;
04584          }
04585       }
04586 
04587       *((enum ast_t38_state *) data) = state;
04588       res = 0;
04589 
04590       break;
04591    case AST_OPTION_DIGIT_DETECT:
04592       cp = (char *) data;
04593       *cp = p->dsp ? 1 : 0;
04594       ast_debug(1, "Reporting digit detection %sabled on %s\n", *cp ? "en" : "dis", chan->name);
04595       break;
04596    case AST_OPTION_SECURE_SIGNALING:
04597       *((unsigned int *) data) = p->req_secure_signaling;
04598       res = 0;
04599       break;
04600    case AST_OPTION_SECURE_MEDIA:
04601       *((unsigned int *) data) = ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP) ? 1 : 0;
04602       res = 0;
04603       break;
04604    case AST_OPTION_DEVICE_NAME:
04605       if (p && p->outgoing_call) {
04606          cp = (char *) data;
04607          ast_copy_string(cp, p->dialstring, *datalen);
04608          res = 0;
04609       }
04610       /* We purposely break with a return of -1 in the
04611        * implied else case here
04612        */
04613       break;
04614    default:
04615       break;
04616    }
04617 
04618    sip_pvt_unlock(p);
04619 
04620    return res;
04621 }
04622 
04623 /*! \brief Locate closing quote in a string, skipping escaped quotes.
04624  * optionally with a limit on the search.
04625  * start must be past the first quote.
04626  */
04627 const char *find_closing_quote(const char *start, const char *lim)
04628 {
04629    char last_char = '\0';
04630    const char *s;
04631    for (s = start; *s && s != lim; last_char = *s++) {
04632       if (*s == '"' && last_char != '\\')
04633          break;
04634    }
04635    return s;
04636 }
04637 
04638 /*! \brief Send message with Access-URL header, if this is an HTML URL only! */
04639 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
04640 {
04641    struct sip_pvt *p = chan->tech_pvt;
04642 
04643    if (subclass != AST_HTML_URL)
04644       return -1;
04645 
04646    ast_string_field_build(p, url, "<%s>;mode=active", data);
04647 
04648    if (sip_debug_test_pvt(p))
04649       ast_debug(1, "Send URL %s, state = %u!\n", data, chan->_state);
04650 
04651    switch (chan->_state) {
04652    case AST_STATE_RING:
04653       transmit_response(p, "100 Trying", &p->initreq);
04654       break;
04655    case AST_STATE_RINGING:
04656       transmit_response(p, "180 Ringing", &p->initreq);
04657       break;
04658    case AST_STATE_UP:
04659       if (!p->pendinginvite) {      /* We are up, and have no outstanding invite */
04660          transmit_reinvite_with_sdp(p, FALSE, FALSE);
04661       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
04662          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);   
04663       }  
04664       break;
04665    default:
04666       ast_log(LOG_WARNING, "Don't know how to send URI when state is %u!\n", chan->_state);
04667    }
04668 
04669    return 0;
04670 }
04671 
04672 /*! \brief Deliver SIP call ID for the call */
04673 static const char *sip_get_callid(struct ast_channel *chan)
04674 {
04675    return chan->tech_pvt ? ((struct sip_pvt *) chan->tech_pvt)->callid : "";
04676 }
04677 
04678 /*!
04679  * \internal
04680  * \brief Send SIP MESSAGE text within a call
04681  * \note Called from PBX core sendtext() application
04682  */
04683 static int sip_sendtext(struct ast_channel *ast, const char *text)
04684 {
04685    struct sip_pvt *dialog = ast->tech_pvt;
04686    int debug;
04687 
04688    if (!dialog) {
04689       return -1;
04690    }
04691    /* NOT ast_strlen_zero, because a zero-length message is specifically
04692     * allowed by RFC 3428 (See section 10, Examples) */
04693    if (!text) {
04694       return 0;
04695    }
04696    if(!is_method_allowed(&dialog->allowed_methods, SIP_MESSAGE)) {
04697       ast_debug(2, "Trying to send MESSAGE to device that does not support it.\n");
04698       return(0);
04699    }
04700 
04701    debug = sip_debug_test_pvt(dialog);
04702    if (debug) {
04703       ast_verbose("Sending text %s on %s\n", text, ast->name);
04704    }
04705 
04706    transmit_message_with_text(dialog, text);
04707    return 0;   
04708 }
04709 
04710 /*! \brief Update peer object in realtime storage
04711    If the Asterisk system name is set in asterisk.conf, we will use
04712    that name and store that in the "regserver" field in the sippeers
04713    table to facilitate multi-server setups.
04714 */
04715 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)
04716 {
04717    char port[10];
04718    char ipaddr[INET6_ADDRSTRLEN];
04719    char regseconds[20];
04720    char *tablename = NULL;
04721    char str_lastms[20];
04722 
04723    const char *sysname = ast_config_AST_SYSTEM_NAME;
04724    char *syslabel = NULL;
04725 
04726    time_t nowtime = time(NULL) + expirey;
04727    const char *fc = fullcontact ? "fullcontact" : NULL;
04728 
04729    int realtimeregs = ast_check_realtime("sipregs");
04730 
04731    tablename = realtimeregs ? "sipregs" : "sippeers";
04732    
04733 
04734    snprintf(str_lastms, sizeof(str_lastms), "%d", lastms);
04735    snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);  /* Expiration time */
04736    ast_copy_string(ipaddr, ast_sockaddr_isnull(addr) ? "" : ast_sockaddr_stringify_addr(addr), sizeof(ipaddr));
04737    ast_copy_string(port, ast_sockaddr_port(addr) ? ast_sockaddr_stringify_port(addr) : "", sizeof(port));
04738 
04739    if (ast_strlen_zero(sysname)) /* No system name, disable this */
04740       sysname = NULL;
04741    else if (sip_cfg.rtsave_sysname)
04742       syslabel = "regserver";
04743 
04744    /* XXX IMPORTANT: Anytime you add a new parameter to be updated, you
04745          *  must also add it to contrib/scripts/asterisk.ldap-schema,
04746          *  contrib/scripts/asterisk.ldif,
04747          *  and to configs/res_ldap.conf.sample as described in
04748          *  bugs 15156 and 15895 
04749          */
04750    if (fc) {
04751       ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04752          "port", port, "regseconds", regseconds,
04753          deprecated_username ? "username" : "defaultuser", defaultuser,
04754          "useragent", useragent, "lastms", str_lastms,
04755          fc, fullcontact, syslabel, sysname, SENTINEL); /* note fc and syslabel _can_ be NULL */
04756    } else {
04757       ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04758          "port", port, "regseconds", regseconds,
04759          "useragent", useragent, "lastms", str_lastms,
04760          deprecated_username ? "username" : "defaultuser", defaultuser,
04761          syslabel, sysname, SENTINEL); /* note syslabel _can_ be NULL */
04762    }
04763 }
04764 
04765 /*! \brief Automatically add peer extension to dial plan */
04766 static void register_peer_exten(struct sip_peer *peer, int onoff)
04767 {
04768    char multi[256];
04769    char *stringp, *ext, *context;
04770    struct pbx_find_info q = { .stacklen = 0 };
04771 
04772    /* XXX note that sip_cfg.regcontext is both a global 'enable' flag and
04773     * the name of the global regexten context, if not specified
04774     * individually.
04775     */
04776    if (ast_strlen_zero(sip_cfg.regcontext))
04777       return;
04778 
04779    ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
04780    stringp = multi;
04781    while ((ext = strsep(&stringp, "&"))) {
04782       if ((context = strchr(ext, '@'))) {
04783          *context++ = '\0';   /* split ext@context */
04784          if (!ast_context_find(context)) {
04785             ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
04786             continue;
04787          }
04788       } else {
04789          context = sip_cfg.regcontext;
04790       }
04791       if (onoff) {
04792          if (!ast_exists_extension(NULL, context, ext, 1, NULL)) {
04793             ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
04794                 ast_strdup(peer->name), ast_free_ptr, "SIP");
04795          }
04796       } else if (pbx_find_extension(NULL, NULL, &q, context, ext, 1, NULL, "", E_MATCH)) {
04797          ast_context_remove_extension(context, ext, 1, NULL);
04798       }
04799    }
04800 }
04801 
04802 /*! Destroy mailbox subscriptions */
04803 static void destroy_mailbox(struct sip_mailbox *mailbox)
04804 {
04805    if (mailbox->event_sub)
04806       ast_event_unsubscribe(mailbox->event_sub);
04807    ast_free(mailbox);
04808 }
04809 
04810 /*! Destroy all peer-related mailbox subscriptions */
04811 static void clear_peer_mailboxes(struct sip_peer *peer)
04812 {
04813    struct sip_mailbox *mailbox;
04814 
04815    while ((mailbox = AST_LIST_REMOVE_HEAD(&peer->mailboxes, entry)))
04816       destroy_mailbox(mailbox);
04817 }
04818 
04819 static void sip_destroy_peer_fn(void *peer)
04820 {
04821    sip_destroy_peer(peer);
04822 }
04823 
04824 /*! \brief Destroy peer object from memory */
04825 static void sip_destroy_peer(struct sip_peer *peer)
04826 {
04827    ast_debug(3, "Destroying SIP peer %s\n", peer->name);
04828 
04829    /*
04830     * Remove any mailbox event subscriptions for this peer before
04831     * we destroy anything.  An event subscription callback may be
04832     * happening right now.
04833     */
04834    clear_peer_mailboxes(peer);
04835 
04836    if (peer->outboundproxy) {
04837       ao2_ref(peer->outboundproxy, -1);
04838       peer->outboundproxy = NULL;
04839    }
04840 
04841    /* Delete it, it needs to disappear */
04842    if (peer->call) {
04843       dialog_unlink_all(peer->call);
04844       peer->call = dialog_unref(peer->call, "peer->call is being unset");
04845    }
04846 
04847    if (peer->mwipvt) {  /* We have an active subscription, delete it */
04848       dialog_unlink_all(peer->mwipvt);
04849       peer->mwipvt = dialog_unref(peer->mwipvt, "unreffing peer->mwipvt");
04850    }
04851    
04852    if (peer->chanvars) {
04853       ast_variables_destroy(peer->chanvars);
04854       peer->chanvars = NULL;
04855    }
04856    
04857    register_peer_exten(peer, FALSE);
04858    ast_free_ha(peer->ha);
04859    ast_free_ha(peer->directmediaha);
04860    if (peer->selfdestruct)
04861       ast_atomic_fetchadd_int(&apeerobjs, -1);
04862    else if (!ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->is_realtime) {
04863       ast_atomic_fetchadd_int(&rpeerobjs, -1);
04864       ast_debug(3, "-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
04865    } else
04866       ast_atomic_fetchadd_int(&speerobjs, -1);
04867    if (peer->auth) {
04868       ao2_t_ref(peer->auth, -1, "Removing peer authentication");
04869       peer->auth = NULL;
04870    }
04871 
04872    if (peer->socket.tcptls_session) {
04873       ao2_ref(peer->socket.tcptls_session, -1);
04874       peer->socket.tcptls_session = NULL;
04875    }
04876 
04877    ast_cc_config_params_destroy(peer->cc_params);
04878 
04879    ast_string_field_free_memory(peer);
04880 }
04881 
04882 /*! \brief Update peer data in database (if used) */
04883 static void update_peer(struct sip_peer *p, int expire)
04884 {
04885    int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
04886    if (sip_cfg.peer_rtupdate &&
04887        (p->is_realtime || rtcachefriends)) {
04888       realtime_update_peer(p->name, &p->addr, p->username, p->fullcontact, p->useragent, expire, p->deprecated_username, p->lastms);
04889    }
04890 }
04891 
04892 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *cfg)
04893 {
04894    struct ast_variable *var = NULL;
04895    struct ast_flags flags = {0};
04896    char *cat = NULL;
04897    const char *insecure;
04898    while ((cat = ast_category_browse(cfg, cat))) {
04899       insecure = ast_variable_retrieve(cfg, cat, "insecure");
04900       set_insecure_flags(&flags, insecure, -1);
04901       if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
04902          var = ast_category_root(cfg, cat);
04903          break;
04904       }
04905    }
04906    return var;
04907 }
04908 
04909 static struct ast_variable *get_insecure_variable_from_sippeers(const char *column, const char *value)
04910 {
04911    struct ast_config *peerlist;
04912    struct ast_variable *var = NULL;
04913    if ((peerlist = ast_load_realtime_multientry("sippeers", column, value, "insecure LIKE", "%port%", SENTINEL))) {
04914       if ((var = get_insecure_variable_from_config(peerlist))) {
04915          /* Must clone, because var will get freed along with
04916           * peerlist. */
04917          var = ast_variables_dup(var);
04918       }
04919       ast_config_destroy(peerlist);
04920    }
04921    return var;
04922 }
04923 
04924 /* Yes.. the only column that makes sense to pass is "ipaddr", but for
04925  * consistency's sake, we require the column name to be passed. As extra
04926  * argument, we take a pointer to var. We already got the info, so we better
04927  * return it and save the caller a query. If return value is nonzero, then *var
04928  * is nonzero too (and the other way around). */
04929 static struct ast_variable *get_insecure_variable_from_sipregs(const char *column, const char *value, struct ast_variable **var)
04930 {
04931    struct ast_variable *varregs = NULL;
04932    struct ast_config *regs, *peers;
04933    char *regscat;
04934    const char *regname;
04935 
04936    if (!(regs = ast_load_realtime_multientry("sipregs", column, value, SENTINEL))) {
04937       return NULL;
04938    }
04939 
04940    /* Load *all* peers that are probably insecure=port */
04941    if (!(peers = ast_load_realtime_multientry("sippeers", "insecure LIKE", "%port%", SENTINEL))) {
04942       ast_config_destroy(regs);
04943       return NULL;
04944    }
04945 
04946    /* Loop over the sipregs that match IP address and attempt to find an
04947     * insecure=port match to it in sippeers. */
04948    regscat = NULL;
04949    while ((regscat = ast_category_browse(regs, regscat)) && (regname = ast_variable_retrieve(regs, regscat, "name"))) {
04950       char *peerscat;
04951       const char *peername;
04952 
04953       peerscat = NULL;
04954       while ((peerscat = ast_category_browse(peers, peerscat)) && (peername = ast_variable_retrieve(peers, peerscat, "name"))) {
04955          if (!strcasecmp(regname, peername)) {
04956             /* Ensure that it really is insecure=port and
04957              * not something else. */
04958             const char *insecure = ast_variable_retrieve(peers, peerscat, "insecure");
04959             struct ast_flags flags = {0};
04960             set_insecure_flags(&flags, insecure, -1);
04961             if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
04962                /* ENOMEM checks till the bitter end. */
04963                if ((varregs = ast_variables_dup(ast_category_root(regs, regscat)))) {
04964                   if (!(*var = ast_variables_dup(ast_category_root(peers, peerscat)))) {
04965                      ast_variables_destroy(varregs);
04966                      varregs = NULL;
04967                   }
04968                }
04969                goto done;
04970             }
04971          }
04972       }
04973    }
04974 
04975 done:
04976    ast_config_destroy(regs);
04977    ast_config_destroy(peers);
04978    return varregs;
04979 }
04980 
04981 static const char *get_name_from_variable(const struct ast_variable *var)
04982 {
04983    /* Don't expect this to return non-NULL. Both NULL and empty
04984     * values can cause the option to get removed from the variable
04985     * list. This is called on ast_variables gotten from both
04986     * ast_load_realtime and ast_load_realtime_multientry.
04987     * - ast_load_realtime removes options with empty values
04988     * - ast_load_realtime_multientry does not!
04989     * For consistent behaviour, we check for the empty name and
04990     * return NULL instead. */
04991    const struct ast_variable *tmp;
04992    for (tmp = var; tmp; tmp = tmp->next) {
04993       if (!strcasecmp(tmp->name, "name")) {
04994          if (!ast_strlen_zero(tmp->value)) {
04995             return tmp->value;
04996          }
04997          break;
04998       }
04999    }
05000    return NULL;
05001 }
05002 
05003 /* If varregs is NULL, we don't use sipregs.
05004  * Using empty if-bodies instead of goto's while avoiding unnecessary indents */
05005 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)
05006 {
05007    /* Peer by name and host=dynamic */
05008    if ((*var = ast_load_realtime("sippeers", "name", *name, "host", "dynamic", SENTINEL))) {
05009       ;
05010    /* Peer by name and host=IP */
05011    } else if (addr && !(*var = ast_load_realtime("sippeers", "name", *name, "host", ipaddr, SENTINEL))) {
05012       ;
05013    /* Peer by name and host=HOSTNAME */
05014    } else if ((*var = ast_load_realtime("sippeers", "name", *name, SENTINEL))) {
05015       /*!\note
05016        * If this one loaded something, then we need to ensure that the host
05017        * field matched.  The only reason why we can't have this as a criteria
05018        * is because we only have the IP address and the host field might be
05019        * set as a name (and the reverse PTR might not match).
05020        */
05021       if (addr) {
05022          struct ast_variable *tmp;
05023          for (tmp = *var; tmp; tmp = tmp->next) {
05024             if (!strcasecmp(tmp->name, "host")) {
05025                struct ast_sockaddr *addrs = NULL;
05026 
05027                if (ast_sockaddr_resolve(&addrs,
05028                          tmp->value,
05029                          PARSE_PORT_FORBID,
05030                          get_address_family_filter(SIP_TRANSPORT_UDP)) <= 0 ||
05031                          ast_sockaddr_cmp(&addrs[0], addr)) {
05032                   /* No match */
05033                   ast_variables_destroy(*var);
05034                   *var = NULL;
05035                }
05036                ast_free(addrs);
05037                break;
05038             }
05039          }
05040       }
05041    }
05042 
05043    /* Did we find anything? */
05044    if (*var) {
05045       if (varregs) {
05046          *varregs = ast_load_realtime("sipregs", "name", *name, SENTINEL);
05047       }
05048       return 1;
05049    }
05050    return 0;
05051 }
05052 
05053 /* Another little helper function for backwards compatibility: this
05054  * checks/fetches the sippeer that belongs to the sipreg. If none is
05055  * found, we free the sipreg and return false. This way we can do the
05056  * check inside the if-condition below. In the old code, not finding
05057  * the sippeer also had it continue look for another match, so we do
05058  * the same. */
05059 static struct ast_variable *realtime_peer_get_sippeer_helper(const char **name, struct ast_variable **varregs) {
05060    struct ast_variable *var = NULL;
05061    const char *old_name = *name;
05062    *name = get_name_from_variable(*varregs);
05063    if (!*name || !(var = ast_load_realtime("sippeers", "name", *name, SENTINEL))) {
05064       if (!*name) {
05065          ast_log(LOG_WARNING, "Found sipreg but it has no name\n");
05066       }
05067       ast_variables_destroy(*varregs);
05068       *varregs = NULL;
05069       *name = old_name;
05070    }
05071    return var;
05072 }
05073 
05074 /* If varregs is NULL, we don't use sipregs. If we return true, then *name is
05075  * set. Using empty if-bodies instead of goto's while avoiding unnecessary
05076  * indents. */
05077 static int realtime_peer_by_addr(const char **name, struct ast_sockaddr *addr, const char *ipaddr, struct ast_variable **var, struct ast_variable **varregs)
05078 {
05079    char portstring[6]; /* up to 5 digits plus null terminator */
05080    ast_copy_string(portstring, ast_sockaddr_stringify_port(addr), sizeof(portstring));
05081 
05082    /* We're not finding this peer by this name anymore. Reset it. */
05083    *name = NULL;
05084 
05085    /* First check for fixed IP hosts */
05086    if ((*var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, SENTINEL))) {
05087       ;
05088    /* Check for registered hosts (in sipregs) */
05089    } else if (varregs && (*varregs = ast_load_realtime("sipregs", "ipaddr", ipaddr, "port", portstring, SENTINEL)) &&
05090          (*var = realtime_peer_get_sippeer_helper(name, varregs))) {
05091       ;
05092    /* Check for registered hosts (in sippeers) */
05093    } else if (!varregs && (*var = ast_load_realtime("sippeers", "ipaddr", ipaddr, "port", portstring, SENTINEL))) {
05094       ;
05095    /* We couldn't match on ipaddress and port, so we need to check if port is insecure */
05096    } else if ((*var = get_insecure_variable_from_sippeers("host", ipaddr))) {
05097       ;
05098    /* Same as above, but try the IP address field (in sipregs)
05099     * Observe that it fetches the name/var at the same time, without the
05100     * realtime_peer_get_sippeer_helper. Also note that it is quite inefficient.
05101     * Avoid sipregs if possible. */
05102    } else if (varregs && (*varregs = get_insecure_variable_from_sipregs("ipaddr", ipaddr, var))) {
05103       ;
05104    /* Same as above, but try the IP address field (in sippeers) */
05105    } else if (!varregs && (*var = get_insecure_variable_from_sippeers("ipaddr", ipaddr))) {
05106       ;
05107    }
05108 
05109    /* Nothing found? */
05110    if (!*var) {
05111       return 0;
05112    }
05113 
05114    /* Check peer name. It must not be empty. There may exist a
05115     * different match that does have a name, but it's too late for
05116     * that now. */
05117    if (!*name && !(*name = get_name_from_variable(*var))) {
05118       ast_log(LOG_WARNING, "Found peer for IP %s but it has no name\n", ipaddr);
05119       ast_variables_destroy(*var);
05120       *var = NULL;
05121       if (varregs && *varregs) {
05122          ast_variables_destroy(*varregs);
05123          *varregs = NULL;
05124       }
05125       return 0;
05126    }
05127 
05128    /* Make sure varregs is populated if var is. The inverse,
05129     * ensuring that var is set when varregs is, is taken
05130     * care of by realtime_peer_get_sippeer_helper(). */
05131    if (varregs && !*varregs) {
05132       *varregs = ast_load_realtime("sipregs", "name", *name, SENTINEL);
05133    }
05134    return 1;
05135 }
05136 
05137 /*! \brief  realtime_peer: Get peer from realtime storage
05138  * Checks the "sippeers" realtime family from extconfig.conf
05139  * Checks the "sipregs" realtime family from extconfig.conf if it's configured.
05140  * This returns a pointer to a peer and because we use build_peer, we can rest
05141  * assured that the refcount is bumped.
05142  * 
05143  * \note This is never called with both newpeername and addr at the same time.
05144  * If you do, be prepared to get a peer with a different name than newpeername.
05145  */
05146 static struct sip_peer *realtime_peer(const char *newpeername, struct ast_sockaddr *addr, int devstate_only, int which_objects)
05147 {
05148    struct sip_peer *peer = NULL;
05149    struct ast_variable *var = NULL;
05150    struct ast_variable *varregs = NULL;
05151    char ipaddr[INET6_ADDRSTRLEN];
05152    int realtimeregs = ast_check_realtime("sipregs");
05153 
05154    if (addr) {
05155       ast_copy_string(ipaddr, ast_sockaddr_stringify_addr(addr), sizeof(ipaddr));
05156    } else {
05157       ipaddr[0] = '\0';
05158    }
05159 
05160    if (newpeername && realtime_peer_by_name(&newpeername, addr, ipaddr, &var, realtimeregs ? &varregs : NULL)) {
05161       ;
05162    } else if (addr && realtime_peer_by_addr(&newpeername, addr, ipaddr, &var, realtimeregs ? &varregs : NULL)) {
05163       ;
05164    } else {
05165       return NULL;
05166    }
05167 
05168    /* If we're looking for users, don't return peers (although this check
05169     * should probably be done in realtime_peer_by_* instead...) */
05170    if (which_objects == FINDUSERS) {
05171       struct ast_variable *tmp;
05172       for (tmp = var; tmp; tmp = tmp->next) {
05173          if (!strcasecmp(tmp->name, "type") && (!strcasecmp(tmp->value, "peer"))) {
05174             goto cleanup;
05175          }
05176       }
05177    }
05178 
05179    /* Peer found in realtime, now build it in memory */
05180    peer = build_peer(newpeername, var, varregs, TRUE, devstate_only);
05181    if (!peer) {
05182       goto cleanup;
05183    }
05184 
05185    /* Previous versions of Asterisk did not require the type field to be
05186     * set for real time peers.  This statement preserves that behavior. */
05187    if  (peer->type == 0) {
05188       if (which_objects == FINDUSERS) {
05189          peer->type = SIP_TYPE_USER;
05190       } else if (which_objects == FINDPEERS) {
05191          peer->type = SIP_TYPE_PEER;
05192       } else {
05193          peer->type = SIP_TYPE_PEER | SIP_TYPE_USER;
05194       }
05195    }
05196 
05197    ast_debug(3, "-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);
05198 
05199    if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && !devstate_only) {
05200       /* Cache peer */
05201       ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
05202       if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
05203          AST_SCHED_REPLACE_UNREF(peer->expire, sched, sip_cfg.rtautoclear * 1000, expire_register, peer,
05204                unref_peer(_data, "remove registration ref"),
05205                unref_peer(peer, "remove registration ref"),
05206                ref_peer(peer, "add registration ref"));
05207       }
05208       ao2_t_link(peers, peer, "link peer into peers table");
05209       if (!ast_sockaddr_isnull(&peer->addr)) {
05210          ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
05211       }
05212    }
05213    peer->is_realtime = 1;
05214 
05215 cleanup:
05216    ast_variables_destroy(var);
05217    ast_variables_destroy(varregs);
05218    return peer;
05219 }
05220 
05221 /* Function to assist finding peers by name only */
05222 static int find_by_name(void *obj, void *arg, void *data, int flags)
05223 {
05224    struct sip_peer *search = obj, *match = arg;
05225    int *which_objects = data;
05226 
05227    /* Usernames in SIP uri's are case sensitive. Domains are not */
05228    if (strcmp(search->name, match->name)) {
05229       return 0;
05230    }
05231 
05232    switch (*which_objects) {
05233    case FINDUSERS:
05234       if (!(search->type & SIP_TYPE_USER)) {
05235          return 0;
05236       }
05237       break;
05238    case FINDPEERS:
05239       if (!(search->type & SIP_TYPE_PEER)) {
05240          return 0;
05241       }
05242       break;
05243    case FINDALLDEVICES:
05244       break;
05245    }
05246 
05247    return CMP_MATCH | CMP_STOP;
05248 }
05249 
05250 /*!
05251  * \brief Locate device by name or ip address
05252  * \param peer, sin, realtime, devstate_only, transport
05253  * \param which_objects Define which objects should be matched when doing a lookup
05254  *        by name.  Valid options are FINDUSERS, FINDPEERS, or FINDALLDEVICES.
05255  *        Note that this option is not used at all when doing a lookup by IP.
05256  *
05257  * This is used on find matching device on name or ip/port.
05258  * If the device was declared as type=peer, we don't match on peer name on incoming INVITEs.
05259  *
05260  * \note Avoid using this function in new functions if there is a way to avoid it,
05261  * since it might cause a database lookup.
05262  */
05263 static struct sip_peer *find_peer(const char *peer, struct ast_sockaddr *addr, int realtime, int which_objects, int devstate_only, int transport)
05264 {
05265    struct sip_peer *p = NULL;
05266    struct sip_peer tmp_peer;
05267 
05268    if (peer) {
05269       ast_copy_string(tmp_peer.name, peer, sizeof(tmp_peer.name));
05270       p = ao2_t_callback_data(peers, OBJ_POINTER, find_by_name, &tmp_peer, &which_objects, "ao2_find in peers table");
05271    } else if (addr) { /* search by addr? */
05272       ast_sockaddr_copy(&tmp_peer.addr, addr);
05273       tmp_peer.flags[0].flags = 0;
05274       tmp_peer.transports = transport;
05275       p = ao2_t_find(peers_by_ip, &tmp_peer, OBJ_POINTER, "ao2_find in peers_by_ip table"); /* WAS:  p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, name, sip_addr_hashfunc, 1, sip_addrcmp); */
05276       if (!p) {
05277          ast_set_flag(&tmp_peer.flags[0], SIP_INSECURE_PORT);
05278          p = ao2_t_find(peers_by_ip, &tmp_peer, OBJ_POINTER, "ao2_find in peers_by_ip table 2"); /* WAS:  p = ASTOBJ_CONTAINER_FIND_FULL(&peerl, sin, name, sip_addr_hashfunc, 1, sip_addrcmp); */
05279          if (p) {
05280             return p;
05281          }
05282       }
05283    }
05284 
05285    if (!p && (realtime || devstate_only)) {
05286       p = realtime_peer(peer, addr, devstate_only, which_objects);
05287       if (p) {
05288          switch (which_objects) {
05289          case FINDUSERS:
05290             if (!(p->type & SIP_TYPE_USER)) {
05291                unref_peer(p, "Wrong type of realtime SIP endpoint");
05292                return NULL;
05293             }
05294             break;
05295          case FINDPEERS:
05296             if (!(p->type & SIP_TYPE_PEER)) {
05297                unref_peer(p, "Wrong type of realtime SIP endpoint");
05298                return NULL;
05299             }
05300             break;
05301          case FINDALLDEVICES:
05302             break;
05303          }
05304       }
05305    }
05306 
05307    return p;
05308 }
05309 
05310 /*! \brief Set nat mode on the various data sockets */
05311 static void do_setnat(struct sip_pvt *p)
05312 {
05313    const char *mode;
05314    int natflags;
05315 
05316    natflags = ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
05317    mode = natflags ? "On" : "Off";
05318 
05319    if (p->rtp) {
05320       ast_debug(1, "Setting NAT on RTP to %s\n", mode);
05321       ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_NAT, natflags);
05322    }
05323    if (p->vrtp) {
05324       ast_debug(1, "Setting NAT on VRTP to %s\n", mode);
05325       ast_rtp_instance_set_prop(p->vrtp, AST_RTP_PROPERTY_NAT, natflags);
05326    }
05327    if (p->udptl) {
05328       ast_debug(1, "Setting NAT on UDPTL to %s\n", mode);
05329       ast_udptl_setnat(p->udptl, natflags);
05330    }
05331    if (p->trtp) {
05332       ast_debug(1, "Setting NAT on TRTP to %s\n", mode);
05333       ast_rtp_instance_set_prop(p->trtp, AST_RTP_PROPERTY_NAT, natflags);
05334    }
05335 }
05336 
05337 /*! \brief Change the T38 state on a SIP dialog */
05338 static void change_t38_state(struct sip_pvt *p, int state)
05339 {
05340    int old = p->t38.state;
05341    struct ast_channel *chan = p->owner;
05342    struct ast_control_t38_parameters parameters = { .request_response = 0 };
05343 
05344    /* Don't bother changing if we are already in the state wanted */
05345    if (old == state)
05346       return;
05347 
05348    p->t38.state = state;
05349    ast_debug(2, "T38 state changed to %u on channel %s\n", p->t38.state, chan ? chan->name : "<none>");
05350 
05351    /* If no channel was provided we can't send off a control frame */
05352    if (!chan)
05353       return;
05354 
05355    /* Given the state requested and old state determine what control frame we want to queue up */
05356    switch (state) {
05357    case T38_PEER_REINVITE:
05358       parameters = p->t38.their_parms;
05359       parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05360       parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
05361       ast_udptl_set_tag(p->udptl, "%s", chan->name);
05362       break;
05363    case T38_ENABLED:
05364       parameters = p->t38.their_parms;
05365       parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05366       parameters.request_response = AST_T38_NEGOTIATED;
05367       ast_udptl_set_tag(p->udptl, "%s", chan->name);
05368       break;
05369    case T38_DISABLED:
05370       if (old == T38_ENABLED) {
05371          parameters.request_response = AST_T38_TERMINATED;
05372       } else if (old == T38_LOCAL_REINVITE) {
05373          parameters.request_response = AST_T38_REFUSED;
05374       }
05375       break;
05376    case T38_LOCAL_REINVITE:
05377       /* wait until we get a peer response before responding to local reinvite */
05378       break;
05379    }
05380 
05381    /* Woot we got a message, create a control frame and send it on! */
05382    if (parameters.request_response)
05383       ast_queue_control_data(chan, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));
05384 }
05385 
05386 /*! \brief Set the global T38 capabilities on a SIP dialog structure */
05387 static void set_t38_capabilities(struct sip_pvt *p)
05388 {
05389    if (p->udptl) {
05390       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY) {
05391                         ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
05392       } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_FEC) {
05393          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
05394       } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL) {
05395          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
05396       }
05397    }
05398 }
05399 
05400 static void copy_socket_data(struct sip_socket *to_sock, const struct sip_socket *from_sock)
05401 {
05402    if (to_sock->tcptls_session) {
05403       ao2_ref(to_sock->tcptls_session, -1);
05404       to_sock->tcptls_session = NULL;
05405    }
05406 
05407    if (from_sock->tcptls_session) {
05408       ao2_ref(from_sock->tcptls_session, +1);
05409    }
05410 
05411    *to_sock = *from_sock;
05412 }
05413 
05414 /*! \brief Initialize RTP portion of a dialog
05415  * \return -1 on failure, 0 on success
05416  */
05417 static int dialog_initialize_rtp(struct sip_pvt *dialog)
05418 {
05419    struct ast_sockaddr bindaddr_tmp;
05420 
05421    if (!sip_methods[dialog->method].need_rtp) {
05422       return 0;
05423    }
05424 
05425    ast_sockaddr_copy(&bindaddr_tmp, &bindaddr);
05426    if (!(dialog->rtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
05427       return -1;
05428    }
05429 
05430    if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) ||
05431          (ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) && (dialog->capability & AST_FORMAT_VIDEO_MASK))) {
05432       if (!(dialog->vrtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
05433          return -1;
05434       }
05435       ast_rtp_instance_set_timeout(dialog->vrtp, dialog->rtptimeout);
05436       ast_rtp_instance_set_hold_timeout(dialog->vrtp, dialog->rtpholdtimeout);
05437       ast_rtp_instance_set_keepalive(dialog->vrtp, dialog->rtpkeepalive);
05438 
05439       ast_rtp_instance_set_prop(dialog->vrtp, AST_RTP_PROPERTY_RTCP, 1);
05440       ast_rtp_instance_set_qos(dialog->vrtp, global_tos_video, global_cos_video, "SIP VIDEO");
05441    }
05442 
05443    if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT)) {
05444       if (!(dialog->trtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
05445          return -1;
05446       }
05447       /* Do not timeout text as its not constant*/
05448       ast_rtp_instance_set_keepalive(dialog->trtp, dialog->rtpkeepalive);
05449 
05450       ast_rtp_instance_set_prop(dialog->trtp, AST_RTP_PROPERTY_RTCP, 1);
05451    }
05452 
05453    ast_rtp_instance_set_timeout(dialog->rtp, dialog->rtptimeout);
05454    ast_rtp_instance_set_hold_timeout(dialog->rtp, dialog->rtpholdtimeout);
05455    ast_rtp_instance_set_keepalive(dialog->rtp, dialog->rtpkeepalive);
05456 
05457    ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_RTCP, 1);
05458    ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
05459    ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
05460 
05461    ast_rtp_instance_set_qos(dialog->rtp, global_tos_audio, global_cos_audio, "SIP RTP");
05462 
05463    do_setnat(dialog);
05464 
05465    return 0;
05466 }
05467 
05468 /*! \brief Create address structure from peer reference.
05469  * This function copies data from peer to the dialog, so we don't have to look up the peer
05470  * again from memory or database during the life time of the dialog.
05471  *
05472  * \return -1 on error, 0 on success.
05473  *
05474  */
05475 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
05476 {
05477    struct sip_auth_container *credentials;
05478 
05479    /* this checks that the dialog is contacting the peer on a valid
05480     * transport type based on the peers transport configuration,
05481     * otherwise, this function bails out */
05482    if (dialog->socket.type && check_request_transport(peer, dialog))
05483       return -1;
05484    copy_socket_data(&dialog->socket, &peer->socket);
05485 
05486    if (!(ast_sockaddr_isnull(&peer->addr) && ast_sockaddr_isnull(&peer->defaddr)) &&
05487        (!peer->maxms || ((peer->lastms >= 0)  && (peer->lastms <= peer->maxms)))) {
05488       dialog->sa = ast_sockaddr_isnull(&peer->addr) ? peer->defaddr : peer->addr;
05489       dialog->recv = dialog->sa;
05490    } else
05491       return -1;
05492 
05493    /* XXX TODO: get flags directly from peer only as they are needed using dialog->relatedpeer */
05494    ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
05495    ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
05496    ast_copy_flags(&dialog->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
05497    dialog->capability = peer->capability;
05498    dialog->prefs = peer->prefs;
05499    dialog->amaflags = peer->amaflags;
05500 
05501    ast_string_field_set(dialog, engine, peer->engine);
05502 
05503    dialog->rtptimeout = peer->rtptimeout;
05504    dialog->rtpholdtimeout = peer->rtpholdtimeout;
05505    dialog->rtpkeepalive = peer->rtpkeepalive;
05506    if (dialog_initialize_rtp(dialog)) {
05507       return -1;
05508    }
05509 
05510    if (dialog->rtp) { /* Audio */
05511       ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
05512       ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
05513       /* Set Frame packetization */
05514       ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(dialog->rtp), dialog->rtp, &dialog->prefs);
05515       dialog->autoframing = peer->autoframing;
05516    }
05517 
05518    /* XXX TODO: get fields directly from peer only as they are needed using dialog->relatedpeer */
05519    ast_string_field_set(dialog, peername, peer->name);
05520    ast_string_field_set(dialog, authname, peer->username);
05521    ast_string_field_set(dialog, username, peer->username);
05522    ast_string_field_set(dialog, peersecret, peer->secret);
05523    ast_string_field_set(dialog, peermd5secret, peer->md5secret);
05524    ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
05525    ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
05526    ast_string_field_set(dialog, tohost, peer->tohost);
05527    ast_string_field_set(dialog, fullcontact, peer->fullcontact);
05528    ast_string_field_set(dialog, accountcode, peer->accountcode);
05529    ast_string_field_set(dialog, context, peer->context);
05530    ast_string_field_set(dialog, cid_num, peer->cid_num);
05531    ast_string_field_set(dialog, cid_name, peer->cid_name);
05532    ast_string_field_set(dialog, cid_tag, peer->cid_tag);
05533    ast_string_field_set(dialog, mwi_from, peer->mwi_from);
05534    if (!ast_strlen_zero(peer->parkinglot)) {
05535       ast_string_field_set(dialog, parkinglot, peer->parkinglot);
05536    }
05537    ast_string_field_set(dialog, engine, peer->engine);
05538    ref_proxy(dialog, obproxy_get(dialog, peer));
05539    dialog->callgroup = peer->callgroup;
05540    dialog->pickupgroup = peer->pickupgroup;
05541    dialog->allowtransfer = peer->allowtransfer;
05542    dialog->jointnoncodeccapability = dialog->noncodeccapability;
05543 
05544    /* Update dialog authorization credentials */
05545    ao2_lock(peer);
05546    credentials = peer->auth;
05547    if (credentials) {
05548       ao2_t_ref(credentials, +1, "Ref peer auth for dialog");
05549    }
05550    ao2_unlock(peer);
05551    ao2_lock(dialog);
05552    if (dialog->peerauth) {
05553       ao2_t_ref(dialog->peerauth, -1, "Unref old dialog peer auth");
05554    }
05555    dialog->peerauth = credentials;
05556    ao2_unlock(dialog);
05557 
05558    dialog->maxcallbitrate = peer->maxcallbitrate;
05559    dialog->disallowed_methods = peer->disallowed_methods;
05560    ast_cc_copy_config_params(dialog->cc_params, peer->cc_params);
05561    if (ast_strlen_zero(dialog->tohost))
05562       ast_string_field_set(dialog, tohost, ast_sockaddr_stringify_host_remote(&dialog->sa));
05563    if (!ast_strlen_zero(peer->fromdomain)) {
05564       ast_string_field_set(dialog, fromdomain, peer->fromdomain);
05565       if (!dialog->initreq.headers) {
05566          char *new_callid;
05567          char *tmpcall = ast_strdupa(dialog->callid);
05568          /* this sure looks to me like we are going to change the callid on this dialog!! */
05569          new_callid = strchr(tmpcall, '@');
05570          if (new_callid) {
05571             int callid_size;
05572 
05573             *new_callid = '\0';
05574 
05575             /* Change the dialog callid. */
05576             callid_size = strlen(tmpcall) + strlen(peer->fromdomain) + 2;
05577             new_callid = ast_alloca(callid_size);
05578             snprintf(new_callid, callid_size, "%s@%s", tmpcall, peer->fromdomain);
05579             change_callid_pvt(dialog, new_callid);
05580          }
05581       }
05582    }
05583    if (!ast_strlen_zero(peer->fromuser))
05584       ast_string_field_set(dialog, fromuser, peer->fromuser);
05585    if (!ast_strlen_zero(peer->language))
05586       ast_string_field_set(dialog, language, peer->language);
05587    /* Set timer T1 to RTT for this peer (if known by qualify=) */
05588    /* Minimum is settable or default to 100 ms */
05589    /* If there is a maxms and lastms from a qualify use that over a manual T1
05590       value. Otherwise, use the peer's T1 value. */
05591    if (peer->maxms && peer->lastms)
05592       dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
05593    else
05594       dialog->timer_t1 = peer->timer_t1;
05595 
05596    /* Set timer B to control transaction timeouts, the peer setting is the default and overrides
05597       the known timer */
05598    if (peer->timer_b)
05599       dialog->timer_b = peer->timer_b;
05600    else
05601       dialog->timer_b = 64 * dialog->timer_t1;
05602 
05603    if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
05604        (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
05605       dialog->noncodeccapability |= AST_RTP_DTMF;
05606    else
05607       dialog->noncodeccapability &= ~AST_RTP_DTMF;
05608    dialog->directmediaha = ast_duplicate_ha_list(peer->directmediaha);
05609    if (peer->call_limit)
05610       ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
05611    if (!dialog->portinuri)
05612       dialog->portinuri = peer->portinuri;
05613    dialog->chanvars = copy_vars(peer->chanvars);
05614    if (peer->fromdomainport)
05615       dialog->fromdomainport = peer->fromdomainport;
05616    dialog->callingpres = peer->callingpres;
05617 
05618    return 0;
05619 }
05620 
05621 /*! \brief The default sip port for the given transport */
05622 static inline int default_sip_port(enum sip_transport type)
05623 {
05624    return type == SIP_TRANSPORT_TLS ? STANDARD_TLS_PORT : STANDARD_SIP_PORT;
05625 }
05626 
05627 /*! \brief create address structure from device name
05628  *      Or, if peer not found, find it in the global DNS
05629  *      returns TRUE (-1) on failure, FALSE on success */
05630 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog)
05631 {
05632    struct sip_peer *peer;
05633    char *peername, *peername2, *hostn;
05634    char host[MAXHOSTNAMELEN];
05635    char service[MAXHOSTNAMELEN];
05636    int srv_ret = 0;
05637    int tportno;
05638 
05639    AST_DECLARE_APP_ARGS(hostport,
05640       AST_APP_ARG(host);
05641       AST_APP_ARG(port);
05642    );
05643 
05644    peername = ast_strdupa(opeer);
05645    peername2 = ast_strdupa(opeer);
05646    AST_NONSTANDARD_RAW_ARGS(hostport, peername2, ':');
05647 
05648    if (hostport.port)
05649       dialog->portinuri = 1;
05650 
05651    dialog->timer_t1 = global_t1; /* Default SIP retransmission timer T1 (RFC 3261) */
05652    dialog->timer_b = global_timer_b; /* Default SIP transaction timer B (RFC 3261) */
05653    peer = find_peer(peername, NULL, TRUE, FINDPEERS, FALSE, 0);
05654 
05655    if (peer) {
05656       int res;
05657       if (newdialog) {
05658          set_socket_transport(&dialog->socket, 0);
05659       }
05660       res = create_addr_from_peer(dialog, peer);
05661       dialog->relatedpeer = ref_peer(peer, "create_addr: setting dialog's relatedpeer pointer");
05662       unref_peer(peer, "create_addr: unref peer from find_peer hashtab lookup");
05663       return res;
05664    } else if (ast_check_digits(peername)) {
05665       /* Although an IPv4 hostname *could* be represented as a 32-bit integer, it is uncommon and
05666        * it makes dialing SIP/${EXTEN} for a peer that isn't defined resolve to an IP that is
05667        * almost certainly not intended. It is much better to just reject purely numeric hostnames */
05668       ast_log(LOG_WARNING, "Purely numeric hostname (%s), and not a peer--rejecting!\n", peername);
05669       return -1;
05670    } else {
05671       dialog->rtptimeout = global_rtptimeout;
05672       dialog->rtpholdtimeout = global_rtpholdtimeout;
05673       dialog->rtpkeepalive = global_rtpkeepalive;
05674       if (dialog_initialize_rtp(dialog)) {
05675          return -1;
05676       }
05677    }
05678 
05679    ast_string_field_set(dialog, tohost, hostport.host);
05680    dialog->allowed_methods &= ~sip_cfg.disallowed_methods;
05681 
05682    /* Get the outbound proxy information */
05683    ref_proxy(dialog, obproxy_get(dialog, NULL));
05684 
05685    if (addr) {
05686       /* This address should be updated using dnsmgr */
05687       ast_sockaddr_copy(&dialog->sa, addr);
05688    } else {
05689 
05690       /* Let's see if we can find the host in DNS. First try DNS SRV records,
05691          then hostname lookup */
05692       /*! \todo Fix this function. When we ask for SRV, we should check all transports
05693            In the future, we should first check NAPTR to find out transport preference
05694        */
05695       hostn = peername;
05696       /* Section 4.2 of RFC 3263 specifies that if a port number is specified, then
05697        * an A record lookup should be used instead of SRV.
05698        */
05699       if (!hostport.port && sip_cfg.srvlookup) {
05700          snprintf(service, sizeof(service), "_%s._%s.%s", 
05701              get_srv_service(dialog->socket.type),
05702              get_srv_protocol(dialog->socket.type), peername);
05703          if ((srv_ret = ast_get_srv(NULL, host, sizeof(host), &tportno,
05704                      service)) > 0) {
05705             hostn = host;
05706          }
05707       }
05708 
05709       if (ast_sockaddr_resolve_first_transport(&dialog->sa, hostn, 0, dialog->socket.type ? dialog->socket.type : SIP_TRANSPORT_UDP)) {
05710          ast_log(LOG_WARNING, "No such host: %s\n", peername);
05711          return -1;
05712       }
05713 
05714       if (srv_ret > 0) {
05715          ast_sockaddr_set_port(&dialog->sa, tportno);
05716       }
05717    }
05718 
05719    if (!dialog->socket.type)
05720       set_socket_transport(&dialog->socket, SIP_TRANSPORT_UDP);
05721    if (!dialog->socket.port) {
05722       dialog->socket.port = htons(ast_sockaddr_port(&bindaddr));
05723    }
05724 
05725    if (!ast_sockaddr_port(&dialog->sa)) {
05726       ast_sockaddr_set_port(&dialog->sa, default_sip_port(dialog->socket.type));
05727    }
05728    ast_sockaddr_copy(&dialog->recv, &dialog->sa);
05729    return 0;
05730 }
05731 
05732 /*! \brief Scheduled congestion on a call.
05733  * Only called by the scheduler, must return the reference when done.
05734  */
05735 static int auto_congest(const void *arg)
05736 {
05737    struct sip_pvt *p = (struct sip_pvt *)arg;
05738 
05739    sip_pvt_lock(p);
05740    p->initid = -1;   /* event gone, will not be rescheduled */
05741    if (p->owner) {
05742       /* XXX fails on possible deadlock */
05743       if (!ast_channel_trylock(p->owner)) {
05744          append_history(p, "Cong", "Auto-congesting (timer)");
05745          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
05746          ast_channel_unlock(p->owner);
05747       }
05748 
05749       /* Give the channel a chance to act before we proceed with destruction */
05750       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05751    }
05752    sip_pvt_unlock(p);
05753    dialog_unref(p, "unreffing arg passed into auto_congest callback (p->initid)");
05754    return 0;
05755 }
05756 
05757 
05758 /*! \brief Initiate SIP call from PBX
05759  *      used from the dial() application      */
05760 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
05761 {
05762    int res;
05763    struct sip_pvt *p = ast->tech_pvt;  /* chan is locked, so the reference cannot go away */
05764    struct varshead *headp;
05765    struct ast_var_t *current;
05766    const char *referer = NULL;   /* SIP referrer */
05767    int cc_core_id;
05768    char uri[SIPBUFSIZE] = "";
05769 
05770    if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
05771       ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
05772       return -1;
05773    }
05774 
05775    if (ast_cc_is_recall(ast, &cc_core_id, "SIP")) {
05776       char device_name[AST_CHANNEL_NAME];
05777       struct ast_cc_monitor *recall_monitor;
05778       struct sip_monitor_instance *monitor_instance;
05779       ast_channel_get_device_name(ast, device_name, sizeof(device_name));
05780       if ((recall_monitor = ast_cc_get_monitor_by_recall_core_id(cc_core_id, device_name))) {
05781          monitor_instance = recall_monitor->private_data;
05782          ast_copy_string(uri, monitor_instance->notify_uri, sizeof(uri));
05783          ao2_t_ref(recall_monitor, -1, "Got the URI we need so unreffing monitor");
05784       }
05785    }
05786 
05787    /* Check whether there is vxml_url, distinctive ring variables */
05788    headp=&ast->varshead;
05789    AST_LIST_TRAVERSE(headp, current, entries) {
05790       /* Check whether there is a VXML_URL variable */
05791       if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
05792          p->options->vxml_url = ast_var_value(current);
05793       } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
05794          p->options->uri_options = ast_var_value(current);
05795       } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
05796          /* Check whether there is a variable with a name starting with SIPADDHEADER */
05797          p->options->addsipheaders = 1;
05798       } else if (!strcasecmp(ast_var_name(current), "SIPFROMDOMAIN")) {
05799          ast_string_field_set(p, fromdomain, ast_var_value(current));
05800       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
05801          /* This is a transferred call */
05802          p->options->transfer = 1;
05803       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
05804          /* This is the referrer */
05805          referer = ast_var_value(current);
05806       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
05807          /* We're replacing a call. */
05808          p->options->replaces = ast_var_value(current);
05809       } else if (!strcasecmp(ast_var_name(current), "SIP_MAX_FORWARDS")) {
05810          if (sscanf(ast_var_value(current), "%d", &(p->maxforwards)) != 1) {
05811             ast_log(LOG_WARNING, "The SIP_MAX_FORWARDS channel variable is not a valid integer.\n");
05812          }
05813       }
05814    }
05815 
05816    /* Check to see if we should try to force encryption */
05817    if (p->req_secure_signaling && p->socket.type != SIP_TRANSPORT_TLS) {
05818       ast_log(LOG_WARNING, "Encrypted signaling is required\n");
05819       ast->hangupcause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05820       return -1;
05821    }
05822 
05823    if (ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP)) {
05824       if (ast_test_flag(&p->flags[0], SIP_REINVITE)) {
05825          ast_debug(1, "Direct media not possible when using SRTP, ignoring canreinvite setting\n");
05826          ast_clear_flag(&p->flags[0], SIP_REINVITE);
05827       }
05828 
05829       if (p->rtp && !p->srtp && setup_srtp(&p->srtp) < 0) {
05830          ast_log(LOG_WARNING, "SRTP audio setup failed\n");
05831          return -1;
05832       }
05833 
05834       if (p->vrtp && !p->vsrtp && setup_srtp(&p->vsrtp) < 0) {
05835          ast_log(LOG_WARNING, "SRTP video setup failed\n");
05836          return -1;
05837       }
05838 
05839       if (p->trtp && !p->tsrtp && setup_srtp(&p->tsrtp) < 0) {
05840          ast_log(LOG_WARNING, "SRTP text setup failed\n");
05841          return -1;
05842       }
05843    }
05844 
05845    res = 0;
05846    ast_set_flag(&p->flags[0], SIP_OUTGOING);
05847 
05848    /* T.38 re-INVITE FAX detection should never be done for outgoing calls,
05849     * so ensure it is disabled.
05850     */
05851    ast_clear_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38);
05852 
05853    if (p->options->transfer) {
05854       char buf[SIPBUFSIZE/2];
05855 
05856       if (referer) {
05857          if (sipdebug)
05858             ast_debug(3, "Call for %s transferred by %s\n", p->username, referer);
05859          snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
05860       } else
05861          snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
05862       ast_string_field_set(p, cid_name, buf);
05863    }
05864    ast_debug(1, "Outgoing Call for %s\n", p->username);
05865 
05866    res = update_call_counter(p, INC_CALL_RINGING);
05867 
05868    if (res == -1) {
05869       ast->hangupcause = AST_CAUSE_USER_BUSY;
05870       return res;
05871    }
05872    p->callingpres = ast_party_id_presentation(&ast->caller.id);
05873    p->jointcapability = ast_rtp_instance_available_formats(p->rtp, p->capability, p->prefcodec);
05874    p->jointnoncodeccapability = p->noncodeccapability;
05875 
05876    /* If there are no audio formats left to offer, punt */
05877    if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
05878       ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
05879       res = -1;
05880    } else {
05881       int xmitres;
05882       struct ast_party_connected_line connected;
05883       struct ast_set_party_connected_line update_connected;
05884 
05885       sip_pvt_lock(p);
05886 
05887       /* Supply initial connected line information if available. */
05888       memset(&update_connected, 0, sizeof(update_connected));
05889       ast_party_connected_line_init(&connected);
05890       if (!ast_strlen_zero(p->cid_num)
05891          || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
05892          update_connected.id.number = 1;
05893          connected.id.number.valid = 1;
05894          connected.id.number.str = (char *) p->cid_num;
05895          connected.id.number.presentation = p->callingpres;
05896       }
05897       if (!ast_strlen_zero(p->cid_name)
05898          || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
05899          update_connected.id.name = 1;
05900          connected.id.name.valid = 1;
05901          connected.id.name.str = (char *) p->cid_name;
05902          connected.id.name.presentation = p->callingpres;
05903       }
05904       if (update_connected.id.number || update_connected.id.name) {
05905          connected.id.tag = (char *) p->cid_tag;
05906          connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
05907          ast_channel_queue_connected_line_update(ast, &connected, &update_connected);
05908       }
05909 
05910       xmitres = transmit_invite(p, SIP_INVITE, 1, 2, uri);
05911       if (xmitres == XMIT_ERROR) {
05912          sip_pvt_unlock(p);
05913          return -1;
05914       }
05915       p->invitestate = INV_CALLING;
05916 
05917       /* Initialize auto-congest time */
05918       AST_SCHED_REPLACE_UNREF(p->initid, sched, p->timer_b, auto_congest, p,
05919                         dialog_unref(_data, "dialog ptr dec when SCHED_REPLACE del op succeeded"),
05920                         dialog_unref(p, "dialog ptr dec when SCHED_REPLACE add failed"),
05921                         dialog_ref(p, "dialog ptr inc when SCHED_REPLACE add succeeded") );
05922       sip_pvt_unlock(p);
05923    }
05924    return res;
05925 }
05926 
05927 /*! \brief Destroy registry object
05928    Objects created with the register= statement in static configuration */
05929 static void sip_registry_destroy(struct sip_registry *reg)
05930 {
05931    /* Really delete */
05932    ast_debug(3, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
05933 
05934    if (reg->call) {
05935       /* Clear registry before destroying to ensure
05936          we don't get reentered trying to grab the registry lock */
05937       reg->call->registry = registry_unref(reg->call->registry, "destroy reg->call->registry");
05938       ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
05939       dialog_unlink_all(reg->call);
05940       reg->call = dialog_unref(reg->call, "unref reg->call");
05941       /* reg->call = sip_destroy(reg->call); */
05942    }
05943    AST_SCHED_DEL(sched, reg->expire);
05944    AST_SCHED_DEL(sched, reg->timeout);
05945 
05946    ast_string_field_free_memory(reg);
05947    ast_atomic_fetchadd_int(&regobjs, -1);
05948    ast_free(reg);
05949 }
05950 
05951 /*! \brief Destroy MWI subscription object */
05952 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi)
05953 {
05954    if (mwi->call) {
05955       mwi->call->mwi = NULL;
05956       mwi->call = dialog_unref(mwi->call, "sip_subscription_mwi destruction");
05957    }
05958 
05959    AST_SCHED_DEL(sched, mwi->resub);
05960    ast_string_field_free_memory(mwi);
05961    ast_free(mwi);
05962 }
05963 
05964 /*! \brief Execute destruction of SIP dialog structure, release memory */
05965 void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
05966 {
05967    struct sip_request *req;
05968 
05969    /* Destroy Session-Timers if allocated */
05970    if (p->stimer) {
05971       p->stimer->quit_flag = 1;
05972       stop_session_timer(p);
05973       ast_free(p->stimer);
05974       p->stimer = NULL;
05975    }
05976 
05977    if (sip_debug_test_pvt(p))
05978       ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
05979 
05980    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
05981       update_call_counter(p, DEC_CALL_LIMIT);
05982       ast_debug(2, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
05983    }
05984 
05985    /* Unlink us from the owner if we have one */
05986    if (p->owner) {
05987       if (lockowner)
05988          ast_channel_lock(p->owner);
05989       ast_debug(1, "Detaching from %s\n", p->owner->name);
05990       p->owner->tech_pvt = NULL;
05991       /* Make sure that the channel knows its backend is going away */
05992       p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
05993       if (lockowner)
05994          ast_channel_unlock(p->owner);
05995       /* Give the channel a chance to react before deallocation */
05996       usleep(1);
05997    }
05998 
05999    /* Remove link from peer to subscription of MWI */
06000    if (p->relatedpeer && p->relatedpeer->mwipvt == p)
06001       p->relatedpeer->mwipvt = dialog_unref(p->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
06002    if (p->relatedpeer && p->relatedpeer->call == p)
06003       p->relatedpeer->call = dialog_unref(p->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
06004    
06005    if (p->relatedpeer)
06006       p->relatedpeer = unref_peer(p->relatedpeer,"unsetting a dialog relatedpeer field in sip_destroy");
06007    
06008    if (p->registry) {
06009       if (p->registry->call == p)
06010          p->registry->call = dialog_unref(p->registry->call, "nulling out the registry's call dialog field in unlink_all");
06011       p->registry = registry_unref(p->registry, "delete p->registry");
06012    }
06013    
06014    if (p->mwi) {
06015       p->mwi->call = NULL;
06016       p->mwi = NULL;
06017    }
06018 
06019    if (dumphistory)
06020       sip_dump_history(p);
06021 
06022    if (p->options) {
06023       if (p->options->outboundproxy) {
06024          ao2_ref(p->options->outboundproxy, -1);
06025       }
06026       ast_free(p->options);
06027       p->options = NULL;
06028    }
06029 
06030    if (p->outboundproxy) {
06031       ref_proxy(p, NULL);
06032    }
06033 
06034    if (p->notify) {
06035       ast_variables_destroy(p->notify->headers);
06036       ast_free(p->notify->content);
06037       ast_free(p->notify);
06038       p->notify = NULL;
06039    }
06040    if (p->rtp) {
06041       ast_rtp_instance_destroy(p->rtp);
06042       p->rtp = NULL;
06043    }
06044    if (p->vrtp) {
06045       ast_rtp_instance_destroy(p->vrtp);
06046       p->vrtp = NULL;
06047    }
06048    if (p->trtp) {
06049       ast_rtp_instance_destroy(p->trtp);
06050       p->trtp = NULL;
06051    }
06052    if (p->udptl) {
06053       ast_udptl_destroy(p->udptl);
06054       p->udptl = NULL;
06055    }
06056    if (p->refer) {
06057       if (p->refer->refer_call) {
06058          p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
06059       }
06060       ast_free(p->refer);
06061       p->refer = NULL;
06062    }
06063    if (p->route) {
06064       free_old_route(p->route);
06065       p->route = NULL;
06066    }
06067    deinit_req(&p->initreq);
06068 
06069    /* Clear history */
06070    if (p->history) {
06071       struct sip_history *hist;
06072       while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
06073          ast_free(hist);
06074          p->history_entries--;
06075       }
06076       ast_free(p->history);
06077       p->history = NULL;
06078    }
06079 
06080    while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
06081       ast_free(req);
06082    }
06083 
06084    if (p->chanvars) {
06085       ast_variables_destroy(p->chanvars);
06086       p->chanvars = NULL;
06087    }
06088 
06089    if (p->srtp) {
06090       sip_srtp_destroy(p->srtp);
06091       p->srtp = NULL;
06092    }
06093 
06094    if (p->vsrtp) {
06095       sip_srtp_destroy(p->vsrtp);
06096       p->vsrtp = NULL;
06097    }
06098 
06099    if (p->tsrtp) {
06100       sip_srtp_destroy(p->tsrtp);
06101       p->tsrtp = NULL;
06102    }
06103 
06104    if (p->directmediaha) {
06105       ast_free_ha(p->directmediaha);
06106       p->directmediaha = NULL;
06107    }
06108 
06109    ast_string_field_free_memory(p);
06110 
06111    ast_cc_config_params_destroy(p->cc_params);
06112    p->cc_params = NULL;
06113 
06114    if (p->epa_entry) {
06115       ao2_ref(p->epa_entry, -1);
06116       p->epa_entry = NULL;
06117    }
06118 
06119    if (p->socket.tcptls_session) {
06120       ao2_ref(p->socket.tcptls_session, -1);
06121       p->socket.tcptls_session = NULL;
06122    }
06123 
06124    if (p->peerauth) {
06125       ao2_t_ref(p->peerauth, -1, "Removing active peer authentication");
06126       p->peerauth = NULL;
06127    }
06128 }
06129 
06130 /*! \brief  update_call_counter: Handle call_limit for SIP devices
06131  * Setting a call-limit will cause calls above the limit not to be accepted.
06132  *
06133  * Remember that for a type=friend, there's one limit for the user and
06134  * another for the peer, not a combined call limit.
06135  * This will cause unexpected behaviour in subscriptions, since a "friend"
06136  * is *two* devices in Asterisk, not one.
06137  *
06138  * Thought: For realtime, we should probably update storage with inuse counter...
06139  *
06140  * \return 0 if call is ok (no call limit, below threshold)
06141  * -1 on rejection of call
06142  *
06143  */
06144 static int update_call_counter(struct sip_pvt *fup, int event)
06145 {
06146    char name[256];
06147    int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
06148    int outgoing = fup->outgoing_call;
06149    struct sip_peer *p = NULL;
06150 
06151    ast_debug(3, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
06152 
06153 
06154    /* Test if we need to check call limits, in order to avoid
06155       realtime lookups if we do not need it */
06156    if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT) && !ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD))
06157       return 0;
06158 
06159    ast_copy_string(name, fup->username, sizeof(name));
06160 
06161    /* Check the list of devices */
06162    if (fup->relatedpeer) {
06163       p = ref_peer(fup->relatedpeer, "ref related peer for update_call_counter");
06164       inuse = &p->inUse;
06165       call_limit = &p->call_limit;
06166       inringing = &p->inRinging;
06167       ast_copy_string(name, fup->peername, sizeof(name));
06168    }
06169    if (!p) {
06170       ast_debug(2, "%s is not a local device, no call limit\n", name);
06171       return 0;
06172    }
06173 
06174    switch(event) {
06175    /* incoming and outgoing affects the inUse counter */
06176    case DEC_CALL_LIMIT:
06177       /* Decrement inuse count if applicable */
06178       if (inuse) {
06179          sip_pvt_lock(fup);
06180          ao2_lock(p);
06181          if (*inuse > 0) {
06182             if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
06183                (*inuse)--;
06184                ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
06185             }
06186          } else {
06187             *inuse = 0;
06188          }
06189          ao2_unlock(p);
06190          sip_pvt_unlock(fup);
06191       }
06192 
06193       /* Decrement ringing count if applicable */
06194       if (inringing) {
06195          sip_pvt_lock(fup);
06196          ao2_lock(p);
06197          if (*inringing > 0) {
06198             if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
06199                (*inringing)--;
06200                ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
06201             }
06202          } else {
06203             *inringing = 0;
06204          }
06205          ao2_unlock(p);
06206          sip_pvt_unlock(fup);
06207       }
06208 
06209       /* Decrement onhold count if applicable */
06210       sip_pvt_lock(fup);
06211       ao2_lock(p);
06212       if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && sip_cfg.notifyhold) {
06213          ast_clear_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD);
06214          ao2_unlock(p);
06215          sip_pvt_unlock(fup);
06216          sip_peer_hold(fup, FALSE);
06217       } else {
06218          ao2_unlock(p);
06219          sip_pvt_unlock(fup);
06220       }
06221       if (sipdebug)
06222          ast_debug(2, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
06223       break;
06224 
06225    case INC_CALL_RINGING:
06226    case INC_CALL_LIMIT:
06227       /* If call limit is active and we have reached the limit, reject the call */
06228       if (*call_limit > 0 ) {
06229          if (*inuse >= *call_limit) {
06230             ast_log(LOG_NOTICE, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
06231             unref_peer(p, "update_call_counter: unref peer p, call limit exceeded");
06232             return -1;
06233          }
06234       }
06235       if (inringing && (event == INC_CALL_RINGING)) {
06236          sip_pvt_lock(fup);
06237          ao2_lock(p);
06238          if (!ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
06239             (*inringing)++;
06240             ast_set_flag(&fup->flags[0], SIP_INC_RINGING);
06241          }
06242          ao2_unlock(p);
06243          sip_pvt_unlock(fup);
06244       }
06245       if (inuse) {
06246          sip_pvt_lock(fup);
06247          ao2_lock(p);
06248          if (!ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
06249             (*inuse)++;
06250             ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
06251          }
06252          ao2_unlock(p);
06253          sip_pvt_unlock(fup);
06254       }
06255       if (sipdebug) {
06256          ast_debug(2, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", "peer", name, *inuse, *call_limit);
06257       }
06258       break;
06259 
06260    case DEC_CALL_RINGING:
06261       if (inringing) {
06262          sip_pvt_lock(fup);
06263          ao2_lock(p);
06264          if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
06265             if (*inringing > 0) {
06266                (*inringing)--;
06267             }
06268             ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
06269          }
06270          ao2_unlock(p);
06271          sip_pvt_unlock(fup);
06272       }
06273       break;
06274 
06275    default:
06276       ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
06277    }
06278 
06279    if (p) {
06280       ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", p->name);
06281       unref_peer(p, "update_call_counter: unref_peer from call counter");
06282    }
06283    return 0;
06284 }
06285 
06286 
06287 static void sip_destroy_fn(void *p)
06288 {
06289    sip_destroy(p);
06290 }
06291 
06292 /*! \brief Destroy SIP call structure.
06293  * Make it return NULL so the caller can do things like
06294  * foo = sip_destroy(foo);
06295  * and reduce the chance of bugs due to dangling pointers.
06296  */
06297 struct sip_pvt *sip_destroy(struct sip_pvt *p)
06298 {
06299    ast_debug(3, "Destroying SIP dialog %s\n", p->callid);
06300    __sip_destroy(p, TRUE, TRUE);
06301    return NULL;
06302 }
06303 
06304 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
06305 int hangup_sip2cause(int cause)
06306 {
06307    /* Possible values taken from causes.h */
06308 
06309    switch(cause) {
06310       case 401:   /* Unauthorized */
06311          return AST_CAUSE_CALL_REJECTED;
06312       case 403:   /* Not found */
06313          return AST_CAUSE_CALL_REJECTED;
06314       case 404:   /* Not found */
06315          return AST_CAUSE_UNALLOCATED;
06316       case 405:   /* Method not allowed */
06317          return AST_CAUSE_INTERWORKING;
06318       case 407:   /* Proxy authentication required */
06319          return AST_CAUSE_CALL_REJECTED;
06320       case 408:   /* No reaction */
06321          return AST_CAUSE_NO_USER_RESPONSE;
06322       case 409:   /* Conflict */
06323          return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
06324       case 410:   /* Gone */
06325          return AST_CAUSE_NUMBER_CHANGED;
06326       case 411:   /* Length required */
06327          return AST_CAUSE_INTERWORKING;
06328       case 413:   /* Request entity too large */
06329          return AST_CAUSE_INTERWORKING;
06330       case 414:   /* Request URI too large */
06331          return AST_CAUSE_INTERWORKING;
06332       case 415:   /* Unsupported media type */
06333          return AST_CAUSE_INTERWORKING;
06334       case 420:   /* Bad extension */
06335          return AST_CAUSE_NO_ROUTE_DESTINATION;
06336       case 480:   /* No answer */
06337          return AST_CAUSE_NO_ANSWER;
06338       case 481:   /* No answer */
06339          return AST_CAUSE_INTERWORKING;
06340       case 482:   /* Loop detected */
06341          return AST_CAUSE_INTERWORKING;
06342       case 483:   /* Too many hops */
06343          return AST_CAUSE_NO_ANSWER;
06344       case 484:   /* Address incomplete */
06345          return AST_CAUSE_INVALID_NUMBER_FORMAT;
06346       case 485:   /* Ambiguous */
06347          return AST_CAUSE_UNALLOCATED;
06348       case 486:   /* Busy everywhere */
06349          return AST_CAUSE_BUSY;
06350       case 487:   /* Request terminated */
06351          return AST_CAUSE_INTERWORKING;
06352       case 488:   /* No codecs approved */
06353          return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
06354       case 491:   /* Request pending */
06355          return AST_CAUSE_INTERWORKING;
06356       case 493:   /* Undecipherable */
06357          return AST_CAUSE_INTERWORKING;
06358       case 500:   /* Server internal failure */
06359          return AST_CAUSE_FAILURE;
06360       case 501:   /* Call rejected */
06361          return AST_CAUSE_FACILITY_REJECTED;
06362       case 502:
06363          return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
06364       case 503:   /* Service unavailable */
06365          return AST_CAUSE_CONGESTION;
06366       case 504:   /* Gateway timeout */
06367          return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
06368       case 505:   /* SIP version not supported */
06369          return AST_CAUSE_INTERWORKING;
06370       case 600:   /* Busy everywhere */
06371          return AST_CAUSE_USER_BUSY;
06372       case 603:   /* Decline */
06373          return AST_CAUSE_CALL_REJECTED;
06374       case 604:   /* Does not exist anywhere */
06375          return AST_CAUSE_UNALLOCATED;
06376       case 606:   /* Not acceptable */
06377          return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
06378       default:
06379          if (cause < 500 && cause >= 400) {
06380             /* 4xx class error that is unknown - someting wrong with our request */
06381             return AST_CAUSE_INTERWORKING;
06382          } else if (cause < 600 && cause >= 500) {
06383             /* 5xx class error - problem in the remote end */
06384             return AST_CAUSE_CONGESTION;
06385          } else if (cause < 700 && cause >= 600) {
06386             /* 6xx - global errors in the 4xx class */
06387             return AST_CAUSE_INTERWORKING;
06388          }
06389          return AST_CAUSE_NORMAL;
06390    }
06391    /* Never reached */
06392    return 0;
06393 }
06394 
06395 /*! \brief Convert Asterisk hangup causes to SIP codes
06396 \verbatim
06397  Possible values from causes.h
06398         AST_CAUSE_NOTDEFINED    AST_CAUSE_NORMAL        AST_CAUSE_BUSY
06399         AST_CAUSE_FAILURE       AST_CAUSE_CONGESTION    AST_CAUSE_UNALLOCATED
06400 
06401    In addition to these, a lot of PRI codes is defined in causes.h
06402    ...should we take care of them too ?
06403 
06404    Quote RFC 3398
06405 
06406    ISUP Cause value                        SIP response
06407    ----------------                        ------------
06408    1  unallocated number                   404 Not Found
06409    2  no route to network                  404 Not found
06410    3  no route to destination              404 Not found
06411    16 normal call clearing                 --- (*)
06412    17 user busy                            486 Busy here
06413    18 no user responding                   408 Request Timeout
06414    19 no answer from the user              480 Temporarily unavailable
06415    20 subscriber absent                    480 Temporarily unavailable
06416    21 call rejected                        403 Forbidden (+)
06417    22 number changed (w/o diagnostic)      410 Gone
06418    22 number changed (w/ diagnostic)       301 Moved Permanently
06419    23 redirection to new destination       410 Gone
06420    26 non-selected user clearing           404 Not Found (=)
06421    27 destination out of order             502 Bad Gateway
06422    28 address incomplete                   484 Address incomplete
06423    29 facility rejected                    501 Not implemented
06424    31 normal unspecified                   480 Temporarily unavailable
06425 \endverbatim
06426 */
06427 const char *hangup_cause2sip(int cause)
06428 {
06429    switch (cause) {
06430       case AST_CAUSE_UNALLOCATED:      /* 1 */
06431       case AST_CAUSE_NO_ROUTE_DESTINATION:   /* 3 IAX2: Can't find extension in context */
06432       case AST_CAUSE_NO_ROUTE_TRANSIT_NET:   /* 2 */
06433          return "404 Not Found";
06434       case AST_CAUSE_CONGESTION:    /* 34 */
06435       case AST_CAUSE_SWITCH_CONGESTION:   /* 42 */
06436          return "503 Service Unavailable";
06437       case AST_CAUSE_NO_USER_RESPONSE: /* 18 */
06438          return "408 Request Timeout";
06439       case AST_CAUSE_NO_ANSWER:     /* 19 */
06440       case AST_CAUSE_UNREGISTERED:        /* 20 */
06441          return "480 Temporarily unavailable";
06442       case AST_CAUSE_CALL_REJECTED:    /* 21 */
06443          return "403 Forbidden";
06444       case AST_CAUSE_NUMBER_CHANGED:      /* 22 */
06445          return "410 Gone";
06446       case AST_CAUSE_NORMAL_UNSPECIFIED:  /* 31 */
06447          return "480 Temporarily unavailable";
06448       case AST_CAUSE_INVALID_NUMBER_FORMAT:
06449          return "484 Address incomplete";
06450       case AST_CAUSE_USER_BUSY:
06451          return "486 Busy here";
06452       case AST_CAUSE_FAILURE:
06453          return "500 Server internal failure";
06454       case AST_CAUSE_FACILITY_REJECTED:   /* 29 */
06455          return "501 Not Implemented";
06456       case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
06457          return "503 Service Unavailable";
06458       /* Used in chan_iax2 */
06459       case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
06460          return "502 Bad Gateway";
06461       case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */
06462          return "488 Not Acceptable Here";
06463          
06464       case AST_CAUSE_NOTDEFINED:
06465       default:
06466          ast_debug(1, "AST hangup cause %d (no match found in SIP)\n", cause);
06467          return NULL;
06468    }
06469 
06470    /* Never reached */
06471    return 0;
06472 }
06473 
06474 static int reinvite_timeout(const void *data)
06475 {
06476    struct sip_pvt *dialog = (struct sip_pvt *) data;
06477    struct ast_channel *owner = sip_pvt_lock_full(dialog);
06478    dialog->reinviteid = -1;
06479    check_pendings(dialog);
06480    if (owner) {
06481       ast_channel_unlock(owner);
06482       ast_channel_unref(owner);
06483    }
06484    ao2_unlock(dialog);
06485    dialog_unref(dialog, "unref for reinvite timeout");
06486    return 0;
06487 }
06488 
06489 /*! \brief  sip_hangup: Hangup SIP call
06490  * Part of PBX interface, called from ast_hangup */
06491 static int sip_hangup(struct ast_channel *ast)
06492 {
06493    struct sip_pvt *p = ast->tech_pvt;
06494    int needcancel = FALSE;
06495    int needdestroy = 0;
06496    struct ast_channel *oldowner = ast;
06497 
06498    if (!p) {
06499       ast_debug(1, "Asked to hangup channel that was not connected\n");
06500       return 0;
06501    }
06502    if (ast_test_flag(ast, AST_FLAG_ANSWERED_ELSEWHERE) || ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
06503       ast_debug(1, "This call was answered elsewhere\n");
06504       if (ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
06505          ast_debug(1, "####### It's the cause code, buddy. The cause code!!!\n");
06506       }
06507       append_history(p, "Cancel", "Call answered elsewhere");
06508       p->answered_elsewhere = TRUE;
06509    }
06510 
06511    /* Store hangupcause locally in PVT so we still have it before disconnect */
06512    if (p->owner)
06513       p->hangupcause = p->owner->hangupcause;
06514 
06515    if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
06516       if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
06517          if (sipdebug)
06518             ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
06519          update_call_counter(p, DEC_CALL_LIMIT);
06520       }
06521       ast_debug(4, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
06522       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06523       ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Really hang up next time */
06524       p->needdestroy = 0;
06525       if (p->owner) {
06526          p->owner->tech_pvt = dialog_unref(p->owner->tech_pvt, "unref p->owner->tech_pvt");
06527          sip_pvt_lock(p);
06528          p->owner = NULL;  /* Owner will be gone after we return, so take it away */
06529          sip_pvt_unlock(p);
06530       }
06531       ast_module_unref(ast_module_info->self);
06532       return 0;
06533    }
06534 
06535    ast_debug(1, "Hangup call %s, SIP callid %s\n", ast->name, p->callid);
06536 
06537    sip_pvt_lock(p);
06538    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
06539       if (sipdebug)
06540          ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
06541       update_call_counter(p, DEC_CALL_LIMIT);
06542    }
06543 
06544    /* Determine how to disconnect */
06545    if (p->owner != ast) {
06546       ast_log(LOG_WARNING, "Huh?  We aren't the owner? Can't hangup call.\n");
06547       sip_pvt_unlock(p);
06548       return 0;
06549    }
06550    /* If the call is not UP, we need to send CANCEL instead of BYE */
06551    /* In case of re-invites, the call might be UP even though we have an incomplete invite transaction */
06552    if (p->invitestate < INV_COMPLETED && p->owner->_state != AST_STATE_UP) {
06553       needcancel = TRUE;
06554       ast_debug(4, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
06555    }
06556 
06557    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
06558 
06559    append_history(p, needcancel ? "Cancel" : "Hangup", "Cause %s", ast_cause2str(p->hangupcause));
06560 
06561    /* Disconnect */
06562    disable_dsp_detect(p);
06563 
06564    p->owner = NULL;
06565    ast->tech_pvt = dialog_unref(ast->tech_pvt, "unref ast->tech_pvt");
06566 
06567    ast_module_unref(ast_module_info->self);
06568    /* Do not destroy this pvt until we have timeout or
06569       get an answer to the BYE or INVITE/CANCEL
06570       If we get no answer during retransmit period, drop the call anyway.
06571       (Sorry, mother-in-law, you can't deny a hangup by sending
06572       603 declined to BYE...)
06573    */
06574    if (p->alreadygone)
06575       needdestroy = 1;  /* Set destroy flag at end of this function */
06576    else if (p->invitestate != INV_CALLING)
06577       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06578 
06579    /* Start the process if it's not already started */
06580    if (!p->alreadygone && p->initreq.data && ast_str_strlen(p->initreq.data)) {
06581       if (needcancel) { /* Outgoing call, not up */
06582          if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06583             /* if we can't send right now, mark it pending */
06584             if (p->invitestate == INV_CALLING) {
06585                /* We can't send anything in CALLING state */
06586                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
06587                /* 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. */
06588                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06589                append_history(p, "DELAY", "Not sending cancel, waiting for timeout");
06590             } else {
06591                struct sip_pkt *cur;
06592 
06593                for (cur = p->packets; cur; cur = cur->next) {
06594                   __sip_semi_ack(p, cur->seqno, cur->is_resp, cur->method ? cur->method : find_sip_method(ast_str_buffer(cur->data)));
06595                }
06596                p->invitestate = INV_CANCELLED;
06597                /* Send a new request: CANCEL */
06598                transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
06599                /* Actually don't destroy us yet, wait for the 487 on our original
06600                   INVITE, but do set an autodestruct just in case we never get it. */
06601                needdestroy = 0;
06602                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06603             }
06604          } else { /* Incoming call, not up */
06605             const char *res;
06606             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"));
06607             if (p->hangupcause && (res = hangup_cause2sip(p->hangupcause)))
06608                transmit_response_reliable(p, res, &p->initreq);
06609             else
06610                transmit_response_reliable(p, "603 Declined", &p->initreq);
06611             p->invitestate = INV_TERMINATED;
06612          }
06613       } else { /* Call is in UP state, send BYE */
06614          if (p->stimer->st_active == TRUE) {
06615             stop_session_timer(p);
06616          }
06617 
06618          if (!p->pendinginvite) {
06619             struct ast_channel *bridge = ast_bridged_channel(oldowner);
06620             char quality_buf[AST_MAX_USER_FIELD], *quality;
06621 
06622             /* We need to get the lock on bridge because ast_rtp_instance_set_stats_vars will attempt
06623              * to lock the bridge. This may get hairy...
06624              */
06625             while (bridge && ast_channel_trylock(bridge)) {
06626                sip_pvt_unlock(p);
06627                do {
06628                   CHANNEL_DEADLOCK_AVOIDANCE(oldowner);
06629                } while (sip_pvt_trylock(p));
06630                bridge = ast_bridged_channel(oldowner);
06631             }
06632 
06633             if (p->rtp) {
06634                ast_rtp_instance_set_stats_vars(oldowner, p->rtp);
06635             }
06636 
06637             if (bridge) {
06638                struct sip_pvt *q = bridge->tech_pvt;
06639 
06640                if (IS_SIP_TECH(bridge->tech) && q && q->rtp) {
06641                   ast_rtp_instance_set_stats_vars(bridge, q->rtp);
06642                }
06643                ast_channel_unlock(bridge);
06644             }
06645 
06646             /*
06647              * The channel variables are set below just to get the AMI
06648              * VarSet event because the channel is being hungup.
06649              */
06650             if (p->rtp && (quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
06651                if (p->do_history) {
06652                   append_history(p, "RTCPaudio", "Quality:%s", quality);
06653                }
06654                pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", quality);
06655             }
06656             if (p->vrtp && (quality = ast_rtp_instance_get_quality(p->vrtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
06657                if (p->do_history) {
06658                   append_history(p, "RTCPvideo", "Quality:%s", quality);
06659                }
06660                pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", quality);
06661             }
06662             if (p->trtp && (quality = ast_rtp_instance_get_quality(p->trtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
06663                if (p->do_history) {
06664                   append_history(p, "RTCPtext", "Quality:%s", quality);
06665                }
06666                pbx_builtin_setvar_helper(oldowner, "RTPTEXTQOS", quality);
06667             }
06668 
06669             /* Send a hangup */
06670             if (oldowner->_state == AST_STATE_UP) {
06671                transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
06672             }
06673 
06674          } else {
06675             /* Note we will need a BYE when this all settles out
06676                but we can't send one while we have "INVITE" outstanding. */
06677             ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
06678             ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE); 
06679             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"));
06680             if (sip_cancel_destroy(p)) {
06681                ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
06682             }
06683             /* If we have an ongoing reinvite, there is a chance that we have gotten a provisional
06684              * response, but something weird has happened and we will never receive a final response.
06685              * So, just in case, check for pending actions after a bit of time to trigger the pending
06686              * bye that we are setting above */
06687             if (p->ongoing_reinvite && p->reinviteid < 0) {
06688                p->reinviteid = ast_sched_add(sched, 32 * p->timer_t1, reinvite_timeout, dialog_ref(p, "ref for reinvite_timeout"));
06689             }
06690          }
06691       }
06692    }
06693    if (needdestroy) {
06694       pvt_set_needdestroy(p, "hangup");
06695    }
06696    sip_pvt_unlock(p);
06697    return 0;
06698 }
06699 
06700 /*! \brief Try setting codec suggested by the SIP_CODEC channel variable */
06701 static void try_suggested_sip_codec(struct sip_pvt *p)
06702 {
06703    format_t fmt;
06704    const char *codec;
06705 
06706    if (p->outgoing_call) {
06707       codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC_OUTBOUND");
06708    } else if (!(codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC_INBOUND"))) {
06709       codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
06710    }
06711 
06712    if (!codec) 
06713       return;
06714 
06715    fmt = ast_getformatbyname(codec);
06716    if (fmt) {
06717       ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
06718       if (p->jointcapability & fmt) {
06719          p->jointcapability &= fmt;
06720          p->capability &= fmt;
06721       } else
06722          ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
06723    } else
06724       ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
06725    return;  
06726 }
06727 
06728 /*! \brief  sip_answer: Answer SIP call , send 200 OK on Invite
06729  * Part of PBX interface */
06730 static int sip_answer(struct ast_channel *ast)
06731 {
06732    int res = 0;
06733    struct sip_pvt *p = ast->tech_pvt;
06734    int oldsdp = FALSE;
06735 
06736    if (!p) {
06737       ast_debug(1, "Asked to answer channel %s without tech pvt; ignoring\n",
06738             ast->name);
06739       return res;
06740    }
06741    sip_pvt_lock(p);
06742    if (ast->_state != AST_STATE_UP) {
06743       try_suggested_sip_codec(p);   
06744 
06745       if (ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT)) {
06746          oldsdp = TRUE;
06747       }
06748 
06749       ast_setstate(ast, AST_STATE_UP);
06750       ast_debug(1, "SIP answering channel: %s\n", ast->name);
06751       ast_rtp_instance_update_source(p->rtp);
06752       res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL, oldsdp, TRUE);
06753       ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
06754       /* RFC says the session timer starts counting on 200,
06755        * not on INVITE. */
06756       if (p->stimer->st_active == TRUE) {
06757          start_session_timer(p);
06758       }
06759    }
06760    sip_pvt_unlock(p);
06761    return res;
06762 }
06763 
06764 /*! \brief Send frame to media channel (rtp) */
06765 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
06766 {
06767    struct sip_pvt *p = ast->tech_pvt;
06768    int res = 0;
06769 
06770    switch (frame->frametype) {
06771    case AST_FRAME_VOICE:
06772       if (!(frame->subclass.codec & ast->nativeformats)) {
06773          char s1[512], s2[512], s3[512];
06774          ast_log(LOG_WARNING, "Asked to transmit frame type %s, while native formats is %s read/write = %s/%s\n",
06775             ast_getformatname(frame->subclass.codec),
06776             ast_getformatname_multiple(s1, sizeof(s1), ast->nativeformats & AST_FORMAT_AUDIO_MASK),
06777             ast_getformatname_multiple(s2, sizeof(s2), ast->readformat),
06778             ast_getformatname_multiple(s3, sizeof(s3), ast->writeformat));
06779          return 0;
06780       }
06781       if (p) {
06782          sip_pvt_lock(p);
06783          if (p->t38.state == T38_ENABLED) {
06784             /* drop frame, can't sent VOICE frames while in T.38 mode */
06785             sip_pvt_unlock(p);
06786             break;
06787          } else if (p->rtp) {
06788             /* If channel is not up, activate early media session */
06789             if ((ast->_state != AST_STATE_UP) &&
06790                 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06791                 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06792                ast_rtp_instance_update_source(p->rtp);
06793                if (!global_prematuremediafilter) {
06794                   p->invitestate = INV_EARLY_MEDIA;
06795                   transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06796                   ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06797                }
06798             }
06799             p->lastrtptx = time(NULL);
06800             res = ast_rtp_instance_write(p->rtp, frame);
06801          }
06802          sip_pvt_unlock(p);
06803       }
06804       break;
06805    case AST_FRAME_VIDEO:
06806       if (p) {
06807          sip_pvt_lock(p);
06808          if (p->vrtp) {
06809             /* Activate video early media */
06810             if ((ast->_state != AST_STATE_UP) &&
06811                 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06812                 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06813                p->invitestate = INV_EARLY_MEDIA;
06814                transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06815                ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06816             }
06817             p->lastrtptx = time(NULL);
06818             res = ast_rtp_instance_write(p->vrtp, frame);
06819          }
06820          sip_pvt_unlock(p);
06821       }
06822       break;
06823    case AST_FRAME_TEXT:
06824       if (p) {
06825          sip_pvt_lock(p);
06826          if (p->red) {
06827             ast_rtp_red_buffer(p->trtp, frame);
06828          } else {
06829             if (p->trtp) {
06830                /* Activate text early media */
06831                if ((ast->_state != AST_STATE_UP) &&
06832                    !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06833                    !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06834                   p->invitestate = INV_EARLY_MEDIA;
06835                   transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06836                   ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06837                }
06838                p->lastrtptx = time(NULL);
06839                res = ast_rtp_instance_write(p->trtp, frame);
06840             }
06841          }
06842          sip_pvt_unlock(p);
06843       }
06844       break;
06845    case AST_FRAME_IMAGE:
06846       return 0;
06847       break;
06848    case AST_FRAME_MODEM:
06849       if (p) {
06850          sip_pvt_lock(p);
06851          /* UDPTL requires two-way communication, so early media is not needed here.
06852             we simply forget the frames if we get modem frames before the bridge is up.
06853             Fax will re-transmit.
06854          */
06855          if ((ast->_state == AST_STATE_UP) &&
06856              p->udptl &&
06857              (p->t38.state == T38_ENABLED)) {
06858             res = ast_udptl_write(p->udptl, frame);
06859          }
06860          sip_pvt_unlock(p);
06861       }
06862       break;
06863    default:
06864       ast_log(LOG_WARNING, "Can't send %u type frames with SIP write\n", frame->frametype);
06865       return 0;
06866    }
06867 
06868    return res;
06869 }
06870 
06871 /*! \brief  sip_fixup: Fix up a channel:  If a channel is consumed, this is called.
06872         Basically update any ->owner links */
06873 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
06874 {
06875    int ret = -1;
06876    struct sip_pvt *p;
06877 
06878    if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE))
06879       ast_debug(1, "New channel is zombie\n");
06880    if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE))
06881       ast_debug(1, "Old channel is zombie\n");
06882 
06883    if (!newchan || !newchan->tech_pvt) {
06884       if (!newchan)
06885          ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", oldchan->name);
06886       else
06887          ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name);
06888       return -1;
06889    }
06890    p = newchan->tech_pvt;
06891 
06892    sip_pvt_lock(p);
06893    append_history(p, "Masq", "Old channel: %s\n", oldchan->name);
06894    append_history(p, "Masq (cont)", "...new owner: %s\n", newchan->name);
06895    if (p->owner != oldchan)
06896       ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
06897    else {
06898       p->owner = newchan;
06899       /* Re-invite RTP back to Asterisk. Needed if channel is masqueraded out of a native
06900          RTP bridge (i.e., RTP not going through Asterisk): RTP bridge code might not be
06901          able to do this if the masquerade happens before the bridge breaks (e.g., AMI
06902          redirect of both channels). Note that a channel can not be masqueraded *into*
06903          a native bridge. So there is no danger that this breaks a native bridge that
06904          should stay up. */
06905       sip_set_rtp_peer(newchan, NULL, NULL, 0, 0, 0);
06906       ret = 0;
06907    }
06908    ast_debug(3, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, p->owner->name, oldchan->name);
06909 
06910    sip_pvt_unlock(p);
06911    return ret;
06912 }
06913 
06914 static int sip_senddigit_begin(struct ast_channel *ast, char digit)
06915 {
06916    struct sip_pvt *p = ast->tech_pvt;
06917    int res = 0;
06918 
06919    if (!p) {
06920       ast_debug(1, "Asked to begin DTMF digit on channel %s with no pvt; ignoring\n",
06921             ast->name);
06922       return res;
06923    }
06924 
06925    sip_pvt_lock(p);
06926    switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
06927    case SIP_DTMF_INBAND:
06928       res = -1; /* Tell Asterisk to generate inband indications */
06929       break;
06930    case SIP_DTMF_RFC2833:
06931       if (p->rtp)
06932          ast_rtp_instance_dtmf_begin(p->rtp, digit);
06933       break;
06934    default:
06935       break;
06936    }
06937    sip_pvt_unlock(p);
06938 
06939    return res;
06940 }
06941 
06942 /*! \brief Send DTMF character on SIP channel
06943    within one call, we're able to transmit in many methods simultaneously */
06944 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
06945 {
06946    struct sip_pvt *p = ast->tech_pvt;
06947    int res = 0;
06948 
06949    if (!p) {
06950       ast_debug(1, "Asked to end DTMF digit on channel %s with no pvt; ignoring\n",
06951             ast->name);
06952       return res;
06953    }
06954 
06955    sip_pvt_lock(p);
06956    switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
06957    case SIP_DTMF_INFO:
06958    case SIP_DTMF_SHORTINFO:
06959       transmit_info_with_digit(p, digit, duration);
06960       break;
06961    case SIP_DTMF_RFC2833:
06962       if (p->rtp)
06963          ast_rtp_instance_dtmf_end_with_duration(p->rtp, digit, duration);
06964       break;
06965    case SIP_DTMF_INBAND:
06966       res = -1; /* Tell Asterisk to stop inband indications */
06967       break;
06968    }
06969    sip_pvt_unlock(p);
06970 
06971    return res;
06972 }
06973 
06974 /*! \brief Transfer SIP call */
06975 static int sip_transfer(struct ast_channel *ast, const char *dest)
06976 {
06977    struct sip_pvt *p = ast->tech_pvt;
06978    int res;
06979 
06980    if (!p) {
06981       ast_debug(1, "Asked to transfer channel %s with no pvt; ignoring\n",
06982             ast->name);
06983       return -1;
06984    }
06985 
06986    if (dest == NULL) /* functions below do not take a NULL */
06987       dest = "";
06988    sip_pvt_lock(p);
06989    if (ast->_state == AST_STATE_RING)
06990       res = sip_sipredirect(p, dest);
06991    else
06992       res = transmit_refer(p, dest);
06993    sip_pvt_unlock(p);
06994    return res;
06995 }
06996 
06997 /*! \brief Helper function which updates T.38 capability information and triggers a reinvite */
06998 static int interpret_t38_parameters(struct sip_pvt *p, const struct ast_control_t38_parameters *parameters)
06999 {
07000    int res = 0;
07001 
07002    if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) || !p->udptl) {
07003       return -1;
07004    }
07005    switch (parameters->request_response) {
07006    case AST_T38_NEGOTIATED:
07007    case AST_T38_REQUEST_NEGOTIATE:         /* Request T38 */
07008       /* Negotiation can not take place without a valid max_ifp value. */
07009       if (!parameters->max_ifp) {
07010          change_t38_state(p, T38_DISABLED);
07011          if (p->t38.state == T38_PEER_REINVITE) {
07012             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"));
07013             transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
07014          }
07015          break;
07016       } else if (p->t38.state == T38_PEER_REINVITE) {
07017          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"));
07018          p->t38.our_parms = *parameters;
07019          /* modify our parameters to conform to the peer's parameters,
07020           * based on the rules in the ITU T.38 recommendation
07021           */
07022          if (!p->t38.their_parms.fill_bit_removal) {
07023             p->t38.our_parms.fill_bit_removal = FALSE;
07024          }
07025          if (!p->t38.their_parms.transcoding_mmr) {
07026             p->t38.our_parms.transcoding_mmr = FALSE;
07027          }
07028          if (!p->t38.their_parms.transcoding_jbig) {
07029             p->t38.our_parms.transcoding_jbig = FALSE;
07030          }
07031          p->t38.our_parms.version = MIN(p->t38.our_parms.version, p->t38.their_parms.version);
07032          p->t38.our_parms.rate_management = p->t38.their_parms.rate_management;
07033          ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
07034          change_t38_state(p, T38_ENABLED);
07035          transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
07036       } else if (p->t38.state != T38_ENABLED) {
07037          p->t38.our_parms = *parameters;
07038          ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
07039          change_t38_state(p, T38_LOCAL_REINVITE);
07040          if (!p->pendinginvite) {
07041             transmit_reinvite_with_sdp(p, TRUE, FALSE);
07042          } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
07043             ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
07044          }
07045       }
07046       break;
07047    case AST_T38_TERMINATED:
07048    case AST_T38_REFUSED:
07049    case AST_T38_REQUEST_TERMINATE:         /* Shutdown T38 */
07050       if (p->t38.state == T38_PEER_REINVITE) {
07051          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"));
07052          change_t38_state(p, T38_DISABLED);
07053          transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
07054       } else if (p->t38.state == T38_ENABLED)
07055          transmit_reinvite_with_sdp(p, FALSE, FALSE);
07056       break;
07057    case AST_T38_REQUEST_PARMS: {    /* Application wants remote's parameters re-sent */
07058       struct ast_control_t38_parameters parameters = p->t38.their_parms;
07059 
07060       if (p->t38.state == T38_PEER_REINVITE) {
07061          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"));
07062          parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
07063          parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
07064          if (p->owner) {
07065             ast_queue_control_data(p->owner, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));
07066          }
07067          /* we need to return a positive value here, so that applications that
07068           * send this request can determine conclusively whether it was accepted or not...
07069           * older versions of chan_sip would just silently accept it and return zero.
07070           */
07071          res = AST_T38_REQUEST_PARMS;
07072       }
07073       break;
07074    }
07075    default:
07076       res = -1;
07077       break;
07078    }
07079 
07080    return res;
07081 }
07082 
07083 /*! \internal \brief Create and initialize UDPTL for the specified dialog
07084  * \param p SIP private structure to create UDPTL object for
07085  * \pre p is locked
07086  * \pre p->owner is locked
07087  *
07088  * \note In the case of failure, SIP_PAGE2_T38SUPPORT is cleared on p
07089  *
07090  * \return 0 on success, any other value on failure
07091  */
07092 static int initialize_udptl(struct sip_pvt *p)
07093 {
07094    int natflags = ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
07095 
07096    if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
07097       return 1;
07098    }
07099 
07100    /* If we've already initialized T38, don't take any further action */
07101    if (p->udptl) {
07102       return 0;
07103    }
07104 
07105    /* T38 can be supported by this dialog, create it and set the derived properties */
07106    if ((p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, &bindaddr))) {
07107       if (p->owner) {
07108          ast_channel_set_fd(p->owner, 5, ast_udptl_fd(p->udptl));
07109       }
07110 
07111       ast_udptl_setqos(p->udptl, global_tos_audio, global_cos_audio);
07112       p->t38_maxdatagram = p->relatedpeer ? p->relatedpeer->t38_maxdatagram : global_t38_maxdatagram;
07113       set_t38_capabilities(p);
07114 
07115       ast_debug(1, "Setting NAT on UDPTL to %s\n", natflags ? "On" : "Off");
07116       ast_udptl_setnat(p->udptl, natflags);
07117    } else {
07118       ast_log(AST_LOG_WARNING, "UDPTL creation failed - disabling T38 for this dialog\n");
07119       ast_clear_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT);
07120       return 1;
07121    }
07122 
07123    return 0;
07124 }
07125 
07126 /*! \brief Play indication to user
07127  * With SIP a lot of indications is sent as messages, letting the device play
07128    the indication - busy signal, congestion etc
07129    \return -1 to force ast_indicate to send indication in audio, 0 if SIP can handle the indication by sending a message
07130 */
07131 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
07132 {
07133    struct sip_pvt *p = ast->tech_pvt;
07134    int res = 0;
07135 
07136    if (!p) {
07137       ast_debug(1, "Asked to indicate condition on channel %s with no pvt; ignoring\n",
07138             ast->name);
07139       return res;
07140    }
07141 
07142    sip_pvt_lock(p);
07143    switch(condition) {
07144    case AST_CONTROL_RINGING:
07145       if (ast->_state == AST_STATE_RING) {
07146          p->invitestate = INV_EARLY_MEDIA;
07147          if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
07148              (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {            
07149             /* Send 180 ringing if out-of-band seems reasonable */
07150             transmit_provisional_response(p, "180 Ringing", &p->initreq, 0);
07151             ast_set_flag(&p->flags[0], SIP_RINGING);
07152             if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
07153                break;
07154          } else {
07155             /* Well, if it's not reasonable, just send in-band */
07156          }
07157       }
07158       res = -1;
07159       break;
07160    case AST_CONTROL_BUSY:
07161       if (ast->_state != AST_STATE_UP) {
07162          transmit_response_reliable(p, "486 Busy Here", &p->initreq);
07163          p->invitestate = INV_COMPLETED;
07164          sip_alreadygone(p);
07165          ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
07166          break;
07167       }
07168       res = -1;
07169       break;
07170    case AST_CONTROL_CONGESTION:
07171       if (ast->_state != AST_STATE_UP) {
07172          transmit_response_reliable(p, "503 Service Unavailable", &p->initreq);
07173          p->invitestate = INV_COMPLETED;
07174          sip_alreadygone(p);
07175          ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
07176          break;
07177       }
07178       res = -1;
07179       break;
07180    case AST_CONTROL_INCOMPLETE:
07181       if (ast->_state != AST_STATE_UP) {
07182          switch (ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)) {
07183          case SIP_PAGE2_ALLOWOVERLAP_YES:
07184             transmit_response_reliable(p, "484 Address Incomplete", &p->initreq);
07185             p->invitestate = INV_COMPLETED;
07186             sip_alreadygone(p);
07187             ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
07188             break;
07189          case SIP_PAGE2_ALLOWOVERLAP_DTMF:
07190             /* Just wait for inband DTMF digits */
07191             break;
07192          default:
07193             /* it actually means no support for overlap */
07194             transmit_response_reliable(p, "404 Not Found", &p->initreq);
07195             p->invitestate = INV_COMPLETED;
07196             sip_alreadygone(p);
07197             ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
07198             break;
07199          }
07200       }
07201       break;
07202    case AST_CONTROL_PROCEEDING:
07203       if ((ast->_state != AST_STATE_UP) &&
07204           !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
07205           !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
07206          transmit_response(p, "100 Trying", &p->initreq);
07207          p->invitestate = INV_PROCEEDING;
07208          break;
07209       }
07210       res = -1;
07211       break;
07212    case AST_CONTROL_PROGRESS:
07213       if ((ast->_state != AST_STATE_UP) &&
07214           !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
07215           !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
07216          p->invitestate = INV_EARLY_MEDIA;
07217          transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
07218          ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
07219          break;
07220       }
07221       res = -1;
07222       break;
07223    case AST_CONTROL_HOLD:
07224       ast_rtp_instance_update_source(p->rtp);
07225       ast_moh_start(ast, data, p->mohinterpret);
07226       break;
07227    case AST_CONTROL_UNHOLD:
07228       ast_rtp_instance_update_source(p->rtp);
07229       ast_moh_stop(ast);
07230       break;
07231    case AST_CONTROL_VIDUPDATE:   /* Request a video frame update */
07232       if (p->vrtp && !p->novideo) {
07233          transmit_info_with_vidupdate(p);
07234          /* ast_rtcp_send_h261fur(p->vrtp); */
07235       } else
07236          res = -1;
07237       break;
07238    case AST_CONTROL_T38_PARAMETERS:
07239       res = -1;
07240       if (datalen != sizeof(struct ast_control_t38_parameters)) {
07241          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);
07242       } else {
07243          const struct ast_control_t38_parameters *parameters = data;
07244          if (!initialize_udptl(p)) {
07245             res = interpret_t38_parameters(p, parameters);
07246          }
07247       }
07248       break;
07249    case AST_CONTROL_SRCUPDATE:
07250       ast_rtp_instance_update_source(p->rtp);
07251       break;
07252    case AST_CONTROL_SRCCHANGE:
07253       ast_rtp_instance_change_source(p->rtp);
07254       break;
07255    case AST_CONTROL_CONNECTED_LINE:
07256       update_connectedline(p, data, datalen);
07257       break;
07258    case AST_CONTROL_REDIRECTING:
07259       update_redirecting(p, data, datalen);
07260       break;
07261    case AST_CONTROL_AOC:
07262       {
07263          struct ast_aoc_decoded *decoded = ast_aoc_decode((struct ast_aoc_encoded *) data, datalen, ast);
07264          if (!decoded) {
07265             ast_log(LOG_ERROR, "Error decoding indicated AOC data\n");
07266             res = -1;
07267             break;
07268          }
07269          switch (ast_aoc_get_msg_type(decoded)) {
07270          case AST_AOC_REQUEST:
07271             if (ast_aoc_get_termination_request(decoded)) {
07272                /* TODO, once there is a way to get AOC-E on hangup, attempt that here
07273                 * before hanging up the channel.*/
07274 
07275                /* The other side has already initiated the hangup. This frame
07276                 * just says they are waiting to get AOC-E before completely tearing
07277                 * the call down.  Since SIP does not support this at the moment go
07278                 * ahead and terminate the call here to avoid an unnecessary timeout. */
07279                ast_debug(1, "AOC-E termination request received on %s. This is not yet supported on sip. Continue with hangup \n", p->owner->name);
07280                ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
07281             }
07282             break;
07283          case AST_AOC_D:
07284          case AST_AOC_E:
07285             if (ast_test_flag(&p->flags[2], SIP_PAGE3_SNOM_AOC)) {
07286                transmit_info_with_aoc(p, decoded);
07287             }
07288             break;
07289          case AST_AOC_S: /* S not supported yet */
07290          default:
07291             break;
07292          }
07293          ast_aoc_destroy_decoded(decoded);
07294       }
07295       break;
07296    case AST_CONTROL_UPDATE_RTP_PEER: /* Absorb this since it is handled by the bridge */
07297       break;
07298    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. */
07299       res = -1;
07300       break;
07301    case -1:
07302       res = -1;
07303       break;
07304    default:
07305       ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
07306       res = -1;
07307       break;
07308    }
07309    sip_pvt_unlock(p);
07310    return res;
07311 }
07312 
07313 /*!
07314  * \brief Initiate a call in the SIP channel
07315  *
07316  * \note called from sip_request_call (calls from the pbx ) for
07317  * outbound channels and from handle_request_invite for inbound
07318  * channels
07319  *
07320  * \pre i is locked
07321  *
07322  * \return New ast_channel locked.
07323  */
07324 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title, const char *linkedid)
07325 {
07326    struct ast_channel *tmp;
07327    struct ast_variable *v = NULL;
07328    format_t fmt;
07329    format_t what;
07330    format_t video;
07331    format_t text;
07332    format_t needvideo = 0;
07333    int needtext = 0;
07334    char buf[SIPBUFSIZE];
07335    char *exten;
07336 
07337    if (option_debug > 1) {
07338       ast_verbose(VERBOSE_PREFIX_3 "NEW SIP CHANNEL, title: <%s>\n", title?title:"Null");
07339       ast_verbose(VERBOSE_PREFIX_3 "from: %s\n", i->from);
07340       ast_verbose(VERBOSE_PREFIX_3 "username: <%s>\n", i->username);
07341       ast_verbose(VERBOSE_PREFIX_3 "peername: <%s>\n", i->peername);
07342       ast_verbose(VERBOSE_PREFIX_3 "fromdomain: %s\n", i->fromdomain);
07343       ast_verbose(VERBOSE_PREFIX_3 "fromuser: %s\n", i->fromuser);
07344       ast_verbose(VERBOSE_PREFIX_3 "fromname: %s\n", i->fromname);
07345       ast_verbose(VERBOSE_PREFIX_3 "fullcontact: %s\n", i->fullcontact);
07346    }
07347    {
07348       char my_name[128];    /* pick a good name */
07349 
07350       if (!ast_strlen_zero(i->username)) {
07351          if (!ast_strlen_zero(title) && strcmp(i->username, title)) {
07352             /* title not empty and different from username */
07353             snprintf(my_name, sizeof(my_name), "%s@%s", i->username, title);
07354          } else {
07355             /* username not empty, title is empty or equal to username */
07356             snprintf(my_name, sizeof(my_name), "%s", i->username);
07357          }
07358       } else { /* username empty */ 
07359          if (title) {
07360             snprintf(my_name, sizeof(my_name), "%s", title);
07361          } else {
07362             snprintf(my_name, sizeof(my_name), "%s", i->fromdomain);
07363          }
07364       }
07365 
07366       sip_pvt_unlock(i);
07367       /* Don't hold a sip pvt lock while we allocate a channel */
07368       tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, i->accountcode, i->exten, i->context, linkedid, i->amaflags, "SIP/%s-%08x", my_name, (unsigned)ast_atomic_fetchadd_int((int *)&chan_idx, +1));
07369    }
07370    if (!tmp) {
07371       ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
07372       sip_pvt_lock(i);
07373       return NULL;
07374    }
07375    ast_channel_lock(tmp);
07376    sip_pvt_lock(i);
07377    ast_channel_cc_params_init(tmp, i->cc_params);
07378    tmp->caller.id.tag = ast_strdup(i->cid_tag);
07379 
07380    tmp->tech = ( 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;
07381 
07382    /* Select our native format based on codec preference until we receive
07383       something from another device to the contrary. */
07384    if (i->jointcapability) {  /* The joint capabilities of us and peer */
07385       what = i->jointcapability;
07386       video = i->jointcapability & AST_FORMAT_VIDEO_MASK;
07387       text = i->jointcapability & AST_FORMAT_TEXT_MASK;
07388    } else if (i->capability) {      /* Our configured capability for this peer */
07389       what = i->capability;
07390       video = i->capability & AST_FORMAT_VIDEO_MASK;
07391       text = i->capability & AST_FORMAT_TEXT_MASK;
07392    } else {
07393       what = sip_cfg.capability; /* Global codec support */
07394       video = sip_cfg.capability & AST_FORMAT_VIDEO_MASK;
07395       text = sip_cfg.capability & AST_FORMAT_TEXT_MASK;
07396    }
07397 
07398    /* Set the native formats for audio  and merge in video */
07399    tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | video | text;
07400    ast_debug(3, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, tmp->nativeformats));
07401    ast_debug(3, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->jointcapability));
07402    ast_debug(3, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->capability));
07403    ast_debug(3, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, ast_codec_choose(&i->prefs, what, 1)));
07404    if (i->prefcodec)
07405       ast_debug(3, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->prefcodec));
07406 
07407    /* XXX Why are we choosing a codec from the native formats?? */
07408    fmt = ast_best_codec(tmp->nativeformats);
07409 
07410    /* If we have a prefcodec setting, we have an inbound channel that set a
07411       preferred format for this call. Otherwise, we check the jointcapability
07412       We also check for vrtp. If it's not there, we are not allowed do any video anyway.
07413     */
07414    if (i->vrtp) {
07415       if (ast_test_flag(&i->flags[1], SIP_PAGE2_VIDEOSUPPORT))
07416          needvideo = AST_FORMAT_VIDEO_MASK;
07417       else if (i->prefcodec)
07418          needvideo = i->prefcodec & AST_FORMAT_VIDEO_MASK;  /* Outbound call */
07419       else
07420          needvideo = i->jointcapability & AST_FORMAT_VIDEO_MASK;  /* Inbound call */
07421    }
07422 
07423    if (i->trtp) {
07424       if (i->prefcodec)
07425          needtext = i->prefcodec & AST_FORMAT_TEXT_MASK; /* Outbound call */
07426       else
07427          needtext = i->jointcapability & AST_FORMAT_TEXT_MASK; /* Inbound call */
07428    }
07429 
07430    if (needvideo)
07431       ast_debug(3, "This channel can handle video! HOLLYWOOD next!\n");
07432    else
07433       ast_debug(3, "This channel will not be able to handle video.\n");
07434 
07435    enable_dsp_detect(i);
07436 
07437    if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
07438        (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
07439       if (i->rtp) {
07440          ast_rtp_instance_dtmf_mode_set(i->rtp, AST_RTP_DTMF_MODE_INBAND);
07441       }
07442    } else if (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) {
07443       if (i->rtp) {
07444          ast_rtp_instance_dtmf_mode_set(i->rtp, AST_RTP_DTMF_MODE_RFC2833);
07445       }
07446    }
07447 
07448    /* Set file descriptors for audio, video, and realtime text.  Since
07449     * UDPTL is created as needed in the lifetime of a dialog, its file
07450     * descriptor is set in initialize_udptl */
07451    if (i->rtp) {
07452       ast_channel_set_fd(tmp, 0, ast_rtp_instance_fd(i->rtp, 0));
07453       ast_channel_set_fd(tmp, 1, ast_rtp_instance_fd(i->rtp, 1));
07454       ast_rtp_instance_set_write_format(i->rtp, fmt);
07455       ast_rtp_instance_set_read_format(i->rtp, fmt);
07456    }
07457    if (needvideo && i->vrtp) {
07458       ast_channel_set_fd(tmp, 2, ast_rtp_instance_fd(i->vrtp, 0));
07459       ast_channel_set_fd(tmp, 3, ast_rtp_instance_fd(i->vrtp, 1));
07460    }
07461    if (needtext && i->trtp) {
07462       ast_channel_set_fd(tmp, 4, ast_rtp_instance_fd(i->trtp, 0));
07463    }
07464    if (i->udptl) {
07465       ast_channel_set_fd(tmp, 5, ast_udptl_fd(i->udptl));
07466    }
07467 
07468    if (state == AST_STATE_RING)
07469       tmp->rings = 1;
07470    tmp->adsicpe = AST_ADSI_UNAVAILABLE;
07471 
07472    tmp->writeformat = fmt;
07473    tmp->rawwriteformat = fmt;
07474 
07475    tmp->readformat = fmt;
07476    tmp->rawreadformat = fmt;
07477 
07478    tmp->tech_pvt = dialog_ref(i, "sip_new: set chan->tech_pvt to i");
07479 
07480    tmp->callgroup = i->callgroup;
07481    tmp->pickupgroup = i->pickupgroup;
07482    tmp->caller.id.name.presentation = i->callingpres;
07483    tmp->caller.id.number.presentation = i->callingpres;
07484    if (!ast_strlen_zero(i->parkinglot))
07485       ast_string_field_set(tmp, parkinglot, i->parkinglot);
07486    if (!ast_strlen_zero(i->accountcode))
07487       ast_string_field_set(tmp, accountcode, i->accountcode);
07488    if (i->amaflags)
07489       tmp->amaflags = i->amaflags;
07490    if (!ast_strlen_zero(i->language))
07491       ast_string_field_set(tmp, language, i->language);
07492    i->owner = tmp;
07493    ast_module_ref(ast_module_info->self);
07494    ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
07495    /*Since it is valid to have extensions in the dialplan that have unescaped characters in them
07496     * we should decode the uri before storing it in the channel, but leave it encoded in the sip_pvt
07497     * structure so that there aren't issues when forming URI's
07498     */
07499    exten = ast_strdupa(i->exten);
07500    sip_pvt_unlock(i);
07501    ast_channel_unlock(tmp);
07502    if (!ast_exists_extension(NULL, i->context, i->exten, 1, i->cid_num)) {
07503       ast_uri_decode(exten);
07504    }
07505    ast_channel_lock(tmp);
07506    sip_pvt_lock(i);
07507    ast_copy_string(tmp->exten, exten, sizeof(tmp->exten));
07508 
07509    /* Don't use ast_set_callerid() here because it will
07510     * generate an unnecessary NewCallerID event  */
07511    if (!ast_strlen_zero(i->cid_num)) {
07512       tmp->caller.ani.number.valid = 1;
07513       tmp->caller.ani.number.str = ast_strdup(i->cid_num);
07514    }
07515    if (!ast_strlen_zero(i->rdnis)) {
07516       tmp->redirecting.from.number.valid = 1;
07517       tmp->redirecting.from.number.str = ast_strdup(i->rdnis);
07518    }
07519 
07520    if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s")) {
07521       tmp->dialed.number.str = ast_strdup(i->exten);
07522    }
07523 
07524    tmp->priority = 1;
07525    if (!ast_strlen_zero(i->uri))
07526       pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
07527    if (!ast_strlen_zero(i->domain))
07528       pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
07529    if (!ast_strlen_zero(i->callid))
07530       pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
07531    if (i->rtp)
07532       ast_jb_configure(tmp, &global_jbconf);
07533 
07534    if (!i->relatedpeer) {
07535       tmp->flags |= AST_FLAG_DISABLE_DEVSTATE_CACHE;
07536    }
07537    /* Set channel variables for this call from configuration */
07538    for (v = i->chanvars ; v ; v = v->next) {
07539       char valuebuf[1024];
07540       pbx_builtin_setvar_helper(tmp, v->name, ast_get_encoded_str(v->value, valuebuf, sizeof(valuebuf)));
07541    }
07542 
07543    if (i->do_history)
07544       append_history(i, "NewChan", "Channel %s - from %s", tmp->name, i->callid);
07545 
07546    /* Inform manager user about new channel and their SIP call ID */
07547    if (sip_cfg.callevents)
07548       manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
07549          "Channel: %s\r\nUniqueid: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\n",
07550          tmp->name, tmp->uniqueid, "SIP", i->callid, i->fullcontact);
07551 
07552    return tmp;
07553 }
07554 
07555 /*! \brief Reads one line of SIP message body */
07556 static char *get_body_by_line(const char *line, const char *name, int nameLen, char delimiter)
07557 {
07558    if (!strncasecmp(line, name, nameLen) && line[nameLen] == delimiter)
07559       return ast_skip_blanks(line + nameLen + 1);
07560 
07561    return "";
07562 }
07563 
07564 /*! \brief Lookup 'name' in the SDP starting
07565  * at the 'start' line. Returns the matching line, and 'start'
07566  * is updated with the next line number.
07567  */
07568 static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
07569 {
07570    int len = strlen(name);
07571 
07572    while (*start < (req->sdp_start + req->sdp_count)) {
07573       const char *r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[(*start)++]), name, len, '=');
07574       if (r[0] != '\0')
07575          return r;
07576    }
07577 
07578    /* if the line was not found, ensure that *start points past the SDP */
07579    (*start)++;
07580 
07581    return "";
07582 }
07583 
07584 /*! \brief Fetches the next valid SDP line between the 'start' line
07585  * (inclusive) and the 'stop' line (exclusive). Returns the type
07586  * ('a', 'c', ...) and matching line in reference 'start' is updated
07587  * with the next line number.
07588  */
07589 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value)
07590 {
07591    char type = '\0';
07592    const char *line = NULL;
07593 
07594    if (stop > (req->sdp_start + req->sdp_count)) {
07595       stop = req->sdp_start + req->sdp_count;
07596    }
07597 
07598    while (*start < stop) {
07599       line = REQ_OFFSET_TO_STR(req, line[(*start)++]);
07600       if (line[1] == '=') {
07601          type = line[0];
07602          *value = ast_skip_blanks(line + 2);
07603          break;
07604       }
07605    }
07606 
07607    return type;
07608 }
07609 
07610 /*! \brief Get a specific line from the message body */
07611 static char *get_body(struct sip_request *req, char *name, char delimiter)
07612 {
07613    int x;
07614    int len = strlen(name);
07615    char *r;
07616 
07617    for (x = 0; x < req->lines; x++) {
07618       r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[x]), name, len, delimiter);
07619       if (r[0] != '\0')
07620          return r;
07621    }
07622 
07623    return "";
07624 }
07625 
07626 /*! \brief Find compressed SIP alias */
07627 static const char *find_alias(const char *name, const char *_default)
07628 {
07629    /*! \brief Structure for conversion between compressed SIP and "normal" SIP */
07630    static const struct cfalias {
07631       char * const fullname;
07632       char * const shortname;
07633    } aliases[] = {
07634       { "Content-Type",  "c" },
07635       { "Content-Encoding",    "e" },
07636       { "From",       "f" },
07637       { "Call-ID",       "i" },
07638       { "Contact",       "m" },
07639       { "Content-Length",   "l" },
07640       { "Subject",       "s" },
07641       { "To",         "t" },
07642       { "Supported",     "k" },
07643       { "Refer-To",      "r" },
07644       { "Referred-By",   "b" },
07645       { "Allow-Events",  "u" },
07646       { "Event",      "o" },
07647       { "Via",     "v" },
07648       { "Accept-Contact",      "a" },
07649       { "Reject-Contact",      "j" },
07650       { "Request-Disposition", "d" },
07651       { "Session-Expires",     "x" },
07652       { "Identity",            "y" },
07653       { "Identity-Info",       "n" },
07654    };
07655    int x;
07656 
07657    for (x = 0; x < ARRAY_LEN(aliases); x++) {
07658       if (!strcasecmp(aliases[x].fullname, name))
07659          return aliases[x].shortname;
07660    }
07661 
07662    return _default;
07663 }
07664 
07665 static const char *__get_header(const struct sip_request *req, const char *name, int *start)
07666 {
07667    /*
07668     * Technically you can place arbitrary whitespace both before and after the ':' in
07669     * a header, although RFC3261 clearly says you shouldn't before, and place just
07670     * one afterwards.  If you shouldn't do it, what absolute idiot decided it was
07671     * a good idea to say you can do it, and if you can do it, why in the hell would.
07672     * you say you shouldn't.
07673     * Anyways, pedanticsipchecking controls whether we allow spaces before ':',
07674     * and we always allow spaces after that for compatibility.
07675     */
07676    const char *sname = find_alias(name, NULL);
07677    int x, len = strlen(name), slen = (sname ? 1 : 0);
07678    for (x = *start; x < req->headers; x++) {
07679       const char *header = REQ_OFFSET_TO_STR(req, header[x]);
07680       int smatch = 0, match = !strncasecmp(header, name, len);
07681       if (slen) {
07682          smatch = !strncasecmp(header, sname, slen);
07683       }
07684       if (match || smatch) {
07685          /* skip name */
07686          const char *r = header + (match ? len : slen );
07687          if (sip_cfg.pedanticsipchecking) {
07688             r = ast_skip_blanks(r);
07689          }
07690 
07691          if (*r == ':') {
07692             *start = x+1;
07693             return ast_skip_blanks(r+1);
07694          }
07695       }
07696    }
07697 
07698    /* Don't return NULL, so get_header is always a valid pointer */
07699    return "";
07700 }
07701 
07702 /*! \brief Get header from SIP request
07703    \return Always return something, so don't check for NULL because it won't happen :-)
07704 */
07705 static const char *get_header(const struct sip_request *req, const char *name)
07706 {
07707    int start = 0;
07708    return __get_header(req, name, &start);
07709 }
07710 
07711 /*! \brief Read RTP from network */
07712 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
07713 {
07714    /* Retrieve audio/etc from channel.  Assumes p->lock is already held. */
07715    struct ast_frame *f;
07716    
07717    if (!p->rtp) {
07718       /* We have no RTP allocated for this channel */
07719       return &ast_null_frame;
07720    }
07721 
07722    switch(ast->fdno) {
07723    case 0:
07724       f = ast_rtp_instance_read(p->rtp, 0);  /* RTP Audio */
07725       break;
07726    case 1:
07727       f = ast_rtp_instance_read(p->rtp, 1);  /* RTCP Control Channel */
07728       break;
07729    case 2:
07730       f = ast_rtp_instance_read(p->vrtp, 0); /* RTP Video */
07731       break;
07732    case 3:
07733       f = ast_rtp_instance_read(p->vrtp, 1); /* RTCP Control Channel for video */
07734       break;
07735    case 4:
07736       f = ast_rtp_instance_read(p->trtp, 0); /* RTP Text */
07737       if (sipdebug_text) {
07738          int i;
07739          unsigned char* arr = f->data.ptr;
07740          for (i=0; i < f->datalen; i++)
07741             ast_verbose("%c", (arr[i] > ' ' && arr[i] < '}') ? arr[i] : '.');
07742          ast_verbose(" -> ");
07743          for (i=0; i < f->datalen; i++)
07744             ast_verbose("%02X ", (unsigned)arr[i]);
07745          ast_verbose("\n");
07746       }
07747       break;
07748    case 5:
07749       f = ast_udptl_read(p->udptl); /* UDPTL for T.38 */
07750       break;
07751    default:
07752       f = &ast_null_frame;
07753    }
07754    /* Don't forward RFC2833 if we're not supposed to */
07755    if (f && (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) &&
07756        (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833)) {
07757       ast_debug(1, "Ignoring DTMF (%c) RTP frame because dtmfmode is not RFC2833\n", f->subclass.integer);
07758       ast_frfree(f);
07759       return &ast_null_frame;
07760    }
07761 
07762    /* We already hold the channel lock */
07763    if (!p->owner || (f && f->frametype != AST_FRAME_VOICE))
07764       return f;
07765 
07766    if (f && f->subclass.codec != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
07767       if (!(f->subclass.codec & p->jointcapability)) {
07768          ast_debug(1, "Bogus frame of format '%s' received from '%s'!\n",
07769             ast_getformatname(f->subclass.codec), p->owner->name);
07770          ast_frfree(f);
07771          return &ast_null_frame;
07772       }
07773       ast_debug(1, "Oooh, format changed to %s\n",
07774          ast_getformatname(f->subclass.codec));
07775       p->owner->nativeformats = (p->owner->nativeformats & (AST_FORMAT_VIDEO_MASK | AST_FORMAT_TEXT_MASK)) | f->subclass.codec;
07776       ast_set_read_format(p->owner, p->owner->readformat);
07777       ast_set_write_format(p->owner, p->owner->writeformat);
07778    }
07779 
07780    if (f && p->dsp) {
07781       f = ast_dsp_process(p->owner, p->dsp, f);
07782       if (f && f->frametype == AST_FRAME_DTMF) {
07783          if (f->subclass.integer == 'f') {
07784             ast_debug(1, "Fax CNG detected on %s\n", ast->name);
07785             *faxdetect = 1;
07786             /* If we only needed this DSP for fax detection purposes we can just drop it now */
07787             if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
07788                ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
07789             } else {
07790                ast_dsp_free(p->dsp);
07791                p->dsp = NULL;
07792             }
07793          } else {
07794             ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass.integer);
07795          }
07796       }
07797    }
07798 
07799    return f;
07800 }
07801 
07802 /*! \brief Read SIP RTP from channel */
07803 static struct ast_frame *sip_read(struct ast_channel *ast)
07804 {
07805    struct ast_frame *fr;
07806    struct sip_pvt *p = ast->tech_pvt;
07807    int faxdetected = FALSE;
07808 
07809    sip_pvt_lock(p);
07810    fr = sip_rtp_read(ast, p, &faxdetected);
07811    p->lastrtprx = time(NULL);
07812 
07813    /* If we detect a CNG tone and fax detection is enabled then send us off to the fax extension */
07814    if (faxdetected && ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
07815       if (strcmp(ast->exten, "fax")) {
07816          const char *target_context = S_OR(ast->macrocontext, ast->context);
07817          /* We need to unlock 'ast' here because
07818           * ast_exists_extension has the potential to start and
07819           * stop an autoservice on the channel. Such action is
07820           * prone to deadlock if the channel is locked.
07821           */
07822          sip_pvt_unlock(p);
07823          ast_channel_unlock(ast);
07824          if (ast_exists_extension(ast, target_context, "fax", 1,
07825             S_COR(ast->caller.id.number.valid, ast->caller.id.number.str, NULL))) {
07826             ast_channel_lock(ast);
07827             sip_pvt_lock(p);
07828             ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to CNG detection\n", ast->name);
07829             pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast->exten);
07830             if (ast_async_goto(ast, target_context, "fax", 1)) {
07831                ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast->name, target_context);
07832             }
07833             ast_frfree(fr);
07834             fr = &ast_null_frame;
07835          } else {
07836             ast_channel_lock(ast);
07837             sip_pvt_lock(p);
07838             ast_log(LOG_NOTICE, "FAX CNG detected but no fax extension\n");
07839          }
07840       }
07841    }
07842 
07843    /* Only allow audio through if they sent progress with SDP, or if the channel is actually answered */
07844    if (fr && fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast->_state != AST_STATE_UP) {
07845       ast_frfree(fr);
07846       fr = &ast_null_frame;
07847    }
07848 
07849    sip_pvt_unlock(p);
07850 
07851    return fr;
07852 }
07853 
07854 
07855 /*! \brief Generate 32 byte random string for callid's etc */
07856 static char *generate_random_string(char *buf, size_t size)
07857 {
07858    long val[4];
07859    int x;
07860 
07861    for (x=0; x<4; x++)
07862       val[x] = ast_random();
07863    snprintf(buf, size, "%08lx%08lx%08lx%08lx", (unsigned long)val[0], (unsigned long)val[1], (unsigned long)val[2], (unsigned long)val[3]);
07864 
07865    return buf;
07866 }
07867 
07868 static char *generate_uri(struct sip_pvt *pvt, char *buf, size_t size)
07869 {
07870    struct ast_str *uri = ast_str_alloca(size);
07871    ast_str_set(&uri, 0, "%s", pvt->socket.type == SIP_TRANSPORT_TLS ? "sips:" : "sip:");
07872    /* Here would be a great place to generate a UUID, but for now we'll
07873     * use the handy random string generation function we already have
07874     */
07875    ast_str_append(&uri, 0, "%s", generate_random_string(buf, size));
07876    ast_str_append(&uri, 0, "@%s", ast_sockaddr_stringify_remote(&pvt->ourip));
07877    ast_copy_string(buf, ast_str_buffer(uri), size);
07878    return buf;
07879 }
07880 
07881 /*!
07882  * \brief Build SIP Call-ID value for a non-REGISTER transaction
07883  *
07884  * \note The passed in pvt must not be in a dialogs container
07885  * since this function changes the hash key used by the
07886  * container.
07887  */
07888 static void build_callid_pvt(struct sip_pvt *pvt)
07889 {
07890    char buf[33];
07891    const char *host = S_OR(pvt->fromdomain, ast_sockaddr_stringify_remote(&pvt->ourip));
07892 
07893    ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
07894 }
07895 
07896 /*! \brief Unlink the given object from the container and return TRUE if it was in the container. */
07897 #define CONTAINER_UNLINK(container, obj, tag)                        \
07898    ({                                                    \
07899       int found = 0;                                        \
07900       typeof((obj)) __removed_obj;                             \
07901       __removed_obj = ao2_t_callback((container),                    \
07902          OBJ_UNLINK | OBJ_POINTER, ao2_match_by_addr, (obj), (tag));    \
07903       if (__removed_obj) {                                  \
07904          ao2_ref(__removed_obj, -1);                              \
07905          found = 1;                                         \
07906       }                                                  \
07907       found;                                                \
07908    })
07909 
07910 /*!
07911  * \internal
07912  * \brief Safely change the callid of the given SIP dialog.
07913  *
07914  * \param pvt SIP private structure to change callid
07915  * \param callid Specified new callid to use.  NULL if generate new callid.
07916  *
07917  * \return Nothing
07918  */
07919 static void change_callid_pvt(struct sip_pvt *pvt, const char *callid)
07920 {
07921    int in_dialog_container;
07922    char *oldid = ast_strdupa(pvt->callid);
07923 
07924    ao2_lock(dialogs);
07925    in_dialog_container = CONTAINER_UNLINK(dialogs, pvt,
07926       "About to change the callid -- remove the old name");
07927    if (callid) {
07928       ast_string_field_set(pvt, callid, callid);
07929    } else {
07930       build_callid_pvt(pvt);
07931    }
07932    if (in_dialog_container) {
07933       ao2_t_link(dialogs, pvt, "New dialog callid -- inserted back into table");
07934    }
07935    ao2_unlock(dialogs);
07936 
07937    if (strcmp(oldid, pvt->callid)) {
07938       ast_debug(1, "SIP call-id changed from '%s' to '%s'\n", oldid, pvt->callid);
07939    }
07940 }
07941 
07942 /*! \brief Build SIP Call-ID value for a REGISTER transaction */
07943 static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain)
07944 {
07945    char buf[33];
07946 
07947    const char *host = S_OR(fromdomain, ast_sockaddr_stringify_host_remote(ourip));
07948 
07949    ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
07950 }
07951 
07952 /*! \brief Build SIP From tag value for REGISTER */
07953 static void build_localtag_registry(struct sip_registry *reg)
07954 {
07955    ast_string_field_build(reg, localtag, "as%08lx", (unsigned long)ast_random());
07956 }
07957 
07958 /*! \brief Make our SIP dialog tag */
07959 static void make_our_tag(struct sip_pvt *pvt)
07960 {
07961    ast_string_field_build(pvt, tag, "as%08lx", (unsigned long)ast_random());
07962 }
07963 
07964 /*! \brief Allocate Session-Timers struct w/in dialog */
07965 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p)
07966 {
07967    struct sip_st_dlg *stp;
07968 
07969    if (p->stimer) {
07970       ast_log(LOG_ERROR, "Session-Timer struct already allocated\n");
07971       return p->stimer;
07972    }
07973 
07974    if (!(stp = ast_calloc(1, sizeof(struct sip_st_dlg))))
07975       return NULL;
07976 
07977    p->stimer = stp;
07978 
07979    stp->st_schedid = -1;           /* Session-Timers ast_sched scheduler id */
07980 
07981    return p->stimer;
07982 }
07983 
07984 /*! \brief Allocate sip_pvt structure, set defaults and link in the container.
07985  * Returns a reference to the object so whoever uses it later must
07986  * remember to release the reference.
07987  */
07988 struct sip_pvt *sip_alloc(ast_string_field callid, struct ast_sockaddr *addr,
07989              int useglobal_nat, const int intended_method, struct sip_request *req)
07990 {
07991    struct sip_pvt *p;
07992 
07993    if (!(p = ao2_t_alloc(sizeof(*p), sip_destroy_fn, "allocate a dialog(pvt) struct")))
07994       return NULL;
07995 
07996    if (ast_string_field_init(p, 512)) {
07997       ao2_t_ref(p, -1, "failed to string_field_init, drop p");
07998       return NULL;
07999    }
08000 
08001    if (!(p->cc_params = ast_cc_config_params_init())) {
08002       ao2_t_ref(p, -1, "Yuck, couldn't allocate cc_params struct. Get rid o' p");
08003       return NULL;
08004    }
08005 
08006    /* If this dialog is created as the result of an incoming Request. Lets store
08007     * some information about that request */
08008    if (req) {
08009       struct sip_via *via;
08010       const char *cseq = get_header(req, "Cseq");
08011       uint32_t seqno;
08012 
08013       /* get branch parameter from initial Request that started this dialog */
08014       via = parse_via(get_header(req, "Via"));
08015       if (via) {
08016          /* only store the branch if it begins with the magic prefix "z9hG4bK", otherwise
08017           * it is not useful to us to have it */
08018          if (!ast_strlen_zero(via->branch) && !strncasecmp(via->branch, "z9hG4bK", 7)) {
08019             ast_string_field_set(p, initviabranch, via->branch);
08020             ast_string_field_set(p, initviasentby, via->sent_by);
08021          }
08022          free_via(via);
08023       }
08024 
08025       /* Store initial incoming cseq. An error in sscanf here is ignored.  There is no approperiate
08026        * except not storing the number.  CSeq validation must take place before dialog creation in find_call */
08027       if (!ast_strlen_zero(cseq) && (sscanf(cseq, "%30u", &seqno) == 1)) {
08028          p->init_icseq = seqno;
08029       }
08030       /* Later in ast_sip_ouraddrfor we need this to choose the right ip and port for the specific transport */
08031       set_socket_transport(&p->socket, req->socket.type);
08032    } else {
08033       set_socket_transport(&p->socket, SIP_TRANSPORT_UDP);
08034    }
08035 
08036    p->socket.fd = -1;
08037    p->method = intended_method;
08038    p->initid = -1;
08039    p->waitid = -1;
08040    p->reinviteid = -1;
08041    p->autokillid = -1;
08042    p->request_queue_sched_id = -1;
08043    p->provisional_keepalive_sched_id = -1;
08044    p->t38id = -1;
08045    p->subscribed = NONE;
08046    p->stateid = -1;
08047    p->sessionversion_remote = -1;
08048    p->session_modify = TRUE;
08049    p->stimer = NULL;
08050    p->prefs = default_prefs;     /* Set default codecs for this call */
08051    p->maxforwards = sip_cfg.default_max_forwards;
08052 
08053    if (intended_method != SIP_OPTIONS) {  /* Peerpoke has it's own system */
08054       p->timer_t1 = global_t1;   /* Default SIP retransmission timer T1 (RFC 3261) */
08055       p->timer_b = global_timer_b;  /* Default SIP transaction timer B (RFC 3261) */
08056    }
08057 
08058    if (!addr) {
08059       p->ourip = internip;
08060    } else {
08061       ast_sockaddr_copy(&p->sa, addr);
08062       ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
08063    }
08064 
08065    /* Copy global flags to this PVT at setup. */
08066    ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
08067    ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
08068    ast_copy_flags(&p->flags[2], &global_flags[2], SIP_PAGE3_FLAGS_TO_COPY);
08069 
08070    p->do_history = recordhistory;
08071 
08072    p->branch = ast_random();  
08073    make_our_tag(p);
08074    p->ocseq = INITIAL_CSEQ;
08075    p->allowed_methods = UINT_MAX;
08076 
08077    if (sip_methods[intended_method].need_rtp) {
08078       p->maxcallbitrate = default_maxcallbitrate;
08079       p->autoframing = global_autoframing;
08080    }
08081 
08082    if (useglobal_nat && addr) {
08083       /* Setup NAT structure according to global settings if we have an address */
08084       ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT_FORCE_RPORT);
08085       ast_sockaddr_copy(&p->recv, addr);
08086 
08087       do_setnat(p);
08088    }
08089 
08090    if (p->method != SIP_REGISTER) {
08091       ast_string_field_set(p, fromdomain, default_fromdomain);
08092       p->fromdomainport = default_fromdomainport;
08093    }
08094    build_via(p);
08095    if (!callid)
08096       build_callid_pvt(p);
08097    else
08098       ast_string_field_set(p, callid, callid);
08099    /* Assign default music on hold class */
08100    ast_string_field_set(p, mohinterpret, default_mohinterpret);
08101    ast_string_field_set(p, mohsuggest, default_mohsuggest);
08102    p->capability = sip_cfg.capability;
08103    p->allowtransfer = sip_cfg.allowtransfer;
08104    if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
08105        (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
08106       p->noncodeccapability |= AST_RTP_DTMF;
08107    }
08108    ast_string_field_set(p, context, sip_cfg.default_context);
08109    ast_string_field_set(p, parkinglot, default_parkinglot);
08110    ast_string_field_set(p, engine, default_engine);
08111 
08112    AST_LIST_HEAD_INIT_NOLOCK(&p->request_queue);
08113 
08114    /* Add to active dialog list */
08115 
08116    ao2_t_link(dialogs, p, "link pvt into dialogs table");
08117    
08118    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");
08119    return p;
08120 }
08121 
08122 /*!
08123  * \brief Check if an ip is an multicast IP.
08124  * \parm addr the address to check
08125  *
08126  * This function checks if an address is in the 224.0.0.0/4 network block.
08127  * \return non-zero if this is a multicast address
08128  */
08129 static int addr_is_multicast(const struct ast_sockaddr *addr)
08130 {
08131    return ((ast_sockaddr_ipv4(addr) & 0xf0000000) == 0xe0000000);
08132 }
08133 
08134 /*!
08135  * \brief Process the Via header according to RFC 3261 section 18.2.2.
08136  * \param p a sip_pvt structure that will be modified according to the received
08137  * header
08138  * \param req a sip request with a Via header to process
08139  *
08140  * This function will update the destination of the response according to the
08141  * Via header in the request and RFC 3261 section 18.2.2. We do not have a
08142  * transport layer so we ignore certain values like the 'received' param (we
08143  * set the destination address to the addres the request came from in the
08144  * respprep() function).
08145  *
08146  * \retval -1 error
08147  * \retval 0 success
08148  */
08149 static int process_via(struct sip_pvt *p, const struct sip_request *req)
08150 {
08151    struct sip_via *via = parse_via(get_header(req, "Via"));
08152 
08153    if (!via) {
08154       ast_log(LOG_ERROR, "error processing via header\n");
08155       return -1;
08156    }
08157 
08158    if (via->maddr) {
08159       if (ast_sockaddr_resolve_first_transport(&p->sa, via->maddr, PARSE_PORT_FORBID, p->socket.type)) {
08160          ast_log(LOG_WARNING, "Can't find address for maddr '%s'\n", via->maddr);
08161          ast_log(LOG_ERROR, "error processing via header\n");
08162          free_via(via);
08163          return -1;
08164       }
08165 
08166       if (addr_is_multicast(&p->sa)) {
08167          setsockopt(sipsock, IPPROTO_IP, IP_MULTICAST_TTL, &via->ttl, sizeof(via->ttl));
08168       }
08169    }
08170 
08171    ast_sockaddr_set_port(&p->sa, via->port ? via->port : STANDARD_SIP_PORT);
08172 
08173    free_via(via);
08174    return 0;
08175 }
08176 
08177 /* \brief arguments used for Request/Response to matching */
08178 struct match_req_args {
08179    int method;
08180    const char *callid;
08181    const char *totag;
08182    const char *fromtag;
08183    uint32_t seqno;
08184 
08185    /* Set if the method is a Request */
08186    const char *ruri;
08187    const char *viabranch;
08188    const char *viasentby;
08189 
08190    /* Set this if the Authentication header is present in the Request. */
08191    int authentication_present;
08192 };
08193 
08194 enum match_req_res {
08195    SIP_REQ_MATCH,
08196    SIP_REQ_NOT_MATCH,
08197    SIP_REQ_LOOP_DETECTED,
08198 };
08199 
08200 /*
08201  * \brief Match a incoming Request/Response to a dialog
08202  *
08203  * \retval enum match_req_res indicating if the dialog matches the arg
08204  */
08205 static enum match_req_res match_req_to_dialog(struct sip_pvt *sip_pvt_ptr, struct match_req_args *arg)
08206 {
08207    const char *init_ruri = NULL;
08208    if (sip_pvt_ptr->initreq.headers) {
08209       init_ruri = REQ_OFFSET_TO_STR(&sip_pvt_ptr->initreq, rlPart2);
08210    }
08211 
08212    /*
08213     * Match Tags and call-id to Dialog
08214     */
08215    if (!ast_strlen_zero(arg->callid) && strcmp(sip_pvt_ptr->callid, arg->callid)) {
08216       /* call-id does not match. */
08217       return SIP_REQ_NOT_MATCH;
08218    }
08219    if (arg->method == SIP_RESPONSE) {
08220       /* Verify totag if we have one stored for this dialog, but never be strict about this for
08221        * a response until the dialog is established */
08222       if (!ast_strlen_zero(sip_pvt_ptr->theirtag) && ast_test_flag(&sip_pvt_ptr->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
08223          if (ast_strlen_zero(arg->totag)) {
08224             /* missing totag when they already gave us one earlier */
08225             return SIP_REQ_NOT_MATCH;
08226          }
08227          if (strcmp(arg->totag, sip_pvt_ptr->theirtag)) {
08228             /* The totag of the response does not match the one we have stored */
08229             return SIP_REQ_NOT_MATCH;
08230          }
08231       }
08232       /* Verify fromtag of response matches the tag we gave them. */
08233       if (strcmp(arg->fromtag, sip_pvt_ptr->tag)) {
08234          /* fromtag from response does not match our tag */
08235          return SIP_REQ_NOT_MATCH;
08236       }
08237    } else {
08238       /* Verify the fromtag of Request matches the tag they provided earlier.
08239        * If this is a Request with authentication credentials, forget their old
08240        * tag as it is not valid after the 401 or 407 response. */
08241       if (!arg->authentication_present && strcmp(arg->fromtag, sip_pvt_ptr->theirtag)) {
08242          /* their tag does not match the one was have stored for them */
08243          return SIP_REQ_NOT_MATCH;
08244       }
08245       /* Verify if totag is present in Request, that it matches what we gave them as our tag earlier */
08246       if (!ast_strlen_zero(arg->totag) && (strcmp(arg->totag, sip_pvt_ptr->tag))) {
08247          /* totag from Request does not match our tag */
08248          return SIP_REQ_NOT_MATCH;
08249       }
08250    }
08251 
08252    /*
08253     * Compare incoming request against initial transaction.
08254     * 
08255     * This is a best effort attempt at distinguishing forked requests from
08256     * our initial transaction.  If all the elements are NOT in place to evaluate
08257     * this, this block is ignored and the dialog match is made regardless.
08258     * Once the totag is established after the dialog is confirmed, this is not necessary.
08259     *
08260     * CRITERIA required for initial transaction matching.
08261     * 
08262     * 1. Is a Request
08263     * 2. Callid and theirtag match (this is done in the dialog matching block)
08264     * 3. totag is NOT present
08265     * 4. CSeq matchs our initial transaction's cseq number
08266     * 5. pvt has init via branch parameter stored
08267     */
08268    if ((arg->method != SIP_RESPONSE) &&                 /* must be a Request */
08269       ast_strlen_zero(arg->totag) &&                   /* must not have a totag */
08270       (sip_pvt_ptr->init_icseq == arg->seqno) &&       /* the cseq must be the same as this dialogs initial cseq */
08271       !ast_strlen_zero(sip_pvt_ptr->initviabranch) &&  /* The dialog must have started with a RFC3261 compliant branch tag */
08272       init_ruri) {                                     /* the dialog must have an initial request uri associated with it */
08273       /* This Request matches all the criteria required for Loop/Merge detection.
08274        * Now we must go down the path of comparing VIA's and RURIs. */
08275       if (ast_strlen_zero(arg->viabranch) ||
08276          strcmp(arg->viabranch, sip_pvt_ptr->initviabranch) ||
08277          ast_strlen_zero(arg->viasentby) ||
08278          strcmp(arg->viasentby, sip_pvt_ptr->initviasentby)) {
08279          /* At this point, this request does not match this Dialog.*/
08280 
08281          /* if methods are different this is just a mismatch */
08282          if ((sip_pvt_ptr->method != arg->method)) {
08283             return SIP_REQ_NOT_MATCH;
08284          }
08285 
08286          /* If RUIs are different, this is a forked request to a separate URI.
08287           * Returning a mismatch allows this Request to be processed separately. */
08288          if (sip_uri_cmp(init_ruri, arg->ruri)) {
08289             /* not a match, request uris are different */
08290             return SIP_REQ_NOT_MATCH;
08291          }
08292 
08293          /* Loop/Merge Detected
08294           *
08295           * ---Current Matches to Initial Request---
08296           * request uri
08297           * Call-id
08298           * their-tag
08299           * no totag present
08300           * method
08301           * cseq
08302           *
08303           * --- Does not Match Initial Request ---
08304           * Top Via
08305           *
08306           * Without the same Via, this can not match our initial transaction for this dialog,
08307           * but given that this Request matches everything else associated with that initial
08308           * Request this is most certainly a Forked request in which we have already received
08309           * part of the fork.
08310           */
08311          return SIP_REQ_LOOP_DETECTED;
08312       }
08313    } /* end of Request Via check */
08314 
08315    /* Match Authentication Request.
08316     *
08317     * A Request with an Authentication header must come back with the
08318     * same Request URI.  Otherwise it is not a match.
08319     */
08320    if ((arg->method != SIP_RESPONSE) &&      /* Must be a Request type to even begin checking this */
08321       ast_strlen_zero(arg->totag) &&        /* no totag is present to match */
08322       arg->authentication_present &&        /* Authentication header is present in Request */
08323       sip_uri_cmp(init_ruri, arg->ruri)) {  /* Compare the Request URI of both the last Request and this new one */
08324 
08325       /* Authentication was provided, but the Request URI did not match the last one on this dialog. */
08326       return SIP_REQ_NOT_MATCH;
08327    }
08328 
08329    return SIP_REQ_MATCH;
08330 }
08331 
08332 /*! \internal
08333  *
08334  * \brief Locks both pvt and pvt owner if owner is present.
08335  *
08336  * \note This function gives a ref to pvt->owner if it is present and locked.
08337  *       This reference must be decremented after pvt->owner is unlocked.
08338  *
08339  * \note This function will never give you up,
08340  * \note This function will never let you down.
08341  * \note This function will run around and desert you.
08342  *
08343  * \pre pvt is not locked
08344  * \post pvt is locked
08345  * \post pvt->owner is locked and its reference count is increased (if pvt->owner is not NULL)
08346  *
08347  * \returns a pointer to the locked and reffed pvt->owner channel if it exists.
08348  */
08349 static struct ast_channel *sip_pvt_lock_full(struct sip_pvt *pvt)
08350 {
08351    struct ast_channel *chan;
08352 
08353    /* Locking is simple when it is done right.  If you see a deadlock resulting
08354     * in this function, it is not this function's fault, Your problem exists elsewhere.
08355     * This function is perfect... seriously. */
08356    for (;;) {
08357       /* First, get the channel and grab a reference to it */
08358       sip_pvt_lock(pvt);
08359       chan = pvt->owner;
08360       if (chan) {
08361          /* The channel can not go away while we hold the pvt lock.
08362           * Give the channel a ref so it will not go away after we let
08363           * the pvt lock go. */
08364          ast_channel_ref(chan);
08365       } else {
08366          /* no channel, return pvt locked */
08367          return NULL;
08368       }
08369 
08370       /* We had to hold the pvt lock while getting a ref to the owner channel
08371        * but now we have to let this lock go in order to preserve proper
08372        * locking order when grabbing the channel lock */
08373       sip_pvt_unlock(pvt);
08374 
08375       /* Look, no deadlock avoidance, hooray! */
08376       ast_channel_lock(chan);
08377       sip_pvt_lock(pvt);
08378 
08379       if (pvt->owner == chan) {
08380          /* done */
08381          break;
08382       }
08383 
08384       /* If the owner changed while everything was unlocked, no problem,
08385        * just start over and everthing will work.  This is rare, do not be
08386        * confused by this loop and think this it is an expensive operation.
08387        * The majority of the calls to this function will never involve multiple
08388        * executions of this loop. */
08389       ast_channel_unlock(chan);
08390       ast_channel_unref(chan);
08391       sip_pvt_unlock(pvt);
08392    }
08393 
08394    /* If owner exists, it is locked and reffed */
08395    return pvt->owner;
08396 }
08397 
08398 /*! \brief find or create a dialog structure for an incoming SIP message.
08399  * Connect incoming SIP message to current dialog or create new dialog structure
08400  * Returns a reference to the sip_pvt object, remember to give it back once done.
08401  *     Called by handle_request_do
08402  */
08403 static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method)
08404 {
08405    char totag[128];
08406    char fromtag[128];
08407    const char *callid = get_header(req, "Call-ID");
08408    const char *from = get_header(req, "From");
08409    const char *to = get_header(req, "To");
08410    const char *cseq = get_header(req, "Cseq");
08411    struct sip_pvt *sip_pvt_ptr;
08412    uint32_t seqno;
08413    /* Call-ID, to, from and Cseq are required by RFC 3261. (Max-forwards and via too - ignored now) */
08414    /* get_header always returns non-NULL so we must use ast_strlen_zero() */
08415    if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
08416          ast_strlen_zero(from) || ast_strlen_zero(cseq) ||
08417          (sscanf(cseq, "%30u", &seqno) != 1)) {
08418 
08419       /* RFC 3261 section 24.4.1.   Send a 400 Bad Request if the request is malformed. */
08420       if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
08421          transmit_response_using_temp(callid, addr, 1, intended_method,
08422                        req, "400 Bad Request");
08423       }
08424       return NULL;   /* Invalid packet */
08425    }
08426 
08427    if (sip_cfg.pedanticsipchecking) {
08428       /* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
08429          we need more to identify a branch - so we have to check branch, from
08430          and to tags to identify a call leg.
08431          For Asterisk to behave correctly, you need to turn on pedanticsipchecking
08432          in sip.conf
08433          */
08434       if (gettag(req, "To", totag, sizeof(totag)))
08435          req->has_to_tag = 1; /* Used in handle_request/response */
08436       gettag(req, "From", fromtag, sizeof(fromtag));
08437 
08438       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);
08439 
08440       /* All messages must always have From: tag */
08441       if (ast_strlen_zero(fromtag)) {
08442          ast_debug(5, "%s request has no from tag, dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
08443          return NULL;
08444       }
08445       /* reject requests that must always have a To: tag */
08446       if (ast_strlen_zero(totag) && (req->method == SIP_ACK || req->method == SIP_BYE || req->method == SIP_INFO )) {
08447          ast_debug(5, "%s must have a to tag. dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
08448          return NULL;
08449       }
08450    }
08451 
08452    if (!sip_cfg.pedanticsipchecking) {
08453       struct sip_pvt tmp_dialog = {
08454          .callid = callid,
08455       };
08456       sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find in dialogs");
08457       if (sip_pvt_ptr) {  /* well, if we don't find it-- what IS in there? */
08458          /* Found the call */
08459          return sip_pvt_ptr;
08460       }
08461    } else { /* in pedantic mode! -- do the fancy search */
08462       struct sip_pvt tmp_dialog = {
08463          .callid = callid,
08464       };
08465       struct match_req_args args = { 0, };
08466       int found;
08467       struct ao2_iterator *iterator = ao2_t_callback(dialogs,
08468          OBJ_POINTER | OBJ_MULTIPLE,
08469          dialog_find_multiple,
08470          &tmp_dialog,
08471          "pedantic ao2_find in dialogs");
08472       struct sip_via *via = NULL;
08473 
08474       args.method = req->method;
08475       args.callid = NULL; /* we already matched this. */
08476       args.totag = totag;
08477       args.fromtag = fromtag;
08478       args.seqno = seqno;
08479 
08480       /* If this is a Request, set the Via and Authorization header arguments */
08481       if (req->method != SIP_RESPONSE) {
08482          args.ruri = REQ_OFFSET_TO_STR(req, rlPart2);
08483          via = parse_via(get_header(req, "Via"));
08484          if (via) {
08485             args.viasentby = via->sent_by;
08486             args.viabranch = via->branch;
08487          }
08488          if (!ast_strlen_zero(get_header(req, "Authorization")) ||
08489             !ast_strlen_zero(get_header(req, "Proxy-Authorization"))) {
08490             args.authentication_present = 1;
08491          }
08492       }
08493 
08494       /* Iterate a list of dialogs already matched by Call-id */
08495       while (iterator && (sip_pvt_ptr = ao2_iterator_next(iterator))) {
08496          sip_pvt_lock(sip_pvt_ptr);
08497          found = match_req_to_dialog(sip_pvt_ptr, &args);
08498          sip_pvt_unlock(sip_pvt_ptr);
08499 
08500          switch (found) {
08501          case SIP_REQ_MATCH:
08502             ao2_iterator_destroy(iterator);
08503             free_via(via);
08504             return sip_pvt_ptr; /* return pvt with ref */
08505          case SIP_REQ_LOOP_DETECTED:
08506             /* This is likely a forked Request that somehow resulted in us receiving multiple parts of the fork.
08507             * RFC 3261 section 8.2.2.2, Indicate that we want to merge requests by sending a 482 response. */
08508             transmit_response_using_temp(callid, addr, 1, intended_method, req, "482 (Loop Detected)");
08509             dialog_unref(sip_pvt_ptr, "pvt did not match incoming SIP msg, unref from search.");
08510             ao2_iterator_destroy(iterator);
08511             free_via(via);
08512             return NULL;
08513          case SIP_REQ_NOT_MATCH:
08514          default:
08515             dialog_unref(sip_pvt_ptr, "pvt did not match incoming SIP msg, unref from search");
08516             break;
08517          }
08518       }
08519       if (iterator) {
08520          ao2_iterator_destroy(iterator);
08521       }
08522 
08523       free_via(via);
08524    } /* end of pedantic mode Request/Reponse to Dialog matching */
08525 
08526    /* See if the method is capable of creating a dialog */
08527    if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
08528       struct sip_pvt *p = NULL;
08529 
08530       if (intended_method == SIP_REFER) {
08531          /* We do support REFER, but not outside of a dialog yet */
08532          transmit_response_using_temp(callid, addr, 1, intended_method, req, "603 Declined (no dialog)");
08533    
08534       /* Ok, time to create a new SIP dialog object, a pvt */
08535       } else if (!(p = sip_alloc(callid, addr, 1, intended_method, req)))  {
08536          /* We have a memory or file/socket error (can't allocate RTP sockets or something) so we're not
08537             getting a dialog from sip_alloc.
08538 
08539             Without a dialog we can't retransmit and handle ACKs and all that, but at least
08540             send an error message.
08541 
08542             Sorry, we apologize for the inconvienience
08543          */
08544          transmit_response_using_temp(callid, addr, 1, intended_method, req, "500 Server internal error");
08545          ast_debug(4, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
08546       }
08547       return p; /* can be NULL */
08548    } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
08549       /* A method we do not support, let's take it on the volley */
08550       transmit_response_using_temp(callid, addr, 1, intended_method, req, "501 Method Not Implemented");
08551       ast_debug(2, "Got a request with unsupported SIP method.\n");
08552    } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
08553       /* This is a request outside of a dialog that we don't know about */
08554       transmit_response_using_temp(callid, addr, 1, intended_method, req, "481 Call leg/transaction does not exist");
08555       ast_debug(2, "That's odd...  Got a request in unknown dialog. Callid %s\n", callid ? callid : "<unknown>");
08556    }
08557    /* We do not respond to responses for dialogs that we don't know about, we just drop
08558       the session quickly */
08559    if (intended_method == SIP_RESPONSE)
08560       ast_debug(2, "That's odd...  Got a response on a call we don't know about. Callid %s\n", callid ? callid : "<unknown>");
08561 
08562    return NULL;
08563 }
08564 
08565 /*! \brief create sip_registry object from register=> line in sip.conf and link into reg container */
08566 static int sip_register(const char *value, int lineno)
08567 {
08568    struct sip_registry *reg;
08569 
08570    if (!(reg = ast_calloc_with_stringfields(1, struct sip_registry, 256))) {
08571       ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
08572       return -1;
08573    }
08574 
08575    ast_atomic_fetchadd_int(&regobjs, 1);
08576    ASTOBJ_INIT(reg);
08577 
08578    if (sip_parse_register_line(reg, default_expiry, value, lineno)) {
08579       registry_unref(reg, "failure to parse, unref the reg pointer");
08580       return -1;
08581    }
08582 
08583    /* set default expiry if necessary */
08584    if (reg->refresh && !reg->expiry && !reg->configured_expiry) {
08585       reg->refresh = reg->expiry = reg->configured_expiry = default_expiry;
08586    }
08587 
08588    /* Add the new registry entry to the list */
08589    ASTOBJ_CONTAINER_LINK(&regl, reg);
08590 
08591    /* release the reference given by ASTOBJ_INIT. The container has another reference */
08592    registry_unref(reg, "unref the reg pointer");
08593 
08594    return 0;
08595 }
08596 
08597 /*! \brief Parse mwi=> line in sip.conf and add to list */
08598 static int sip_subscribe_mwi(const char *value, int lineno)
08599 {
08600    struct sip_subscription_mwi *mwi;
08601    int portnum = 0;
08602    enum sip_transport transport = SIP_TRANSPORT_UDP;
08603    char buf[256] = "";
08604    char *username = NULL, *hostname = NULL, *secret = NULL, *authuser = NULL, *porta = NULL, *mailbox = NULL;
08605 
08606    if (!value) {
08607       return -1;
08608    }
08609 
08610    ast_copy_string(buf, value, sizeof(buf));
08611 
08612    username = buf;
08613 
08614    if ((hostname = strrchr(buf, '@'))) {
08615       *hostname++ = '\0';
08616    } else {
08617       return -1;
08618    }
08619 
08620    if ((secret = strchr(username, ':'))) {
08621       *secret++ = '\0';
08622       if ((authuser = strchr(secret, ':'))) {
08623          *authuser++ = '\0';
08624       }
08625    }
08626 
08627    if ((mailbox = strchr(hostname, '/'))) {
08628       *mailbox++ = '\0';
08629    }
08630 
08631    if (ast_strlen_zero(username) || ast_strlen_zero(hostname) || ast_strlen_zero(mailbox)) {
08632       ast_log(LOG_WARNING, "Format for MWI subscription is user[:secret[:authuser]]@host[:port]/mailbox at line %d\n", lineno);
08633       return -1;
08634    }
08635 
08636    if ((porta = strchr(hostname, ':'))) {
08637       *porta++ = '\0';
08638       if (!(portnum = atoi(porta))) {
08639          ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
08640          return -1;
08641       }
08642    }
08643 
08644    if (!(mwi = ast_calloc_with_stringfields(1, struct sip_subscription_mwi, 256))) {
08645       return -1;
08646    }
08647 
08648    ASTOBJ_INIT(mwi);
08649    ast_string_field_set(mwi, username, username);
08650    if (secret) {
08651       ast_string_field_set(mwi, secret, secret);
08652    }
08653    if (authuser) {
08654       ast_string_field_set(mwi, authuser, authuser);
08655    }
08656    ast_string_field_set(mwi, hostname, hostname);
08657    ast_string_field_set(mwi, mailbox, mailbox);
08658    mwi->resub = -1;
08659    mwi->portno = portnum;
08660    mwi->transport = transport;
08661 
08662    ASTOBJ_CONTAINER_LINK(&submwil, mwi);
08663    ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
08664 
08665    return 0;
08666 }
08667 
08668 static void mark_method_allowed(unsigned int *allowed_methods, enum sipmethod method)
08669 {
08670    (*allowed_methods) |= (1 << method);
08671 }
08672 
08673 static void mark_method_unallowed(unsigned int *allowed_methods, enum sipmethod method)
08674 {
08675    (*allowed_methods) &= ~(1 << method);
08676 }
08677 
08678 /*! \brief Check if method is allowed for a device or a dialog */
08679 static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method)
08680 {
08681    return ((*allowed_methods) >> method) & 1;
08682 }
08683 
08684 static void mark_parsed_methods(unsigned int *methods, char *methods_str)
08685 {
08686    char *method;
08687    for (method = strsep(&methods_str, ","); !ast_strlen_zero(method); method = strsep(&methods_str, ",")) {
08688       int id = find_sip_method(ast_skip_blanks(method));
08689       if (id == SIP_UNKNOWN) {
08690          continue;
08691       }
08692       mark_method_allowed(methods, id);
08693    }
08694 }
08695 /*!
08696  * \brief parse the Allow header to see what methods the endpoint we
08697  * are communicating with allows.
08698  *
08699  * We parse the allow header on incoming Registrations and save the
08700  * result to the SIP peer that is registering. When the registration
08701  * expires, we clear what we know about the peer's allowed methods.
08702  * When the peer re-registers, we once again parse to see if the
08703  * list of allowed methods has changed.
08704  *
08705  * For peers that do not register, we parse the first message we receive
08706  * during a call to see what is allowed, and save the information
08707  * for the duration of the call.
08708  * \param req The SIP request we are parsing
08709  * \retval The methods allowed
08710  */
08711 static unsigned int parse_allowed_methods(struct sip_request *req)
08712 {
08713    char *allow = ast_strdupa(get_header(req, "Allow"));
08714    unsigned int allowed_methods = SIP_UNKNOWN;
08715 
08716    if (ast_strlen_zero(allow)) {
08717       /* I have witnessed that REGISTER requests from Polycom phones do not
08718        * place the phone's allowed methods in an Allow header. Instead, they place the
08719        * allowed methods in a methods= parameter in the Contact header.
08720        */
08721       char *contact = ast_strdupa(get_header(req, "Contact"));
08722       char *methods = strstr(contact, ";methods=");
08723 
08724       if (ast_strlen_zero(methods)) {
08725          /* RFC 3261 states:
08726           *
08727           * "The absence of an Allow header field MUST NOT be
08728           * interpreted to mean that the UA sending the message supports no
08729           * methods.   Rather, it implies that the UA is not providing any
08730           * information on what methods it supports."
08731           *
08732           * For simplicity, we'll assume that the peer allows all known
08733           * SIP methods if they have no Allow header. We can then clear out the necessary
08734           * bits if the peer lets us know that we have sent an unsupported method.
08735           */
08736          return UINT_MAX;
08737       }
08738       allow = ast_strip_quoted(methods + 9, "\"", "\"");
08739    }
08740    mark_parsed_methods(&allowed_methods, allow);
08741    return allowed_methods;
08742 }
08743 
08744 /*! A wrapper for parse_allowed_methods geared toward sip_pvts
08745  *
08746  * This function, in addition to setting the allowed methods for a sip_pvt
08747  * also will take into account the setting of the SIP_PAGE2_RPID_UPDATE flag.
08748  *
08749  * \param pvt The sip_pvt we are setting the allowed_methods for
08750  * \param req The request which we are parsing
08751  * \retval The methods alloweded by the sip_pvt
08752  */
08753 static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req)
08754 {
08755    pvt->allowed_methods = parse_allowed_methods(req);
08756    
08757    if (ast_test_flag(&pvt->flags[1], SIP_PAGE2_RPID_UPDATE)) {
08758       mark_method_allowed(&pvt->allowed_methods, SIP_UPDATE);
08759    }
08760    pvt->allowed_methods &= ~(pvt->disallowed_methods);
08761 
08762    return pvt->allowed_methods;
08763 }
08764 
08765 /*! \brief  Parse multiline SIP headers into one header
08766    This is enabled if pedanticsipchecking is enabled */
08767 static void lws2sws(struct ast_str *data)
08768 {
08769    char *msgbuf = data->str;
08770    int len = ast_str_strlen(data);
08771    int h = 0, t = 0;
08772    int lws = 0;
08773 
08774    for (; h < len;) {
08775       /* Eliminate all CRs */
08776       if (msgbuf[h] == '\r') {
08777          h++;
08778          continue;
08779       }
08780       /* Check for end-of-line */
08781       if (msgbuf[h] == '\n') {
08782          /* Check for end-of-message */
08783          if (h + 1 == len)
08784             break;
08785          /* Check for a continuation line */
08786          if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
08787             /* Merge continuation line */
08788             h++;
08789             continue;
08790          }
08791          /* Propagate LF and start new line */
08792          msgbuf[t++] = msgbuf[h++];
08793          lws = 0;
08794          continue;
08795       }
08796       if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
08797          if (lws) {
08798             h++;
08799             continue;
08800          }
08801          msgbuf[t++] = msgbuf[h++];
08802          lws = 1;
08803          continue;
08804       }
08805       msgbuf[t++] = msgbuf[h++];
08806       if (lws)
08807          lws = 0;
08808    }
08809    msgbuf[t] = '\0';
08810    data->used = t;
08811 }
08812 
08813 /*! \brief Parse a SIP message
08814    \note this function is used both on incoming and outgoing packets
08815 */
08816 static int parse_request(struct sip_request *req)
08817 {
08818    char *c = req->data->str;
08819    ptrdiff_t *dst = req->header;
08820    int i = 0, lim = SIP_MAX_HEADERS - 1;
08821    unsigned int skipping_headers = 0;
08822    ptrdiff_t current_header_offset = 0;
08823    char *previous_header = "";
08824 
08825    req->header[0] = 0;
08826    req->headers = -1;   /* mark that we are working on the header */
08827    for (; *c; c++) {
08828       if (*c == '\r') {    /* remove \r */
08829          *c = '\0';
08830       } else if (*c == '\n') {   /* end of this line */
08831          *c = '\0';
08832          current_header_offset = (c + 1) - ast_str_buffer(req->data);
08833          previous_header = ast_str_buffer(req->data) + dst[i];
08834          if (skipping_headers) {
08835             /* check to see if this line is blank; if so, turn off
08836                the skipping flag, so the next line will be processed
08837                as a body line */
08838             if (ast_strlen_zero(previous_header)) {
08839                skipping_headers = 0;
08840             }
08841             dst[i] = current_header_offset; /* record start of next line */
08842             continue;
08843          }
08844          if (sipdebug) {
08845             ast_debug(4, "%7s %2d [%3d]: %s\n",
08846                  req->headers < 0 ? "Header" : "Body",
08847                  i, (int) strlen(previous_header), previous_header);
08848          }
08849          if (ast_strlen_zero(previous_header) && req->headers < 0) {
08850             req->headers = i; /* record number of header lines */
08851             dst = req->line;  /* start working on the body */
08852             i = 0;
08853             lim = SIP_MAX_LINES - 1;
08854          } else { /* move to next line, check for overflows */
08855             if (i++ == lim) {
08856                /* if we're processing headers, then skip any remaining
08857                   headers and move on to processing the body, otherwise
08858                   we're done */
08859                if (req->headers != -1) {
08860                   break;
08861                } else {
08862                   req->headers = i;
08863                   dst = req->line;
08864                   i = 0;
08865                   lim = SIP_MAX_LINES - 1;
08866                   skipping_headers = 1;
08867                }
08868             }
08869          }
08870          dst[i] = current_header_offset; /* record start of next line */
08871       }
08872    }
08873 
08874    /* Check for last header or body line without CRLF. The RFC for SDP requires CRLF,
08875       but since some devices send without, we'll be generous in what we accept. However,
08876       if we've already reached the maximum number of lines for portion of the message
08877       we were parsing, we can't accept any more, so just ignore it.
08878    */
08879    previous_header = ast_str_buffer(req->data) + dst[i];
08880    if ((i < lim) && !ast_strlen_zero(previous_header)) {
08881       if (sipdebug) {
08882          ast_debug(4, "%7s %2d [%3d]: %s\n",
08883               req->headers < 0 ? "Header" : "Body",
08884               i, (int) strlen(previous_header), previous_header );
08885       }
08886       i++;
08887    }
08888 
08889    /* update count of header or body lines */
08890    if (req->headers >= 0) {   /* we are in the body */
08891       req->lines = i;
08892    } else {       /* no body */
08893       req->headers = i;
08894       req->lines = 0;
08895       /* req->data->used will be a NULL byte */
08896       req->line[0] = ast_str_strlen(req->data);
08897    }
08898 
08899    if (*c) {
08900       ast_log(LOG_WARNING, "Too many lines, skipping <%s>\n", c);
08901    }
08902 
08903    /* Split up the first line parts */
08904    return determine_firstline_parts(req);
08905 }
08906 
08907 /*!
08908   \brief Determine whether a SIP message contains an SDP in its body
08909   \param req the SIP request to process
08910   \return 1 if SDP found, 0 if not found
08911 
08912   Also updates req->sdp_start and req->sdp_count to indicate where the SDP
08913   lives in the message body.
08914 */
08915 static int find_sdp(struct sip_request *req)
08916 {
08917    const char *content_type;
08918    const char *content_length;
08919    const char *search;
08920    char *boundary;
08921    unsigned int x;
08922    int boundaryisquoted = FALSE;
08923    int found_application_sdp = FALSE;
08924    int found_end_of_headers = FALSE;
08925 
08926    content_length = get_header(req, "Content-Length");
08927 
08928    if (!ast_strlen_zero(content_length)) {
08929       if (sscanf(content_length, "%30u", &x) != 1) {
08930          ast_log(LOG_WARNING, "Invalid Content-Length: %s\n", content_length);
08931          return 0;
08932       }
08933 
08934       /* Content-Length of zero means there can't possibly be an
08935          SDP here, even if the Content-Type says there is */
08936       if (x == 0)
08937          return 0;
08938    }
08939 
08940    content_type = get_header(req, "Content-Type");
08941 
08942    /* if the body contains only SDP, this is easy */
08943    if (!strncasecmp(content_type, "application/sdp", 15)) {
08944       req->sdp_start = 0;
08945       req->sdp_count = req->lines;
08946       return req->lines ? 1 : 0;
08947    }
08948 
08949    /* if it's not multipart/mixed, there cannot be an SDP */
08950    if (strncasecmp(content_type, "multipart/mixed", 15))
08951       return 0;
08952 
08953    /* if there is no boundary marker, it's invalid */
08954    if ((search = strcasestr(content_type, ";boundary=")))
08955       search += 10;
08956    else if ((search = strcasestr(content_type, "; boundary=")))
08957       search += 11;
08958    else
08959       return 0;
08960 
08961    if (ast_strlen_zero(search))
08962       return 0;
08963 
08964    /* If the boundary is quoted with ", remove quote */
08965    if (*search == '\"')  {
08966       search++;
08967       boundaryisquoted = TRUE;
08968    }
08969 
08970    /* make a duplicate of the string, with two extra characters
08971       at the beginning */
08972    boundary = ast_strdupa(search - 2);
08973    boundary[0] = boundary[1] = '-';
08974    /* Remove final quote */
08975    if (boundaryisquoted)
08976       boundary[strlen(boundary) - 1] = '\0';
08977 
08978    /* search for the boundary marker, the empty line delimiting headers from
08979       sdp part and the end boundry if it exists */
08980 
08981    for (x = 0; x < (req->lines); x++) {
08982       const char *line = REQ_OFFSET_TO_STR(req, line[x]);
08983       if (!strncasecmp(line, boundary, strlen(boundary))){
08984          if (found_application_sdp && found_end_of_headers) {
08985             req->sdp_count = (x - 1) - req->sdp_start;
08986             return 1;
08987          }
08988          found_application_sdp = FALSE;
08989       }
08990       if (!strcasecmp(line, "Content-Type: application/sdp"))
08991          found_application_sdp = TRUE;
08992       
08993       if (ast_strlen_zero(line)) {
08994          if (found_application_sdp && !found_end_of_headers){
08995             req->sdp_start = x;
08996             found_end_of_headers = TRUE;
08997          }
08998       }
08999    }
09000    if (found_application_sdp && found_end_of_headers) {
09001       req->sdp_count = x - req->sdp_start;
09002       return TRUE;
09003    }
09004    return FALSE;
09005 }
09006 
09007 /*! \brief Change hold state for a call */
09008 static void change_hold_state(struct sip_pvt *dialog, struct sip_request *req, int holdstate, int sendonly)
09009 {
09010    if (sip_cfg.notifyhold && (!holdstate || !ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD)))
09011       sip_peer_hold(dialog, holdstate);
09012    if (sip_cfg.callevents)
09013       manager_event(EVENT_FLAG_CALL, "Hold",
09014                "Status: %s\r\n"
09015                "Channel: %s\r\n"
09016                "Uniqueid: %s\r\n",
09017                holdstate ? "On" : "Off",
09018                dialog->owner->name,
09019                dialog->owner->uniqueid);
09020    append_history(dialog, holdstate ? "Hold" : "Unhold", "%s", ast_str_buffer(req->data));
09021    if (!holdstate) { /* Put off remote hold */
09022       ast_clear_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD);   /* Clear both flags */
09023       return;
09024    }
09025    /* No address for RTP, we're on hold */
09026 
09027    /* Ensure hold flags are cleared so that overlapping flags do not conflict */
09028    ast_clear_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD);
09029 
09030    if (sendonly == 1)   /* One directional hold (sendonly/recvonly) */
09031       ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
09032    else if (sendonly == 2) /* Inactive stream */
09033       ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
09034    else
09035       ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
09036    return;
09037 }
09038 
09039 
09040 static int get_ip_and_port_from_sdp(struct sip_request *req, const enum media_type media, struct ast_sockaddr *addr)
09041 {
09042    const char *m;
09043    const char *c;
09044    int miterator = req->sdp_start;
09045    int citerator = req->sdp_start;
09046    unsigned int x = 0;
09047    unsigned int numberofports;
09048    int len;
09049    int af;
09050    char proto[4], host[258] = ""; /*Initialize to empty so we will know if we have any input */
09051 
09052    c = get_sdp_iterate(&citerator, req, "c");
09053    if (sscanf(c, "IN %3s %256s", proto, host) != 2) {
09054          ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
09055          /* Continue since there may be a valid host in a c= line specific to the audio stream */
09056    }
09057    /* We only want the m and c lines for audio */
09058    for (m = get_sdp_iterate(&miterator, req, "m"); !ast_strlen_zero(m); m = get_sdp_iterate(&miterator, req, "m")) {
09059       if ((media == SDP_AUDIO && ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
09060           (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0))) ||
09061          (media == SDP_VIDEO && ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
09062           (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len > 0)))) {
09063          /* See if there's a c= line for this media stream.
09064           * XXX There is no guarantee that we'll be grabbing the c= line for this
09065           * particular media stream here. However, this is the same logic used in process_sdp.
09066           */
09067          c = get_sdp_iterate(&citerator, req, "c");
09068          if (!ast_strlen_zero(c)) {
09069             sscanf(c, "IN %3s %256s", proto, host);
09070          }
09071          break;
09072       }
09073    }
09074 
09075    if (!strcmp("IP4", proto)) {
09076       af = AF_INET;
09077    } else if (!strcmp("IP6", proto)) {
09078       af = AF_INET6;
09079    } else {
09080       ast_log(LOG_WARNING, "Unknown protocol '%s'.\n", proto);
09081       return -1;
09082    }
09083 
09084    if (ast_strlen_zero(host) || x == 0) {
09085       ast_log(LOG_WARNING, "Failed to read an alternate host or port in SDP. Expect %s problems\n", media == SDP_AUDIO ? "audio" : "video");
09086       return -1;
09087    }
09088 
09089    if (ast_sockaddr_resolve_first_af(addr, host, 0, af)) {
09090       ast_log(LOG_WARNING, "Could not look up IP address of alternate hostname. Expect %s problems\n", media == SDP_AUDIO? "audio" : "video");
09091       return -1;
09092    }
09093 
09094    return 0;
09095 }
09096 
09097 /*! \internal
09098  * \brief Returns whether or not the address is null or ANY / unspecified (0.0.0.0 or ::)
09099  * \retval TRUE if the address is null or any
09100  * \retval FALSE if the address it not null or any
09101  * \note In some circumstances, calls should be placed on hold if either of these conditions exist.
09102  */
09103 static int sockaddr_is_null_or_any(const struct ast_sockaddr *addr)
09104 {
09105    return ast_sockaddr_isnull(addr) || ast_sockaddr_is_any(addr);
09106 }
09107 
09108 /*! \brief Process SIP SDP offer, select formats and activate media channels
09109    If offer is rejected, we will not change any properties of the call
09110    Return 0 on success, a negative value on errors.
09111    Must be called after find_sdp().
09112 */
09113 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
09114 {
09115    /* Iterators for SDP parsing */
09116    int start = req->sdp_start;
09117    int next = start;
09118    int iterator = start;
09119 
09120    /* Temporary vars for SDP parsing */
09121    char type = '\0';
09122    const char *value = NULL;
09123    const char *m = NULL;           /* SDP media offer */
09124    const char *nextm = NULL;
09125    int len = -1;
09126 
09127    /* Host information */
09128    struct ast_sockaddr sessionsa;
09129    struct ast_sockaddr audiosa;
09130    struct ast_sockaddr videosa;
09131    struct ast_sockaddr textsa;
09132    struct ast_sockaddr imagesa;
09133    struct ast_sockaddr *sa = NULL;     /*!< RTP audio destination IP address */
09134    struct ast_sockaddr *vsa = NULL; /*!< RTP video destination IP address */
09135    struct ast_sockaddr *tsa = NULL; /*!< RTP text destination IP address */
09136    struct ast_sockaddr *isa = NULL; /*!< UDPTL image destination IP address */
09137    int portno = -1;        /*!< RTP audio destination port number */
09138    int vportno = -1;       /*!< RTP video destination port number */
09139    int tportno = -1;       /*!< RTP text destination port number */
09140    int udptlportno = -1;         /*!< UDPTL image destination port number */
09141 
09142    /* Peer capability is the capability in the SDP, non codec is RFC2833 DTMF (101) */
09143    format_t peercapability = 0, vpeercapability = 0, tpeercapability = 0;
09144    int peernoncodeccapability = 0, vpeernoncodeccapability = 0, tpeernoncodeccapability = 0;
09145 
09146    struct ast_rtp_codecs newaudiortp, newvideortp, newtextrtp;
09147    format_t newjointcapability;           /* Negotiated capability */
09148    format_t newpeercapability;
09149    int newnoncodeccapability;
09150 
09151    const char *codecs;
09152    unsigned int codec;
09153 
09154    /* SRTP */
09155    int secure_audio = FALSE;
09156    int secure_video = FALSE;
09157 
09158    /* Others */
09159    int sendonly = -1;
09160    unsigned int numberofports;
09161    int numberofmediastreams = 0;
09162    int last_rtpmap_codec = 0;
09163    int red_data_pt[10];    /* For T.140 RED */
09164    int red_num_gen = 0;    /* For T.140 RED */
09165    char red_fmtp[100] = "empty"; /* For T.140 RED */
09166    int debug = sip_debug_test_pvt(p);
09167 
09168    /* START UNKNOWN */
09169    char buf[SIPBUFSIZE];
09170    /* END UNKNOWN */
09171 
09172    /* Initial check */
09173    if (!p->rtp) {
09174       ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
09175       return -1;
09176    }
09177 
09178    /* Make sure that the codec structures are all cleared out */
09179    ast_rtp_codecs_payloads_clear(&newaudiortp, NULL);
09180    ast_rtp_codecs_payloads_clear(&newvideortp, NULL);
09181    ast_rtp_codecs_payloads_clear(&newtextrtp, NULL);
09182 
09183    /* Update our last rtprx when we receive an SDP, too */
09184    p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
09185 
09186    memset(p->offered_media, 0, sizeof(p->offered_media));
09187 
09188    /* default: novideo and notext set */
09189    p->novideo = TRUE;
09190    p->notext = TRUE;
09191 
09192    /* Scan for the first media stream (m=) line to limit scanning of globals */
09193    nextm = get_sdp_iterate(&next, req, "m");
09194    if (ast_strlen_zero(nextm)) {
09195       ast_log(LOG_WARNING, "Insufficient information for SDP (m= not found)\n");
09196       return -1;
09197    }
09198 
09199    /* Scan session level SDP parameters (lines before first media stream) */
09200    while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
09201       int processed = FALSE;
09202       switch (type) {
09203       case 'o':
09204          /* If we end up receiving SDP that doesn't actually modify the session we don't want to treat this as a fatal
09205           * error. We just want to ignore the SDP and let the rest of the packet be handled as normal.
09206           */
09207          if (!process_sdp_o(value, p)) {
09208             return (p->session_modify == FALSE) ? 0 : -1;
09209          }
09210          processed = TRUE;
09211          break;
09212       case 'c':
09213          if (process_sdp_c(value, &sessionsa)) {
09214             processed = TRUE;
09215             sa = &sessionsa;
09216             vsa = sa;
09217             tsa = sa;
09218             isa = sa;
09219          }
09220          break;
09221       case 'a':
09222          if (process_sdp_a_sendonly(value, &sendonly)) {
09223             processed = TRUE;
09224          }
09225          else if (process_sdp_a_audio(value, p, &newaudiortp, &last_rtpmap_codec))
09226             processed = TRUE;
09227          else if (process_sdp_a_video(value, p, &newvideortp, &last_rtpmap_codec))
09228             processed = TRUE;
09229          else if (process_sdp_a_text(value, p, &newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
09230             processed = TRUE;
09231          else if (process_sdp_a_image(value, p))
09232             processed = TRUE;
09233          break;
09234       }
09235 
09236       ast_debug(3, "Processing session-level SDP %c=%s... %s\n", type, value, (processed == TRUE)? "OK." : "UNSUPPORTED OR FAILED.");
09237    }
09238 
09239    /* Scan media stream (m=) specific parameters loop */
09240    while (!ast_strlen_zero(nextm)) {
09241       int audio = FALSE;
09242       int video = FALSE;
09243       int image = FALSE;
09244       int text = FALSE;
09245       int processed_crypto = FALSE;
09246       char protocol[18] = {0,};
09247       unsigned int x;
09248 
09249       numberofports = 0;
09250       len = -1;
09251       start = next;
09252       m = nextm;
09253       iterator = next;
09254       nextm = get_sdp_iterate(&next, req, "m");
09255 
09256       /* Check for 'audio' media offer */
09257       if (strncmp(m, "audio ", 6) == 0) {
09258          if ((sscanf(m, "audio %30u/%30u RTP/%4s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||
09259              (sscanf(m, "audio %30u RTP/%4s %n", &x, protocol, &len) == 2 && len > 0)) {
09260             if (x == 0) {
09261                ast_log(LOG_WARNING, "Ignoring audio media offer because port number is zero\n");
09262                continue;
09263             }
09264 
09265             /* Check number of ports offered for stream */
09266             if (numberofports > 1) {
09267                ast_log(LOG_WARNING, "%u ports offered for audio media, not supported by Asterisk. Will try anyway...\n", numberofports);
09268             }
09269 
09270             if (!strcmp(protocol, "SAVP")) {
09271                secure_audio = 1;
09272             } else if (strcmp(protocol, "AVP")) {
09273                ast_log(LOG_WARNING, "Unknown RTP profile in audio offer: %s\n", m);
09274                continue;
09275             }
09276 
09277             if (p->offered_media[SDP_AUDIO].order_offered) {
09278                ast_log(LOG_WARNING, "Rejecting non-primary audio stream: %s\n", m);
09279                return -1;
09280             }
09281 
09282             audio = TRUE;
09283             p->offered_media[SDP_AUDIO].order_offered = ++numberofmediastreams;
09284             portno = x;
09285 
09286             /* Scan through the RTP payload types specified in a "m=" line: */
09287             codecs = m + len;
09288             ast_copy_string(p->offered_media[SDP_AUDIO].codecs, codecs, sizeof(p->offered_media[SDP_AUDIO].codecs));
09289             for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
09290                if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
09291                   ast_log(LOG_WARNING, "Invalid syntax in RTP audio format list: %s\n", codecs);
09292                   return -1;
09293                }
09294                if (debug) {
09295                   ast_verbose("Found RTP audio format %u\n", codec);
09296                }
09297 
09298                ast_rtp_codecs_payloads_set_m_type(&newaudiortp, NULL, codec);
09299             }
09300          } else {
09301             ast_log(LOG_WARNING, "Rejecting audio media offer due to invalid or unsupported syntax: %s\n", m);
09302             return -1;
09303          }
09304       }
09305       /* Check for 'video' media offer */
09306       else if (strncmp(m, "video ", 6) == 0) {
09307          if ((sscanf(m, "video %30u/%30u RTP/%4s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||
09308              (sscanf(m, "video %30u RTP/%4s %n", &x, protocol, &len) == 2 && len > 0)) {
09309             if (x == 0) {
09310                ast_log(LOG_WARNING, "Ignoring video media offer because port number is zero\n");
09311                continue;
09312             }
09313 
09314             /* Check number of ports offered for stream */
09315             if (numberofports > 1) {
09316                ast_log(LOG_WARNING, "%u ports offered for video media, not supported by Asterisk. Will try anyway...\n", numberofports);
09317             }
09318 
09319             if (!strcmp(protocol, "SAVP")) {
09320                secure_video = 1;
09321             } else if (strcmp(protocol, "AVP")) {
09322                ast_log(LOG_WARNING, "Unknown RTP profile in video offer: %s\n", m);
09323                continue;
09324             }
09325 
09326             if (p->offered_media[SDP_VIDEO].order_offered) {
09327                ast_log(LOG_WARNING, "Rejecting non-primary video stream: %s\n", m);
09328                return -1;
09329             }
09330 
09331             video = TRUE;
09332             p->novideo = FALSE;
09333             p->offered_media[SDP_VIDEO].order_offered = ++numberofmediastreams;
09334             vportno = x;
09335 
09336             /* Scan through the RTP payload types specified in a "m=" line: */
09337             codecs = m + len;
09338             ast_copy_string(p->offered_media[SDP_VIDEO].codecs, codecs, sizeof(p->offered_media[SDP_VIDEO].codecs));
09339             for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
09340                if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
09341                   ast_log(LOG_WARNING, "Invalid syntax in RTP video format list: %s\n", codecs);
09342                   return -1;
09343                }
09344                if (debug) {
09345                   ast_verbose("Found RTP video format %u\n", codec);
09346                }
09347                ast_rtp_codecs_payloads_set_m_type(&newvideortp, NULL, codec);
09348             }
09349          } else {
09350             ast_log(LOG_WARNING, "Rejecting video media offer due to invalid or unsupported syntax: %s\n", m);
09351             return -1;
09352          }
09353       }
09354       /* Check for 'text' media offer */
09355       else if (strncmp(m, "text ", 5) == 0) {
09356          if ((sscanf(m, "text %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
09357              (sscanf(m, "text %30u RTP/AVP %n", &x, &len) == 1 && len > 0)) {
09358             if (x == 0) {
09359                ast_log(LOG_WARNING, "Ignoring text media offer because port number is zero\n");
09360                continue;
09361             }
09362 
09363             /* Check number of ports offered for stream */
09364             if (numberofports > 1) {
09365                ast_log(LOG_WARNING, "%u ports offered for text media, not supported by Asterisk. Will try anyway...\n", numberofports);
09366             }
09367 
09368             if (p->offered_media[SDP_TEXT].order_offered) {
09369                ast_log(LOG_WARNING, "Rejecting non-primary text stream: %s\n", m);
09370                return -1;
09371             }
09372 
09373             text = TRUE;
09374             p->notext = FALSE;
09375             p->offered_media[SDP_TEXT].order_offered = ++numberofmediastreams;
09376             tportno = x;
09377 
09378             /* Scan through the RTP payload types specified in a "m=" line: */
09379             codecs = m + len;
09380             ast_copy_string(p->offered_media[SDP_TEXT].codecs, codecs, sizeof(p->offered_media[SDP_TEXT].codecs));
09381             for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
09382                if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
09383                   ast_log(LOG_WARNING, "Invalid syntax in RTP video format list: %s\n", codecs);
09384                   return -1;
09385                }
09386                if (debug) {
09387                   ast_verbose("Found RTP text format %u\n", codec);
09388                }
09389                ast_rtp_codecs_payloads_set_m_type(&newtextrtp, NULL, codec);
09390             }
09391          } else {
09392             ast_log(LOG_WARNING, "Rejecting text media offer due to invalid or unsupported syntax: %s\n", m);
09393             return -1;
09394          }
09395       }
09396       /* Check for 'image' media offer */
09397       else if (strncmp(m, "image ", 6) == 0) {
09398          if (((sscanf(m, "image %30u udptl t38%n", &x, &len) == 1 && len > 0) ||
09399               (sscanf(m, "image %30u UDPTL t38%n", &x, &len) == 1 && len > 0))) {
09400             if (x == 0) {
09401                ast_log(LOG_WARNING, "Ignoring image media offer because port number is zero\n");
09402                continue;
09403             }
09404 
09405             if (initialize_udptl(p)) {
09406                ast_log(LOG_WARNING, "Rejecting offer with image stream due to UDPTL initialization failure\n");
09407                return -1;
09408             }
09409 
09410             if (p->offered_media[SDP_IMAGE].order_offered) {
09411                ast_log(LOG_WARNING, "Rejecting non-primary image stream: %s\n", m);
09412                return -1;
09413             }
09414 
09415             image = TRUE;
09416             if (debug) {
09417                ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
09418             }
09419 
09420             p->offered_media[SDP_IMAGE].order_offered = ++numberofmediastreams;
09421             udptlportno = x;
09422 
09423             if (p->t38.state != T38_ENABLED) {
09424                memset(&p->t38.their_parms, 0, sizeof(p->t38.their_parms));
09425 
09426                /* default EC to none, the remote end should
09427                 * respond with the EC they want to use */
09428                ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
09429             }
09430          } else if (sscanf(m, "image %30u %17s t38%n", &x, protocol, &len) == 2 && len > 0) {
09431             ast_log(LOG_WARNING, "Declining image stream due to unsupported transport: %s\n", m);
09432             continue;
09433          } else {
09434             ast_log(LOG_WARNING, "Rejecting image media offer due to invalid or unsupported syntax: %s\n", m);
09435             return -1;
09436          }
09437       } else {
09438          ast_log(LOG_WARNING, "Unsupported top-level media type in offer: %s\n", m);
09439          continue;
09440       }
09441 
09442       /* Media stream specific parameters */
09443       while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
09444          int processed = FALSE;
09445 
09446          switch (type) {
09447          case 'c':
09448             if (audio) {
09449                if (process_sdp_c(value, &audiosa)) {
09450                   processed = TRUE;
09451                   sa = &audiosa;
09452                }
09453             } else if (video) {
09454                if (process_sdp_c(value, &videosa)) {
09455                   processed = TRUE;
09456                   vsa = &videosa;
09457                }
09458             } else if (text) {
09459                if (process_sdp_c(value, &textsa)) {
09460                   processed = TRUE;
09461                   tsa = &textsa;
09462                }
09463             } else if (image) {
09464                if (process_sdp_c(value, &imagesa)) {
09465                   processed = TRUE;
09466                   isa = &imagesa;
09467                }
09468             }
09469             break;
09470          case 'a':
09471             /* Audio specific scanning */
09472             if (audio) {
09473                if (process_sdp_a_sendonly(value, &sendonly)) {
09474                   processed = TRUE;
09475                } else if (!processed_crypto && process_crypto(p, p->rtp, &p->srtp, value)) {
09476                   processed_crypto = TRUE;
09477                   processed = TRUE;
09478                } else if (process_sdp_a_audio(value, p, &newaudiortp, &last_rtpmap_codec)) {
09479                   processed = TRUE;
09480                }
09481             }
09482             /* Video specific scanning */
09483             else if (video) {
09484                if (!processed_crypto && process_crypto(p, p->vrtp, &p->vsrtp, value)) {
09485                   processed_crypto = TRUE;
09486                   processed = TRUE;
09487                } else if (process_sdp_a_video(value, p, &newvideortp, &last_rtpmap_codec)) {
09488                   processed = TRUE;
09489                }
09490             }
09491             /* Text (T.140) specific scanning */
09492             else if (text) {
09493                if (process_sdp_a_text(value, p, &newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec)) {
09494                   processed = TRUE;
09495                } else if (!processed_crypto && process_crypto(p, p->trtp, &p->tsrtp, value)) {
09496                   processed_crypto = TRUE;
09497                   processed = TRUE;
09498                }
09499             }
09500             /* Image (T.38 FAX) specific scanning */
09501             else if (image) {
09502                if (process_sdp_a_image(value, p))
09503                   processed = TRUE;
09504             }
09505             break;
09506          }
09507 
09508          ast_debug(3, "Processing media-level (%s) SDP %c=%s... %s\n",
09509               (audio == TRUE)? "audio" : (video == TRUE)? "video" : (text == TRUE)? "text" : "image",
09510               type, value,
09511               (processed == TRUE)? "OK." : "UNSUPPORTED OR FAILED.");
09512       }
09513 
09514       /* Ensure crypto lines are provided where necessary */
09515       if (audio && secure_audio && !processed_crypto) {
09516          ast_log(LOG_WARNING, "Rejecting secure audio stream without encryption details: %s\n", m);
09517          return -1;
09518       } else if (video && secure_video && !processed_crypto) {
09519          ast_log(LOG_WARNING, "Rejecting secure video stream without encryption details: %s\n", m);
09520          return -1;
09521       }
09522    }
09523 
09524    /* Sanity checks */
09525    if (!sa && !vsa && !tsa && !isa) {
09526       ast_log(LOG_WARNING, "Insufficient information in SDP (c=)...\n");
09527       return -1;
09528    }
09529 
09530    if ((portno == -1) &&
09531        (vportno == -1) &&
09532        (tportno == -1) &&
09533        (udptlportno == -1)) {
09534       ast_log(LOG_WARNING, "Failing due to no acceptable offer found\n");
09535       return -1;
09536    }
09537 
09538    if (secure_audio && !(p->srtp && (ast_test_flag(p->srtp, SRTP_CRYPTO_OFFER_OK)))) {
09539       ast_log(LOG_WARNING, "Can't provide secure audio requested in SDP offer\n");
09540       return -1;
09541    }
09542 
09543    if (!secure_audio && p->srtp) {
09544       ast_log(LOG_WARNING, "We are requesting SRTP for audio, but they responded without it!\n");
09545       return -1;
09546    }
09547 
09548    if (secure_video && !(p->vsrtp && (ast_test_flag(p->vsrtp, SRTP_CRYPTO_OFFER_OK)))) {
09549       ast_log(LOG_WARNING, "Can't provide secure video requested in SDP offer\n");
09550       return -1;
09551    }
09552 
09553    if (!p->novideo && !secure_video && p->vsrtp) {
09554       ast_log(LOG_WARNING, "We are requesting SRTP for video, but they responded without it!\n");
09555       return -1;
09556    }
09557 
09558    if (!(secure_audio || secure_video) && ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP)) {
09559       ast_log(LOG_WARNING, "Matched device setup to use SRTP, but request was not!\n");
09560       return -1;
09561    }
09562 
09563    if (udptlportno == -1) {
09564       change_t38_state(p, T38_DISABLED);
09565    }
09566 
09567    /* Now gather all of the codecs that we are asked for: */
09568    ast_rtp_codecs_payload_formats(&newaudiortp, &peercapability, &peernoncodeccapability);
09569    ast_rtp_codecs_payload_formats(&newvideortp, &vpeercapability, &vpeernoncodeccapability);
09570    ast_rtp_codecs_payload_formats(&newtextrtp, &tpeercapability, &tpeernoncodeccapability);
09571 
09572    newjointcapability = p->capability & (peercapability | vpeercapability | tpeercapability);
09573    newpeercapability = (peercapability | vpeercapability | tpeercapability);
09574    newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
09575 
09576    if (debug) {
09577       /* shame on whoever coded this.... */
09578       char s1[SIPBUFSIZE], s2[SIPBUFSIZE], s3[SIPBUFSIZE], s4[SIPBUFSIZE], s5[SIPBUFSIZE];
09579 
09580       ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s/text=%s, combined - %s\n",
09581              ast_getformatname_multiple(s1, SIPBUFSIZE, p->capability),
09582              ast_getformatname_multiple(s2, SIPBUFSIZE, peercapability),
09583              ast_getformatname_multiple(s3, SIPBUFSIZE, vpeercapability),
09584              ast_getformatname_multiple(s4, SIPBUFSIZE, tpeercapability),
09585              ast_getformatname_multiple(s5, SIPBUFSIZE, newjointcapability));
09586    }
09587    if (debug) {
09588       struct ast_str *s1 = ast_str_alloca(SIPBUFSIZE);
09589       struct ast_str *s2 = ast_str_alloca(SIPBUFSIZE);
09590       struct ast_str *s3 = ast_str_alloca(SIPBUFSIZE);
09591 
09592       ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
09593              ast_rtp_lookup_mime_multiple2(s1, p->noncodeccapability, 0, 0),
09594              ast_rtp_lookup_mime_multiple2(s2, peernoncodeccapability, 0, 0),
09595              ast_rtp_lookup_mime_multiple2(s3, newnoncodeccapability, 0, 0));
09596    }
09597    if (!newjointcapability && udptlportno == -1) {
09598       ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
09599       /* Do NOT Change current setting */
09600       return -1;
09601    }
09602 
09603    if (portno != -1 || vportno != -1 || tportno != -1) {
09604       /* We are now ready to change the sip session and RTP structures with the offered codecs, since
09605          they are acceptable */
09606       p->jointcapability = newjointcapability;                /* Our joint codec profile for this call */
09607       p->peercapability = newpeercapability;                  /* The other side's capability in latest offer */
09608       p->jointnoncodeccapability = newnoncodeccapability;     /* DTMF capabilities */
09609 
09610       /* respond with single most preferred joint codec, limiting the other side's choice */
09611       if (ast_test_flag(&p->flags[1], SIP_PAGE2_PREFERRED_CODEC)) {
09612          p->jointcapability = ast_codec_choose(&p->prefs, p->jointcapability, 1);
09613       }
09614    }
09615 
09616    /* Setup audio address and port */
09617    if (p->rtp) {
09618       if (sa && portno > 0) {
09619          ast_sockaddr_set_port(sa, portno);
09620          ast_rtp_instance_set_remote_address(p->rtp, sa);
09621          if (debug) {
09622             ast_verbose("Peer audio RTP is at port %s\n",
09623                    ast_sockaddr_stringify(sa));
09624          }
09625 
09626          ast_rtp_codecs_payloads_copy(&newaudiortp, ast_rtp_instance_get_codecs(p->rtp), p->rtp);
09627          /* Ensure RTCP is enabled since it may be inactive
09628             if we're coming back from a T.38 session */
09629          ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 1);
09630          /* Ensure audio RTCP reads are enabled */
09631          if (p->owner) {
09632             ast_channel_set_fd(p->owner, 1, ast_rtp_instance_fd(p->rtp, 1));
09633          }
09634 
09635          if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
09636             ast_clear_flag(&p->flags[0], SIP_DTMF);
09637             if (newnoncodeccapability & AST_RTP_DTMF) {
09638                /* XXX Would it be reasonable to drop the DSP at this point? XXX */
09639                ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
09640                /* Since RFC2833 is now negotiated we need to change some properties of the RTP stream */
09641                ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, 1);
09642                ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
09643             } else {
09644                ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
09645             }
09646          }
09647       } else if (udptlportno > 0) {
09648          if (debug)
09649             ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session.\n");
09650          /* Prevent audio RTCP reads */
09651          if (p->owner) {
09652             ast_channel_set_fd(p->owner, 1, -1);
09653          }
09654          /* Silence RTCP while audio RTP is inactive */
09655          ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 0);
09656       } else {
09657          ast_rtp_instance_stop(p->rtp);
09658          if (debug)
09659             ast_verbose("Peer doesn't provide audio\n");
09660       }
09661    }
09662 
09663    /* Setup video address and port */
09664    if (p->vrtp) {
09665       if (vsa && vportno > 0) {
09666          ast_sockaddr_set_port(vsa, vportno);
09667          ast_rtp_instance_set_remote_address(p->vrtp, vsa);
09668          if (debug) {
09669             ast_verbose("Peer video RTP is at port %s\n",
09670                    ast_sockaddr_stringify(vsa));
09671          }
09672          ast_rtp_codecs_payloads_copy(&newvideortp, ast_rtp_instance_get_codecs(p->vrtp), p->vrtp);
09673       } else {
09674          ast_rtp_instance_stop(p->vrtp);
09675          if (debug)
09676             ast_verbose("Peer doesn't provide video\n");
09677       }
09678    }
09679 
09680    /* Setup text address and port */
09681    if (p->trtp) {
09682       if (tsa && tportno > 0) {
09683          ast_sockaddr_set_port(tsa, tportno);
09684          ast_rtp_instance_set_remote_address(p->trtp, tsa);
09685          if (debug) {
09686             ast_verbose("Peer T.140 RTP is at port %s\n",
09687                    ast_sockaddr_stringify(tsa));
09688          }
09689          if ((p->jointcapability & AST_FORMAT_T140RED)) {
09690             p->red = 1;
09691             ast_rtp_red_init(p->trtp, 300, red_data_pt, 2);
09692          } else {
09693             p->red = 0;
09694          }
09695          ast_rtp_codecs_payloads_copy(&newtextrtp, ast_rtp_instance_get_codecs(p->trtp), p->trtp);
09696       } else {
09697          ast_rtp_instance_stop(p->trtp);
09698          if (debug)
09699             ast_verbose("Peer doesn't provide T.140\n");
09700       }
09701    }
09702 
09703    /* Setup image address and port */
09704    if (p->udptl) {
09705       if (isa && udptlportno > 0) {
09706          if (ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP) && ast_test_flag(&p->flags[1], SIP_PAGE2_UDPTL_DESTINATION)) {
09707             ast_rtp_instance_get_remote_address(p->rtp, isa);
09708             if (!ast_sockaddr_isnull(isa) && debug) {
09709                ast_debug(1, "Peer T.38 UDPTL is set behind NAT and with destination, destination address now %s\n", ast_sockaddr_stringify(isa));
09710             }
09711          }
09712          ast_sockaddr_set_port(isa, udptlportno);
09713          ast_udptl_set_peer(p->udptl, isa);
09714          if (debug)
09715             ast_debug(1,"Peer T.38 UDPTL is at port %s\n", ast_sockaddr_stringify(isa));
09716 
09717          /* verify the far max ifp can be calculated. this requires far max datagram to be set. */
09718          if (!ast_udptl_get_far_max_datagram(p->udptl)) {
09719             /* setting to zero will force a default if none was provided by the SDP */
09720             ast_udptl_set_far_max_datagram(p->udptl, 0);
09721          }
09722 
09723          /* Remote party offers T38, we need to update state */
09724          if ((t38action == SDP_T38_ACCEPT) &&
09725              (p->t38.state == T38_LOCAL_REINVITE)) {
09726             change_t38_state(p, T38_ENABLED);
09727          } else if ((t38action == SDP_T38_INITIATE) &&
09728                p->owner && p->lastinvite) {
09729             change_t38_state(p, T38_PEER_REINVITE); /* T38 Offered in re-invite from remote party */
09730             /* If fax detection is enabled then send us off to the fax extension */
09731             if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38)) {
09732                ast_channel_lock(p->owner);
09733                if (strcmp(p->owner->exten, "fax")) {
09734                   const char *target_context = S_OR(p->owner->macrocontext, p->owner->context);
09735                   ast_channel_unlock(p->owner);
09736                   if (ast_exists_extension(p->owner, target_context, "fax", 1,
09737                      S_COR(p->owner->caller.id.number.valid, p->owner->caller.id.number.str, NULL))) {
09738                      ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to peer T.38 re-INVITE\n", p->owner->name);
09739                      pbx_builtin_setvar_helper(p->owner, "FAXEXTEN", p->owner->exten);
09740                      if (ast_async_goto(p->owner, target_context, "fax", 1)) {
09741                         ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", p->owner->name, target_context);
09742                      }
09743                   } else {
09744                      ast_log(LOG_NOTICE, "T.38 re-INVITE detected but no fax extension\n");
09745                   }
09746                } else {
09747                   ast_channel_unlock(p->owner);
09748                }
09749             }
09750          }
09751       } else {
09752          change_t38_state(p, T38_DISABLED);
09753          ast_udptl_stop(p->udptl);
09754          if (debug)
09755             ast_debug(1, "Peer doesn't provide T.38 UDPTL\n");
09756       }
09757    }
09758 
09759    if ((portno == -1) && (p->t38.state != T38_DISABLED)) {
09760       ast_debug(3, "Have T.38 but no audio, accepting offer anyway\n");
09761       return 0;
09762         }
09763 
09764    /* Ok, we're going with this offer */
09765    ast_debug(2, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, p->jointcapability));
09766 
09767    if (!p->owner)    /* There's no open channel owning us so we can return here. For a re-invite or so, we proceed */
09768       return 0;
09769 
09770    ast_debug(4, "We have an owner, now see if we need to change this call\n");
09771 
09772    if (!(p->owner->nativeformats & p->jointcapability) && (p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
09773       if (debug) {
09774          char s1[SIPBUFSIZE], s2[SIPBUFSIZE];
09775          ast_debug(1, "Oooh, we need to change our audio formats since our peer supports only %s and not %s\n",
09776             ast_getformatname_multiple(s1, SIPBUFSIZE, p->jointcapability),
09777             ast_getformatname_multiple(s2, SIPBUFSIZE, p->owner->nativeformats));
09778       }
09779       p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1) | (p->capability & vpeercapability) | (p->capability & tpeercapability);
09780       ast_set_read_format(p->owner, p->owner->readformat);
09781       ast_set_write_format(p->owner, p->owner->writeformat);
09782    }
09783 
09784    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)) {
09785       ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
09786       /* Activate a re-invite */
09787       ast_queue_frame(p->owner, &ast_null_frame);
09788       change_hold_state(p, req, FALSE, sendonly);
09789    } 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)) {
09790       ast_queue_control_data(p->owner, AST_CONTROL_HOLD,
09791                    S_OR(p->mohsuggest, NULL),
09792                    !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
09793       if (sendonly)
09794          ast_rtp_instance_stop(p->rtp);
09795       /* RTCP needs to go ahead, even if we're on hold!!! */
09796       /* Activate a re-invite */
09797       ast_queue_frame(p->owner, &ast_null_frame);
09798       change_hold_state(p, req, TRUE, sendonly);
09799    }
09800 
09801    return 0;
09802 }
09803 
09804 static int process_sdp_o(const char *o, struct sip_pvt *p)
09805 {
09806    char *o_copy;
09807    char *token;
09808    int64_t rua_version;
09809 
09810    /* Store the SDP version number of remote UA. This will allow us to
09811    distinguish between session modifications and session refreshes. If
09812    the remote UA does not send an incremented SDP version number in a
09813    subsequent RE-INVITE then that means its not changing media session.
09814    The RE-INVITE may have been sent to update connected party, remote
09815    target or to refresh the session (Session-Timers).  Asterisk must not
09816    change media session and increment its own version number in answer
09817    SDP in this case. */
09818 
09819    p->session_modify = TRUE;
09820 
09821    if (ast_strlen_zero(o)) {
09822       ast_log(LOG_WARNING, "SDP syntax error. SDP without an o= line\n");
09823       return FALSE;
09824    }
09825 
09826    o_copy = ast_strdupa(o);
09827    token = strsep(&o_copy, " ");  /* Skip username   */
09828    if (!o_copy) {
09829       ast_log(LOG_WARNING, "SDP syntax error in o= line username\n");
09830       return FALSE;
09831    }
09832    token = strsep(&o_copy, " ");  /* Skip session-id */
09833    if (!o_copy) {
09834       ast_log(LOG_WARNING, "SDP syntax error in o= line session-id\n");
09835       return FALSE;
09836    }
09837    token = strsep(&o_copy, " ");  /* Version         */
09838    if (!o_copy) {
09839       ast_log(LOG_WARNING, "SDP syntax error in o= line\n");
09840       return FALSE;
09841    }
09842    if (!sscanf(token, "%30" SCNd64, &rua_version)) {
09843       ast_log(LOG_WARNING, "SDP syntax error in o= line version\n");
09844       return FALSE;
09845    }
09846 
09847    /* we need to check the SDP version number the other end sent us;
09848     * our rules for deciding what to accept are a bit complex.
09849     *
09850     * 1) if 'ignoresdpversion' has been set for this dialog, then
09851     *    we will just accept whatever they sent and assume it is
09852     *    a modification of the session, even if it is not
09853     * 2) otherwise, if this is the first SDP we've seen from them
09854     *    we accept it
09855     * 3) otherwise, if the new SDP version number is higher than the
09856     *    old one, we accept it
09857     * 4) otherwise, if this SDP is in response to us requesting a switch
09858     *    to T.38, we accept the SDP, but also generate a warning message
09859     *    that this peer should have the 'ignoresdpversion' option set,
09860     *    because it is not following the SDP offer/answer RFC; if we did
09861     *    not request a switch to T.38, then we stop parsing the SDP, as it
09862     *    has not changed from the previous version
09863     */
09864 
09865    if (ast_test_flag(&p->flags[1], SIP_PAGE2_IGNORESDPVERSION) ||
09866        (p->sessionversion_remote < 0) ||
09867        (p->sessionversion_remote < rua_version)) {
09868       p->sessionversion_remote = rua_version;
09869    } else {
09870       if (p->t38.state == T38_LOCAL_REINVITE) {
09871          p->sessionversion_remote = rua_version;
09872          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);
09873       } else {
09874          p->session_modify = FALSE;
09875          ast_debug(2, "Call %s responded to our reinvite without changing SDP version; ignoring SDP.\n", p->callid);
09876          return FALSE;
09877       }
09878    }
09879 
09880    return TRUE;
09881 }
09882 
09883 static int process_sdp_c(const char *c, struct ast_sockaddr *addr)
09884 {
09885    char proto[4], host[258];
09886    int af;
09887 
09888    /* Check for Media-description-level-address */
09889    if (sscanf(c, "IN %3s %255s", proto, host) == 2) {
09890       if (!strcmp("IP4", proto)) {
09891          af = AF_INET;
09892       } else if (!strcmp("IP6", proto)) {
09893          af = AF_INET6;
09894       } else {
09895          ast_log(LOG_WARNING, "Unknown protocol '%s'.\n", proto);
09896          return FALSE;
09897       }
09898       if (ast_sockaddr_resolve_first_af(addr, host, 0, af)) {
09899          ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in c= line, '%s'\n", c);
09900          return FALSE;
09901       }
09902       return TRUE;
09903    } else {
09904       ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
09905       return FALSE;
09906    }
09907    return FALSE;
09908 }
09909 
09910 static int process_sdp_a_sendonly(const char *a, int *sendonly)
09911 {
09912    int found = FALSE;
09913 
09914    if (!strcasecmp(a, "sendonly")) {
09915       if (*sendonly == -1)
09916          *sendonly = 1;
09917       found = TRUE;
09918    } else if (!strcasecmp(a, "inactive")) {
09919       if (*sendonly == -1)
09920          *sendonly = 2;
09921       found = TRUE;
09922    }  else if (!strcasecmp(a, "sendrecv")) {
09923       if (*sendonly == -1)
09924          *sendonly = 0;
09925       found = TRUE;
09926    }
09927    return found;
09928 }
09929 
09930 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec)
09931 {
09932    int found = FALSE;
09933    unsigned int codec;
09934    char mimeSubtype[128];
09935    char fmtp_string[64];
09936    unsigned int sample_rate;
09937    int debug = sip_debug_test_pvt(p);
09938 
09939    if (!strncasecmp(a, "ptime", 5)) {
09940       char *tmp = strrchr(a, ':');
09941       long int framing = 0;
09942       if (tmp) {
09943          tmp++;
09944          framing = strtol(tmp, NULL, 10);
09945          if (framing == LONG_MIN || framing == LONG_MAX) {
09946             framing = 0;
09947             ast_debug(1, "Can't read framing from SDP: %s\n", a);
09948          }
09949       }
09950       if (framing && p->autoframing) {
09951          struct ast_codec_pref *pref = &ast_rtp_instance_get_codecs(p->rtp)->pref;
09952          int codec_n;
09953          for (codec_n = 0; codec_n < AST_RTP_MAX_PT; codec_n++) {
09954             struct ast_rtp_payload_type format = ast_rtp_codecs_payload_lookup(ast_rtp_instance_get_codecs(p->rtp), codec_n);
09955             if (!format.asterisk_format || !format.code) /* non-codec or not found */
09956                continue;
09957             ast_debug(1, "Setting framing for %s to %ld\n", ast_getformatname(format.code), framing);
09958             ast_codec_pref_setsize(pref, format.code, framing);
09959          }
09960          ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, pref);
09961       }
09962       found = TRUE;
09963    } else if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
09964       /* We have a rtpmap to handle */
09965       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
09966          if (!(ast_rtp_codecs_payloads_set_rtpmap_type_rate(newaudiortp, NULL, codec, "audio", mimeSubtype,
09967              ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0, sample_rate))) {
09968             if (debug)
09969                ast_verbose("Found audio description format %s for ID %u\n", mimeSubtype, codec);
09970             //found_rtpmap_codecs[last_rtpmap_codec] = codec;
09971             (*last_rtpmap_codec)++;
09972             found = TRUE;
09973          } else {
09974             ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
09975             if (debug)
09976                ast_verbose("Found unknown media description format %s for ID %u\n", mimeSubtype, codec);
09977          }
09978       } else {
09979          if (debug)
09980             ast_verbose("Discarded description format %s for ID %u\n", mimeSubtype, codec);
09981       }
09982    } else if (sscanf(a, "fmtp: %30u %63[^\t\n]", &codec, fmtp_string) == 2) {
09983       struct ast_rtp_payload_type payload;
09984 
09985       payload = ast_rtp_codecs_payload_lookup(newaudiortp, codec);
09986       if (payload.code && payload.asterisk_format) {
09987          unsigned int bit_rate;
09988 
09989          switch (payload.code) {
09990          case AST_FORMAT_SIREN7:
09991             if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
09992                if (bit_rate != 32000) {
09993                   ast_log(LOG_WARNING, "Got Siren7 offer at %u bps, but only 32000 bps supported; ignoring.\n", bit_rate);
09994                   ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
09995                } else {
09996                   found = TRUE;
09997                }
09998             }
09999             break;
10000          case AST_FORMAT_SIREN14:
10001             if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
10002                if (bit_rate != 48000) {
10003                   ast_log(LOG_WARNING, "Got Siren14 offer at %u bps, but only 48000 bps supported; ignoring.\n", bit_rate);
10004                   ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
10005                } else {
10006                   found = TRUE;
10007                }
10008             }
10009             break;
10010          case AST_FORMAT_G719:
10011             if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
10012                if (bit_rate != 64000) {
10013                   ast_log(LOG_WARNING, "Got G.719 offer at %u bps, but only 64000 bps supported; ignoring.\n", bit_rate);
10014                   ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
10015                } else {
10016                   found = TRUE;
10017                }
10018             }
10019          }
10020       }
10021    }
10022 
10023    return found;
10024 }
10025 
10026 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec)
10027 {
10028    int found = FALSE;
10029    unsigned int codec;
10030    char mimeSubtype[128];
10031    unsigned int sample_rate;
10032    int debug = sip_debug_test_pvt(p);
10033 
10034    if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
10035       /* We have a rtpmap to handle */
10036       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
10037          /* Note: should really look at the '#chans' params too */
10038          if (!strncasecmp(mimeSubtype, "H26", 3) || !strncasecmp(mimeSubtype, "MP4", 3)) {
10039             if (!(ast_rtp_codecs_payloads_set_rtpmap_type_rate(newvideortp, NULL, codec, "video", mimeSubtype, 0, sample_rate))) {
10040                if (debug)
10041                   ast_verbose("Found video description format %s for ID %u\n", mimeSubtype, codec);
10042                //found_rtpmap_codecs[last_rtpmap_codec] = codec;
10043                (*last_rtpmap_codec)++;
10044                found = TRUE;
10045             } else {
10046                ast_rtp_codecs_payloads_unset(newvideortp, NULL, codec);
10047                if (debug)
10048                   ast_verbose("Found unknown media description format %s for ID %u\n", mimeSubtype, codec);
10049             }
10050          }
10051       } else {
10052          if (debug)
10053             ast_verbose("Discarded description format %s for ID %u\n", mimeSubtype, codec);
10054       }
10055    }
10056 
10057    return found;
10058 }
10059 
10060 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)
10061 {
10062    int found = FALSE;
10063    unsigned int codec;
10064    char mimeSubtype[128];
10065    unsigned int sample_rate;
10066    char *red_cp;
10067    int debug = sip_debug_test_pvt(p);
10068 
10069    if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
10070       /* We have a rtpmap to handle */
10071       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
10072          if (!strncasecmp(mimeSubtype, "T140", 4)) { /* Text */
10073             if (p->trtp) {
10074                /* ast_verbose("Adding t140 mimeSubtype to textrtp struct\n"); */
10075                ast_rtp_codecs_payloads_set_rtpmap_type_rate(newtextrtp, NULL, codec, "text", mimeSubtype, 0, sample_rate);
10076                found = TRUE;
10077             }
10078          } else if (!strncasecmp(mimeSubtype, "RED", 3)) { /* Text with Redudancy */
10079             if (p->trtp) {
10080                ast_rtp_codecs_payloads_set_rtpmap_type_rate(newtextrtp, NULL, codec, "text", mimeSubtype, 0, sample_rate);
10081                sprintf(red_fmtp, "fmtp:%u ", codec);
10082                if (debug)
10083                   ast_verbose("RED submimetype has payload type: %u\n", codec);
10084                found = TRUE;
10085             }
10086          }
10087       } else {
10088          if (debug)
10089             ast_verbose("Discarded description format %s for ID %u\n", mimeSubtype, codec);
10090       }
10091    } else if (!strncmp(a, red_fmtp, strlen(red_fmtp))) {
10092       /* count numbers of generations in fmtp */
10093       red_cp = &red_fmtp[strlen(red_fmtp)];
10094       strncpy(red_fmtp, a, 100);
10095 
10096       sscanf(red_cp, "%30u", (unsigned *)&red_data_pt[*red_num_gen]);
10097       red_cp = strtok(red_cp, "/");
10098       while (red_cp && (*red_num_gen)++ < AST_RED_MAX_GENERATION) {
10099          sscanf(red_cp, "%30u", (unsigned *)&red_data_pt[*red_num_gen]);
10100          red_cp = strtok(NULL, "/");
10101       }
10102       red_cp = red_fmtp;
10103       found = TRUE;
10104    }
10105 
10106    return found;
10107 }
10108 
10109 static int process_sdp_a_image(const char *a, struct sip_pvt *p)
10110 {
10111    int found = FALSE;
10112    char s[256];
10113    unsigned int x;
10114    char *attrib = ast_strdupa(a);
10115    char *pos;
10116 
10117    if (initialize_udptl(p)) {
10118       return found;
10119    }
10120 
10121    /* Due to a typo in an IANA registration of one of the T.38 attributes,
10122     * RFC5347 section 2.5.2 recommends that all T.38 attributes be parsed in
10123     * a case insensitive manner. Hence, the importance of proof reading (and
10124     * code reviews).
10125     */
10126    for (pos = attrib; *pos; ++pos) {
10127       *pos = tolower(*pos);
10128    }
10129 
10130    if ((sscanf(attrib, "t38faxmaxbuffer:%30u", &x) == 1)) {
10131       ast_debug(3, "MaxBufferSize:%u\n", x);
10132       found = TRUE;
10133    } else if ((sscanf(attrib, "t38maxbitrate:%30u", &x) == 1) || (sscanf(attrib, "t38faxmaxrate:%30u", &x) == 1)) {
10134       ast_debug(3, "T38MaxBitRate: %u\n", x);
10135       switch (x) {
10136       case 14400:
10137          p->t38.their_parms.rate = AST_T38_RATE_14400;
10138          break;
10139       case 12000:
10140          p->t38.their_parms.rate = AST_T38_RATE_12000;
10141          break;
10142       case 9600:
10143          p->t38.their_parms.rate = AST_T38_RATE_9600;
10144          break;
10145       case 7200:
10146          p->t38.their_parms.rate = AST_T38_RATE_7200;
10147          break;
10148       case 4800:
10149          p->t38.their_parms.rate = AST_T38_RATE_4800;
10150          break;
10151       case 2400:
10152          p->t38.their_parms.rate = AST_T38_RATE_2400;
10153          break;
10154       }
10155       found = TRUE;
10156    } else if ((sscanf(attrib, "t38faxversion:%30u", &x) == 1)) {
10157       ast_debug(3, "FaxVersion: %u\n", x);
10158       p->t38.their_parms.version = x;
10159       found = TRUE;
10160    } else if ((sscanf(attrib, "t38faxmaxdatagram:%30u", &x) == 1) || (sscanf(attrib, "t38maxdatagram:%30u", &x) == 1)) {
10161       /* override the supplied value if the configuration requests it */
10162       if (((signed int) p->t38_maxdatagram >= 0) && ((unsigned int) p->t38_maxdatagram > x)) {
10163          ast_debug(1, "Overriding T38FaxMaxDatagram '%u' with '%u'\n", x, p->t38_maxdatagram);
10164          x = p->t38_maxdatagram;
10165       }
10166       ast_debug(3, "FaxMaxDatagram: %u\n", x);
10167       ast_udptl_set_far_max_datagram(p->udptl, x);
10168       found = TRUE;
10169    } else if ((strncmp(attrib, "t38faxfillbitremoval", 20) == 0)) {
10170       if (sscanf(attrib, "t38faxfillbitremoval:%30u", &x) == 1) {
10171          ast_debug(3, "FillBitRemoval: %u\n", x);
10172          if (x == 1) {
10173             p->t38.their_parms.fill_bit_removal = TRUE;
10174          }
10175       } else {
10176          ast_debug(3, "FillBitRemoval\n");
10177          p->t38.their_parms.fill_bit_removal = TRUE;
10178       }
10179       found = TRUE;
10180    } else if ((strncmp(attrib, "t38faxtranscodingmmr", 20) == 0)) {
10181       if (sscanf(attrib, "t38faxtranscodingmmr:%30u", &x) == 1) {
10182          ast_debug(3, "Transcoding MMR: %u\n", x);
10183          if (x == 1) {
10184             p->t38.their_parms.transcoding_mmr = TRUE;
10185          }
10186       } else {
10187          ast_debug(3, "Transcoding MMR\n");
10188          p->t38.their_parms.transcoding_mmr = TRUE;
10189       }
10190       found = TRUE;
10191    } else if ((strncmp(attrib, "t38faxtranscodingjbig", 21) == 0)) {
10192       if (sscanf(attrib, "t38faxtranscodingjbig:%30u", &x) == 1) {
10193          ast_debug(3, "Transcoding JBIG: %u\n", x);
10194          if (x == 1) {
10195             p->t38.their_parms.transcoding_jbig = TRUE;
10196          }
10197       } else {
10198          ast_debug(3, "Transcoding JBIG\n");
10199          p->t38.their_parms.transcoding_jbig = TRUE;
10200       }
10201       found = TRUE;
10202    } else if ((sscanf(attrib, "t38faxratemanagement:%255s", s) == 1)) {
10203       ast_debug(3, "RateManagement: %s\n", s);
10204       if (!strcasecmp(s, "localTCF"))
10205          p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_LOCAL_TCF;
10206       else if (!strcasecmp(s, "transferredTCF"))
10207          p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF;
10208       found = TRUE;
10209    } else if ((sscanf(attrib, "t38faxudpec:%255s", s) == 1)) {
10210       ast_debug(3, "UDP EC: %s\n", s);
10211       if (!strcasecmp(s, "t38UDPRedundancy")) {
10212          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
10213       } else if (!strcasecmp(s, "t38UDPFEC")) {
10214          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
10215       } else {
10216          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
10217       }
10218       found = TRUE;
10219    }
10220 
10221    return found;
10222 }
10223 
10224 /*! \brief Add "Supported" header to sip message.  Since some options may
10225  *  be disabled in the config, the sip_pvt must be inspected to determine what
10226  *  is supported for this dialog. */
10227 static int add_supported_header(struct sip_pvt *pvt, struct sip_request *req)
10228 {
10229    int res;
10230    if (st_get_mode(pvt, 0) != SESSION_TIMER_MODE_REFUSE) {
10231       res = add_header(req, "Supported", "replaces, timer");
10232    } else {
10233       res = add_header(req, "Supported", "replaces");
10234    }
10235    return res;
10236 }
10237 
10238 /*! \brief Add header to SIP message */
10239 static int add_header(struct sip_request *req, const char *var, const char *value)
10240 {
10241    if (req->headers == SIP_MAX_HEADERS) {
10242       ast_log(LOG_WARNING, "Out of SIP header space\n");
10243       return -1;
10244    }
10245 
10246    if (req->lines) {
10247       ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
10248       return -1;
10249    }
10250 
10251    if (sip_cfg.compactheaders) {
10252       var = find_alias(var, var);
10253    }
10254 
10255    ast_str_append(&req->data, 0, "%s: %s\r\n", var, value);
10256    req->header[req->headers] = ast_str_strlen(req->data);
10257 
10258    req->headers++;
10259 
10260    return 0;   
10261 }
10262 
10263 /*! 
10264  * \pre dialog is assumed to be locked while calling this function
10265  * \brief Add 'Max-Forwards' header to SIP message 
10266  */
10267 static int add_header_max_forwards(struct sip_pvt *dialog, struct sip_request *req)
10268 {
10269    char clen[10];
10270 
10271    snprintf(clen, sizeof(clen), "%d", dialog->maxforwards);
10272 
10273    return add_header(req, "Max-Forwards", clen);
10274 }
10275 
10276 /*! \brief Add 'Content-Length' header and content to SIP message */
10277 static int finalize_content(struct sip_request *req)
10278 {
10279    char clen[10];
10280 
10281    if (req->lines) {
10282       ast_log(LOG_WARNING, "finalize_content() called on a message that has already been finalized\n");
10283       return -1;
10284    }
10285 
10286    snprintf(clen, sizeof(clen), "%zu", ast_str_strlen(req->content));
10287    add_header(req, "Content-Length", clen);
10288 
10289    if (ast_str_strlen(req->content)) {
10290       ast_str_append(&req->data, 0, "\r\n%s", ast_str_buffer(req->content));
10291    }
10292    req->lines = ast_str_strlen(req->content) ? 1 : 0;
10293    return 0;
10294 }
10295 
10296 /*! \brief Add content (not header) to SIP message */
10297 static int add_content(struct sip_request *req, const char *line)
10298 {
10299    if (req->lines) {
10300       ast_log(LOG_WARNING, "Can't add more content when the content has been finalized\n");
10301       return -1;
10302    }
10303 
10304    ast_str_append(&req->content, 0, "%s", line);
10305    return 0;
10306 }
10307 
10308 /*! \brief Copy one header field from one request to another */
10309 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
10310 {
10311    const char *tmp = get_header(orig, field);
10312 
10313    if (!ast_strlen_zero(tmp)) /* Add what we're responding to */
10314       return add_header(req, field, tmp);
10315    ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
10316    return -1;
10317 }
10318 
10319 /*! \brief Copy all headers from one request to another */
10320 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
10321 {
10322    int start = 0;
10323    int copied = 0;
10324    for (;;) {
10325       const char *tmp = __get_header(orig, field, &start);
10326 
10327       if (ast_strlen_zero(tmp))
10328          break;
10329       /* Add what we're responding to */
10330       add_header(req, field, tmp);
10331       copied++;
10332    }
10333    return copied ? 0 : -1;
10334 }
10335 
10336 /*! \brief Copy SIP VIA Headers from the request to the response
10337 \note If the client indicates that it wishes to know the port we received from,
10338    it adds ;rport without an argument to the topmost via header. We need to
10339    add the port number (from our point of view) to that parameter.
10340 \verbatim
10341    We always add ;received=<ip address> to the topmost via header.
10342 \endverbatim
10343    Received: RFC 3261, rport RFC 3581 */
10344 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
10345 {
10346    int copied = 0;
10347    int start = 0;
10348 
10349    for (;;) {
10350       char new[512];
10351       const char *oh = __get_header(orig, field, &start);
10352 
10353       if (ast_strlen_zero(oh))
10354          break;
10355 
10356       if (!copied) { /* Only check for empty rport in topmost via header */
10357          char leftmost[512], *others, *rport;
10358 
10359          /* Only work on leftmost value */
10360          ast_copy_string(leftmost, oh, sizeof(leftmost));
10361          others = strchr(leftmost, ',');
10362          if (others)
10363              *others++ = '\0';
10364 
10365          /* Find ;rport;  (empty request) */
10366          rport = strstr(leftmost, ";rport");
10367          if (rport && *(rport+6) == '=')
10368             rport = NULL;     /* We already have a parameter to rport */
10369 
10370          if (((ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT)) || (rport && ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)))) {
10371             /* We need to add received port - rport */
10372             char *end;
10373 
10374             rport = strstr(leftmost, ";rport");
10375 
10376             if (rport) {
10377                end = strchr(rport + 1, ';');
10378                if (end)
10379                   memmove(rport, end, strlen(end) + 1);
10380                else
10381                   *rport = '\0';
10382             }
10383 
10384             /* Add rport to first VIA header if requested */
10385             snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
10386                leftmost, ast_sockaddr_stringify_addr_remote(&p->recv),
10387                ast_sockaddr_port(&p->recv),
10388                others ? "," : "", others ? others : "");
10389          } else {
10390             /* We should *always* add a received to the topmost via */
10391             snprintf(new, sizeof(new), "%s;received=%s%s%s",
10392                leftmost, ast_sockaddr_stringify_addr_remote(&p->recv),
10393                others ? "," : "", others ? others : "");
10394          }
10395          oh = new;   /* the header to copy */
10396       }  /* else add the following via headers untouched */
10397       add_header(req, field, oh);
10398       copied++;
10399    }
10400    if (!copied) {
10401       ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
10402       return -1;
10403    }
10404    return 0;
10405 }
10406 
10407 /*! \brief Add route header into request per learned route */
10408 static void add_route(struct sip_request *req, struct sip_route *route)
10409 {
10410    char r[SIPBUFSIZE*2], *p;
10411    int n, rem = sizeof(r);
10412 
10413    if (!route)
10414       return;
10415 
10416    p = r;
10417    for (;route ; route = route->next) {
10418       n = strlen(route->hop);
10419       if (rem < n+3) /* we need room for ",<route>" */
10420          break;
10421       if (p != r) {  /* add a separator after fist route */
10422          *p++ = ',';
10423          --rem;
10424       }
10425       *p++ = '<';
10426       ast_copy_string(p, route->hop, rem); /* cannot fail */
10427       p += n;
10428       *p++ = '>';
10429       rem -= (n+2);
10430    }
10431    *p = '\0';
10432    add_header(req, "Route", r);
10433 }
10434 
10435 /*! \brief Set destination from SIP URI
10436  *
10437  * Parse uri to h (host) and port - uri is already just the part inside the <>
10438  * general form we are expecting is sip[s]:username[:password][;parameter]@host[:port][;...]
10439  * If there's a port given, turn NAPTR/SRV off. NAPTR might indicate SIPS preference even
10440  * for SIP: uri's
10441  *
10442  * If there's a sips: uri scheme, TLS will be required.
10443  */
10444 static void set_destination(struct sip_pvt *p, char *uri)
10445 {
10446    char *h, *maddr, hostname[256];
10447    int hn;
10448    int debug=sip_debug_test_pvt(p);
10449    int tls_on = FALSE;
10450 
10451    if (debug)
10452       ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
10453 
10454    /* Find and parse hostname */
10455    h = strchr(uri, '@');
10456    if (h)
10457       ++h;
10458    else {
10459       h = uri;
10460       if (!strncasecmp(h, "sip:", 4)) {
10461          h += 4;
10462       } else if (!strncasecmp(h, "sips:", 5)) {
10463          h += 5;
10464          tls_on = TRUE;
10465       }
10466    }
10467    hn = strcspn(h, ";>") + 1;
10468    if (hn > sizeof(hostname))
10469       hn = sizeof(hostname);
10470    ast_copy_string(hostname, h, hn);
10471    /* XXX bug here if string has been trimmed to sizeof(hostname) */
10472    h += hn - 1;
10473 
10474    /*! \todo XXX If we have sip_cfg.srvlookup on, then look for NAPTR/SRV,
10475     * otherwise, just look for A records */
10476    if (ast_sockaddr_resolve_first_transport(&p->sa, hostname, 0, p->socket.type)) {
10477       ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
10478       return;
10479    }
10480 
10481    /* Got the hostname - but maybe there's a "maddr=" to override address? */
10482    maddr = strstr(h, "maddr=");
10483    if (maddr) {
10484       int port;
10485 
10486       maddr += 6;
10487       hn = strspn(maddr, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
10488                     "0123456789-.:[]") + 1;
10489       if (hn > sizeof(hostname))
10490          hn = sizeof(hostname);
10491       ast_copy_string(hostname, maddr, hn);
10492 
10493       port = ast_sockaddr_port(&p->sa);
10494 
10495       /*! \todo XXX If we have sip_cfg.srvlookup on, then look for
10496        * NAPTR/SRV, otherwise, just look for A records */
10497       if (ast_sockaddr_resolve_first_transport(&p->sa, hostname, PARSE_PORT_FORBID, p->socket.type)) {
10498          ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
10499          return;
10500       }
10501 
10502       ast_sockaddr_set_port(&p->sa, port);
10503    }
10504 
10505    if (!ast_sockaddr_port(&p->sa)) {
10506       ast_sockaddr_set_port(&p->sa, tls_on ?
10507                   STANDARD_TLS_PORT : STANDARD_SIP_PORT);
10508    }
10509 
10510    if (debug) {
10511       ast_verbose("set_destination: set destination to %s\n",
10512              ast_sockaddr_stringify(&p->sa));
10513    }
10514 }
10515 
10516 /*! \brief Initialize SIP response, based on SIP request */
10517 static int init_resp(struct sip_request *resp, const char *msg)
10518 {
10519    /* Initialize a response */
10520    memset(resp, 0, sizeof(*resp));
10521    resp->method = SIP_RESPONSE;
10522    if (!(resp->data = ast_str_create(SIP_MIN_PACKET)))
10523       goto e_return;
10524    if (!(resp->content = ast_str_create(SIP_MIN_PACKET)))
10525       goto e_free_data;
10526    resp->header[0] = 0;
10527    ast_str_set(&resp->data, 0, "SIP/2.0 %s\r\n", msg);
10528    resp->headers++;
10529    return 0;
10530 
10531 e_free_data:
10532    ast_free(resp->data);
10533    resp->data = NULL;
10534 e_return:
10535    return -1;
10536 }
10537 
10538 /*! \brief Initialize SIP request */
10539 static int init_req(struct sip_request *req, int sipmethod, const char *recip)
10540 {
10541    /* Initialize a request */
10542    memset(req, 0, sizeof(*req));
10543    if (!(req->data = ast_str_create(SIP_MIN_PACKET)))
10544       goto e_return;
10545    if (!(req->content = ast_str_create(SIP_MIN_PACKET)))
10546       goto e_free_data;
10547    req->method = sipmethod;
10548    req->header[0] = 0;
10549    ast_str_set(&req->data, 0, "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
10550    req->headers++;
10551    return 0;
10552 
10553 e_free_data:
10554    ast_free(req->data);
10555    req->data = NULL;
10556 e_return:
10557    return -1;
10558 }
10559 
10560 /*! \brief Deinitialize SIP response/request */
10561 static void deinit_req(struct sip_request *req)
10562 {
10563    if (req->data) {
10564       ast_free(req->data);
10565       req->data = NULL;
10566    }
10567    if (req->content) {
10568       ast_free(req->content);
10569       req->content = NULL;
10570    }
10571 }
10572 
10573 
10574 /*! \brief Test if this response needs a contact header */
10575 static inline int resp_needs_contact(const char *msg, enum sipmethod method) {
10576    /* Requirements for Contact header inclusion in responses generated
10577     * from the header tables found in the following RFCs.  Where the
10578     * Contact header was marked mandatory (m) or optional (o) this
10579     * function returns 1.
10580     *
10581     * - RFC 3261 (ACK, BYE, CANCEL, INVITE, OPTIONS, REGISTER)
10582     * - RFC 2976 (INFO)
10583     * - RFC 3262 (PRACK)
10584     * - RFC 3265 (SUBSCRIBE, NOTIFY)
10585     * - RFC 3311 (UPDATE)
10586     * - RFC 3428 (MESSAGE)
10587     * - RFC 3515 (REFER)
10588     * - RFC 3903 (PUBLISH)
10589     */
10590 
10591    switch (method) {
10592       /* 1xx, 2xx, 3xx, 485 */
10593       case SIP_INVITE:
10594       case SIP_UPDATE:
10595       case SIP_SUBSCRIBE:
10596       case SIP_NOTIFY:
10597          if ((msg[0] >= '1' && msg[0] <= '3') || !strncmp(msg, "485", 3))
10598             return 1;
10599          break;
10600 
10601       /* 2xx, 3xx, 485 */
10602       case SIP_REGISTER:
10603       case SIP_OPTIONS:
10604          if (msg[0] == '2' || msg[0] == '3' || !strncmp(msg, "485", 3))
10605             return 1;
10606          break;
10607 
10608       /* 3xx, 485 */
10609       case SIP_BYE:
10610       case SIP_PRACK:
10611       case SIP_MESSAGE:
10612       case SIP_PUBLISH:
10613          if (msg[0] == '3' || !strncmp(msg, "485", 3))
10614             return 1;
10615          break;
10616 
10617       /* 2xx, 3xx, 4xx, 5xx, 6xx */
10618       case SIP_REFER:
10619          if (msg[0] >= '2' && msg[0] <= '6')
10620             return 1;
10621          break;
10622 
10623       /* contact will not be included for everything else */
10624       case SIP_ACK:
10625       case SIP_CANCEL:
10626       case SIP_INFO:
10627       case SIP_PING:
10628       default:
10629          return 0;
10630    }
10631    return 0;
10632 }
10633 
10634 /*! \brief Prepare SIP response packet */
10635 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
10636 {
10637    char newto[256];
10638    const char *ot;
10639 
10640    init_resp(resp, msg);
10641    copy_via_headers(p, resp, req, "Via");
10642    if (msg[0] == '1' || msg[0] == '2')
10643       copy_all_header(resp, req, "Record-Route");
10644    copy_header(resp, req, "From");
10645    ot = get_header(req, "To");
10646    if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
10647       /* Add the proper tag if we don't have it already.  If they have specified
10648          their tag, use it.  Otherwise, use our own tag */
10649       if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
10650          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
10651       else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
10652          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
10653       else
10654          ast_copy_string(newto, ot, sizeof(newto));
10655       ot = newto;
10656    }
10657    add_header(resp, "To", ot);
10658    copy_header(resp, req, "Call-ID");
10659    copy_header(resp, req, "CSeq");
10660    if (!ast_strlen_zero(global_useragent))
10661       add_header(resp, "Server", global_useragent);
10662    add_header(resp, "Allow", ALLOWED_METHODS);
10663    add_supported_header(p, resp);
10664 
10665    /* If this is an invite, add Session-Timers related headers if the feature is active for this session */
10666    if (p->method == SIP_INVITE && p->stimer && p->stimer->st_active == TRUE) {
10667       char se_hdr[256];
10668       snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
10669          p->stimer->st_ref == SESSION_TIMER_REFRESHER_US ? "uas" : "uac");
10670       add_header(resp, "Session-Expires", se_hdr);
10671       /* RFC 2048, Section 9
10672        * If the refresher parameter in the Session-Expires header field in the
10673        * 2xx response has a value of 'uac', the UAS MUST place a Require
10674        * header field into the response with the value 'timer'.
10675        * ...
10676        * If the refresher parameter in
10677        * the 2xx response has a value of 'uas' and the Supported header field
10678        * in the request contained the value 'timer', the UAS SHOULD place a
10679        * Require header field into the response with the value 'timer'
10680        */
10681       if (p->stimer->st_ref == SESSION_TIMER_REFRESHER_THEM ||
10682             (p->stimer->st_ref == SESSION_TIMER_REFRESHER_US &&
10683              p->stimer->st_active_peer_ua == TRUE)) {
10684          resp->reqsipoptions |= SIP_OPT_TIMER;
10685       }
10686    }
10687 
10688    if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_PUBLISH)) {
10689       /* For registration responses, we also need expiry and
10690          contact info */
10691       char tmp[256];
10692 
10693       snprintf(tmp, sizeof(tmp), "%d", p->expiry);
10694       add_header(resp, "Expires", tmp);
10695       if (p->expiry) {  /* Only add contact if we have an expiry time */
10696          char contact[SIPBUFSIZE];
10697          const char *contact_uri = p->method == SIP_SUBSCRIBE ? p->our_contact : p->fullcontact;
10698          char *brackets = strchr(contact_uri, '<');
10699          snprintf(contact, sizeof(contact), "%s%s%s;expires=%d", brackets ? "" : "<", contact_uri, brackets ? "" : ">", p->expiry);
10700          add_header(resp, "Contact", contact);  /* Not when we unregister */
10701       }
10702    } else if (!ast_strlen_zero(p->our_contact) && resp_needs_contact(msg, p->method)) {
10703       add_header(resp, "Contact", p->our_contact);
10704    }
10705 
10706    if (!ast_strlen_zero(p->url)) {
10707       add_header(resp, "Access-URL", p->url);
10708       ast_string_field_set(p, url, NULL);
10709    }
10710 
10711    /* default to routing the response to the address where the request
10712     * came from.  Since we don't have a transport layer, we do this here.
10713     * The process_via() function will update the port to either the port
10714     * specified in the via header or the default port later on (per RFC
10715     * 3261 section 18.2.2).
10716     */
10717    p->sa = p->recv;
10718 
10719    if (process_via(p, req)) {
10720       ast_log(LOG_WARNING, "error processing via header, will send response to originating address\n");
10721    }
10722 
10723    return 0;
10724 }
10725 
10726 /*! \brief Initialize a SIP request message (not the initial one in a dialog) */
10727 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, uint32_t seqno, int newbranch)
10728 {
10729    struct sip_request *orig = &p->initreq;
10730    char stripped[80];
10731    char tmp[80];
10732    char newto[256];
10733    const char *c;
10734    const char *ot, *of;
10735    int is_strict = FALSE;     /*!< Strict routing flag */
10736    int is_outbound = ast_test_flag(&p->flags[0], SIP_OUTGOING);   /* Session direction */
10737 
10738    snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
10739    
10740    if (!seqno) {
10741       p->ocseq++;
10742       seqno = p->ocseq;
10743    }
10744    
10745    /* A CANCEL must have the same branch as the INVITE that it is canceling. */
10746    if (sipmethod == SIP_CANCEL) {
10747       p->branch = p->invite_branch;
10748       build_via(p);
10749    } else if (newbranch && (sipmethod == SIP_INVITE)) {
10750       p->branch ^= ast_random();
10751       p->invite_branch = p->branch;
10752       build_via(p);
10753    } else if (newbranch) {
10754       p->branch ^= ast_random();
10755       build_via(p);
10756    }
10757 
10758    /* Check for strict or loose router */
10759    if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop, ";lr") == NULL) {
10760       is_strict = TRUE;
10761       if (sipdebug)
10762          ast_debug(1, "Strict routing enforced for session %s\n", p->callid);
10763    }
10764    
10765    if (sipmethod == SIP_CANCEL)
10766       c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2); /* Use original URI */
10767    else if (sipmethod == SIP_ACK) {
10768       /* Use URI from Contact: in 200 OK (if INVITE)
10769       (we only have the contacturi on INVITEs) */
10770       if (!ast_strlen_zero(p->okcontacturi))
10771          c = is_strict ? p->route->hop : p->okcontacturi;
10772       else
10773          c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
10774    } else if (!ast_strlen_zero(p->okcontacturi))
10775       c = is_strict ? p->route->hop : p->okcontacturi; /* Use for BYE or REINVITE */
10776    else if (!ast_strlen_zero(p->uri))
10777       c = p->uri;
10778    else {
10779       char *n;
10780       /* We have no URI, use To: or From:  header as URI (depending on direction) */
10781       ast_copy_string(stripped, get_header(orig, is_outbound ? "To" : "From"),
10782             sizeof(stripped));
10783       n = get_in_brackets(stripped);
10784       c = remove_uri_parameters(n);
10785    }  
10786    init_req(req, sipmethod, c);
10787 
10788    snprintf(tmp, sizeof(tmp), "%u %s", seqno, sip_methods[sipmethod].text);
10789 
10790    add_header(req, "Via", p->via);
10791    /*
10792     * Use the learned route set unless this is a CANCEL on an ACK for a non-2xx
10793     * final response. For a CANCEL or ACK, we have to send to the same destination
10794     * as the original INVITE.
10795     */
10796    if (p->route &&
10797          !(sipmethod == SIP_CANCEL ||
10798             (sipmethod == SIP_ACK && (p->invitestate == INV_COMPLETED || p->invitestate == INV_CANCELLED)))) {
10799       set_destination(p, p->route->hop);
10800       add_route(req, is_strict ? p->route->next : p->route);
10801    }
10802    add_header_max_forwards(p, req);
10803 
10804    ot = get_header(orig, "To");
10805    of = get_header(orig, "From");
10806 
10807    /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
10808       as our original request, including tag (or presumably lack thereof) */
10809    if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
10810       /* Add the proper tag if we don't have it already.  If they have specified
10811          their tag, use it.  Otherwise, use our own tag */
10812       if (is_outbound && !ast_strlen_zero(p->theirtag))
10813          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
10814       else if (!is_outbound)
10815          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
10816       else
10817          snprintf(newto, sizeof(newto), "%s", ot);
10818       ot = newto;
10819    }
10820 
10821    if (is_outbound) {
10822       add_header(req, "From", of);
10823       add_header(req, "To", ot);
10824    } else {
10825       add_header(req, "From", ot);
10826       add_header(req, "To", of);
10827    }
10828    /* Do not add Contact for MESSAGE, BYE and Cancel requests */
10829    if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
10830       add_header(req, "Contact", p->our_contact);
10831 
10832    copy_header(req, orig, "Call-ID");
10833    add_header(req, "CSeq", tmp);
10834 
10835    if (!ast_strlen_zero(global_useragent))
10836       add_header(req, "User-Agent", global_useragent);
10837 
10838    if (!ast_strlen_zero(p->url)) {
10839       add_header(req, "Access-URL", p->url);
10840       ast_string_field_set(p, url, NULL);
10841    }
10842 
10843    /* Add Session-Timers related headers if the feature is active for this session.
10844       An exception to this behavior is the ACK request. Since Asterisk never requires
10845       session-timers support from a remote end-point (UAS) in an INVITE, it must
10846       not send 'Require: timer' header in the ACK request.
10847       This should only be added in the INVITE transactions, not MESSAGE or REFER or other
10848       in-dialog messages.
10849    */
10850    if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE
10851        && sipmethod == SIP_INVITE) {
10852       char se_hdr[256];
10853       snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
10854          p->stimer->st_ref == SESSION_TIMER_REFRESHER_US ? "uac" : "uas");
10855       add_header(req, "Session-Expires", se_hdr);
10856       snprintf(se_hdr, sizeof(se_hdr), "%d", st_get_se(p, FALSE));
10857       add_header(req, "Min-SE", se_hdr);
10858    }
10859 
10860    return 0;
10861 }
10862 
10863 /*! \brief Base transmit response function */
10864 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
10865 {
10866    struct sip_request resp;
10867    uint32_t seqno = 0;
10868 
10869    if (reliable && (sscanf(get_header(req, "CSeq"), "%30u ", &seqno) != 1)) {
10870       ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
10871       return -1;
10872    }
10873    respprep(&resp, p, msg, req);
10874 
10875    if (ast_test_flag(&p->flags[0], SIP_SENDRPID)
10876          && ast_test_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND)
10877          && (!strncmp(msg, "180", 3) || !strncmp(msg, "183", 3))) {
10878       ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
10879       add_rpid(&resp, p);
10880    }
10881    if (ast_test_flag(&p->flags[0], SIP_OFFER_CC)) {
10882       add_cc_call_info_to_response(p, &resp);
10883    }
10884 
10885    /* If we are sending a 302 Redirect we can add a diversion header if the redirect information is set */
10886    if (!strncmp(msg, "302", 3)) {
10887       add_diversion_header(&resp, p);
10888    }
10889 
10890    /* If we are cancelling an incoming invite for some reason, add information
10891       about the reason why we are doing this in clear text */
10892    if (p->method == SIP_INVITE && msg[0] != '1') {
10893       char buf[20];
10894 
10895       if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON)) {
10896          int hangupcause = 0;
10897 
10898          if (p->owner && p->owner->hangupcause) {
10899             hangupcause = p->owner->hangupcause;
10900          } else if (p->hangupcause) {
10901             hangupcause = p->hangupcause;
10902          } else {
10903             int respcode;
10904             if (sscanf(msg, "%30d ", &respcode))
10905                hangupcause = hangup_sip2cause(respcode);
10906          }
10907 
10908          if (hangupcause) {
10909             sprintf(buf, "Q.850;cause=%i", hangupcause & 0x7f);
10910             add_header(&resp, "Reason", buf);
10911          }
10912       }
10913 
10914       if (p->owner && p->owner->hangupcause) {
10915          add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
10916          snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
10917          add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
10918       }
10919    }
10920    return send_response(p, &resp, reliable, seqno);
10921 }
10922 
10923 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)
10924 {
10925    struct sip_request resp;
10926 
10927    if (need_new_etag) {
10928       create_new_sip_etag(esc_entry, 1);
10929    }
10930    respprep(&resp, p, msg, req);
10931    add_header(&resp, "SIP-ETag", esc_entry->entity_tag);
10932 
10933    return send_response(p, &resp, 0, 0);
10934 }
10935 
10936 static int temp_pvt_init(void *data)
10937 {
10938    struct sip_pvt *p = data;
10939 
10940    p->do_history = 0;   /* XXX do we need it ? isn't already all 0 ? */
10941    return ast_string_field_init(p, 512);
10942 }
10943 
10944 static void temp_pvt_cleanup(void *data)
10945 {
10946    struct sip_pvt *p = data;
10947 
10948    ast_string_field_free_memory(p);
10949 
10950    ast_free(data);
10951 }
10952 
10953 /*! \brief Transmit response, no retransmits, using a temporary pvt structure */
10954 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)
10955 {
10956    struct sip_pvt *p = NULL;
10957 
10958    if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
10959       ast_log(LOG_ERROR, "Failed to get temporary pvt\n");
10960       return -1;
10961    }
10962 
10963    /* XXX the structure may be dirty from previous usage.
10964     * Here we should state clearly how we should reinitialize it
10965     * before using it.
10966     * E.g. certainly the threadstorage should be left alone,
10967     * but other thihngs such as flags etc. maybe need cleanup ?
10968     */
10969 
10970    /* Initialize the bare minimum */
10971    p->method = intended_method;
10972 
10973    if (!addr) {
10974       ast_sockaddr_copy(&p->ourip, &internip);
10975    } else {
10976       ast_sockaddr_copy(&p->sa, addr);
10977       ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
10978    }
10979 
10980    p->branch = ast_random();
10981    make_our_tag(p);
10982    p->ocseq = INITIAL_CSEQ;
10983 
10984    if (useglobal_nat && addr) {
10985       ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT_FORCE_RPORT);
10986       ast_sockaddr_copy(&p->recv, addr);
10987       do_setnat(p);
10988    }
10989 
10990    ast_string_field_set(p, fromdomain, default_fromdomain);
10991    p->fromdomainport = default_fromdomainport;
10992    build_via(p);
10993    ast_string_field_set(p, callid, callid);
10994 
10995    copy_socket_data(&p->socket, &req->socket);
10996 
10997    /* Use this temporary pvt structure to send the message */
10998    __transmit_response(p, msg, req, XMIT_UNRELIABLE);
10999 
11000    /* Free the string fields, but not the pool space */
11001    ast_string_field_init(p, 0);
11002 
11003    return 0;
11004 }
11005 
11006 /*! \brief Transmit response, no retransmits */
11007 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req)
11008 {
11009    return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
11010 }
11011 
11012 /*! \brief Transmit response, no retransmits */
11013 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported)
11014 {
11015    struct sip_request resp;
11016    respprep(&resp, p, msg, req);
11017    append_date(&resp);
11018    add_header(&resp, "Unsupported", unsupported);
11019    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
11020 }
11021 
11022 /*! \brief Transmit 422 response with Min-SE header (Session-Timers)  */
11023 static int transmit_response_with_minse(struct sip_pvt *p, const char *msg, const struct sip_request *req, int minse_int)
11024 {
11025    struct sip_request resp;
11026    char minse_str[20];
11027 
11028    respprep(&resp, p, msg, req);
11029    append_date(&resp);
11030 
11031    snprintf(minse_str, sizeof(minse_str), "%d", minse_int);
11032    add_header(&resp, "Min-SE", minse_str);
11033    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
11034 }
11035 
11036 
11037 /*! \brief Transmit response, Make sure you get an ACK
11038    This is only used for responses to INVITEs, where we need to make sure we get an ACK
11039 */
11040 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
11041 {
11042    return __transmit_response(p, msg, req, req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL);
11043 }
11044 
11045 /*! \brief Append date to SIP message */
11046 static void append_date(struct sip_request *req)
11047 {
11048    char tmpdat[256];
11049    struct tm tm;
11050    time_t t = time(NULL);
11051 
11052    gmtime_r(&t, &tm);
11053    strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
11054    add_header(req, "Date", tmpdat);
11055 }
11056 
11057 /*! \brief Append Retry-After header field when transmitting response */
11058 static int transmit_response_with_retry_after(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *seconds)
11059 {
11060    struct sip_request resp;
11061    respprep(&resp, p, msg, req);
11062    add_header(&resp, "Retry-After", seconds);
11063    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
11064 }
11065 
11066 /*! \brief Append date and content length before transmitting response */
11067 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
11068 {
11069    struct sip_request resp;
11070    respprep(&resp, p, msg, req);
11071    append_date(&resp);
11072    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
11073 }
11074 
11075 /*! \brief Append Accept header, content length before transmitting response */
11076 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
11077 {
11078    struct sip_request resp;
11079    respprep(&resp, p, msg, req);
11080    add_header(&resp, "Accept", "application/sdp");
11081    return send_response(p, &resp, reliable, 0);
11082 }
11083 
11084 /*! \brief Append Min-Expires header, content length before transmitting response */
11085 static int transmit_response_with_minexpires(struct sip_pvt *p, const char *msg, const struct sip_request *req)
11086 {
11087    struct sip_request resp;
11088    char tmp[32];
11089 
11090    snprintf(tmp, sizeof(tmp), "%d", min_expiry);
11091    respprep(&resp, p, msg, req);
11092    add_header(&resp, "Min-Expires", tmp);
11093    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
11094 }
11095 
11096 /*! \brief Respond with authorization request */
11097 static int transmit_response_with_auth(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *randdata, enum xmittype reliable, const char *header, int stale)
11098 {
11099    struct sip_request resp;
11100    char tmp[512];
11101    uint32_t seqno = 0;
11102 
11103    if (reliable && (sscanf(get_header(req, "CSeq"), "%30u ", &seqno) != 1)) {
11104       ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
11105       return -1;
11106    }
11107    /* Choose Realm */
11108    get_realm(p, req);
11109 
11110    /* Stale means that they sent us correct authentication, but
11111       based it on an old challenge (nonce) */
11112    snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", p->realm, randdata, stale ? ", stale=true" : "");
11113    respprep(&resp, p, msg, req);
11114    add_header(&resp, header, tmp);
11115    append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
11116    return send_response(p, &resp, reliable, seqno);
11117 }
11118 
11119 /*!
11120  \brief Extract domain from SIP To/From header
11121  \return -1 on error, 1 if domain string is empty, 0 if domain was properly extracted
11122  \note TODO: Such code is all over SIP channel, there is a sense to organize
11123       this patern in one function
11124 */
11125 static int get_domain(const char *str, char *domain, int len)
11126 {
11127    char tmpf[256];
11128    char *a, *from;
11129 
11130    *domain = '\0';
11131    ast_copy_string(tmpf, str, sizeof(tmpf));
11132    from = get_in_brackets(tmpf);
11133    if (!ast_strlen_zero(from)) {
11134       if (strncasecmp(from, "sip:", 4)) {
11135          ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", from);
11136          return -1;
11137       }
11138       from += 4;
11139    } else
11140       from = NULL;
11141 
11142    if (from) {
11143       int bracket = 0;
11144 
11145       /* Strip any params or options from user */
11146       if ((a = strchr(from, ';')))
11147          *a = '\0';
11148       /* Strip port from domain if present */
11149       for (a = from; *a != '\0'; ++a) {
11150          if (*a == ':' && bracket == 0) {
11151             *a = '\0';
11152             break;
11153          } else if (*a == '[') {
11154             ++bracket;
11155          } else if (*a == ']') {
11156             --bracket;
11157          }
11158       }
11159       if ((a = strchr(from, '@'))) {
11160          *a = '\0';
11161          ast_copy_string(domain, a + 1, len);
11162       } else
11163          ast_copy_string(domain, from, len);
11164    }
11165 
11166    return ast_strlen_zero(domain);
11167 }
11168 
11169 /*!
11170   \brief Choose realm based on From header and then To header or use globaly configured realm.
11171   Realm from From/To header should be listed among served domains in config file: domain=...
11172 */
11173 static void get_realm(struct sip_pvt *p, const struct sip_request *req)
11174 {
11175    char domain[MAXHOSTNAMELEN];
11176 
11177    if (!ast_strlen_zero(p->realm))
11178       return;
11179 
11180    if (sip_cfg.domainsasrealm &&
11181        !AST_LIST_EMPTY(&domain_list))
11182    {
11183       /* Check From header first */
11184       if (!get_domain(get_header(req, "From"), domain, sizeof(domain))) {
11185          if (check_sip_domain(domain, NULL, 0)) {
11186             ast_string_field_set(p, realm, domain);
11187             return;
11188          }
11189       }
11190       /* Check To header */
11191       if (!get_domain(get_header(req, "To"), domain, sizeof(domain))) {
11192          if (check_sip_domain(domain, NULL, 0)) {
11193             ast_string_field_set(p, realm, domain);
11194             return;
11195          }
11196       }
11197    }
11198    
11199    /* Use default realm from config file */
11200    ast_string_field_set(p, realm, sip_cfg.realm);
11201 }
11202 
11203 /*!
11204  * \internal
11205  *
11206  * \arg msg Only use a string constant for the msg, here, it is shallow copied
11207  *
11208  * \note assumes the sip_pvt is locked.
11209  */
11210 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp)
11211 {
11212    int res;
11213 
11214    if (!(res = with_sdp ? transmit_response_with_sdp(p, msg, req, XMIT_UNRELIABLE, FALSE, FALSE) : transmit_response(p, msg, req))) {
11215       p->last_provisional = msg;
11216       update_provisional_keepalive(p, with_sdp);
11217    }
11218 
11219    return res;
11220 }
11221 
11222 /*! \brief Add text body to SIP message */
11223 static int add_text(struct sip_request *req, const char *text)
11224 {
11225    /* XXX Convert \n's to \r\n's XXX */
11226    add_header(req, "Content-Type", "text/plain;charset=UTF-8");
11227    add_content(req, text);
11228    return 0;
11229 }
11230 
11231 /*! \brief Add DTMF INFO tone to sip message
11232    Mode =   0 for application/dtmf-relay (Cisco)
11233       1 for application/dtmf
11234 */
11235 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode)
11236 {
11237    char tmp[256];
11238    int event;
11239    if (mode) {
11240       /* Application/dtmf short version used by some implementations */
11241       if ('0' <= digit && digit <= '9') {
11242          event = digit - '0';
11243       } else if (digit == '*') {
11244          event = 10;
11245       } else if (digit == '#') {
11246          event = 11;
11247       } else if ('A' <= digit && digit <= 'D') {
11248          event = 12 + digit - 'A';
11249       } else if ('a' <= digit && digit <= 'd') {
11250          event = 12 + digit - 'a';
11251       } else {
11252          /* Unknown digit */
11253          event = 0;
11254       }
11255       snprintf(tmp, sizeof(tmp), "%d\r\n", event);
11256       add_header(req, "Content-Type", "application/dtmf");
11257       add_content(req, tmp);
11258    } else {
11259       /* Application/dtmf-relay as documented by Cisco */
11260       snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
11261       add_header(req, "Content-Type", "application/dtmf-relay");
11262       add_content(req, tmp);
11263    }
11264    return 0;
11265 }
11266 
11267 /*!
11268  * \pre if p->owner exists, it must be locked
11269  * \brief Add Remote-Party-ID header to SIP message
11270  */
11271 static int add_rpid(struct sip_request *req, struct sip_pvt *p)
11272 {
11273    struct ast_str *tmp = ast_str_alloca(256);
11274    char tmp2[256];
11275    char lid_name_buf[128];
11276    char *lid_num;
11277    char *lid_name;
11278    int lid_pres;
11279    const char *fromdomain;
11280    const char *privacy = NULL;
11281    const char *screen = NULL;
11282    const char *anonymous_string = "\"Anonymous\" <sip:anonymous@anonymous.invalid>";
11283 
11284    if (!ast_test_flag(&p->flags[0], SIP_SENDRPID)) {
11285       return 0;
11286    }
11287 
11288    if (!p->owner) {
11289       return 0;
11290    }
11291    lid_num = S_COR(p->owner->connected.id.number.valid,
11292       p->owner->connected.id.number.str,
11293       NULL);
11294    if (!lid_num) {
11295       return 0;
11296    }
11297    lid_name = S_COR(p->owner->connected.id.name.valid,
11298       p->owner->connected.id.name.str,
11299       NULL);
11300    if (!lid_name) {
11301       lid_name = lid_num;
11302    }
11303    ast_escape_quoted(lid_name, lid_name_buf, sizeof(lid_name_buf));
11304    lid_pres = ast_party_id_presentation(&p->owner->connected.id);
11305 
11306    if (((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) &&
11307          (ast_test_flag(&p->flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND) == SIP_PAGE2_TRUST_ID_OUTBOUND_NO)) {
11308       /* If pres is not allowed and we don't trust the peer, we don't apply an RPID header */
11309       return 0;
11310    }
11311 
11312    fromdomain = p->fromdomain;
11313    if (!fromdomain ||
11314          ((ast_test_flag(&p->flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND) == SIP_PAGE2_TRUST_ID_OUTBOUND_YES) &&
11315          !strcmp("anonymous.invalid", fromdomain))) {
11316       /* If the fromdomain is NULL or if it was set to anonymous.invalid due to privacy settings and we trust the peer,
11317        * use the host IP address */
11318       fromdomain = ast_sockaddr_stringify_host_remote(&p->ourip);
11319    }
11320 
11321    lid_num = ast_uri_encode(lid_num, tmp2, sizeof(tmp2), 0);
11322 
11323    if (ast_test_flag(&p->flags[0], SIP_SENDRPID_PAI)) {
11324       if (ast_test_flag(&p->flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND) != SIP_PAGE2_TRUST_ID_OUTBOUND_LEGACY) {
11325          /* trust_id_outbound = yes - Always give full information even if it's private, but append a privacy header
11326           * When private data is included */
11327          ast_str_set(&tmp, -1, "\"%s\" <sip:%s@%s>", lid_name_buf, lid_num, fromdomain);
11328          if ((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
11329             add_header(req, "Privacy", "id");
11330          }
11331       } else {
11332          /* trust_id_outbound = legacy - behave in a non RFC-3325 compliant manner and send anonymized data when
11333           * when handling private data. */
11334          if ((lid_pres & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED) {
11335             ast_str_set(&tmp, -1, "\"%s\" <sip:%s@%s>", lid_name_buf, lid_num, fromdomain);
11336          } else {
11337             ast_str_set(&tmp, -1, "%s", anonymous_string);
11338          }
11339       }
11340       add_header(req, "P-Asserted-Identity", ast_str_buffer(tmp));
11341    } else {
11342       ast_str_set(&tmp, -1, "\"%s\" <sip:%s@%s>;party=%s", lid_name_buf, lid_num, fromdomain, p->outgoing_call ? "calling" : "called");
11343 
11344       switch (lid_pres) {
11345       case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
11346       case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
11347          privacy = "off";
11348          screen = "no";
11349          break;
11350       case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
11351       case AST_PRES_ALLOWED_NETWORK_NUMBER:
11352          privacy = "off";
11353          screen = "yes";
11354          break;
11355       case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
11356       case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
11357          privacy = "full";
11358          screen = "no";
11359          break;
11360       case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
11361       case AST_PRES_PROHIB_NETWORK_NUMBER:
11362          privacy = "full";
11363          screen = "yes";
11364          break;
11365       case AST_PRES_NUMBER_NOT_AVAILABLE:
11366          break;
11367       default:
11368          if ((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
11369             privacy = "full";
11370          }
11371          else
11372             privacy = "off";
11373          screen = "no";
11374          break;
11375       }
11376 
11377       if (!ast_strlen_zero(privacy) && !ast_strlen_zero(screen)) {
11378          ast_str_append(&tmp, -1, ";privacy=%s;screen=%s", privacy, screen);
11379       }
11380 
11381       add_header(req, "Remote-Party-ID", ast_str_buffer(tmp));
11382    }
11383    return 0;
11384 }
11385 
11386 /*! \brief add XML encoded media control with update
11387    \note XML: The only way to turn 0 bits of information into a few hundred. (markster) */
11388 static int add_vidupdate(struct sip_request *req)
11389 {
11390    const char *xml_is_a_huge_waste_of_space =
11391       "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
11392       " <media_control>\r\n"
11393       "  <vc_primitive>\r\n"
11394       "   <to_encoder>\r\n"
11395       "    <picture_fast_update>\r\n"
11396       "    </picture_fast_update>\r\n"
11397       "   </to_encoder>\r\n"
11398       "  </vc_primitive>\r\n"
11399       " </media_control>\r\n";
11400    add_header(req, "Content-Type", "application/media_control+xml");
11401    add_content(req, xml_is_a_huge_waste_of_space);
11402    return 0;
11403 }
11404 
11405 /*! \brief Add codec offer to SDP offer/answer body in INVITE or 200 OK */
11406 static void add_codec_to_sdp(const struct sip_pvt *p, format_t codec,
11407               struct ast_str **m_buf, struct ast_str **a_buf,
11408               int debug, int *min_packet_size)
11409 {
11410    int rtp_code;
11411    struct ast_format_list fmt;
11412 
11413 
11414    if (debug)
11415       ast_verbose("Adding codec 0x%" PRIx64 " (%s) to SDP\n", (uint64_t)codec, ast_getformatname(codec));
11416    if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->rtp), 1, codec)) == -1)
11417       return;
11418 
11419    if (p->rtp) {
11420       struct ast_codec_pref *pref = &ast_rtp_instance_get_codecs(p->rtp)->pref;
11421       fmt = ast_codec_pref_getsize(pref, codec);
11422    } 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 */
11423       return;
11424    ast_str_append(m_buf, 0, " %d", rtp_code);
11425    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%u\r\n", rtp_code,
11426              ast_rtp_lookup_mime_subtype2(1, codec,
11427                      ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0),
11428              ast_rtp_lookup_sample_rate2(1, codec));
11429 
11430    switch (codec) {
11431    case AST_FORMAT_G729A:
11432       /* Indicate that we don't support VAD (G.729 annex B) */
11433       ast_str_append(a_buf, 0, "a=fmtp:%d annexb=no\r\n", rtp_code);
11434       break;
11435    case AST_FORMAT_G723_1:
11436       /* Indicate that we don't support VAD (G.723.1 annex A) */
11437       ast_str_append(a_buf, 0, "a=fmtp:%d annexa=no\r\n", rtp_code);
11438       break;
11439    case AST_FORMAT_ILBC:
11440       /* Add information about us using only 20/30 ms packetization */
11441       ast_str_append(a_buf, 0, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
11442       break;
11443    case AST_FORMAT_SIREN7:
11444       /* Indicate that we only expect 32Kbps */
11445       ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=32000\r\n", rtp_code);
11446       break;
11447    case AST_FORMAT_SIREN14:
11448       /* Indicate that we only expect 48Kbps */
11449       ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=48000\r\n", rtp_code);
11450       break;
11451    case AST_FORMAT_G719:
11452       /* Indicate that we only expect 64Kbps */
11453       ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=64000\r\n", rtp_code);
11454       break;
11455    }
11456 
11457    if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
11458       *min_packet_size = fmt.cur_ms;
11459 
11460    /* Our first codec packetization processed cannot be zero */
11461    if ((*min_packet_size)==0 && fmt.cur_ms)
11462       *min_packet_size = fmt.cur_ms;
11463 }
11464 
11465 /*! \brief Add video codec offer to SDP offer/answer body in INVITE or 200 OK */
11466 /* This is different to the audio one now so we can add more caps later */
11467 static void add_vcodec_to_sdp(const struct sip_pvt *p, format_t codec,
11468               struct ast_str **m_buf, struct ast_str **a_buf,
11469               int debug, int *min_packet_size)
11470 {
11471    int rtp_code;
11472 
11473    if (!p->vrtp)
11474       return;
11475 
11476    if (debug)
11477       ast_verbose("Adding video codec 0x%" PRIx64 " (%s) to SDP\n", (uint64_t)codec, ast_getformatname(codec));
11478 
11479    if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->vrtp), 1, codec)) == -1)
11480       return;
11481 
11482    ast_str_append(m_buf, 0, " %d", rtp_code);
11483    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%u\r\n", rtp_code,
11484              ast_rtp_lookup_mime_subtype2(1, codec, 0),
11485              ast_rtp_lookup_sample_rate2(1, codec));
11486    /* Add fmtp code here */
11487 }
11488 
11489 /*! \brief Add text codec offer to SDP offer/answer body in INVITE or 200 OK */
11490 static void add_tcodec_to_sdp(const struct sip_pvt *p, int codec,
11491               struct ast_str **m_buf, struct ast_str **a_buf,
11492               int debug, int *min_packet_size)
11493 {
11494    int rtp_code;
11495 
11496    if (!p->trtp)
11497       return;
11498 
11499    if (debug)
11500       ast_verbose("Adding text codec 0x%x (%s) to SDP\n", (unsigned)codec, ast_getformatname(codec));
11501 
11502    if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->trtp), 1, codec)) == -1)
11503       return;
11504 
11505    ast_str_append(m_buf, 0, " %d", rtp_code);
11506    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%u\r\n", rtp_code,
11507              ast_rtp_lookup_mime_subtype2(1, codec, 0),
11508              ast_rtp_lookup_sample_rate2(1, codec));
11509    /* Add fmtp code here */
11510 
11511    if (codec == AST_FORMAT_T140RED) {
11512       int t140code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->trtp), 1, AST_FORMAT_T140);
11513       ast_str_append(a_buf, 0, "a=fmtp:%d %d/%d/%d\r\n", rtp_code,
11514           t140code,
11515           t140code,
11516           t140code);
11517 
11518    }
11519 }
11520 
11521 
11522 /*! \brief Get Max T.38 Transmission rate from T38 capabilities */
11523 static unsigned int t38_get_rate(enum ast_control_t38_rate rate)
11524 {
11525    switch (rate) {
11526    case AST_T38_RATE_2400:
11527       return 2400;
11528    case AST_T38_RATE_4800:
11529       return 4800;
11530    case AST_T38_RATE_7200:
11531       return 7200;
11532    case AST_T38_RATE_9600:
11533       return 9600;
11534    case AST_T38_RATE_12000:
11535       return 12000;
11536    case AST_T38_RATE_14400:
11537       return 14400;
11538    default:
11539       return 0;
11540    }
11541 }
11542 
11543 /*! \brief Add RFC 2833 DTMF offer to SDP */
11544 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
11545             struct ast_str **m_buf, struct ast_str **a_buf,
11546             int debug)
11547 {
11548    int rtp_code;
11549 
11550    if (debug)
11551       ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", (unsigned)format, ast_rtp_lookup_mime_subtype2(0, format, 0));
11552    if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->rtp), 0, format)) == -1)
11553       return;
11554 
11555    ast_str_append(m_buf, 0, " %d", rtp_code);
11556    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%u\r\n", rtp_code,
11557              ast_rtp_lookup_mime_subtype2(0, format, 0),
11558              ast_rtp_lookup_sample_rate2(0, format));
11559    if (format == AST_RTP_DTMF)   /* Indicate we support DTMF and FLASH... */
11560       ast_str_append(a_buf, 0, "a=fmtp:%d 0-16\r\n", rtp_code);
11561 }
11562 
11563 /*! \brief Set all IP media addresses for this call
11564    \note called from add_sdp()
11565 */
11566 static void get_our_media_address(struct sip_pvt *p, int needvideo, int needtext,
11567               struct ast_sockaddr *addr, struct ast_sockaddr *vaddr,
11568               struct ast_sockaddr *taddr, struct ast_sockaddr *dest,
11569               struct ast_sockaddr *vdest, struct ast_sockaddr *tdest)
11570 {
11571    int use_externip = 0;
11572 
11573    /* First, get our address */
11574    ast_rtp_instance_get_local_address(p->rtp, addr);
11575    if (p->vrtp) {
11576       ast_rtp_instance_get_local_address(p->vrtp, vaddr);
11577    }
11578    if (p->trtp) {
11579       ast_rtp_instance_get_local_address(p->trtp, taddr);
11580    }
11581 
11582    /* If our real IP differs from the local address returned by the RTP engine, use it. */
11583    /* The premise is that if we are already using that IP to communicate with the client, */
11584    /* we should be using it for RTP too. */
11585         use_externip = ast_sockaddr_cmp_addr(&p->ourip, addr);
11586 
11587    /* Now, try to figure out where we want them to send data */
11588    /* Is this a re-invite to move the media out, then use the original offer from caller  */
11589    if (!ast_sockaddr_isnull(&p->redirip)) {  /* If we have a redirection IP, use it */
11590       ast_sockaddr_copy(dest, &p->redirip);
11591    } else {
11592       /*
11593        * Audio Destination IP:
11594        *
11595        * 1. Specifically configured media address.
11596        * 2. Local address as specified by the RTP engine.
11597        * 3. The local IP as defined by chan_sip.
11598        *
11599        * Audio Destination Port:
11600        *
11601        * 1. Provided by the RTP engine.
11602        */
11603       ast_sockaddr_copy(dest,
11604               !ast_sockaddr_isnull(&media_address) ? &media_address :
11605               !ast_sockaddr_is_any(addr) && !use_externip ? addr    :
11606               &p->ourip);
11607       ast_sockaddr_set_port(dest, ast_sockaddr_port(addr));
11608    }
11609 
11610    if (needvideo) {
11611       /* Determine video destination */
11612       if (!ast_sockaddr_isnull(&p->vredirip)) {
11613          ast_sockaddr_copy(vdest, &p->vredirip);
11614       } else {
11615          /*
11616           * Video Destination IP:
11617           *
11618           * 1. Specifically configured media address.
11619           * 2. Local address as specified by the RTP engine.
11620           * 3. The local IP as defined by chan_sip.
11621           *
11622           * Video Destination Port:
11623           *
11624           * 1. Provided by the RTP engine.
11625           */
11626          ast_sockaddr_copy(vdest,
11627                  !ast_sockaddr_isnull(&media_address) ? &media_address :
11628                  !ast_sockaddr_is_any(vaddr) && !use_externip ? vaddr  :
11629                  &p->ourip);
11630          ast_sockaddr_set_port(vdest, ast_sockaddr_port(vaddr));
11631       }
11632    }
11633 
11634    if (needtext) {
11635       /* Determine text destination */
11636       if (!ast_sockaddr_isnull(&p->tredirip)) {
11637          ast_sockaddr_copy(tdest, &p->tredirip);
11638       } else {
11639          /*
11640           * Text Destination IP:
11641           *
11642           * 1. Specifically configured media address.
11643           * 2. Local address as specified by the RTP engine.
11644           * 3. The local IP as defined by chan_sip.
11645           *
11646           * Text Destination Port:
11647           *
11648           * 1. Provided by the RTP engine.
11649           */
11650          ast_sockaddr_copy(tdest,
11651                  !ast_sockaddr_isnull(&media_address) ? &media_address  :
11652                  !ast_sockaddr_is_any(taddr) && !use_externip ? taddr   :
11653                  &p->ourip);
11654          ast_sockaddr_set_port(tdest, ast_sockaddr_port(taddr));
11655       }
11656    }
11657 }
11658 
11659 static void get_crypto_attrib(struct sip_srtp *srtp, const char **a_crypto)
11660 {
11661    /* Set encryption properties */
11662    if (srtp) {
11663       if (!srtp->crypto) {
11664          srtp->crypto = sdp_crypto_setup();
11665       }
11666       if (srtp->crypto && (sdp_crypto_offer(srtp->crypto) >= 0)) {
11667          *a_crypto = sdp_crypto_attrib(srtp->crypto);
11668       }
11669 
11670       if (!*a_crypto) {
11671          ast_log(LOG_WARNING, "No SRTP key management enabled\n");
11672       }
11673    }
11674 }
11675 
11676 /*! \brief Add Session Description Protocol message
11677 
11678     If oldsdp is TRUE, then the SDP version number is not incremented. This mechanism
11679     is used in Session-Timers where RE-INVITEs are used for refreshing SIP sessions
11680     without modifying the media session in any way.
11681 */
11682 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38)
11683 {
11684    format_t alreadysent = 0;
11685    int doing_directmedia = FALSE;
11686 
11687    struct ast_sockaddr addr = { {0,} };
11688    struct ast_sockaddr vaddr = { {0,} };
11689    struct ast_sockaddr taddr = { {0,} };
11690    struct ast_sockaddr udptladdr = { {0,} };
11691    struct ast_sockaddr dest = { {0,} };
11692    struct ast_sockaddr vdest = { {0,} };
11693    struct ast_sockaddr tdest = { {0,} };
11694    struct ast_sockaddr udptldest = { {0,} };
11695 
11696    /* SDP fields */
11697    char *version =   "v=0\r\n";     /* Protocol version */
11698    char subject[256];            /* Subject of the session */
11699    char owner[256];           /* Session owner/creator */
11700    char connection[256];            /* Connection data */
11701    char *session_time = "t=0 0\r\n";         /* Time the session is active */
11702    char bandwidth[256] = "";        /* Max bitrate */
11703    char *hold = "";
11704    struct ast_str *m_audio = ast_str_alloca(256);  /* Media declaration line for audio */
11705    struct ast_str *m_video = ast_str_alloca(256);  /* Media declaration line for video */
11706    struct ast_str *m_text = ast_str_alloca(256);   /* Media declaration line for text */
11707    struct ast_str *m_modem = ast_str_alloca(256);  /* Media declaration line for modem */
11708    struct ast_str *a_audio = ast_str_alloca(1024); /* Attributes for audio */
11709    struct ast_str *a_video = ast_str_alloca(1024); /* Attributes for video */
11710    struct ast_str *a_text = ast_str_alloca(1024);  /* Attributes for text */
11711    struct ast_str *a_modem = ast_str_alloca(1024); /* Attributes for modem */
11712    const char *a_crypto = NULL;
11713    const char *v_a_crypto = NULL;
11714    const char *t_a_crypto = NULL;
11715 
11716    format_t x;
11717    format_t capability = 0;
11718    int needaudio = FALSE;
11719    int needvideo = FALSE;
11720    int needtext = FALSE;
11721    int debug = sip_debug_test_pvt(p);
11722    int min_audio_packet_size = 0;
11723    int min_video_packet_size = 0;
11724    int min_text_packet_size = 0;
11725 
11726    char codecbuf[SIPBUFSIZE];
11727    char buf[SIPBUFSIZE];
11728    char dummy_answer[256];
11729 
11730    /* Set the SDP session name */
11731    snprintf(subject, sizeof(subject), "s=%s\r\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
11732 
11733    if (!p->rtp) {
11734       ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
11735       return AST_FAILURE;
11736    }
11737    /* XXX We should not change properties in the SIP dialog until
11738       we have acceptance of the offer if this is a re-invite */
11739 
11740    /* Set RTP Session ID and version */
11741    if (!p->sessionid) {
11742       p->sessionid = (int)ast_random();
11743       p->sessionversion = p->sessionid;
11744    } else {
11745       if (oldsdp == FALSE)
11746          p->sessionversion++;
11747    }
11748 
11749    if (add_audio) {
11750       doing_directmedia = (!ast_sockaddr_isnull(&p->redirip) && p->redircodecs) ? TRUE : FALSE;
11751       /* Check if we need video in this call */
11752       if ((p->jointcapability & AST_FORMAT_VIDEO_MASK) && !p->novideo) {
11753          if (doing_directmedia && !(p->jointcapability & AST_FORMAT_VIDEO_MASK & p->redircodecs)) {
11754             ast_debug(2, "This call needs video offers, but caller probably did not offer it!\n");
11755          } else if (p->vrtp) {
11756             needvideo = TRUE;
11757             ast_debug(2, "This call needs video offers!\n");
11758          } else {
11759             ast_debug(2, "This call needs video offers, but there's no video support enabled!\n");
11760          }
11761       }
11762       /* Check if we need text in this call */
11763       if ((p->jointcapability & AST_FORMAT_TEXT_MASK) && !p->notext) {
11764          if (sipdebug_text)
11765             ast_verbose("We think we can do text\n");
11766          if (p->trtp) {
11767             if (sipdebug_text) {
11768                ast_verbose("And we have a text rtp object\n");
11769             }
11770             needtext = TRUE;
11771             ast_debug(2, "This call needs text offers! \n");
11772          } else {
11773             ast_debug(2, "This call needs text offers, but there's no text support enabled ! \n");
11774          }
11775       }
11776    }
11777 
11778    get_our_media_address(p, needvideo, needtext, &addr, &vaddr, &taddr, &dest, &vdest, &tdest);
11779 
11780    snprintf(owner, sizeof(owner), "o=%s %d %d IN %s %s\r\n",
11781        ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner,
11782        p->sessionid, p->sessionversion,
11783        (ast_sockaddr_is_ipv6(&dest) && !ast_sockaddr_is_ipv4_mapped(&dest)) ?
11784          "IP6" : "IP4",
11785        ast_sockaddr_stringify_addr_remote(&dest));
11786 
11787    snprintf(connection, sizeof(connection), "c=IN %s %s\r\n",
11788        (ast_sockaddr_is_ipv6(&dest) && !ast_sockaddr_is_ipv4_mapped(&dest)) ?
11789          "IP6" : "IP4",
11790        ast_sockaddr_stringify_addr_remote(&dest));
11791 
11792    if (add_audio) {
11793       if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR) {
11794          hold = "a=recvonly\r\n";
11795          doing_directmedia = FALSE;
11796       } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE) {
11797          hold = "a=inactive\r\n";
11798          doing_directmedia = FALSE;
11799       } else {
11800          hold = "a=sendrecv\r\n";
11801       }
11802 
11803       capability = p->jointcapability;
11804 
11805       /* XXX note, Video and Text are negated - 'true' means 'no' */
11806       ast_debug(1, "** Our capability: %s Video flag: %s Text flag: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability),
11807            p->novideo ? "True" : "False", p->notext ? "True" : "False");
11808       ast_debug(1, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcodec));
11809 
11810       if (doing_directmedia) {
11811          capability &= p->redircodecs;
11812          ast_debug(1, "** Our native-bridge filtered capablity: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability));
11813       }
11814 
11815       /* Check if we need audio */
11816       if (capability & AST_FORMAT_AUDIO_MASK)
11817          needaudio = TRUE;
11818 
11819       if (debug) {
11820          ast_verbose("Audio is at %s\n", ast_sockaddr_stringify_port(&addr));
11821       }
11822 
11823       /* Ok, we need video. Let's add what we need for video and set codecs.
11824          Video is handled differently than audio since we can not transcode. */
11825       if (needvideo) {
11826          get_crypto_attrib(p->vsrtp, &v_a_crypto);
11827          ast_str_append(&m_video, 0, "m=video %d RTP/%s", ast_sockaddr_port(&vdest),
11828             v_a_crypto ? "SAVP" : "AVP");
11829 
11830          /* Build max bitrate string */
11831          if (p->maxcallbitrate)
11832             snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
11833          if (debug) {
11834             ast_verbose("Video is at %s\n", ast_sockaddr_stringify(&vdest));
11835          }
11836       }
11837 
11838       /* Ok, we need text. Let's add what we need for text and set codecs.
11839          Text is handled differently than audio since we can not transcode. */
11840       if (needtext) {
11841          if (sipdebug_text)
11842             ast_verbose("Lets set up the text sdp\n");
11843          get_crypto_attrib(p->tsrtp, &t_a_crypto);
11844          ast_str_append(&m_text, 0, "m=text %d RTP/%s", ast_sockaddr_port(&tdest),
11845             t_a_crypto ? "SAVP" : "AVP");
11846          if (debug) {  /* XXX should I use tdest below ? */
11847             ast_verbose("Text is at %s\n", ast_sockaddr_stringify(&taddr));
11848          }
11849       }
11850 
11851       /* Start building generic SDP headers */
11852 
11853       /* We break with the "recommendation" and send our IP, in order that our
11854          peer doesn't have to ast_gethostbyname() us */
11855 
11856       get_crypto_attrib(p->srtp, &a_crypto);
11857       ast_str_append(&m_audio, 0, "m=audio %d RTP/%s", ast_sockaddr_port(&dest),
11858          a_crypto ? "SAVP" : "AVP");
11859 
11860       /* Now, start adding audio codecs. These are added in this order:
11861          - First what was requested by the calling channel
11862          - Then preferences in order from sip.conf device config for this peer/user
11863          - Then other codecs in capabilities, including video
11864       */
11865 
11866       /* Prefer the audio codec we were requested to use, first, no matter what
11867          Note that p->prefcodec can include video codecs, so mask them out
11868       */
11869       if ((capability & p->prefcodec) & AST_FORMAT_AUDIO_MASK) {
11870          format_t codec = p->prefcodec & AST_FORMAT_AUDIO_MASK;
11871 
11872          add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
11873          alreadysent |= codec;
11874       }
11875 
11876       /* Start by sending our preferred audio/video codecs */
11877       for (x = 0; x < 64; x++) {
11878          format_t codec;
11879 
11880          if (!(codec = ast_codec_pref_index(&p->prefs, x)))
11881             break;
11882 
11883          if (!(capability & codec))
11884             continue;
11885 
11886          if (alreadysent & codec)
11887             continue;
11888 
11889          add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
11890          alreadysent |= codec;
11891       }
11892 
11893       /* Now send any other common audio and video codecs, and non-codec formats: */
11894       for (x = 1ULL; x <= (needtext ? AST_FORMAT_TEXT_MASK : (needvideo ? AST_FORMAT_VIDEO_MASK : AST_FORMAT_AUDIO_MASK)); x <<= 1) {
11895          if (!(capability & x))  /* Codec not requested */
11896             continue;
11897 
11898          if (alreadysent & x) /* Already added to SDP */
11899             continue;
11900 
11901          if (x & AST_FORMAT_AUDIO_MASK)
11902             add_codec_to_sdp(p, x, &m_audio, &a_audio, debug, &min_audio_packet_size);
11903          else if (x & AST_FORMAT_VIDEO_MASK)
11904             add_vcodec_to_sdp(p, x, &m_video, &a_video, debug, &min_video_packet_size);
11905          else if (x & AST_FORMAT_TEXT_MASK)
11906             add_tcodec_to_sdp(p, x, &m_text, &a_text, debug, &min_text_packet_size);
11907       }
11908 
11909       /* Now add DTMF RFC2833 telephony-event as a codec */
11910       for (x = 1LL; x <= AST_RTP_MAX; x <<= 1) {
11911          if (!(p->jointnoncodeccapability & x))
11912             continue;
11913 
11914          add_noncodec_to_sdp(p, x, &m_audio, &a_audio, debug);
11915       }
11916 
11917       ast_debug(3, "-- Done with adding codecs to SDP\n");
11918 
11919       if (!p->owner || p->owner->timingfd == -1) {
11920          ast_str_append(&a_audio, 0, "a=silenceSupp:off - - - -\r\n");
11921       }
11922 
11923       if (min_audio_packet_size)
11924          ast_str_append(&a_audio, 0, "a=ptime:%d\r\n", min_audio_packet_size);
11925 
11926       /* XXX don't think you can have ptime for video */
11927       if (min_video_packet_size)
11928          ast_str_append(&a_video, 0, "a=ptime:%d\r\n", min_video_packet_size);
11929 
11930       /* XXX don't think you can have ptime for text */
11931       if (min_text_packet_size)
11932          ast_str_append(&a_text, 0, "a=ptime:%d\r\n", min_text_packet_size);
11933 
11934       if (ast_str_size(m_audio) - ast_str_strlen(m_audio) < 2 || ast_str_size(m_video) - ast_str_strlen(m_video) < 2 ||
11935           ast_str_size(m_text) - ast_str_strlen(m_text) < 2 || ast_str_size(a_text) - ast_str_strlen(a_text) < 2 ||
11936           ast_str_size(a_audio) - ast_str_strlen(a_audio) < 2 || ast_str_size(a_video) - ast_str_strlen(a_video) < 2)
11937          ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
11938    }
11939 
11940    if (add_t38) {
11941       /* Our T.38 end is */
11942       ast_udptl_get_us(p->udptl, &udptladdr);
11943 
11944       /* We don't use directmedia for T.38, so keep the destination the same as our IP address. */
11945       ast_sockaddr_copy(&udptldest, &p->ourip);
11946       ast_sockaddr_set_port(&udptldest, ast_sockaddr_port(&udptladdr));
11947 
11948       if (debug) {
11949          ast_debug(1, "T.38 UDPTL is at %s port %d\n", ast_sockaddr_stringify_addr(&p->ourip), ast_sockaddr_port(&udptladdr));
11950       }
11951 
11952       /* We break with the "recommendation" and send our IP, in order that our
11953          peer doesn't have to ast_gethostbyname() us */
11954 
11955       ast_str_append(&m_modem, 0, "m=image %d udptl t38\r\n", ast_sockaddr_port(&udptldest));
11956 
11957       if (ast_sockaddr_cmp(&udptldest, &dest)) {
11958          ast_str_append(&m_modem, 0, "c=IN %s %s\r\n",
11959                (ast_sockaddr_is_ipv6(&udptldest) && !ast_sockaddr_is_ipv4_mapped(&udptldest)) ?
11960                "IP6" : "IP4", ast_sockaddr_stringify_addr_remote(&udptldest));
11961       }
11962 
11963       ast_str_append(&a_modem, 0, "a=T38FaxVersion:%u\r\n", p->t38.our_parms.version);
11964       ast_str_append(&a_modem, 0, "a=T38MaxBitRate:%u\r\n", t38_get_rate(p->t38.our_parms.rate));
11965       if (p->t38.our_parms.fill_bit_removal) {
11966          ast_str_append(&a_modem, 0, "a=T38FaxFillBitRemoval\r\n");
11967       }
11968       if (p->t38.our_parms.transcoding_mmr) {
11969          ast_str_append(&a_modem, 0, "a=T38FaxTranscodingMMR\r\n");
11970       }
11971       if (p->t38.our_parms.transcoding_jbig) {
11972          ast_str_append(&a_modem, 0, "a=T38FaxTranscodingJBIG\r\n");
11973       }
11974       switch (p->t38.our_parms.rate_management) {
11975       case AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF:
11976          ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:transferredTCF\r\n");
11977          break;
11978       case AST_T38_RATE_MANAGEMENT_LOCAL_TCF:
11979          ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:localTCF\r\n");
11980          break;
11981       }
11982       ast_str_append(&a_modem, 0, "a=T38FaxMaxDatagram:%u\r\n", ast_udptl_get_local_max_datagram(p->udptl));
11983       switch (ast_udptl_get_error_correction_scheme(p->udptl)) {
11984       case UDPTL_ERROR_CORRECTION_NONE:
11985          break;
11986       case UDPTL_ERROR_CORRECTION_FEC:
11987          ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPFEC\r\n");
11988          break;
11989       case UDPTL_ERROR_CORRECTION_REDUNDANCY:
11990          ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPRedundancy\r\n");
11991          break;
11992       }
11993    }
11994 
11995    if (needaudio)
11996       ast_str_append(&m_audio, 0, "\r\n");
11997    if (needvideo)
11998       ast_str_append(&m_video, 0, "\r\n");
11999    if (needtext)
12000       ast_str_append(&m_text, 0, "\r\n");
12001 
12002    add_header(resp, "Content-Type", "application/sdp");
12003    add_content(resp, version);
12004    add_content(resp, owner);
12005    add_content(resp, subject);
12006    add_content(resp, connection);
12007    /* only if video response is appropriate */
12008    if (needvideo) {
12009       add_content(resp, bandwidth);
12010    }
12011    add_content(resp, session_time);
12012    /* if this is a response to an invite, order our offers properly */
12013    if (p->offered_media[SDP_AUDIO].order_offered ||
12014       p->offered_media[SDP_VIDEO].order_offered ||
12015       p->offered_media[SDP_TEXT].order_offered ||
12016       p->offered_media[SDP_IMAGE].order_offered) {
12017       int i;
12018       /* we have up to 3 streams as limited by process_sdp */
12019       for (i = 1; i <= 3; i++) {
12020          if (p->offered_media[SDP_AUDIO].order_offered == i) {
12021             if (needaudio) {
12022                add_content(resp, ast_str_buffer(m_audio));
12023                add_content(resp, ast_str_buffer(a_audio));
12024                add_content(resp, hold);
12025                if (a_crypto) {
12026                   add_content(resp, a_crypto);
12027                }
12028             } else {
12029                snprintf(dummy_answer, sizeof(dummy_answer), "m=audio 0 RTP/AVP %s\r\n", p->offered_media[SDP_AUDIO].codecs);
12030                add_content(resp, dummy_answer);
12031             }
12032          } else if (p->offered_media[SDP_VIDEO].order_offered == i) {
12033             if (needvideo) { /* only if video response is appropriate */
12034                add_content(resp, ast_str_buffer(m_video));
12035                add_content(resp, ast_str_buffer(a_video));
12036                add_content(resp, hold);   /* Repeat hold for the video stream */
12037                if (v_a_crypto) {
12038                   add_content(resp, v_a_crypto);
12039                }
12040             } else {
12041                snprintf(dummy_answer, sizeof(dummy_answer), "m=video 0 RTP/AVP %s\r\n", p->offered_media[SDP_VIDEO].codecs);
12042                add_content(resp, dummy_answer);
12043             }
12044          } else if (p->offered_media[SDP_TEXT].order_offered == i) {
12045             if (needtext) { /* only if text response is appropriate */
12046                add_content(resp, ast_str_buffer(m_text));
12047                add_content(resp, ast_str_buffer(a_text));
12048                add_content(resp, hold);   /* Repeat hold for the text stream */
12049                if (t_a_crypto) {
12050                   add_content(resp, t_a_crypto);
12051                }
12052             } else {
12053                snprintf(dummy_answer, sizeof(dummy_answer), "m=text 0 RTP/AVP %s\r\n", p->offered_media[SDP_TEXT].codecs);
12054                add_content(resp, dummy_answer);
12055             }
12056          } else if (p->offered_media[SDP_IMAGE].order_offered == i) {
12057             if (add_t38) {
12058                add_content(resp, ast_str_buffer(m_modem));
12059                add_content(resp, ast_str_buffer(a_modem));
12060             } else {
12061                add_content(resp, "m=image 0 udptl t38\r\n");
12062             }
12063          }
12064       }
12065    } else {
12066       /* generate new SDP from scratch, no offers */
12067       if (needaudio) {
12068          add_content(resp, ast_str_buffer(m_audio));
12069          add_content(resp, ast_str_buffer(a_audio));
12070          add_content(resp, hold);
12071          if (a_crypto) {
12072             add_content(resp, a_crypto);
12073          }
12074       }
12075       if (needvideo) { /* only if video response is appropriate */
12076          add_content(resp, ast_str_buffer(m_video));
12077          add_content(resp, ast_str_buffer(a_video));
12078          add_content(resp, hold);   /* Repeat hold for the video stream */
12079          if (v_a_crypto) {
12080             add_content(resp, v_a_crypto);
12081          }
12082       }
12083       if (needtext) { /* only if text response is appropriate */
12084          add_content(resp, ast_str_buffer(m_text));
12085          add_content(resp, ast_str_buffer(a_text));
12086          add_content(resp, hold);   /* Repeat hold for the text stream */
12087          if (t_a_crypto) {
12088             add_content(resp, t_a_crypto);
12089          }
12090       }
12091       if (add_t38) {
12092          add_content(resp, ast_str_buffer(m_modem));
12093          add_content(resp, ast_str_buffer(a_modem));
12094       }
12095    }
12096 
12097    /* Update lastrtprx when we send our SDP */
12098    p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
12099 
12100    ast_debug(3, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, capability));
12101 
12102    return AST_SUCCESS;
12103 }
12104 
12105 /*! \brief Used for 200 OK and 183 early media */
12106 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
12107 {
12108    struct sip_request resp;
12109    uint32_t seqno;
12110    
12111    if (sscanf(get_header(req, "CSeq"), "%30u ", &seqno) != 1) {
12112       ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
12113       return -1;
12114    }
12115    respprep(&resp, p, msg, req);
12116    if (p->udptl) {
12117       add_sdp(&resp, p, 0, 0, 1);
12118    } else
12119       ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
12120    if (retrans && !p->pendinginvite)
12121       p->pendinginvite = seqno;     /* Buggy clients sends ACK on RINGING too */
12122    return send_response(p, &resp, retrans, seqno);
12123 }
12124 
12125 /*! \brief copy SIP request (mostly used to save request for responses) */
12126 static void copy_request(struct sip_request *dst, const struct sip_request *src)
12127 {
12128    /* XXX this function can encounter memory allocation errors, perhaps it
12129     * should return a value */
12130 
12131    struct ast_str *duplicate = dst->data;
12132    struct ast_str *duplicate_content = dst->content;
12133 
12134    /* copy the entire request then restore the original data and content
12135     * members from the dst request */
12136    *dst = *src;
12137    dst->data = duplicate;
12138    dst->content = duplicate_content;
12139 
12140    /* copy the data into the dst request */
12141    if (!dst->data && !(dst->data = ast_str_create(ast_str_strlen(src->data) + 1))) {
12142       return;
12143    }
12144    ast_str_copy_string(&dst->data, src->data);
12145 
12146    /* copy the content into the dst request (if it exists) */
12147    if (src->content) {
12148       if (!dst->content && !(dst->content = ast_str_create(ast_str_strlen(src->content) + 1))) {
12149          return;
12150       }
12151       ast_str_copy_string(&dst->content, src->content);
12152    }
12153 }
12154 
12155 static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp)
12156 {
12157    char uri[SIPBUFSIZE];
12158    struct ast_str *header = ast_str_alloca(SIPBUFSIZE);
12159    struct ast_cc_agent *agent = find_sip_cc_agent_by_original_callid(p);
12160    struct sip_cc_agent_pvt *agent_pvt;
12161 
12162    if (!agent) {
12163       /* Um, what? How could the SIP_OFFER_CC flag be set but there not be an
12164        * agent? Oh well, we'll just warn and return without adding the header.
12165        */
12166       ast_log(LOG_WARNING, "Can't find SIP CC agent for call '%s' even though OFFER_CC flag was set?\n", p->callid);
12167       return;
12168    }
12169 
12170    agent_pvt = agent->private_data;
12171 
12172    if (!ast_strlen_zero(agent_pvt->subscribe_uri)) {
12173       ast_copy_string(uri, agent_pvt->subscribe_uri, sizeof(uri));
12174    } else {
12175       generate_uri(p, uri, sizeof(uri));
12176       ast_copy_string(agent_pvt->subscribe_uri, uri, sizeof(agent_pvt->subscribe_uri));
12177    }
12178    /* XXX Hardcode "NR" as the m reason for now. This should perhaps be changed
12179     * to be more accurate. This parameter has no bearing on the actual operation
12180     * of the feature; it's just there for informational purposes.
12181     */
12182    ast_str_set(&header, 0, "<%s>;purpose=call-completion;m=%s", uri, "NR");
12183    add_header(resp, "Call-Info", ast_str_buffer(header));
12184    ao2_ref(agent, -1);
12185 }
12186 
12187 /*! \brief Used for 200 OK and 183 early media
12188    \return Will return XMIT_ERROR for network errors.
12189 */
12190 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)
12191 {
12192    struct sip_request resp;
12193    uint32_t seqno;
12194    if (sscanf(get_header(req, "CSeq"), "%30u ", &seqno) != 1) {
12195       ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
12196       return -1;
12197    }
12198    respprep(&resp, p, msg, req);
12199    if (rpid == TRUE) {
12200       add_rpid(&resp, p);
12201    }
12202    if (ast_test_flag(&p->flags[0], SIP_OFFER_CC)) {
12203       add_cc_call_info_to_response(p, &resp);
12204    }
12205    if (p->rtp) {
12206       if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
12207          ast_debug(1, "Setting framing from config on incoming call\n");
12208          ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &p->prefs);
12209       }
12210       ast_rtp_instance_activate(p->rtp);
12211       try_suggested_sip_codec(p);
12212       if (p->t38.state == T38_ENABLED) {
12213          add_sdp(&resp, p, oldsdp, TRUE, TRUE);
12214       } else {
12215          add_sdp(&resp, p, oldsdp, TRUE, FALSE);
12216       }
12217    } else
12218       ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
12219    if (reliable && !p->pendinginvite)
12220       p->pendinginvite = seqno;     /* Buggy clients sends ACK on RINGING too */
12221    add_required_respheader(&resp);
12222    return send_response(p, &resp, reliable, seqno);
12223 }
12224 
12225 /*! \brief Parse first line of incoming SIP request */
12226 static int determine_firstline_parts(struct sip_request *req)
12227 {
12228    char *e = ast_skip_blanks(req->data->str);   /* there shouldn't be any */
12229    char *local_rlPart1;
12230 
12231    if (!*e)
12232       return -1;
12233    req->rlPart1 = e - req->data->str;  /* method or protocol */
12234    local_rlPart1 = e;
12235    e = ast_skip_nonblanks(e);
12236    if (*e)
12237       *e++ = '\0';
12238    /* Get URI or status code */
12239    e = ast_skip_blanks(e);
12240    if ( !*e )
12241       return -1;
12242    ast_trim_blanks(e);
12243 
12244    if (!strcasecmp(local_rlPart1, "SIP/2.0") ) { /* We have a response */
12245       if (strlen(e) < 3)   /* status code is 3 digits */
12246          return -1;
12247       req->rlPart2 = e - req->data->str;
12248    } else { /* We have a request */
12249       if ( *e == '<' ) { /* XXX the spec says it must not be in <> ! */
12250          ast_debug(3, "Oops. Bogus uri in <> %s\n", e);
12251          e++;
12252          if (!*e)
12253             return -1;
12254       }
12255       req->rlPart2 = e - req->data->str;  /* URI */
12256       e = ast_skip_nonblanks(e);
12257       if (*e)
12258          *e++ = '\0';
12259       e = ast_skip_blanks(e);
12260       if (strcasecmp(e, "SIP/2.0") ) {
12261          ast_debug(3, "Skipping packet - Bad request protocol %s\n", e);
12262          return -1;
12263       }
12264    }
12265    return 1;
12266 }
12267 
12268 /*! \brief Transmit reinvite with SDP
12269 \note    A re-invite is basically a new INVITE with the same CALL-ID and TAG as the
12270    INVITE that opened the SIP dialogue
12271    We reinvite so that the audio stream (RTP) go directly between
12272    the SIP UAs. SIP Signalling stays with * in the path.
12273    
12274    If t38version is TRUE, we send T38 SDP for re-invite from audio/video to
12275    T38 UDPTL transmission on the channel
12276 
12277     If oldsdp is TRUE then the SDP version number is not incremented. This
12278     is needed for Session-Timers so we can send a re-invite to refresh the
12279     SIP session without modifying the media session.
12280 */
12281 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp)
12282 {
12283    struct sip_request req;
12284    
12285    reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ?  SIP_UPDATE : SIP_INVITE, 0, 1);
12286 
12287    add_header(&req, "Allow", ALLOWED_METHODS);
12288    add_supported_header(p, &req);
12289    if (sipdebug) {
12290       if (oldsdp == TRUE)
12291          add_header(&req, "X-asterisk-Info", "SIP re-invite (Session-Timers)");
12292       else
12293          add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
12294    }
12295 
12296    if (ast_test_flag(&p->flags[0], SIP_SENDRPID))
12297       add_rpid(&req, p);
12298 
12299    if (p->do_history) {
12300       append_history(p, "ReInv", "Re-invite sent");
12301    }
12302    memset(p->offered_media, 0, sizeof(p->offered_media));
12303 
12304    try_suggested_sip_codec(p);
12305    if (t38version) {
12306       add_sdp(&req, p, oldsdp, FALSE, TRUE);
12307    } else {
12308       add_sdp(&req, p, oldsdp, TRUE, FALSE);
12309    }
12310 
12311    /* Use this as the basis */
12312    initialize_initreq(p, &req);
12313    p->lastinvite = p->ocseq;
12314    ast_set_flag(&p->flags[0], SIP_OUTGOING);       /* Change direction of this dialog */
12315    p->ongoing_reinvite = 1;
12316    return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
12317 }
12318 
12319 /* \brief Remove URI parameters at end of URI, not in username part though */
12320 static char *remove_uri_parameters(char *uri)
12321 {
12322    char *atsign;
12323    atsign = strchr(uri, '@'); /* First, locate the at sign */
12324    if (!atsign) {
12325       atsign = uri;  /* Ok hostname only, let's stick with the rest */
12326    }
12327    atsign = strchr(atsign, ';'); /* Locate semi colon */
12328    if (atsign)
12329       *atsign = '\0';   /* Kill at the semi colon */
12330    return uri;
12331 }
12332 
12333 /*! \brief Check Contact: URI of SIP message */
12334 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
12335 {
12336    char stripped[SIPBUFSIZE];
12337    char *c;
12338 
12339    ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
12340    c = get_in_brackets(stripped);
12341    /* Cut the URI at the at sign after the @, not in the username part */
12342    c = remove_uri_parameters(c);
12343    if (!ast_strlen_zero(c)) {
12344       ast_string_field_set(p, uri, c);
12345    }
12346 
12347 }
12348 
12349 /*! \brief Build contact header - the contact header we send out */
12350 static void build_contact(struct sip_pvt *p)
12351 {
12352    char tmp[SIPBUFSIZE];
12353    char *user = ast_uri_encode(p->exten, tmp, sizeof(tmp), 0);
12354 
12355    if (p->socket.type == SIP_TRANSPORT_UDP) {
12356       ast_string_field_build(p, our_contact, "<sip:%s%s%s>", user,
12357          ast_strlen_zero(user) ? "" : "@", ast_sockaddr_stringify_remote(&p->ourip));
12358    } else {
12359       ast_string_field_build(p, our_contact, "<sip:%s%s%s;transport=%s>", user,
12360          ast_strlen_zero(user) ? "" : "@", ast_sockaddr_stringify_remote(&p->ourip),
12361          get_transport(p->socket.type));
12362    }
12363 }
12364 
12365 /*! \brief Initiate new SIP request to peer/user */
12366 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri)
12367 {
12368    struct ast_str *invite = ast_str_alloca(256);
12369    char from[256];
12370    char to[256];
12371    char tmp_n[SIPBUFSIZE/2];  /* build a local copy of 'n' if needed */
12372    char tmp_l[SIPBUFSIZE/2];  /* build a local copy of 'l' if needed */
12373    const char *l = NULL;   /* XXX what is this, exactly ? */
12374    const char *n = NULL;   /* XXX what is this, exactly ? */
12375    const char *d = NULL;   /* domain in from header */
12376    const char *urioptions = "";
12377    int ourport;
12378 
12379    if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
12380       const char *s = p->username;  /* being a string field, cannot be NULL */
12381 
12382       /* Test p->username against allowed characters in AST_DIGIT_ANY
12383          If it matches the allowed characters list, then sipuser = ";user=phone"
12384          If not, then sipuser = ""
12385       */
12386       /* + is allowed in first position in a tel: uri */
12387       if (*s == '+')
12388          s++;
12389       for (; *s; s++) {
12390          if (!strchr(AST_DIGIT_ANYNUM, *s) )
12391             break;
12392       }
12393       /* If we have only digits, add ;user=phone to the uri */
12394       if (!*s)
12395          urioptions = ";user=phone";
12396    }
12397 
12398 
12399    snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
12400 
12401    if (ast_strlen_zero(p->fromdomain)) {
12402       d = ast_sockaddr_stringify_host_remote(&p->ourip);
12403    }
12404    if (p->owner) {
12405       if ((ast_party_id_presentation(&p->owner->connected.id) & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED) {
12406          l = p->owner->connected.id.number.valid ? p->owner->connected.id.number.str : NULL;
12407          n = p->owner->connected.id.name.valid ? p->owner->connected.id.name.str : NULL;
12408       } else {
12409          /* Even if we are using RPID, we shouldn't leak information in the From if the user wants
12410           * their callerid restricted */
12411          l = "anonymous";
12412          n = CALLERID_UNKNOWN;
12413          d = FROMDOMAIN_INVALID;
12414       }
12415    }
12416 
12417    /* Hey, it's a NOTIFY! See if they've configured a mwi_from.
12418     * XXX Right now, this logic works because the only place that mwi_from
12419     * is set on the sip_pvt is in sip_send_mwi_to_peer. If things changed, then
12420     * we might end up putting the mwi_from setting into other types of NOTIFY
12421     * messages as well.
12422     */
12423    if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->mwi_from)) {
12424       l = p->mwi_from;
12425    }
12426 
12427    if (ast_strlen_zero(l))
12428       l = default_callerid;
12429    if (ast_strlen_zero(n))
12430       n = l;
12431    /* Allow user to be overridden */
12432    if (!ast_strlen_zero(p->fromuser))
12433       l = p->fromuser;
12434    else /* Save for any further attempts */
12435       ast_string_field_set(p, fromuser, l);
12436 
12437    /* Allow user to be overridden */
12438    if (!ast_strlen_zero(p->fromname))
12439       n = p->fromname;
12440    else /* Save for any further attempts */
12441       ast_string_field_set(p, fromname, n);
12442 
12443    /* Allow domain to be overridden */
12444    if (!ast_strlen_zero(p->fromdomain))
12445       d = p->fromdomain;
12446    else /* Save for any further attempts */
12447       ast_string_field_set(p, fromdomain, d);
12448 
12449    ast_copy_string(tmp_l, l, sizeof(tmp_l));
12450    if (sip_cfg.pedanticsipchecking) {
12451       ast_escape_quoted(n, tmp_n, sizeof(tmp_n));
12452       n = tmp_n;
12453       ast_uri_encode(l, tmp_l, sizeof(tmp_l), 0);
12454    }
12455 
12456    ourport = (p->fromdomainport && (p->fromdomainport != STANDARD_SIP_PORT)) ? p->fromdomainport : ast_sockaddr_port(&p->ourip);
12457    if (!sip_standard_port(p->socket.type, ourport)) {
12458       snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=%s", n, tmp_l, d, ourport, p->tag);
12459    } else {
12460       snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%s", n, tmp_l, d, p->tag);
12461    }
12462 
12463    if (!ast_strlen_zero(explicit_uri)) {
12464       ast_str_set(&invite, 0, "%s", explicit_uri);
12465    } else {
12466       /* If we're calling a registered SIP peer, use the fullcontact to dial to the peer */
12467       if (!ast_strlen_zero(p->fullcontact)) {
12468          /* If we have full contact, trust it */
12469          ast_str_append(&invite, 0, "%s", p->fullcontact);
12470       } else {
12471          /* Otherwise, use the username while waiting for registration */
12472          ast_str_append(&invite, 0, "sip:");
12473          if (!ast_strlen_zero(p->username)) {
12474             n = p->username;
12475             if (sip_cfg.pedanticsipchecking) {
12476                ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
12477                n = tmp_n;
12478             }
12479             ast_str_append(&invite, 0, "%s@", n);
12480          }
12481          ast_str_append(&invite, 0, "%s", p->tohost);
12482          if (p->portinuri) {
12483             ast_str_append(&invite, 0, ":%d", ast_sockaddr_port(&p->sa));
12484          }
12485          ast_str_append(&invite, 0, "%s", urioptions);
12486       }
12487    }
12488 
12489    /* If custom URI options have been provided, append them */
12490    if (p->options && !ast_strlen_zero(p->options->uri_options))
12491       ast_str_append(&invite, 0, ";%s", p->options->uri_options);
12492    
12493    /* This is the request URI, which is the next hop of the call
12494       which may or may not be the destination of the call
12495    */
12496    ast_string_field_set(p, uri, ast_str_buffer(invite));
12497 
12498    if (!ast_strlen_zero(p->todnid)) {
12499       /*! \todo Need to add back the VXML URL here at some point, possibly use build_string for all this junk */
12500       if (!strchr(p->todnid, '@')) {
12501          /* We have no domain in the dnid */
12502          snprintf(to, sizeof(to), "<sip:%s@%s>%s%s", p->todnid, p->tohost, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
12503       } else {
12504          snprintf(to, sizeof(to), "<sip:%s>%s%s", p->todnid, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
12505       }
12506    } else {
12507       if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) {
12508          /* If this is a NOTIFY, use the From: tag in the subscribe (RFC 3265) */
12509          snprintf(to, sizeof(to), "<%s%s>;tag=%s", (strncasecmp(p->uri, "sip:", 4) ? "sip:" : ""), p->uri, p->theirtag);
12510       } else if (p->options && p->options->vxml_url) {
12511          /* If there is a VXML URL append it to the SIP URL */
12512          snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
12513       } else {
12514          snprintf(to, sizeof(to), "<%s>", p->uri);
12515       }
12516    }
12517 
12518    init_req(req, sipmethod, p->uri);
12519    /* now tmp_n is available so reuse it to build the CSeq */
12520    snprintf(tmp_n, sizeof(tmp_n), "%u %s", ++p->ocseq, sip_methods[sipmethod].text);
12521 
12522    add_header(req, "Via", p->via);
12523    add_header_max_forwards(p, req);
12524    /* This will be a no-op most of the time. However, under certain circumstances,
12525     * NOTIFY messages will use this function for preparing the request and should
12526     * have Route headers present.
12527     */
12528    add_route(req, p->route);
12529 
12530    add_header(req, "From", from);
12531    add_header(req, "To", to);
12532    ast_string_field_set(p, exten, l);
12533    build_contact(p);
12534    add_header(req, "Contact", p->our_contact);
12535    add_header(req, "Call-ID", p->callid);
12536    add_header(req, "CSeq", tmp_n);
12537    if (!ast_strlen_zero(global_useragent)) {
12538       add_header(req, "User-Agent", global_useragent);
12539    }
12540 }
12541 
12542 /*! \brief Add "Diversion" header to outgoing message
12543  *
12544  * We need to add a Diversion header if the owner channel of
12545  * this dialog has redirecting information associated with it.
12546  *
12547  * \param req The request/response to which we will add the header
12548  * \param pvt The sip_pvt which represents the call-leg
12549  */
12550 static void add_diversion_header(struct sip_request *req, struct sip_pvt *pvt)
12551 {
12552    const char *diverting_number;
12553    const char *diverting_name;
12554    const char *reason;
12555    char header_text[256];
12556 
12557    if (!pvt->owner) {
12558       return;
12559    }
12560 
12561    diverting_number = pvt->owner->redirecting.from.number.str;
12562    if (!pvt->owner->redirecting.from.number.valid
12563       || ast_strlen_zero(diverting_number)) {
12564       return;
12565    }
12566 
12567    reason = sip_reason_code_to_str(pvt->owner->redirecting.reason);
12568 
12569    /* We at least have a number to place in the Diversion header, which is enough */
12570    diverting_name = pvt->owner->redirecting.from.name.str;
12571    if (!pvt->owner->redirecting.from.name.valid
12572       || ast_strlen_zero(diverting_name)) {
12573       snprintf(header_text, sizeof(header_text), "<sip:%s@%s>;reason=%s", diverting_number,
12574             ast_sockaddr_stringify_host_remote(&pvt->ourip), reason);
12575    } else {
12576       char diverting_name_buf[128];
12577 
12578       ast_escape_quoted(diverting_name, diverting_name_buf, sizeof(diverting_name_buf));
12579       snprintf(header_text, sizeof(header_text), "\"%s\" <sip:%s@%s>;reason=%s",
12580             diverting_name_buf, diverting_number,
12581             ast_sockaddr_stringify_host_remote(&pvt->ourip), reason);
12582    }
12583 
12584    add_header(req, "Diversion", header_text);
12585 }
12586 
12587 static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri)
12588 {
12589    struct sip_pvt *pvt;
12590    int expires;
12591 
12592    epa_entry->publish_type = publish_type;
12593 
12594    if (!(pvt = sip_alloc(NULL, NULL, 0, SIP_PUBLISH, NULL))) {
12595       return -1;
12596    }
12597 
12598    sip_pvt_lock(pvt);
12599 
12600    if (create_addr(pvt, epa_entry->destination, NULL, TRUE)) {
12601       sip_pvt_unlock(pvt);
12602       dialog_unlink_all(pvt);
12603       dialog_unref(pvt, "create_addr failed in transmit_publish. Unref dialog");
12604       return -1;
12605    }
12606    ast_sip_ouraddrfor(&pvt->sa, &pvt->ourip, pvt);
12607    ast_set_flag(&pvt->flags[0], SIP_OUTGOING);
12608    expires = (publish_type == SIP_PUBLISH_REMOVE) ? 0 : DEFAULT_PUBLISH_EXPIRES;
12609    pvt->expiry = expires;
12610 
12611    /* Bump refcount for sip_pvt's reference */
12612    ao2_ref(epa_entry, +1);
12613    pvt->epa_entry = epa_entry;
12614 
12615    transmit_invite(pvt, SIP_PUBLISH, FALSE, 2, explicit_uri);
12616    sip_pvt_unlock(pvt);
12617    sip_scheddestroy(pvt, DEFAULT_TRANS_TIMEOUT);
12618    dialog_unref(pvt, "Done with the sip_pvt allocated for transmitting PUBLISH");
12619    return 0;
12620 }
12621 
12622 /*! 
12623  * \brief Build REFER/INVITE/OPTIONS/SUBSCRIBE message and transmit it
12624  * \param p sip_pvt structure
12625  * \param sipmethod
12626  * \param sdp unknown
12627  * \param init 0 = Prepare request within dialog, 1= prepare request, new branch,
12628  *  2= prepare new request and new dialog. do_proxy_auth calls this with init!=2
12629  * \param explicit_uri
12630 */
12631 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri)
12632 {
12633    struct sip_request req;
12634    struct ast_variable *var;
12635 
12636    if (init) {/* Bump branch even on initial requests */
12637       p->branch ^= ast_random();
12638       p->invite_branch = p->branch;
12639       build_via(p);
12640    }
12641    if (init > 1) {
12642       initreqprep(&req, p, sipmethod, explicit_uri);
12643    } else {
12644       /* If init=1, we should not generate a new branch. If it's 0, we need a new branch. */
12645       reqprep(&req, p, sipmethod, 0, init ? 0 : 1);
12646    }
12647 
12648    if (p->options && p->options->auth) {
12649       add_header(&req, p->options->authheader, p->options->auth);
12650    }
12651    append_date(&req);
12652    if (sipmethod == SIP_REFER) { /* Call transfer */
12653       if (p->refer) {
12654          char buf[SIPBUFSIZE];
12655          if (!ast_strlen_zero(p->refer->refer_to)) {
12656             add_header(&req, "Refer-To", p->refer->refer_to);
12657          }
12658          if (!ast_strlen_zero(p->refer->referred_by)) {
12659             snprintf(buf, sizeof(buf), "%s <%s>", p->refer->referred_by_name, p->refer->referred_by);
12660             add_header(&req, "Referred-By", buf);
12661          }
12662       }
12663    } else if (sipmethod == SIP_SUBSCRIBE) {
12664       char buf[SIPBUFSIZE];
12665       if (p->subscribed == MWI_NOTIFICATION) {
12666          add_header(&req, "Event", "message-summary");
12667          add_header(&req, "Accept", "application/simple-message-summary");
12668       } else if (p->subscribed == CALL_COMPLETION) {
12669          add_header(&req, "Event", "call-completion");
12670          add_header(&req, "Accept", "application/call-completion");
12671       }
12672       snprintf(buf, sizeof(buf), "%d", p->expiry);
12673       add_header(&req, "Expires", buf);
12674    }
12675 
12676    /* This new INVITE is part of an attended transfer. Make sure that the
12677    other end knows and replace the current call with this new call */
12678    if (p->options && !ast_strlen_zero(p->options->replaces)) {
12679       add_header(&req, "Replaces", p->options->replaces);
12680       add_header(&req, "Require", "replaces");
12681    }
12682 
12683    /* Add Session-Timers related headers */
12684    if (st_get_mode(p, 0) == SESSION_TIMER_MODE_ORIGINATE
12685       || (st_get_mode(p, 0) == SESSION_TIMER_MODE_ACCEPT
12686          && st_get_se(p, FALSE) != DEFAULT_MIN_SE)) {
12687       char i2astr[10];
12688 
12689       if (!p->stimer->st_interval) {
12690          p->stimer->st_interval = st_get_se(p, TRUE);
12691       }
12692 
12693       p->stimer->st_active = TRUE;
12694       if (st_get_mode(p, 0) == SESSION_TIMER_MODE_ORIGINATE) { 
12695          snprintf(i2astr, sizeof(i2astr), "%d", p->stimer->st_interval);
12696          add_header(&req, "Session-Expires", i2astr);
12697       }
12698 
12699       snprintf(i2astr, sizeof(i2astr), "%d", st_get_se(p, FALSE));
12700       add_header(&req, "Min-SE", i2astr);
12701    }
12702 
12703    add_header(&req, "Allow", ALLOWED_METHODS);
12704    add_supported_header(p, &req);
12705 
12706    if (p->options && p->options->addsipheaders && p->owner) {
12707       struct ast_channel *chan = p->owner; /* The owner channel */
12708       struct varshead *headp;
12709    
12710       ast_channel_lock(chan);
12711 
12712       headp = &chan->varshead;
12713 
12714       if (!headp) {
12715          ast_log(LOG_WARNING, "No Headp for the channel...ooops!\n");
12716       } else {
12717          const struct ast_var_t *current;
12718          AST_LIST_TRAVERSE(headp, current, entries) {
12719             /* SIPADDHEADER: Add SIP header to outgoing call */
12720             if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
12721                char *content, *end;
12722                const char *header = ast_var_value(current);
12723                char *headdup = ast_strdupa(header);
12724 
12725                /* Strip of the starting " (if it's there) */
12726                if (*headdup == '"') {
12727                   headdup++;
12728                }
12729                if ((content = strchr(headdup, ':'))) {
12730                   *content++ = '\0';
12731                   content = ast_skip_blanks(content); /* Skip white space */
12732                   /* Strip the ending " (if it's there) */
12733                   end = content + strlen(content) -1; 
12734                   if (*end == '"') {
12735                      *end = '\0';
12736                   }
12737                
12738                   add_header(&req, headdup, content);
12739                   if (sipdebug) {
12740                      ast_debug(1, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
12741                   }
12742                }
12743             }
12744          }
12745       }
12746 
12747       ast_channel_unlock(chan);
12748    }
12749    if ((sipmethod == SIP_INVITE || sipmethod == SIP_UPDATE) && ast_test_flag(&p->flags[0], SIP_SENDRPID))
12750       add_rpid(&req, p);
12751    if (sipmethod == SIP_INVITE) {
12752       add_diversion_header(&req, p);
12753    }
12754    if (sdp) {
12755       memset(p->offered_media, 0, sizeof(p->offered_media));
12756       if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
12757          ast_debug(1, "T38 is in state %u on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
12758          add_sdp(&req, p, FALSE, FALSE, TRUE);
12759       } else if (p->rtp) {
12760          try_suggested_sip_codec(p);
12761          add_sdp(&req, p, FALSE, TRUE, FALSE);
12762       }
12763    } else if (p->notify) {
12764       for (var = p->notify->headers; var; var = var->next) {
12765          add_header(&req, var->name, var->value);
12766       }
12767       if (ast_str_strlen(p->notify->content)) {
12768          add_content(&req, ast_str_buffer(p->notify->content));
12769       }
12770    } else if (sipmethod == SIP_PUBLISH) {
12771       char expires[SIPBUFSIZE];
12772 
12773       switch (p->epa_entry->static_data->event) {
12774       case CALL_COMPLETION:
12775          snprintf(expires, sizeof(expires), "%d", p->expiry);
12776          add_header(&req, "Event", "call-completion");
12777          add_header(&req, "Expires", expires);
12778          if (p->epa_entry->publish_type != SIP_PUBLISH_INITIAL) {
12779             add_header(&req, "SIP-If-Match", p->epa_entry->entity_tag);
12780          }
12781 
12782          if (!ast_strlen_zero(p->epa_entry->body)) {
12783             add_header(&req, "Content-Type", "application/pidf+xml");
12784             add_content(&req, p->epa_entry->body);
12785          }
12786       default:
12787          break;
12788       }
12789    }
12790 
12791    if (!p->initreq.headers || init > 2) {
12792       initialize_initreq(p, &req);
12793    }
12794    if (sipmethod == SIP_INVITE || sipmethod == SIP_SUBSCRIBE) {
12795       p->lastinvite = p->ocseq;
12796    }
12797    return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
12798 }
12799 
12800 /*! \brief Send a subscription or resubscription for MWI */
12801 static int sip_subscribe_mwi_do(const void *data)
12802 {
12803    struct sip_subscription_mwi *mwi = (struct sip_subscription_mwi*)data;
12804    
12805    if (!mwi) {
12806       return -1;
12807    }
12808    
12809    mwi->resub = -1;
12810    __sip_subscribe_mwi_do(mwi);
12811    ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
12812    
12813    return 0;
12814 }
12815 
12816 static void on_dns_update_registry(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
12817 {
12818    struct sip_registry *reg = data;
12819    const char *old_str;
12820 
12821    /* This shouldn't happen, but just in case */
12822    if (ast_sockaddr_isnull(new)) {
12823       ast_debug(1, "Empty sockaddr change...ignoring!\n");
12824       return;
12825    }
12826 
12827    if (!ast_sockaddr_port(new)) {
12828       ast_sockaddr_set_port(new, reg->portno);
12829    }
12830 
12831    old_str = ast_strdupa(ast_sockaddr_stringify(old));
12832 
12833    ast_debug(1, "Changing registry %s from %s to %s\n", S_OR(reg->peername, reg->hostname), old_str, ast_sockaddr_stringify(new));
12834    ast_sockaddr_copy(&reg->us, new);
12835 }
12836 
12837 static void on_dns_update_peer(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
12838 {
12839    struct sip_peer *peer = data;
12840    const char *old_str;
12841 
12842    /* This shouldn't happen, but just in case */
12843    if (ast_sockaddr_isnull(new)) {
12844       ast_debug(1, "Empty sockaddr change...ignoring!\n");
12845       return;
12846    }
12847 
12848    if (!ast_sockaddr_isnull(&peer->addr)) {
12849       ao2_unlink(peers_by_ip, peer);
12850    }
12851 
12852    if (!ast_sockaddr_port(new)) {
12853       ast_sockaddr_set_port(new, default_sip_port(peer->socket.type));
12854    }
12855 
12856    old_str = ast_strdupa(ast_sockaddr_stringify(old));
12857    ast_debug(1, "Changing peer %s address from %s to %s\n", peer->name, old_str, ast_sockaddr_stringify(new));
12858 
12859    ao2_lock(peer);
12860    ast_sockaddr_copy(&peer->addr, new);
12861    ao2_unlock(peer);
12862 
12863    ao2_link(peers_by_ip, peer);
12864 }
12865 
12866 static void on_dns_update_mwi(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
12867 {
12868    struct sip_subscription_mwi *mwi = data;
12869    const char *old_str;
12870 
12871    /* This shouldn't happen, but just in case */
12872    if (ast_sockaddr_isnull(new)) {
12873       ast_debug(1, "Empty sockaddr change...ignoring!\n");
12874       return;
12875    }
12876 
12877    old_str = ast_strdupa(ast_sockaddr_stringify(old));
12878    ast_debug(1, "Changing mwi %s from %s to %s\n", mwi->hostname, old_str, ast_sockaddr_stringify(new));
12879    ast_sockaddr_copy(&mwi->us, new);
12880 }
12881 
12882 /*! \brief Actually setup an MWI subscription or resubscribe */
12883 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi)
12884 {
12885    /* If we have no DNS manager let's do a lookup */
12886    if (!mwi->dnsmgr) {
12887       char transport[MAXHOSTNAMELEN];
12888       struct sip_subscription_mwi *saved;
12889       snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(mwi->transport), get_srv_protocol(mwi->transport));
12890 
12891       mwi->us.ss.ss_family = get_address_family_filter(mwi->transport); /* Filter address family */
12892       saved = ASTOBJ_REF(mwi);
12893       ast_dnsmgr_lookup_cb(mwi->hostname, &mwi->us, &mwi->dnsmgr, sip_cfg.srvlookup ? transport : NULL, on_dns_update_mwi, saved);
12894       if (!mwi->dnsmgr) {
12895          ASTOBJ_UNREF(saved, sip_subscribe_mwi_destroy); /* dnsmgr disabled, remove reference */
12896       }
12897    }
12898 
12899    /* If we already have a subscription up simply send a resubscription */
12900    if (mwi->call) {
12901       transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 0, NULL);
12902       return 0;
12903    }
12904    
12905    /* Create a dialog that we will use for the subscription */
12906    if (!(mwi->call = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
12907       return -1;
12908    }
12909 
12910    ref_proxy(mwi->call, obproxy_get(mwi->call, NULL));
12911 
12912    if (!ast_sockaddr_port(&mwi->us) && mwi->portno) {
12913       ast_sockaddr_set_port(&mwi->us, mwi->portno);
12914    }
12915    
12916    /* Setup the destination of our subscription */
12917    if (create_addr(mwi->call, mwi->hostname, &mwi->us, 0)) {
12918       dialog_unlink_all(mwi->call);
12919       mwi->call = dialog_unref(mwi->call, "unref dialog after unlink_all");
12920       return 0;
12921    }
12922 
12923    mwi->call->expiry = mwi_expiry;
12924    
12925    if (!mwi->dnsmgr && mwi->portno) {
12926       ast_sockaddr_set_port(&mwi->call->sa, mwi->portno);
12927       ast_sockaddr_set_port(&mwi->call->recv, mwi->portno);
12928    } else {
12929       mwi->portno = ast_sockaddr_port(&mwi->call->sa);
12930    }
12931    
12932    /* Set various other information */
12933    if (!ast_strlen_zero(mwi->authuser)) {
12934       ast_string_field_set(mwi->call, peername, mwi->authuser);
12935       ast_string_field_set(mwi->call, authname, mwi->authuser);
12936       ast_string_field_set(mwi->call, fromuser, mwi->authuser);
12937    } else {
12938       ast_string_field_set(mwi->call, peername, mwi->username);
12939       ast_string_field_set(mwi->call, authname, mwi->username);
12940       ast_string_field_set(mwi->call, fromuser, mwi->username);
12941    }
12942    ast_string_field_set(mwi->call, username, mwi->username);
12943    if (!ast_strlen_zero(mwi->secret)) {
12944       ast_string_field_set(mwi->call, peersecret, mwi->secret);
12945    }
12946    set_socket_transport(&mwi->call->socket, mwi->transport);
12947    mwi->call->socket.port = htons(mwi->portno);
12948    ast_sip_ouraddrfor(&mwi->call->sa, &mwi->call->ourip, mwi->call);
12949    build_contact(mwi->call);
12950    build_via(mwi->call);
12951 
12952    /* Change the dialog callid. */
12953    change_callid_pvt(mwi->call, NULL);
12954 
12955    ast_set_flag(&mwi->call->flags[0], SIP_OUTGOING);
12956    
12957    /* Associate the call with us */
12958    mwi->call->mwi = ASTOBJ_REF(mwi);
12959 
12960    mwi->call->subscribed = MWI_NOTIFICATION;
12961 
12962    /* Actually send the packet */
12963    transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 2, NULL);
12964 
12965    return 0;
12966 }
12967 
12968 /*! \brief Find the channel that is causing the RINGING update */
12969 static int find_calling_channel(void *obj, void *arg, void *data, int flags)
12970 {
12971    struct ast_channel *c = obj;
12972    struct sip_pvt *p = data;
12973    int res;
12974 
12975    ast_channel_lock(c);
12976 
12977    res = (c->pbx &&
12978          (!strcasecmp(c->macroexten, p->exten) || !strcasecmp(c->exten, p->exten)) &&
12979          (sip_cfg.notifycid == IGNORE_CONTEXT || !strcasecmp(c->context, p->context)));
12980 
12981    ast_channel_unlock(c);
12982 
12983    return res ? CMP_MATCH | CMP_STOP : 0;
12984 }
12985 
12986 /*! \brief Builds XML portion of NOTIFY messages for presence or dialog updates */
12987 static void state_notify_build_xml(int state, int full, const char *exten, const char *context, struct ast_str **tmp, struct sip_pvt *p, int subscribed, const char *mfrom, const char *mto)
12988 {
12989    enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
12990    const char *statestring = "terminated";
12991    const char *pidfstate = "--";
12992    const char *pidfnote= "Ready";
12993    char hint[AST_MAX_EXTENSION];
12994 
12995    switch (state) {
12996    case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
12997       statestring = (sip_cfg.notifyringing) ? "early" : "confirmed";
12998       local_state = NOTIFY_INUSE;
12999       pidfstate = "busy";
13000       pidfnote = "Ringing";
13001       break;
13002    case AST_EXTENSION_RINGING:
13003       statestring = "early";
13004       local_state = NOTIFY_INUSE;
13005       pidfstate = "busy";
13006       pidfnote = "Ringing";
13007       break;
13008    case AST_EXTENSION_INUSE:
13009       statestring = "confirmed";
13010       local_state = NOTIFY_INUSE;
13011       pidfstate = "busy";
13012       pidfnote = "On the phone";
13013       break;
13014    case AST_EXTENSION_BUSY:
13015       statestring = "confirmed";
13016       local_state = NOTIFY_CLOSED;
13017       pidfstate = "busy";
13018       pidfnote = "On the phone";
13019       break;
13020    case AST_EXTENSION_UNAVAILABLE:
13021       statestring = "terminated";
13022       local_state = NOTIFY_CLOSED;
13023       pidfstate = "away";
13024       pidfnote = "Unavailable";
13025       break;
13026    case AST_EXTENSION_ONHOLD:
13027       statestring = "confirmed";
13028       local_state = NOTIFY_CLOSED;
13029       pidfstate = "busy";
13030       pidfnote = "On hold";
13031       break;
13032    case AST_EXTENSION_NOT_INUSE:
13033    default:
13034       /* Default setting */
13035       break;
13036    }
13037 
13038    /* Check which device/devices we are watching  and if they are registered */
13039    if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, context, exten)) {
13040       char *hint2 = hint, *individual_hint = NULL;
13041       int hint_count = 0, unavailable_count = 0;
13042 
13043       while ((individual_hint = strsep(&hint2, "&"))) {
13044          hint_count++;
13045 
13046          if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
13047             unavailable_count++;
13048       }
13049 
13050       /* If none of the hinted devices are registered, we will
13051        * override notification and show no availability.
13052        */
13053       if (hint_count > 0 && hint_count == unavailable_count) {
13054          local_state = NOTIFY_CLOSED;
13055          pidfstate = "away";
13056          pidfnote = "Not online";
13057       }
13058    }
13059 
13060    switch (subscribed) {
13061    case XPIDF_XML:
13062    case CPIM_PIDF_XML:
13063       ast_str_append(tmp, 0,
13064          "<?xml version=\"1.0\"?>\n"
13065          "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n"
13066          "<presence>\n");
13067       ast_str_append(tmp, 0, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
13068       ast_str_append(tmp, 0, "<atom id=\"%s\">\n", exten);
13069       ast_str_append(tmp, 0, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
13070       ast_str_append(tmp, 0, "<status status=\"%s\" />\n", (local_state ==  NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
13071       ast_str_append(tmp, 0, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
13072       ast_str_append(tmp, 0, "</address>\n</atom>\n</presence>\n");
13073       break;
13074    case PIDF_XML: /* Eyebeam supports this format */
13075       ast_str_append(tmp, 0,
13076          "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
13077          "<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);
13078       ast_str_append(tmp, 0, "<pp:person><status>\n");
13079       if (pidfstate[0] != '-') {
13080          ast_str_append(tmp, 0, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
13081       }
13082       ast_str_append(tmp, 0, "</status></pp:person>\n");
13083       ast_str_append(tmp, 0, "<note>%s</note>\n", pidfnote); /* Note */
13084       ast_str_append(tmp, 0, "<tuple id=\"%s\">\n", exten); /* Tuple start */
13085       ast_str_append(tmp, 0, "<contact priority=\"1\">%s</contact>\n", mto);
13086       if (pidfstate[0] == 'b') /* Busy? Still open ... */
13087          ast_str_append(tmp, 0, "<status><basic>open</basic></status>\n");
13088       else
13089          ast_str_append(tmp, 0, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
13090       ast_str_append(tmp, 0, "</tuple>\n</presence>\n");
13091       break;
13092    case DIALOG_INFO_XML: /* SNOM subscribes in this format */
13093       ast_str_append(tmp, 0, "<?xml version=\"1.0\"?>\n");
13094       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);
13095 
13096       if ((state & AST_EXTENSION_RINGING) && sip_cfg.notifyringing) {
13097          /* Twice the extension length should be enough for XML encoding */
13098          char local_display[AST_MAX_EXTENSION * 2];
13099          char remote_display[AST_MAX_EXTENSION * 2];
13100          char *local_target = ast_strdupa(mto);
13101          /* It may seem odd to base the remote_target on the To header here,
13102           * but testing by reporters on issue ASTERISK-16735 found that basing
13103           * on the From header would cause ringing state hints to not work
13104           * properly on certain SNOM devices. If you are using notifycid properly
13105           * (i.e. in the same extension and context as the dialed call) then this
13106           * should not be an issue since the data will be overwritten shortly
13107           * with channel caller ID
13108           */
13109          char *remote_target = ast_strdupa(mto);
13110 
13111          ast_xml_escape(exten, local_display, sizeof(local_display));
13112          ast_xml_escape(exten, remote_display, sizeof(remote_display));
13113 
13114          /* There are some limitations to how this works.  The primary one is that the
13115             callee must be dialing the same extension that is being monitored.  Simply dialing
13116             the hint'd device is not sufficient. */
13117          if (sip_cfg.notifycid) {
13118             struct ast_channel *caller;
13119 
13120             if ((caller = ast_channel_callback(find_calling_channel, NULL, p, 0))) {
13121                static char *anonymous = "anonymous";
13122                static char *invalid = "anonymous.invalid";
13123                char *cid_num;
13124                char *connected_num;
13125                int need;
13126                int cid_num_restricted, connected_num_restricted;
13127 
13128                ast_channel_lock(caller);
13129 
13130                cid_num_restricted = (caller->caller.id.number.presentation &
13131                            AST_PRES_RESTRICTION) == AST_PRES_RESTRICTED;
13132                cid_num = S_COR(caller->caller.id.number.valid,
13133                      S_COR(cid_num_restricted, anonymous,
13134                            caller->caller.id.number.str), "");
13135 
13136                need = strlen(cid_num) + (cid_num_restricted ? strlen(invalid) :
13137                           strlen(p->fromdomain)) + sizeof("sip:@");
13138 
13139                remote_target = ast_alloca(need);
13140                snprintf(remote_target, need, "sip:%s@%s", cid_num,
13141                    cid_num_restricted ? invalid : p->fromdomain);
13142 
13143                ast_xml_escape(S_COR(caller->caller.id.name.valid,
13144                           S_COR((caller->caller.id.name.presentation &
13145                              AST_PRES_RESTRICTION) == AST_PRES_RESTRICTED, anonymous,
13146                            caller->caller.id.name.str), ""),
13147                          remote_display, sizeof(remote_display));
13148 
13149                connected_num_restricted = (caller->connected.id.number.presentation &
13150                             AST_PRES_RESTRICTION) == AST_PRES_RESTRICTED;
13151                connected_num = S_COR(caller->connected.id.number.valid,
13152                            S_COR(connected_num_restricted, anonymous,
13153                             caller->connected.id.number.str), "");
13154 
13155                need = strlen(connected_num) + (connected_num_restricted ? strlen(invalid) :
13156                            strlen(p->fromdomain)) + sizeof("sip:@");
13157                local_target = ast_alloca(need);
13158 
13159                snprintf(local_target, need, "sip:%s@%s", connected_num,
13160                    connected_num_restricted ? invalid : p->fromdomain);
13161 
13162                ast_xml_escape(S_COR(caller->connected.id.name.valid,
13163                           S_COR((caller->connected.id.name.presentation &
13164                              AST_PRES_RESTRICTION) == AST_PRES_RESTRICTED, anonymous,
13165                             caller->connected.id.name.str), ""),
13166                          local_display, sizeof(local_display));
13167 
13168                ast_channel_unlock(caller);
13169                caller = ast_channel_unref(caller);
13170             }
13171 
13172             /* We create a fake call-id which the phone will send back in an INVITE
13173                Replaces header which we can grab and do some magic with. */
13174             if (sip_cfg.pedanticsipchecking) {
13175                ast_str_append(tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" local-tag=\"%s\" remote-tag=\"%s\" direction=\"recipient\">\n",
13176                   exten, p->callid, p->theirtag, p->tag);
13177             } else {
13178                ast_str_append(tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" direction=\"recipient\">\n",
13179                   exten, p->callid);
13180             }
13181             ast_str_append(tmp, 0,
13182                   "<remote>\n"
13183                   /* See the limitations of this above.  Luckily the phone seems to still be
13184                      happy when these values are not correct. */
13185                   "<identity display=\"%s\">%s</identity>\n"
13186                   "<target uri=\"%s\"/>\n"
13187                   "</remote>\n"
13188                   "<local>\n"
13189                   "<identity display=\"%s\">%s</identity>\n"
13190                   "<target uri=\"%s\"/>\n"
13191                   "</local>\n",
13192                   remote_display, remote_target, remote_target, local_display, local_target, local_target);
13193          } else {
13194             ast_str_append(tmp, 0, "<dialog id=\"%s\" direction=\"recipient\">\n", exten);
13195          }
13196 
13197       } else {
13198          ast_str_append(tmp, 0, "<dialog id=\"%s\">\n", exten);
13199       }
13200       ast_str_append(tmp, 0, "<state>%s</state>\n", statestring);
13201       if (state == AST_EXTENSION_ONHOLD) {
13202             ast_str_append(tmp, 0, "<local>\n<target uri=\"%s\">\n"
13203                                              "<param pname=\"+sip.rendering\" pvalue=\"no\"/>\n"
13204                                              "</target>\n</local>\n", mto);
13205       }
13206       ast_str_append(tmp, 0, "</dialog>\n</dialog-info>\n");
13207       break;
13208    case NONE:
13209    default:
13210       break;
13211    }
13212 }
13213 
13214 static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state)
13215 {
13216    struct sip_request req;
13217    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
13218    char uri[SIPBUFSIZE];
13219    char state_str[64];
13220    char subscription_state_hdr[64];
13221 
13222    if (state < CC_QUEUED || state > CC_READY) {
13223       ast_log(LOG_WARNING, "Invalid state provided for transmit_cc_notify (%u)\n", state);
13224       return -1;
13225    }
13226 
13227    reqprep(&req, subscription, SIP_NOTIFY, 0, TRUE);
13228    snprintf(state_str, sizeof(state_str), "%s\r\n", sip_cc_notify_state_map[state].state_string);
13229    add_header(&req, "Event", "call-completion");
13230    add_header(&req, "Content-Type", "application/call-completion");
13231    snprintf(subscription_state_hdr, sizeof(subscription_state_hdr), "active;expires=%d", subscription->expiry);
13232    add_header(&req, "Subscription-State", subscription_state_hdr);
13233    if (state == CC_READY) {
13234       generate_uri(subscription, agent_pvt->notify_uri, sizeof(agent_pvt->notify_uri));
13235       snprintf(uri, sizeof(uri) - 1, "cc-URI: %s\r\n", agent_pvt->notify_uri);
13236    }
13237    add_content(&req, state_str);
13238    if (state == CC_READY) {
13239       add_content(&req, uri);
13240    }
13241    return send_request(subscription, &req, XMIT_RELIABLE, subscription->ocseq);
13242 }
13243 
13244 /*! \brief Used in the SUBSCRIBE notification subsystem (RFC3265) */
13245 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout)
13246 {
13247    struct ast_str *tmp = ast_str_alloca(4000);
13248    char from[256], to[256];
13249    char *c, *mfrom, *mto;
13250    struct sip_request req;
13251    const struct cfsubscription_types *subscriptiontype;
13252 
13253    /* If the subscription has not yet been accepted do not send a NOTIFY */
13254    if (!ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
13255       return 0;
13256    }
13257 
13258    memset(from, 0, sizeof(from));
13259    memset(to, 0, sizeof(to));
13260 
13261    subscriptiontype = find_subscription_type(p->subscribed);
13262 
13263    ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
13264    c = get_in_brackets(from);
13265    if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
13266       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
13267       return -1;
13268    }
13269 
13270    mfrom = remove_uri_parameters(c);
13271 
13272    ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
13273    c = get_in_brackets(to);
13274    if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
13275       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
13276       return -1;
13277    }
13278    mto = remove_uri_parameters(c);
13279 
13280    reqprep(&req, p, SIP_NOTIFY, 0, 1);
13281 
13282    switch(state) {
13283    case AST_EXTENSION_DEACTIVATED:
13284       if (timeout)
13285          add_header(&req, "Subscription-State", "terminated;reason=timeout");
13286       else {
13287          add_header(&req, "Subscription-State", "terminated;reason=probation");
13288          add_header(&req, "Retry-After", "60");
13289       }
13290       break;
13291    case AST_EXTENSION_REMOVED:
13292       add_header(&req, "Subscription-State", "terminated;reason=noresource");
13293       break;
13294    default:
13295       if (p->expiry)
13296          add_header(&req, "Subscription-State", "active");
13297       else  /* Expired */
13298          add_header(&req, "Subscription-State", "terminated;reason=timeout");
13299    }
13300 
13301    switch (p->subscribed) {
13302    case XPIDF_XML:
13303    case CPIM_PIDF_XML:
13304       add_header(&req, "Event", subscriptiontype->event);
13305       state_notify_build_xml(state, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
13306       add_header(&req, "Content-Type", subscriptiontype->mediatype);
13307       p->dialogver++;
13308       break;
13309    case PIDF_XML: /* Eyebeam supports this format */
13310       add_header(&req, "Event", subscriptiontype->event);
13311       state_notify_build_xml(state, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
13312       add_header(&req, "Content-Type", subscriptiontype->mediatype);
13313       p->dialogver++;
13314       break;
13315    case DIALOG_INFO_XML: /* SNOM subscribes in this format */
13316       add_header(&req, "Event", subscriptiontype->event);
13317       state_notify_build_xml(state, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
13318       add_header(&req, "Content-Type", subscriptiontype->mediatype);
13319       p->dialogver++;
13320       break;
13321    case NONE:
13322    default:
13323       break;
13324    }
13325 
13326    add_content(&req, ast_str_buffer(tmp));
13327 
13328    p->pendinginvite = p->ocseq;  /* Remember that we have a pending NOTIFY in order not to confuse the NOTIFY subsystem */
13329 
13330    /* Send as XMIT_CRITICAL as we may never receive a 200 OK Response which clears p->pendinginvite.
13331     *
13332     * extensionstate_update() uses p->pendinginvite for queuing control.
13333     * Updates stall if pendinginvite <> 0.
13334     *
13335     * The most appropriate solution is to remove the subscription when the NOTIFY transaction fails.
13336     * The client will re-subscribe after restarting or maxexpiry timeout.
13337     */
13338 
13339    /* RFC6665 4.2.2.  Sending State Information to Subscribers
13340     * If the NOTIFY request fails due to expiration of SIP Timer F (transaction timeout),
13341     * the notifier SHOULD remove the subscription.
13342     */
13343    return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
13344 }
13345 
13346 /*! \brief Notify user of messages waiting in voicemail (RFC3842)
13347 \note - Notification only works for registered peers with mailbox= definitions
13348    in sip.conf
13349    - We use the SIP Event package message-summary
13350     MIME type defaults to  "application/simple-message-summary";
13351  */
13352 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten)
13353 {
13354    struct sip_request req;
13355    struct ast_str *out = ast_str_alloca(500);
13356    int ourport = (p->fromdomainport && (p->fromdomainport != STANDARD_SIP_PORT)) ? p->fromdomainport : ast_sockaddr_port(&p->ourip);
13357    const char *domain;
13358    const char *exten = S_OR(vmexten, default_vmexten);
13359 
13360    initreqprep(&req, p, SIP_NOTIFY, NULL);
13361    add_header(&req, "Event", "message-summary");
13362    add_header(&req, "Content-Type", default_notifymime);
13363    ast_str_append(&out, 0, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
13364 
13365    /* domain initialization occurs here because initreqprep changes ast_sockaddr_stringify string. */
13366    domain = S_OR(p->fromdomain, ast_sockaddr_stringify_host_remote(&p->ourip));
13367 
13368    if (!sip_standard_port(p->socket.type, ourport)) {
13369       if (p->socket.type == SIP_TRANSPORT_UDP) {
13370          ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d\r\n", exten, domain, ourport);
13371       } else {
13372          ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d;transport=%s\r\n", exten, domain, ourport, get_transport(p->socket.type));
13373       }
13374    } else {
13375       if (p->socket.type == SIP_TRANSPORT_UDP) {
13376          ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, domain);
13377       } else {
13378          ast_str_append(&out, 0, "Message-Account: sip:%s@%s;transport=%s\r\n", exten, domain, get_transport(p->socket.type));
13379       }
13380    }
13381    /* Cisco has a bug in the SIP stack where it can't accept the
13382       (0/0) notification. This can temporarily be disabled in
13383       sip.conf with the "buggymwi" option */
13384    ast_str_append(&out, 0, "Voice-Message: %d/%d%s\r\n",
13385       newmsgs, oldmsgs, (ast_test_flag(&p->flags[1], SIP_PAGE2_BUGGY_MWI) ? "" : " (0/0)"));
13386 
13387    if (p->subscribed) {
13388       if (p->expiry) {
13389          add_header(&req, "Subscription-State", "active");
13390       } else { /* Expired */
13391          add_header(&req, "Subscription-State", "terminated;reason=timeout");
13392       }
13393    }
13394 
13395    add_content(&req, ast_str_buffer(out));
13396 
13397    if (!p->initreq.headers) {
13398       initialize_initreq(p, &req);
13399    }
13400    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
13401 }
13402 
13403 /*! \brief Notify a transferring party of the status of transfer (RFC3515) */
13404 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
13405 {
13406    struct sip_request req;
13407    char tmp[SIPBUFSIZE/2];
13408    
13409    reqprep(&req, p, SIP_NOTIFY, 0, 1);
13410    snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
13411    add_header(&req, "Event", tmp);
13412    add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
13413    add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
13414    add_header(&req, "Allow", ALLOWED_METHODS);
13415    add_supported_header(p, &req);
13416 
13417    snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
13418    add_content(&req, tmp);
13419 
13420    if (!p->initreq.headers) {
13421       initialize_initreq(p, &req);
13422    }
13423 
13424    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
13425 }
13426 
13427 static int manager_sipnotify(struct mansession *s, const struct message *m)
13428 {
13429    const char *channame = astman_get_header(m, "Channel");
13430    struct ast_variable *vars = astman_get_variables_order(m, ORDER_NATURAL);
13431    struct sip_pvt *p;
13432    struct ast_variable *header, *var;
13433 
13434    if (ast_strlen_zero(channame)) {
13435       astman_send_error(s, m, "SIPNotify requires a channel name");
13436       return 0;
13437    }
13438 
13439    if (!strncasecmp(channame, "sip/", 4)) {
13440       channame += 4;
13441    }
13442 
13443    if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
13444       astman_send_error(s, m, "Unable to build sip pvt data for notify (memory/socket error)");
13445       return 0;
13446    }
13447 
13448    if (create_addr(p, channame, NULL, 0)) {
13449       /* Maybe they're not registered, etc. */
13450       dialog_unlink_all(p);
13451       dialog_unref(p, "unref dialog inside for loop" );
13452       /* sip_destroy(p); */
13453       astman_send_error(s, m, "Could not create address");
13454       return 0;
13455    }
13456 
13457    /* Notify is outgoing call */
13458    ast_set_flag(&p->flags[0], SIP_OUTGOING);
13459    sip_notify_allocate(p);
13460 
13461    p->notify->headers = header = ast_variable_new("Subscription-State", "terminated", "");
13462 
13463    for (var = vars; var; var = var->next) {
13464       if (!strcasecmp(var->name, "Content")) {
13465          if (ast_str_strlen(p->notify->content))
13466             ast_str_append(&p->notify->content, 0, "\r\n");
13467          ast_str_append(&p->notify->content, 0, "%s", var->value);
13468       } else if (!strcasecmp(var->name, "Content-Length")) {
13469          ast_log(LOG_WARNING, "it is not necessary to specify Content-Length, ignoring\n");
13470       } else {
13471          header->next = ast_variable_new(var->name, var->value, "");
13472          header = header->next;
13473       }
13474    }
13475 
13476    sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
13477    transmit_invite(p, SIP_NOTIFY, 0, 2, NULL);
13478    dialog_unref(p, "bump down the count of p since we're done with it.");
13479 
13480    astman_send_ack(s, m, "Notify Sent");
13481    ast_variables_destroy(vars);
13482    return 0;
13483 }
13484 
13485 /*! \brief Send a provisional response indicating that a call was redirected
13486  */
13487 static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen)
13488 {
13489    struct sip_request resp;
13490 
13491    if (p->owner->_state == AST_STATE_UP || ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
13492       return;
13493    }
13494 
13495    respprep(&resp, p, "181 Call is being forwarded", &p->initreq);
13496    add_diversion_header(&resp, p);
13497    send_response(p, &resp, XMIT_UNRELIABLE, 0);
13498 }
13499 
13500 /*! \brief Notify peer that the connected line has changed */
13501 static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen)
13502 {
13503 
13504    if (!ast_test_flag(&p->flags[0], SIP_SENDRPID)) {
13505       return;
13506    }
13507    if (!p->owner->connected.id.number.valid
13508       || ast_strlen_zero(p->owner->connected.id.number.str)) {
13509       return;
13510    }
13511 
13512    append_history(p, "ConnectedLine", "%s party is now %s <%s>",
13513       ast_test_flag(&p->flags[0], SIP_OUTGOING) ? "Calling" : "Called",
13514       S_COR(p->owner->connected.id.name.valid, p->owner->connected.id.name.str, ""),
13515       S_COR(p->owner->connected.id.number.valid, p->owner->connected.id.number.str, ""));
13516 
13517    if (p->owner->_state == AST_STATE_UP || ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
13518       struct sip_request req;
13519 
13520       if (!p->pendinginvite && (p->invitestate == INV_CONFIRMED || p->invitestate == INV_TERMINATED)) {
13521          reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
13522 
13523          add_header(&req, "Allow", ALLOWED_METHODS);
13524          add_supported_header(p, &req);
13525          add_rpid(&req, p);
13526          add_sdp(&req, p, FALSE, TRUE, FALSE);
13527 
13528          initialize_initreq(p, &req);
13529          p->lastinvite = p->ocseq;
13530          ast_set_flag(&p->flags[0], SIP_OUTGOING);
13531          p->invitestate = INV_CALLING;
13532          send_request(p, &req, XMIT_CRITICAL, p->ocseq);
13533       } else if ((is_method_allowed(&p->allowed_methods, SIP_UPDATE)) && (!ast_strlen_zero(p->okcontacturi))) { 
13534          reqprep(&req, p, SIP_UPDATE, 0, 1);
13535          add_rpid(&req, p);
13536          add_header(&req, "X-Asterisk-rpid-update", "Yes");
13537          send_request(p, &req, XMIT_CRITICAL, p->ocseq);
13538       } else {
13539          /* We cannot send the update yet, so we have to wait until we can */
13540          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
13541       }
13542    } else {
13543       ast_set_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
13544       if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPID_IMMEDIATE)) {
13545          struct sip_request resp;
13546 
13547          if ((p->owner->_state == AST_STATE_RING) && !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT)) {
13548             ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
13549             respprep(&resp, p, "180 Ringing", &p->initreq);
13550             add_rpid(&resp, p);
13551             send_response(p, &resp, XMIT_UNRELIABLE, 0);
13552             ast_set_flag(&p->flags[0], SIP_RINGING);
13553          } else if (p->owner->_state == AST_STATE_RINGING) {
13554             ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
13555             respprep(&resp, p, "183 Session Progress", &p->initreq);
13556             add_rpid(&resp, p);
13557             send_response(p, &resp, XMIT_UNRELIABLE, 0);
13558             ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
13559          } else {
13560             ast_debug(1, "Unable able to send update to '%s' in state '%s'\n", p->owner->name, ast_state2str(p->owner->_state));
13561          }
13562       }
13563    }
13564 }
13565 
13566 static const struct _map_x_s regstatestrings[] = {
13567    { REG_STATE_FAILED,     "Failed" },
13568    { REG_STATE_UNREGISTERED, "Unregistered"},
13569    { REG_STATE_REGSENT, "Request Sent"},
13570    { REG_STATE_AUTHSENT, "Auth. Sent"},
13571    { REG_STATE_REGISTERED, "Registered"},
13572    { REG_STATE_REJECTED, "Rejected"},
13573    { REG_STATE_TIMEOUT, "Timeout"},
13574    { REG_STATE_NOAUTH, "No Authentication"},
13575    { -1, NULL } /* terminator */
13576 };
13577 
13578 /*! \brief Convert registration state status to string */
13579 static const char *regstate2str(enum sipregistrystate regstate)
13580 {
13581    return map_x_s(regstatestrings, regstate, "Unknown");
13582 }
13583 
13584 /*! \brief Update registration with SIP Proxy.
13585  * Called from the scheduler when the previous registration expires,
13586  * so we don't have to cancel the pending event.
13587  * We assume the reference so the sip_registry is valid, since it
13588  * is stored in the scheduled event anyways.
13589  */
13590 static int sip_reregister(const void *data)
13591 {
13592    /* if we are here, we know that we need to reregister. */
13593    struct sip_registry *r = (struct sip_registry *) data;
13594 
13595    /* if we couldn't get a reference to the registry object, punt */
13596    if (!r) {
13597       return 0;
13598    }
13599 
13600    if (r->call && r->call->do_history) {
13601       append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
13602    }
13603    /* Since registry's are only added/removed by the the monitor thread, this
13604       may be overkill to reference/dereference at all here */
13605    if (sipdebug) {
13606       ast_log(LOG_NOTICE, "   -- Re-registration for  %s@%s\n", r->username, r->hostname);
13607    }
13608 
13609    r->expire = -1;
13610    r->expiry = r->configured_expiry;
13611    __sip_do_register(r);
13612    registry_unref(r, "unref the re-register scheduled event");
13613    return 0;
13614 }
13615 
13616 /*! \brief Register with SIP proxy 
13617    \return see \ref __sip_xmit 
13618 */
13619 static int __sip_do_register(struct sip_registry *r)
13620 {
13621    int res;
13622 
13623    res = transmit_register(r, SIP_REGISTER, NULL, NULL);
13624    return res;
13625 }
13626 
13627 /*! \brief Registration timeout, register again
13628  * Registered as a timeout handler during transmit_register(),
13629  * to retransmit the packet if a reply does not come back.
13630  * This is called by the scheduler so the event is not pending anymore when
13631  * we are called.
13632  */
13633 static int sip_reg_timeout(const void *data)
13634 {
13635 
13636    /* if we are here, our registration timed out, so we'll just do it over */
13637    struct sip_registry *r = (struct sip_registry *)data; /* the ref count should have been bumped when the sched item was added */
13638    struct sip_pvt *p;
13639 
13640    /* if we couldn't get a reference to the registry object, punt */
13641    if (!r) {
13642       return 0;
13643    }
13644 
13645    if (r->dnsmgr) {
13646       /* If the registration has timed out, maybe the IP changed.  Force a refresh. */
13647       ast_dnsmgr_refresh(r->dnsmgr);
13648    }
13649 
13650    /* If the initial tranmission failed, we may not have an existing dialog,
13651     * so it is possible that r->call == NULL.
13652     * Otherwise destroy it, as we have a timeout so we don't want it.
13653     */
13654    if (r->call) {
13655       /* Unlink us, destroy old call.  Locking is not relevant here because all this happens
13656          in the single SIP manager thread. */
13657       p = r->call;
13658       sip_pvt_lock(p);
13659       pvt_set_needdestroy(p, "registration timeout");
13660       /* Pretend to ACK anything just in case */
13661       __sip_pretend_ack(p);
13662       sip_pvt_unlock(p);
13663 
13664       /* decouple the two objects */
13665       /* p->registry == r, so r has 2 refs, and the unref won't take the object away */
13666       if (p->registry) {
13667          p->registry = registry_unref(p->registry, "p->registry unreffed");
13668       }
13669       r->call = dialog_unref(r->call, "unrefing r->call");
13670    }
13671    /* If we have a limit, stop registration and give up */
13672    r->timeout = -1;
13673    if (global_regattempts_max && r->regattempts >= global_regattempts_max) {
13674       /* Ok, enough is enough. Don't try any more */
13675       /* We could add an external notification here...
13676          steal it from app_voicemail :-) */
13677       ast_log(LOG_NOTICE, "   -- Last Registration Attempt #%d failed, Giving up forever trying to register '%s@%s'\n", r->regattempts, r->username, r->hostname);
13678       r->regstate = REG_STATE_FAILED;
13679    } else {
13680       r->regstate = REG_STATE_UNREGISTERED;
13681       transmit_register(r, SIP_REGISTER, NULL, NULL);
13682       ast_log(LOG_NOTICE, "   -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts);
13683    }
13684    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));
13685    registry_unref(r, "unreffing registry_unref r");
13686    return 0;
13687 }
13688 
13689 static const char *sip_sanitized_host(const char *host)
13690 {
13691    struct ast_sockaddr addr = { { 0, 0, }, };
13692 
13693    /* peer/sip_pvt->tohost and sip_registry->hostname should never have a port
13694     * in them, so we use PARSE_PORT_FORBID here. If this lookup fails, we return
13695     * the original host which is most likely a host name and not an IP. */
13696    if (!ast_sockaddr_parse(&addr, host, PARSE_PORT_FORBID)) {
13697       return host;
13698    }
13699    return ast_sockaddr_stringify_host_remote(&addr);
13700 }
13701 
13702 /*! \brief Transmit register to SIP proxy or UA
13703  * auth = NULL on the initial registration (from sip_reregister())
13704  */
13705 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
13706 {
13707    struct sip_request req;
13708    char from[256];
13709    char to[256];
13710    char tmp[80];
13711    char addr[80];
13712    struct sip_pvt *p;
13713    struct sip_peer *peer = NULL;
13714    int res;
13715    int portno = 0;
13716 
13717    /* exit if we are already in process with this registrar ?*/
13718    if (r == NULL || ((auth == NULL) && (r->regstate == REG_STATE_REGSENT || r->regstate == REG_STATE_AUTHSENT))) {
13719       if (r) {
13720          ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
13721       }
13722       return 0;
13723    }
13724 
13725    if (r->dnsmgr == NULL) {
13726       char transport[MAXHOSTNAMELEN];
13727       peer = find_peer(r->hostname, NULL, TRUE, FINDPEERS, FALSE, 0);
13728       snprintf(transport, sizeof(transport), "_%s._%s",get_srv_service(r->transport), get_srv_protocol(r->transport)); /* have to use static get_transport function */
13729       r->us.ss.ss_family = get_address_family_filter(r->transport); /* Filter address family */
13730 
13731       /* No point in doing a DNS lookup of the register hostname if we're just going to
13732        * end up using an outbound proxy. obproxy_get is safe to call with either of r->call
13733        * or peer NULL. Since we're only concerned with its existence, we're not going to
13734        * bother getting a ref to the proxy*/
13735       if (!obproxy_get(r->call, peer)) {
13736          registry_addref(r, "add reg ref for dnsmgr");
13737          ast_dnsmgr_lookup_cb(peer ? peer->tohost : r->hostname, &r->us, &r->dnsmgr, sip_cfg.srvlookup ? transport : NULL, on_dns_update_registry, r);
13738          if (!r->dnsmgr) {
13739             /*dnsmgr refresh disabled, no reference added! */
13740             registry_unref(r, "remove reg ref, dnsmgr disabled");
13741          }
13742       }
13743       if (peer) {
13744          peer = unref_peer(peer, "removing peer ref for dnsmgr_lookup");
13745       }
13746    }
13747 
13748    if (r->call) { /* We have a registration */
13749       if (!auth) {
13750          ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
13751          return 0;
13752       } else {
13753          p = dialog_ref(r->call, "getting a copy of the r->call dialog in transmit_register");
13754          ast_string_field_set(p, theirtag, NULL);  /* forget their old tag, so we don't match tags when getting response */
13755       }
13756    } else {
13757       /* Build callid for registration if we haven't registered before */
13758       if (!r->callid_valid) {
13759          build_callid_registry(r, &internip, default_fromdomain);
13760          build_localtag_registry(r);
13761          r->callid_valid = TRUE;
13762       }
13763       /* Allocate SIP dialog for registration */
13764       if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER, NULL))) {
13765          ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
13766          return 0;
13767       }
13768 
13769       /* reset tag to consistent value from registry */
13770       ast_string_field_set(p, tag, r->localtag);
13771 
13772       if (p->do_history) {
13773          append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
13774       }
13775 
13776       p->socket.type = r->transport;
13777 
13778       /* Use port number specified if no SRV record was found */
13779       if (!ast_sockaddr_isnull(&r->us)) {
13780          if (!ast_sockaddr_port(&r->us) && r->portno) {
13781             ast_sockaddr_set_port(&r->us, r->portno);
13782          }
13783 
13784          /* It is possible that DNS was unavailable at the time the peer was created.
13785           * Here, if we've updated the address in the registry via manually calling
13786           * ast_dnsmgr_lookup_cb() above, then we call the same function that dnsmgr would
13787           * call if it was updating a peer's address */
13788          if ((peer = find_peer(S_OR(r->peername, r->hostname), NULL, TRUE, FINDPEERS, FALSE, 0))) {
13789             if (ast_sockaddr_cmp(&peer->addr, &r->us)) {
13790                on_dns_update_peer(&peer->addr, &r->us, peer);
13791             }
13792             peer = unref_peer(peer, "unref after find_peer");
13793          }
13794       }
13795 
13796       /* Find address to hostname */
13797       if (create_addr(p, S_OR(r->peername, r->hostname), &r->us, 0)) {
13798          /* we have what we hope is a temporary network error,
13799           * probably DNS.  We need to reschedule a registration try */
13800          dialog_unlink_all(p);
13801          p = dialog_unref(p, "unref dialog after unlink_all");
13802          if (r->timeout > -1) {
13803             AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
13804                               registry_unref(_data, "del for REPLACE of registry ptr"),
13805                               registry_unref(r, "object ptr dec when SCHED_REPLACE add failed"),
13806                               registry_addref(r,"add for REPLACE registry ptr"));
13807             ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
13808          } else {
13809             r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, registry_addref(r, "add for REPLACE registry ptr"));
13810             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);
13811          }
13812          r->regattempts++;
13813          return 0;
13814       }
13815 
13816       /* Copy back Call-ID in case create_addr changed it */
13817       ast_string_field_set(r, callid, p->callid);
13818 
13819       if (!r->dnsmgr && r->portno) {
13820          ast_sockaddr_set_port(&p->sa, r->portno);
13821          ast_sockaddr_set_port(&p->recv, r->portno);
13822       }
13823       if (!ast_strlen_zero(p->fromdomain)) {
13824          portno = (p->fromdomainport) ? p->fromdomainport : STANDARD_SIP_PORT;
13825       } else if (!ast_strlen_zero(r->regdomain)) {
13826          portno = (r->regdomainport) ? r->regdomainport : STANDARD_SIP_PORT;
13827       } else {
13828          portno = ast_sockaddr_port(&p->sa);
13829       }
13830 
13831       ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Registration is outgoing call */
13832       r->call = dialog_ref(p, "copying dialog into registry r->call");     /* Save pointer to SIP dialog */
13833       p->registry = registry_addref(r, "transmit_register: addref to p->registry in transmit_register"); /* Add pointer to registry in packet */
13834       if (!ast_strlen_zero(r->secret)) {  /* Secret (password) */
13835          ast_string_field_set(p, peersecret, r->secret);
13836       }
13837       if (!ast_strlen_zero(r->md5secret))
13838          ast_string_field_set(p, peermd5secret, r->md5secret);
13839       /* User name in this realm
13840       - if authuser is set, use that, otherwise use username */
13841       if (!ast_strlen_zero(r->authuser)) {
13842          ast_string_field_set(p, peername, r->authuser);
13843          ast_string_field_set(p, authname, r->authuser);
13844       } else if (!ast_strlen_zero(r->username)) {
13845          ast_string_field_set(p, peername, r->username);
13846          ast_string_field_set(p, authname, r->username);
13847          ast_string_field_set(p, fromuser, r->username);
13848       }
13849       if (!ast_strlen_zero(r->username)) {
13850          ast_string_field_set(p, username, r->username);
13851       }
13852       /* Save extension in packet */
13853       if (!ast_strlen_zero(r->callback)) {
13854          ast_string_field_set(p, exten, r->callback);
13855       }
13856 
13857       /* Set transport and port so the correct contact is built */
13858       set_socket_transport(&p->socket, r->transport);
13859       if (r->transport == SIP_TRANSPORT_TLS || r->transport == SIP_TRANSPORT_TCP) {
13860          p->socket.port =
13861              htons(ast_sockaddr_port(&sip_tcp_desc.local_address));
13862       }
13863 
13864       /*
13865         check which address we should use in our contact header
13866         based on whether the remote host is on the external or
13867         internal network so we can register through nat
13868        */
13869       ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
13870       build_contact(p);
13871    }
13872 
13873    /* set up a timeout */
13874    if (auth == NULL)  {
13875       if (r->timeout > -1) {
13876          ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
13877       }
13878       AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
13879                         registry_unref(_data,"reg ptr unrefed from del in SCHED_REPLACE"),
13880                         registry_unref(r,"reg ptr unrefed from add failure in SCHED_REPLACE"),
13881                         registry_addref(r,"reg ptr reffed from add in SCHED_REPLACE"));
13882       ast_debug(1, "Scheduled a registration timeout for %s id  #%d \n", r->hostname, r->timeout);
13883    }
13884 
13885    snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)), p->tag);
13886    if (!ast_strlen_zero(p->theirtag)) {
13887       snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)), p->theirtag);
13888    } else {
13889       snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)));
13890    }
13891 
13892    /* Fromdomain is what we are registering to, regardless of actual
13893       host name from SRV */
13894    if (portno && portno != STANDARD_SIP_PORT) {
13895       snprintf(addr, sizeof(addr), "sip:%s:%d", S_OR(p->fromdomain,S_OR(r->regdomain, sip_sanitized_host(r->hostname))), portno);
13896    } else {
13897       snprintf(addr, sizeof(addr), "sip:%s", S_OR(p->fromdomain,S_OR(r->regdomain, sip_sanitized_host(r->hostname))));
13898    }
13899 
13900    ast_string_field_set(p, uri, addr);
13901 
13902    p->branch ^= ast_random();
13903 
13904    init_req(&req, sipmethod, addr);
13905 
13906    /* Add to CSEQ */
13907    snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
13908    p->ocseq = r->ocseq;
13909 
13910    build_via(p);
13911    add_header(&req, "Via", p->via);
13912    add_header_max_forwards(p, &req);
13913    add_header(&req, "From", from);
13914    add_header(&req, "To", to);
13915    add_header(&req, "Call-ID", p->callid);
13916    add_header(&req, "CSeq", tmp);
13917    if (!ast_strlen_zero(global_useragent))
13918       add_header(&req, "User-Agent", global_useragent);
13919 
13920    if (auth) {    /* Add auth header */
13921       add_header(&req, authheader, auth);
13922    } else if (!ast_strlen_zero(r->nonce)) {
13923       char digest[1024];
13924 
13925       /* We have auth data to reuse, build a digest header.
13926        * Note, this is not always useful because some parties do not
13927        * like nonces to be reused (for good reasons!) so they will
13928        * challenge us anyways.
13929        */
13930       if (sipdebug) {
13931          ast_debug(1, "   >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
13932       }
13933       ast_string_field_set(p, realm, r->realm);
13934       ast_string_field_set(p, nonce, r->nonce);
13935       ast_string_field_set(p, domain, r->authdomain);
13936       ast_string_field_set(p, opaque, r->opaque);
13937       ast_string_field_set(p, qop, r->qop);
13938       p->noncecount = ++r->noncecount;
13939 
13940       memset(digest, 0, sizeof(digest));
13941       if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
13942          add_header(&req, "Authorization", digest);
13943       } else {
13944          ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
13945       }
13946    }
13947 
13948    snprintf(tmp, sizeof(tmp), "%d", r->expiry);
13949    add_header(&req, "Expires", tmp);
13950    add_header(&req, "Contact", p->our_contact);
13951 
13952    initialize_initreq(p, &req);
13953    if (sip_debug_test_pvt(p)) {
13954       ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
13955    }
13956    r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
13957    r->regattempts++; /* Another attempt */
13958    ast_debug(4, "REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
13959    res = send_request(p, &req, XMIT_CRITICAL, p->ocseq);
13960    dialog_unref(p, "p is finished here at the end of transmit_register");
13961    return res;
13962 }
13963 
13964 /*! \brief Transmit text with SIP MESSAGE method */
13965 static int transmit_message_with_text(struct sip_pvt *p, const char *text)
13966 {
13967    struct sip_request req;
13968    
13969    reqprep(&req, p, SIP_MESSAGE, 0, 1);
13970    add_text(&req, text);
13971    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
13972 }
13973 
13974 /*! \brief Allocate SIP refer structure */
13975 static int sip_refer_allocate(struct sip_pvt *p)
13976 {
13977    p->refer = ast_calloc(1, sizeof(struct sip_refer));
13978    return p->refer ? 1 : 0;
13979 }
13980 
13981 /*! \brief Allocate SIP refer structure */
13982 static int sip_notify_allocate(struct sip_pvt *p)
13983 {
13984    p->notify = ast_calloc(1, sizeof(struct sip_notify));
13985    if (p->notify) {
13986       p->notify->content = ast_str_create(128);
13987    }
13988    return p->notify ? 1 : 0;
13989 }
13990 
13991 /*! \brief Transmit SIP REFER message (initiated by the transfer() dialplan application
13992    \note this is currently broken as we have no way of telling the dialplan
13993    engine whether a transfer succeeds or fails.
13994    \todo Fix the transfer() dialplan function so that a transfer may fail
13995 */
13996 static int transmit_refer(struct sip_pvt *p, const char *dest)
13997 {
13998    struct sip_request req = {
13999       .headers = 0,  
14000    };
14001    char from[256];
14002    const char *of;
14003    char *c;
14004    char referto[256];
14005    int   use_tls=FALSE;
14006 
14007    if (sipdebug) {
14008       ast_debug(1, "SIP transfer of %s to %s\n", p->callid, dest);
14009    }
14010 
14011    /* Are we transfering an inbound or outbound call ? */
14012    if (ast_test_flag(&p->flags[0], SIP_OUTGOING))  {
14013       of = get_header(&p->initreq, "To");
14014    } else {
14015       of = get_header(&p->initreq, "From");
14016    }
14017 
14018    ast_copy_string(from, of, sizeof(from));
14019    of = get_in_brackets(from);
14020    ast_string_field_set(p, from, of);
14021    if (!strncasecmp(of, "sip:", 4)) {
14022       of += 4;
14023    } else if (!strncasecmp(of, "sips:", 5)) {
14024       of += 5;
14025       use_tls = TRUE;
14026    } else {
14027       ast_log(LOG_NOTICE, "From address missing 'sip(s):', assuming sip:\n");
14028    }
14029    /* Get just the username part */
14030    if (strchr(dest, '@')) {
14031       c = NULL;
14032    } else if ((c = strchr(of, '@'))) {
14033       *c++ = '\0';
14034    }
14035    if (c) {
14036       snprintf(referto, sizeof(referto), "<sip%s:%s@%s>", use_tls ? "s" : "", dest, c);
14037    } else {
14038       snprintf(referto, sizeof(referto), "<sip%s:%s>", use_tls ? "s" : "", dest);
14039    }
14040 
14041    /* save in case we get 407 challenge */
14042    sip_refer_allocate(p);
14043    ast_copy_string(p->refer->refer_to, referto, sizeof(p->refer->refer_to));
14044    ast_copy_string(p->refer->referred_by, p->our_contact, sizeof(p->refer->referred_by));
14045    p->refer->status = REFER_SENT;   /* Set refer status */
14046 
14047    reqprep(&req, p, SIP_REFER, 0, 1);
14048 
14049    add_header(&req, "Refer-To", referto);
14050    add_header(&req, "Allow", ALLOWED_METHODS);
14051    add_supported_header(p, &req);
14052    if (!ast_strlen_zero(p->our_contact)) {
14053       add_header(&req, "Referred-By", p->our_contact);
14054    }
14055 
14056    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
14057 
14058    /* We should propably wait for a NOTIFY here until we ack the transfer */
14059    /* Maybe fork a new thread and wait for a STATUS of REFER_200OK on the refer status before returning to app_transfer */
14060 
14061    /*! \todo In theory, we should hang around and wait for a reply, before
14062    returning to the dial plan here. Don't know really how that would
14063    affect the transfer() app or the pbx, but, well, to make this
14064    useful we should have a STATUS code on transfer().
14065    */
14066 }
14067 
14068 /*! \brief Send SIP INFO advice of charge message */
14069 static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded)
14070 {
14071    struct sip_request req;
14072    struct ast_str *str = ast_str_alloca(512);
14073    const struct ast_aoc_unit_entry *unit_entry = ast_aoc_get_unit_info(decoded, 0);
14074    enum ast_aoc_charge_type charging = ast_aoc_get_charge_type(decoded);
14075 
14076    reqprep(&req, p, SIP_INFO, 0, 1);
14077 
14078    if (ast_aoc_get_msg_type(decoded) == AST_AOC_D) {
14079       ast_str_append(&str, 0, "type=active;");
14080    } else if (ast_aoc_get_msg_type(decoded) == AST_AOC_E) {
14081       ast_str_append(&str, 0, "type=terminated;");
14082    } else {
14083       /* unsupported message type */
14084       return -1;
14085    }
14086 
14087    switch (charging) {
14088    case AST_AOC_CHARGE_FREE:
14089       ast_str_append(&str, 0, "free-of-charge;");
14090       break;
14091    case AST_AOC_CHARGE_CURRENCY:
14092       ast_str_append(&str, 0, "charging;");
14093       ast_str_append(&str, 0, "charging-info=currency;");
14094       ast_str_append(&str, 0, "amount=%u;", ast_aoc_get_currency_amount(decoded));
14095       ast_str_append(&str, 0, "multiplier=%s;", ast_aoc_get_currency_multiplier_decimal(decoded));
14096       if (!ast_strlen_zero(ast_aoc_get_currency_name(decoded))) {
14097          ast_str_append(&str, 0, "currency=%s;", ast_aoc_get_currency_name(decoded));
14098       }
14099       break;
14100    case AST_AOC_CHARGE_UNIT:
14101       ast_str_append(&str, 0, "charging;");
14102       ast_str_append(&str, 0, "charging-info=pulse;");
14103       if (unit_entry) {
14104          ast_str_append(&str, 0, "recorded-units=%u;", unit_entry->amount);
14105       }
14106       break;
14107    default:
14108       ast_str_append(&str, 0, "not-available;");
14109    };
14110 
14111    add_header(&req, "AOC", ast_str_buffer(str));
14112 
14113    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
14114 }
14115 
14116 /*! \brief Send SIP INFO dtmf message, see Cisco documentation on cisco.com */
14117 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
14118 {
14119    struct sip_request req;
14120    
14121    reqprep(&req, p, SIP_INFO, 0, 1);
14122    add_digit(&req, digit, duration, (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO));
14123    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
14124 }
14125 
14126 /*! \brief Send SIP INFO with video update request */
14127 static int transmit_info_with_vidupdate(struct sip_pvt *p)
14128 {
14129    struct sip_request req;
14130    
14131    reqprep(&req, p, SIP_INFO, 0, 1);
14132    add_vidupdate(&req);
14133    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
14134 }
14135 
14136 /*! \brief Transmit generic SIP request
14137    returns XMIT_ERROR if transmit failed with a critical error (don't retry)
14138 */
14139 static int transmit_request(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch)
14140 {
14141    struct sip_request resp;
14142    
14143    reqprep(&resp, p, sipmethod, seqno, newbranch);
14144    if (sipmethod == SIP_CANCEL && p->answered_elsewhere) {
14145       add_header(&resp, "Reason", "SIP;cause=200;text=\"Call completed elsewhere\"");
14146    }
14147 
14148    if (sipmethod == SIP_ACK) {
14149       p->invitestate = INV_CONFIRMED;
14150    }
14151 
14152    return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
14153 }
14154 
14155 /*! \brief return the request and response header for a 401 or 407 code */
14156 static void auth_headers(enum sip_auth_type code, char **header, char **respheader)
14157 {
14158    if (code == WWW_AUTH) {       /* 401 */
14159       *header = "WWW-Authenticate";
14160       *respheader = "Authorization";
14161    } else if (code == PROXY_AUTH) { /* 407 */
14162       *header = "Proxy-Authenticate";
14163       *respheader = "Proxy-Authorization";
14164    } else {
14165       ast_verbose("-- wrong response code %u\n", code);
14166       *header = *respheader = "Invalid";
14167    }
14168 }
14169 
14170 /*! \brief Transmit SIP request, auth added */
14171 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch)
14172 {
14173    struct sip_request resp;
14174    
14175    reqprep(&resp, p, sipmethod, seqno, newbranch);
14176    if (!ast_strlen_zero(p->realm)) {
14177       char digest[1024];
14178 
14179       memset(digest, 0, sizeof(digest));
14180       if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
14181          char *dummy, *response;
14182          enum sip_auth_type code = p->options ? p->options->auth_type : PROXY_AUTH; /* XXX force 407 if unknown */
14183          auth_headers(code, &dummy, &response);
14184          add_header(&resp, response, digest);
14185       } else {
14186          ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
14187       }
14188    }
14189    /* If we are hanging up and know a cause for that, send it in clear text to make
14190       debugging easier. */
14191    if (sipmethod == SIP_BYE)  {
14192       char buf[20];
14193 
14194       if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON) && p->hangupcause) {
14195          sprintf(buf, "Q.850;cause=%i", p->hangupcause & 0x7f);
14196          add_header(&resp, "Reason", buf);
14197       }
14198 
14199       add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->hangupcause));
14200       snprintf(buf, sizeof(buf), "%d", p->hangupcause);
14201       add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
14202    }
14203 
14204    return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);   
14205 }
14206 
14207 /*! \brief Remove registration data from realtime database or AST/DB when registration expires */
14208 static void destroy_association(struct sip_peer *peer)
14209 {
14210    int realtimeregs = ast_check_realtime("sipregs");
14211    char *tablename = (realtimeregs) ? "sipregs" : "sippeers";
14212 
14213    if (!sip_cfg.ignore_regexpire) {
14214       if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
14215          ast_update_realtime(tablename, "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", "regserver", "", "useragent", "", "lastms", "0", SENTINEL);
14216       } else {
14217          ast_db_del("SIP/Registry", peer->name);
14218          ast_db_del("SIP/PeerMethods", peer->name);
14219       }
14220    }
14221 }
14222 
14223 static void set_socket_transport(struct sip_socket *socket, int transport)
14224 {
14225    /* if the transport type changes, clear all socket data */
14226    if (socket->type != transport) {
14227       socket->fd = -1;
14228       socket->type = transport;
14229       if (socket->tcptls_session) {
14230          ao2_ref(socket->tcptls_session, -1);
14231          socket->tcptls_session = NULL;
14232       }
14233    }
14234 }
14235 
14236 /*! \brief Expire registration of SIP peer */
14237 static int expire_register(const void *data)
14238 {
14239    struct sip_peer *peer = (struct sip_peer *)data;
14240 
14241    if (!peer) {      /* Hmmm. We have no peer. Weird. */
14242       return 0;
14243    }
14244 
14245    peer->expire = -1;
14246    peer->portinuri = 0;
14247 
14248    destroy_association(peer); /* remove registration data from storage */
14249    set_socket_transport(&peer->socket, peer->default_outbound_transport);
14250 
14251    if (peer->socket.tcptls_session) {
14252       ao2_ref(peer->socket.tcptls_session, -1);
14253       peer->socket.tcptls_session = NULL;
14254    }
14255 
14256    manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
14257    register_peer_exten(peer, FALSE);   /* Remove regexten */
14258    ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", peer->name);
14259 
14260    /* Do we need to release this peer from memory?
14261       Only for realtime peers and autocreated peers
14262    */
14263    if (peer->is_realtime) {
14264       ast_debug(3, "-REALTIME- peer expired registration. Name: %s. Realtime peer objects now %d\n", peer->name, rpeerobjs);
14265    }
14266 
14267    if (peer->selfdestruct ||
14268        ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
14269       ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
14270    }
14271    if (!ast_sockaddr_isnull(&peer->addr)) {
14272       /* We still need to unlink the peer from the peers_by_ip table,
14273        * otherwise we end up with multiple copies hanging around each
14274        * time a registration expires and the peer re-registers. */
14275       ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
14276    }
14277 
14278    /* Only clear the addr after we check for destruction.  The addr must remain
14279     * in order to unlink from the peers_by_ip container correctly */
14280    memset(&peer->addr, 0, sizeof(peer->addr));
14281 
14282    unref_peer(peer, "removing peer ref for expire_register");
14283 
14284    return 0;
14285 }
14286 
14287 /*! \brief Poke peer (send qualify to check if peer is alive and well) */
14288 static int sip_poke_peer_s(const void *data)
14289 {
14290    struct sip_peer *peer = (struct sip_peer *)data;
14291    struct sip_peer *foundpeer;
14292 
14293    peer->pokeexpire = -1;
14294 
14295    foundpeer = ao2_find(peers, peer, OBJ_POINTER);
14296    if (!foundpeer) {
14297       unref_peer(peer, "removing poke peer ref");
14298       return 0;
14299    } else if (foundpeer->name != peer->name) {
14300       unref_peer(foundpeer, "removing above peer ref");
14301       unref_peer(peer, "removing poke peer ref");
14302       return 0;
14303    }
14304 
14305    unref_peer(foundpeer, "removing above peer ref");
14306    sip_poke_peer(peer, 0);
14307    unref_peer(peer, "removing poke peer ref");
14308 
14309    return 0;
14310 }
14311 
14312 /*! \brief Get registration details from Asterisk DB */
14313 static void reg_source_db(struct sip_peer *peer)
14314 {
14315    char data[256];
14316    struct ast_sockaddr sa;
14317    int expire;
14318    char full_addr[128];
14319    AST_DECLARE_APP_ARGS(args,
14320       AST_APP_ARG(addr);
14321       AST_APP_ARG(port);
14322       AST_APP_ARG(expiry_str);
14323       AST_APP_ARG(username);
14324       AST_APP_ARG(contact);
14325    );
14326 
14327    /* If read-only RT backend, then refresh from local DB cache */
14328    if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
14329       return;
14330    }
14331    if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data))) {
14332       return;
14333    }
14334 
14335    AST_NONSTANDARD_RAW_ARGS(args, data, ':');
14336 
14337    snprintf(full_addr, sizeof(full_addr), "%s:%s", args.addr, args.port);
14338 
14339    if (!ast_sockaddr_parse(&sa, full_addr, 0)) {
14340       return;
14341    }
14342 
14343    if (args.expiry_str) {
14344       expire = atoi(args.expiry_str);
14345    } else {
14346       return;
14347    }
14348 
14349    if (args.username) {
14350       ast_string_field_set(peer, username, args.username);
14351    }
14352    if (args.contact) {
14353       ast_string_field_set(peer, fullcontact, args.contact);
14354    }
14355 
14356    ast_debug(2, "SIP Seeding peer from astdb: '%s' at %s@%s for %d\n",
14357        peer->name, peer->username, ast_sockaddr_stringify_host(&sa), expire);
14358 
14359    ast_sockaddr_copy(&peer->addr, &sa);
14360    if (peer->maxms) {
14361       /* Don't poke peer immediately, just schedule it within qualifyfreq */
14362       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
14363             ast_random() % ((peer->qualifyfreq) ? peer->qualifyfreq : global_qualifyfreq) + 1,
14364             sip_poke_peer_s, peer,
14365             unref_peer(_data, "removing poke peer ref"),
14366             unref_peer(peer, "removing poke peer ref"),
14367             ref_peer(peer, "adding poke peer ref"));
14368    }
14369    AST_SCHED_REPLACE_UNREF(peer->expire, sched, (expire + 10) * 1000, expire_register, peer,
14370          unref_peer(_data, "remove registration ref"),
14371          unref_peer(peer, "remove registration ref"),
14372          ref_peer(peer, "add registration ref"));
14373    register_peer_exten(peer, TRUE);
14374 }
14375 
14376 /*! \brief Save contact header for 200 OK on INVITE */
14377 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
14378 {
14379    char contact[SIPBUFSIZE];
14380    char *c;
14381 
14382    /* Look for brackets */
14383    ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
14384    c = get_in_brackets(contact);
14385 
14386    /* Save full contact to call pvt for later bye or re-invite */
14387    ast_string_field_set(pvt, fullcontact, c);
14388 
14389    /* Save URI for later ACKs, BYE or RE-invites */
14390    ast_string_field_set(pvt, okcontacturi, c);
14391 
14392    /* We should return false for URI:s we can't handle,
14393       like tel:, mailto:,ldap: etc */
14394    return TRUE;      
14395 }
14396 
14397 /*! \brief parse uri in a way that allows semicolon stripping if legacy mode is enabled
14398  *
14399  * \note This calls parse_uri which has the unexpected property that passing more
14400  *       arguments results in more splitting. Most common is to leave out the pass
14401  *       argument, causing user to contain user:pass if available.
14402  */
14403 static int parse_uri_legacy_check(char *uri, const char *scheme, char **user, char **pass, char **hostport, char **transport)
14404 {
14405    int ret = parse_uri(uri, scheme, user, pass, hostport, transport);
14406    if (sip_cfg.legacy_useroption_parsing) { /* if legacy mode is active, strip semis from the user field */
14407       char *p;
14408       if ((p = strchr(uri, (int)';'))) {
14409          *p = '\0';
14410       }
14411    }
14412    return ret;
14413 }
14414 
14415 static int __set_address_from_contact(const char *fullcontact, struct ast_sockaddr *addr, int tcp)
14416 {
14417    char *hostport, *transport;
14418    char contact_buf[256];
14419    char *contact;
14420 
14421    /* Work on a copy */
14422    ast_copy_string(contact_buf, fullcontact, sizeof(contact_buf));
14423    contact = contact_buf;
14424 
14425    /* 
14426     * We have only the part in <brackets> here so we just need to parse a SIP URI.
14427     *
14428     * Note: The outbound proxy could be using UDP between the proxy and Asterisk.
14429     * We still need to be able to send to the remote agent through the proxy.
14430     */
14431 
14432    if (parse_uri_legacy_check(contact, "sip:,sips:", &contact, NULL, &hostport,
14433             &transport)) {
14434       ast_log(LOG_WARNING, "Invalid contact uri %s (missing sip: or sips:), attempting to use anyway\n", fullcontact);
14435    }
14436 
14437    /* XXX This could block for a long time XXX */
14438    /* We should only do this if it's a name, not an IP */
14439    /* \todo - if there's no PORT number in contact - we are required to check NAPTR/SRV records
14440       to find transport, port address and hostname. If there's a port number, we have to
14441       assume that the hostport part is a host name and only look for an A/AAAA record in DNS.
14442    */
14443 
14444    /* If we took in an invalid URI, hostport may not have been initialized */
14445    /* ast_sockaddr_resolve requires an initialized hostport string. */
14446    if (ast_strlen_zero(hostport)) {
14447       ast_log(LOG_WARNING, "Invalid URI: parse_uri failed to acquire hostport\n");
14448       return -1;
14449    }
14450 
14451    if (ast_sockaddr_resolve_first_transport(addr, hostport, 0, get_transport_str2enum(transport))) {
14452       ast_log(LOG_WARNING, "Invalid host name in Contact: (can't "
14453          "resolve in DNS) : '%s'\n", hostport);
14454       return -1;
14455    }
14456 
14457    /* set port */
14458    if (!ast_sockaddr_port(addr)) {
14459       ast_sockaddr_set_port(addr,
14460                   (get_transport_str2enum(transport) ==
14461                    SIP_TRANSPORT_TLS ||
14462                    !strncasecmp(fullcontact, "sips", 4)) ?
14463                   STANDARD_TLS_PORT : STANDARD_SIP_PORT);
14464    }
14465 
14466    return 0;
14467 }
14468 
14469 /*! \brief Change the other partys IP address based on given contact */
14470 static int set_address_from_contact(struct sip_pvt *pvt)
14471 {
14472    if (ast_test_flag(&pvt->flags[0], SIP_NAT_FORCE_RPORT)) {
14473       /* NAT: Don't trust the contact field.  Just use what they came to us
14474          with. */
14475       /*! \todo We need to save the TRANSPORT here too */
14476       pvt->sa = pvt->recv;
14477       return 0;
14478    }
14479 
14480    return __set_address_from_contact(pvt->fullcontact, &pvt->sa, pvt->socket.type == SIP_TRANSPORT_TLS ? 1 : 0);
14481 }
14482 
14483 /*! \brief Parse contact header and save registration (peer registration) */
14484 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
14485 {
14486    char contact[SIPBUFSIZE];
14487    char data[SIPBUFSIZE];
14488    const char *expires = get_header(req, "Expires");
14489    int expire = atoi(expires);
14490    char *curi = NULL, *hostport = NULL, *transport = NULL;
14491    int transport_type;
14492    const char *useragent;
14493    struct ast_sockaddr oldsin, testsa;
14494    char *firstcuri = NULL;
14495    int start = 0;
14496    int wildcard_found = 0;
14497    int single_binding_found = 0;
14498 
14499    ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
14500 
14501    if (ast_strlen_zero(expires)) {  /* No expires header, try look in Contact: */
14502       char *s = strcasestr(contact, ";expires=");
14503       if (s) {
14504          expires = strsep(&s, ";"); /* trim ; and beyond */
14505          if (sscanf(expires + 9, "%30d", &expire) != 1) {
14506             expire = default_expiry;
14507          }
14508       } else {
14509          /* Nothing has been specified */
14510          expire = default_expiry;
14511       }
14512    }
14513 
14514    if (expire > max_expiry) {
14515       expire = max_expiry;
14516    }
14517    if (expire < min_expiry && expire != 0) {
14518       expire = min_expiry;
14519    }
14520    pvt->expiry = expire;
14521 
14522    copy_socket_data(&pvt->socket, &req->socket);
14523 
14524    do {
14525       /* Look for brackets */
14526       curi = contact;
14527       if (strchr(contact, '<') == NULL)   /* No <, check for ; and strip it */
14528          strsep(&curi, ";");  /* This is Header options, not URI options */
14529       curi = get_in_brackets(contact);
14530       if (!firstcuri) {
14531          firstcuri = ast_strdupa(curi);
14532       }
14533 
14534       if (!strcasecmp(curi, "*")) {
14535          wildcard_found = 1;
14536       } else {
14537          single_binding_found = 1;
14538       }
14539 
14540       if (wildcard_found && (ast_strlen_zero(expires) || expire != 0 || single_binding_found)) {
14541          /* Contact header parameter "*" detected, so punt if: Expires header is missing,
14542           * Expires value is not zero, or another Contact header is present. */
14543          return PARSE_REGISTER_FAILED;
14544       }
14545 
14546       ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
14547    } while (!ast_strlen_zero(contact));
14548    curi = firstcuri;
14549 
14550    /* if they did not specify Contact: or Expires:, they are querying
14551       what we currently have stored as their contact address, so return
14552       it
14553    */
14554    if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
14555       /* If we have an active registration, tell them when the registration is going to expire */
14556       if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact)) {
14557          pvt->expiry = ast_sched_when(sched, peer->expire);
14558       }
14559       return PARSE_REGISTER_QUERY;
14560    } else if (!strcasecmp(curi, "*") || !expire) { /* Unregister this peer */
14561       /* This means remove all registrations and return OK */
14562       AST_SCHED_DEL_UNREF(sched, peer->expire,
14563             unref_peer(peer, "remove register expire ref"));
14564       ast_verb(3, "Unregistered SIP '%s'\n", peer->name);
14565       expire_register(ref_peer(peer,"add ref for explicit expire_register"));
14566       return PARSE_REGISTER_UPDATE;
14567    }
14568 
14569    /* Store whatever we got as a contact from the client */
14570    ast_string_field_set(peer, fullcontact, curi);
14571 
14572    /* For the 200 OK, we should use the received contact */
14573    ast_string_field_build(pvt, our_contact, "<%s>", curi);
14574 
14575    /* Make sure it's a SIP URL */
14576    if (ast_strlen_zero(curi) || parse_uri_legacy_check(curi, "sip:,sips:", &curi, NULL, &hostport, &transport)) {
14577       ast_log(LOG_NOTICE, "Not a valid SIP contact (missing sip:/sips:) trying to use anyway\n");
14578    }
14579 
14580    /* handle the transport type specified in Contact header. */
14581    if (!(transport_type = get_transport_str2enum(transport))) {
14582       transport_type = pvt->socket.type;
14583    }
14584 
14585    /* if the peer's socket type is different than the Registration
14586     * transport type, change it.  If it got this far, it is a
14587     * supported type, but check just in case */
14588    if ((peer->socket.type != transport_type) && (peer->transports & transport_type)) {
14589       set_socket_transport(&peer->socket, transport_type);
14590    }
14591 
14592    oldsin = peer->addr;
14593 
14594    /* If we were already linked into the peers_by_ip container unlink ourselves so nobody can find us */
14595    if (!ast_sockaddr_isnull(&peer->addr) && (!peer->is_realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS))) {
14596       ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
14597    }
14598 
14599    if (!ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) && !ast_test_flag(&peer->flags[0], SIP_NAT_RPORT_PRESENT)) {
14600        /* use the data provided in the Contact header for call routing */
14601       ast_debug(1, "Store REGISTER's Contact header for call routing.\n");
14602       /* XXX This could block for a long time XXX */
14603       /*! \todo Check NAPTR/SRV if we have not got a port in the URI */
14604       if (ast_sockaddr_resolve_first_transport(&testsa, hostport, 0, peer->socket.type)) {
14605          ast_log(LOG_WARNING, "Invalid hostport '%s'\n", hostport);
14606          ast_string_field_set(peer, fullcontact, "");
14607          ast_string_field_set(pvt, our_contact, "");
14608          return PARSE_REGISTER_FAILED;
14609       }
14610 
14611       /* If we have a port number in the given URI, make sure we do remember to not check for NAPTR/SRV records.
14612          The hostport part is actually a host. */
14613       peer->portinuri = ast_sockaddr_port(&testsa) ? TRUE : FALSE;
14614 
14615       if (!ast_sockaddr_port(&testsa)) {
14616          ast_sockaddr_set_port(&testsa, default_sip_port(transport_type));
14617       }
14618 
14619       ast_sockaddr_copy(&peer->addr, &testsa);
14620    } else {
14621       /* Don't trust the contact field.  Just use what they came to us
14622          with */
14623       ast_debug(1, "Store REGISTER's src-IP:port for call routing.\n");
14624       peer->addr = pvt->recv;
14625    }
14626 
14627    /* Check that they're allowed to register at this IP */
14628    if (ast_apply_ha(sip_cfg.contact_ha, &peer->addr) != AST_SENSE_ALLOW ||
14629          ast_apply_ha(peer->contactha, &peer->addr) != AST_SENSE_ALLOW) {
14630       ast_log(LOG_WARNING, "Domain '%s' disallowed by contact ACL (violating IP %s)\n", hostport,
14631             ast_sockaddr_stringify_addr(&peer->addr));
14632       ast_string_field_set(peer, fullcontact, "");
14633       ast_string_field_set(pvt, our_contact, "");
14634       return PARSE_REGISTER_DENIED;
14635    }
14636 
14637    /* if the Contact header information copied into peer->addr matches the
14638     * received address, and the transport types are the same, then copy socket
14639     * data into the peer struct */
14640    if ((peer->socket.type == pvt->socket.type) &&
14641       !ast_sockaddr_cmp(&peer->addr, &pvt->recv)) {
14642       copy_socket_data(&peer->socket, &pvt->socket);
14643    }
14644 
14645    /* Now that our address has been updated put ourselves back into the container for lookups */
14646    if (!peer->is_realtime || ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
14647       ao2_t_link(peers_by_ip, peer, "ao2_link into peers_by_ip table");
14648    }
14649 
14650    /* Save SIP options profile */
14651    peer->sipoptions = pvt->sipoptions;
14652 
14653    if (!ast_strlen_zero(curi) && ast_strlen_zero(peer->username)) {
14654       ast_string_field_set(peer, username, curi);
14655    }
14656 
14657    AST_SCHED_DEL_UNREF(sched, peer->expire,
14658          unref_peer(peer, "remove register expire ref"));
14659 
14660    if (peer->is_realtime && !ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
14661       peer->expire = -1;
14662    } else {
14663       peer->expire = ast_sched_add(sched, (expire + 10) * 1000, expire_register,
14664             ref_peer(peer, "add registration ref"));
14665       if (peer->expire == -1) {
14666          unref_peer(peer, "remote registration ref");
14667       }
14668    }
14669    snprintf(data, sizeof(data), "%s:%d:%s:%s", ast_sockaddr_stringify(&peer->addr),
14670        expire, peer->username, peer->fullcontact);
14671    /* We might not immediately be able to reconnect via TCP, but try caching it anyhow */
14672    if (!peer->rt_fromcontact || !sip_cfg.peer_rtupdate)
14673       ast_db_put("SIP/Registry", peer->name, data);
14674    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));
14675 
14676    /* Is this a new IP address for us? */
14677    if (VERBOSITY_ATLEAST(2) && ast_sockaddr_cmp(&peer->addr, &oldsin)) {
14678       ast_verbose(VERBOSE_PREFIX_3 "Registered SIP '%s' at %s\n", peer->name,
14679             ast_sockaddr_stringify(&peer->addr));
14680    }
14681    sip_pvt_unlock(pvt);
14682    sip_poke_peer(peer, 0);
14683    sip_pvt_lock(pvt);
14684    register_peer_exten(peer, 1);
14685    
14686    /* Save User agent */
14687    useragent = get_header(req, "User-Agent");
14688    if (strcasecmp(useragent, peer->useragent)) {
14689       ast_string_field_set(peer, useragent, useragent);
14690       ast_verb(4, "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
14691    }
14692    return PARSE_REGISTER_UPDATE;
14693 }
14694 
14695 /*! \brief Remove route from route list */
14696 static void free_old_route(struct sip_route *route)
14697 {
14698    struct sip_route *next;
14699 
14700    while (route) {
14701       next = route->next;
14702       ast_free(route);
14703       route = next;
14704    }
14705 }
14706 
14707 /*! \brief List all routes - mostly for debugging */
14708 static void list_route(struct sip_route *route)
14709 {
14710    if (!route) {
14711       ast_verbose("list_route: no route\n");
14712    } else {
14713       for (;route; route = route->next)
14714          ast_verbose("list_route: hop: <%s>\n", route->hop);
14715    }
14716 }
14717 
14718 /*! \brief Build route list from Record-Route header 
14719     \param resp the SIP response code or 0 for a request */
14720 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards, int resp)
14721 {
14722    struct sip_route *thishop, *head, *tail;
14723    int start = 0;
14724    int len;
14725    const char *rr, *c;
14726 
14727    /* Once a persistent route is set, don't fool with it */
14728    if (p->route && p->route_persistent) {
14729       ast_debug(1, "build_route: Retaining previous route: <%s>\n", p->route->hop);
14730       return;
14731    }
14732 
14733    if (p->route) {
14734       free_old_route(p->route);
14735       p->route = NULL;
14736    }
14737 
14738    /* We only want to create the route set the first time this is called except
14739       it is called from a provisional response.*/
14740    if ((resp < 100) || (resp > 199)) {
14741       p->route_persistent = 1;
14742    }
14743 
14744    /* Build a tailq, then assign it to p->route when done.
14745     * If backwards, we add entries from the head so they end up
14746     * in reverse order. However, we do need to maintain a correct
14747     * tail pointer because the contact is always at the end.
14748     */
14749    head = NULL;
14750    tail = head;
14751    /* 1st we pass through all the hops in any Record-Route headers */
14752    for (;;) {
14753       /* Each Record-Route header */
14754       int len = 0;
14755       const char *uri;
14756       rr = __get_header(req, "Record-Route", &start);
14757       if (*rr == '\0') {
14758          break;
14759       }
14760       while (!get_in_brackets_const(rr, &uri, &len)) {
14761          len++;
14762          rr = strchr(rr, ',');
14763          if(rr >= uri && rr < (uri + len)) {
14764             /* comma inside brackets*/
14765             const char *next_br = strchr(rr, '<');
14766             if (next_br && next_br < (uri + len)) {
14767                rr++;
14768                continue;
14769             }
14770             continue;
14771          }
14772          if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
14773             ast_copy_string(thishop->hop, uri, len);
14774             ast_debug(2, "build_route: Record-Route hop: <%s>\n", thishop->hop);
14775             /* Link in */
14776             if (backwards) {
14777                /* Link in at head so they end up in reverse order */
14778                thishop->next = head;
14779                head = thishop;
14780                /* If this was the first then it'll be the tail */
14781                if (!tail) {
14782                   tail = thishop;
14783                }
14784             } else {
14785                thishop->next = NULL;
14786                /* Link in at the end */
14787                if (tail) {
14788                   tail->next = thishop;
14789                } else {
14790                   head = thishop;
14791                }
14792                tail = thishop;
14793             }
14794          }
14795          rr = strchr(uri + len, ',');
14796          if (rr == NULL) {
14797             /* No more field-values, we're done with this header */
14798             break;
14799          }
14800          /* Advance past comma */
14801          rr++;
14802       }
14803    }
14804 
14805    /* Only append the contact if we are dealing with a strict router */
14806    if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop, ";lr") == NULL) ) {
14807       /* 2nd append the Contact: if there is one */
14808       /* Can be multiple Contact headers, comma separated values - we just take the first */
14809       char *contact = ast_strdupa(get_header(req, "Contact"));
14810       if (!ast_strlen_zero(contact)) {
14811          ast_debug(2, "build_route: Contact hop: %s\n", contact);
14812          /* Look for <: delimited address */
14813          c = get_in_brackets(contact);
14814          len = strlen(c) + 1;
14815          if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
14816             /* ast_calloc is not needed because all fields are initialized in this block */
14817             ast_copy_string(thishop->hop, c, len);
14818             thishop->next = NULL;
14819             /* Goes at the end */
14820             if (tail) {
14821                tail->next = thishop;
14822             } else {
14823                head = thishop;
14824             }
14825          }
14826       }
14827    }
14828 
14829    /* Store as new route */
14830    p->route = head;
14831 
14832    /* For debugging dump what we ended up with */
14833    if (sip_debug_test_pvt(p)) {
14834       list_route(p->route);
14835    }
14836 }
14837 
14838 /*! \brief builds the sip_pvt's randdata field which is used for the nonce
14839  *  challenge.  When forceupdate is not set, the nonce is only updated if
14840  *  the current one is stale.  In this case, a stalenonce is one which
14841  *  has already received a response, if a nonce has not received a response
14842  *  it is not always necessary or beneficial to create a new one. */
14843 
14844 static void set_nonce_randdata(struct sip_pvt *p, int forceupdate)
14845 {
14846    if (p->stalenonce || forceupdate || ast_strlen_zero(p->randdata)) {
14847       ast_string_field_build(p, randdata, "%08lx", (unsigned long)ast_random()); /* Create nonce for challenge */
14848       p->stalenonce = 0;
14849    }
14850 }
14851 
14852 AST_THREADSTORAGE(check_auth_buf);
14853 #define CHECK_AUTH_BUF_INITLEN   256
14854 
14855 /*! \brief  Check user authorization from peer definition
14856    Some actions, like REGISTER and INVITEs from peers require
14857    authentication (if peer have secret set)
14858     \return 0 on success, non-zero on error
14859 */
14860 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
14861                 const char *secret, const char *md5secret, int sipmethod,
14862                 const char *uri, enum xmittype reliable, int ignore)
14863 {
14864    const char *response;
14865    char *reqheader, *respheader;
14866    const char *authtoken;
14867    char a1_hash[256];
14868    char resp_hash[256]="";
14869    char *c;
14870    int is_bogus_peer = 0;
14871    int  wrongnonce = FALSE;
14872    int  good_response;
14873    const char *usednonce = p->randdata;
14874    struct ast_str *buf;
14875    int res;
14876 
14877    /* table of recognised keywords, and their value in the digest */
14878    enum keys { K_RESP, K_URI, K_USER, K_NONCE, K_LAST };
14879    struct x {
14880       const char *key;
14881       const char *s;
14882    } *i, keys[] = {
14883       [K_RESP] = { "response=", "" },
14884       [K_URI] = { "uri=", "" },
14885       [K_USER] = { "username=", "" },
14886       [K_NONCE] = { "nonce=", "" },
14887       [K_LAST] = { NULL, NULL}
14888    };
14889 
14890    /* Always OK if no secret */
14891    if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret))
14892       return AUTH_SUCCESSFUL;
14893 
14894    /* Always auth with WWW-auth since we're NOT a proxy */
14895    /* Using proxy-auth in a B2BUA may block proxy authorization in the same transaction */
14896    response = "401 Unauthorized";
14897 
14898    /*
14899     * Note the apparent swap of arguments below, compared to other
14900     * usages of auth_headers().
14901     */
14902    auth_headers(WWW_AUTH, &respheader, &reqheader);
14903 
14904    authtoken =  get_header(req, reqheader);  
14905    if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
14906       /* This is a retransmitted invite/register/etc, don't reconstruct authentication
14907          information */
14908       if (!reliable) {
14909          /* Resend message if this was NOT a reliable delivery.   Otherwise the
14910             retransmission should get it */
14911          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
14912          /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
14913          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14914       }
14915       return AUTH_CHALLENGE_SENT;
14916    } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
14917       /* We have no auth, so issue challenge and request authentication */
14918       set_nonce_randdata(p, 1); /* Create nonce for challenge */
14919       transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
14920       /* Schedule auto destroy in 32 seconds */
14921       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14922       return AUTH_CHALLENGE_SENT;
14923    }
14924 
14925    /* --- We have auth, so check it */
14926 
14927    /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
14928       an example in the spec of just what it is you're doing a hash on. */
14929 
14930    if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
14931       return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
14932    }
14933 
14934    /* Make a copy of the response and parse it */
14935    res = ast_str_set(&buf, 0, "%s", authtoken);
14936 
14937    if (res == AST_DYNSTR_BUILD_FAILED) {
14938       return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
14939    }
14940 
14941    c = buf->str;
14942 
14943    while(c && *(c = ast_skip_blanks(c)) ) { /* lookup for keys */
14944       for (i = keys; i->key != NULL; i++) {
14945          const char *separator = ",";  /* default */
14946 
14947          if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
14948             continue;
14949          }
14950          /* Found. Skip keyword, take text in quotes or up to the separator. */
14951          c += strlen(i->key);
14952          if (*c == '"') { /* in quotes. Skip first and look for last */
14953             c++;
14954             separator = "\"";
14955          }
14956          i->s = c;
14957          strsep(&c, separator);
14958          break;
14959       }
14960       if (i->key == NULL) { /* not found, jump after space or comma */
14961          strsep(&c, " ,");
14962       }
14963    }
14964 
14965    /* We cannot rely on the bogus_peer having a bad md5 value. Someone could
14966     * use it to construct valid auth. */
14967    if (md5secret && strcmp(md5secret, BOGUS_PEER_MD5SECRET) == 0) {
14968       is_bogus_peer = 1;
14969    }
14970 
14971    /* Verify that digest username matches  the username we auth as */
14972    if (strcmp(username, keys[K_USER].s) && !is_bogus_peer) {
14973       ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
14974          username, keys[K_USER].s);
14975       /* Oops, we're trying something here */
14976       return AUTH_USERNAME_MISMATCH;
14977    }
14978 
14979    /* Verify nonce from request matches our nonce, and the nonce has not already been responded to.
14980     * If this check fails, send 401 with new nonce */
14981    if (strcasecmp(p->randdata, keys[K_NONCE].s) || p->stalenonce) { /* XXX it was 'n'casecmp ? */
14982       wrongnonce = TRUE;
14983       usednonce = keys[K_NONCE].s;
14984    } else {
14985       p->stalenonce = 1; /* now, since the nonce has a response, mark it as stale so it can't be sent or responded to again */
14986    }
14987 
14988    if (!ast_strlen_zero(md5secret)) {
14989       ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
14990    } else {
14991       char a1[256];
14992 
14993       snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
14994       ast_md5_hash(a1_hash, a1);
14995    }
14996 
14997    /* compute the expected response to compare with what we received */
14998    {
14999       char a2[256];
15000       char a2_hash[256];
15001       char resp[256];
15002 
15003       snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
15004             S_OR(keys[K_URI].s, uri));
15005       ast_md5_hash(a2_hash, a2);
15006       snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
15007       ast_md5_hash(resp_hash, resp);
15008    }
15009 
15010    good_response = keys[K_RESP].s &&
15011          !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash)) &&
15012          !is_bogus_peer; /* lastly, check that the peer isn't the fake peer */
15013    if (wrongnonce) {
15014       if (good_response) {
15015          if (sipdebug)
15016             ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", get_header(req, "From"));
15017          /* We got working auth token, based on stale nonce . */
15018          set_nonce_randdata(p, 0);
15019          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, TRUE);
15020       } else {
15021          /* Everything was wrong, so give the device one more try with a new challenge */
15022          if (!req->ignore) {
15023             if (sipdebug) {
15024                ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", get_header(req, "To"));
15025             }
15026             set_nonce_randdata(p, 1);
15027          } else {
15028             if (sipdebug) {
15029                ast_log(LOG_NOTICE, "Duplicate authentication received from '%s'\n", get_header(req, "To"));
15030             }
15031          }
15032          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
15033       }
15034 
15035       /* Schedule auto destroy in 32 seconds */
15036       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15037       return AUTH_CHALLENGE_SENT;
15038    }
15039    if (good_response) {
15040       append_history(p, "AuthOK", "Auth challenge successful for %s", username);
15041       return AUTH_SUCCESSFUL;
15042    }
15043 
15044    /* Ok, we have a bad username/secret pair */
15045    /* Tell the UAS not to re-send this authentication data, because
15046       it will continue to fail
15047    */
15048 
15049    return AUTH_SECRET_FAILED;
15050 }
15051 
15052 /*! \brief Change onhold state of a peer using a pvt structure */
15053 static void sip_peer_hold(struct sip_pvt *p, int hold)
15054 {
15055    if (!p->relatedpeer) {
15056       return;
15057    }
15058 
15059    /* If they put someone on hold, increment the value... otherwise decrement it */
15060    ast_atomic_fetchadd_int(&p->relatedpeer->onHold, (hold ? +1 : -1));
15061 
15062    /* Request device state update */
15063    ast_devstate_changed(AST_DEVICE_UNKNOWN, (p->owner->flags & AST_FLAG_DISABLE_DEVSTATE_CACHE ? AST_DEVSTATE_NOT_CACHABLE : AST_DEVSTATE_CACHABLE),
15064               "SIP/%s", p->relatedpeer->name);
15065 
15066    return;
15067 }
15068 
15069 /*! \brief Receive MWI events that we have subscribed to */
15070 static void mwi_event_cb(const struct ast_event *event, void *userdata)
15071 {
15072    struct sip_peer *peer = userdata;
15073 
15074    sip_send_mwi_to_peer(peer, 0);
15075 }
15076 
15077 static void network_change_event_subscribe(void)
15078 {
15079    if (!network_change_event_subscription) {
15080       network_change_event_subscription = ast_event_subscribe(AST_EVENT_NETWORK_CHANGE,
15081          network_change_event_cb, "SIP Network Change", NULL, AST_EVENT_IE_END);
15082    }
15083 }
15084 
15085 static void network_change_event_unsubscribe(void)
15086 {
15087    if (network_change_event_subscription) {
15088       network_change_event_subscription = ast_event_unsubscribe(network_change_event_subscription);
15089    }
15090 }
15091 
15092 static int network_change_event_sched_cb(const void *data)
15093 {
15094    network_change_event_sched_id = -1;
15095    sip_send_all_registers();
15096    sip_send_all_mwi_subscriptions();
15097    return 0;
15098 }
15099 
15100 static void network_change_event_cb(const struct ast_event *event, void *userdata)
15101 {
15102    ast_debug(1, "SIP, got a network change event, renewing all SIP registrations.\n");
15103    if (network_change_event_sched_id == -1) {
15104       network_change_event_sched_id = ast_sched_add(sched, 1000, network_change_event_sched_cb, NULL);
15105    }
15106 }
15107 
15108 static void cb_extensionstate_destroy(int id, void *data)
15109 {
15110    struct sip_pvt *p = data;
15111 
15112    dialog_unref(p, "the extensionstate containing this dialog ptr was destroyed");
15113 }
15114 
15115 /*! \brief Callback for the devicestate notification (SUBSCRIBE) support subsystem
15116 \note If you add an "hint" priority to the extension in the dial plan,
15117    you will get notifications on device state changes */
15118 static int cb_extensionstate(char *context, char* exten, int state, void *data)
15119 {
15120    struct sip_pvt *p = data;
15121 
15122    sip_pvt_lock(p);
15123 
15124    switch(state) {
15125    case AST_EXTENSION_DEACTIVATED:  /* Retry after a while */
15126    case AST_EXTENSION_REMOVED:   /* Extension is gone */
15127       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);  /* Delete subscription in 32 secs */
15128       ast_verb(2, "Extension state: Watcher for hint %s %s. Notify User %s\n", exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", p->username);
15129       p->subscribed = NONE;
15130       append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
15131       break;
15132    default: /* Tell user */
15133       p->laststate = state;
15134       break;
15135    }
15136    if (p->subscribed != NONE) {  /* Only send state NOTIFY if we know the format */
15137       if (!p->pendinginvite) {
15138          transmit_state_notify(p, state, 1, FALSE);
15139       } else {
15140          /* We already have a NOTIFY sent that is not answered. Queue the state up.
15141             if many state changes happen meanwhile, we will only send a notification of the last one */
15142          ast_set_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
15143       }
15144    }
15145    ast_verb(2, "Extension Changed %s[%s] new state %s for Notify User %s %s\n", exten, context, ast_extension_state2str(state), p->username,
15146          ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE) ? "(queued)" : "");
15147 
15148    sip_pvt_unlock(p);
15149 
15150    return 0;
15151 }
15152 
15153 /*! \brief Send a fake 401 Unauthorized response when the administrator
15154   wants to hide the names of local devices  from fishers
15155  */
15156 static void transmit_fake_auth_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable)
15157 {
15158    /* We have to emulate EXACTLY what we'd get with a good peer
15159     * and a bad password, or else we leak information. */
15160    const char *response = "401 Unauthorized";
15161    const char *reqheader = "Authorization";
15162    const char *respheader = "WWW-Authenticate";
15163    const char *authtoken;
15164    struct ast_str *buf;
15165    char *c;
15166 
15167    /* table of recognised keywords, and their value in the digest */
15168    enum keys { K_NONCE, K_LAST };
15169    struct x {
15170       const char *key;
15171       const char *s;
15172    } *i, keys[] = {
15173       [K_NONCE] = { "nonce=", "" },
15174       [K_LAST] = { NULL, NULL}
15175    };
15176 
15177    authtoken = get_header(req, reqheader);
15178    if (req->ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
15179       /* This is a retransmitted invite/register/etc, don't reconstruct authentication
15180        * information */
15181       transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
15182       /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
15183       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15184       return;
15185    } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
15186       /* We have no auth, so issue challenge and request authentication */
15187       set_nonce_randdata(p, 1);
15188       transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
15189       /* Schedule auto destroy in 32 seconds */
15190       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15191       return;
15192    }
15193 
15194    if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
15195       __transmit_response(p, "403 Forbidden", &p->initreq, reliable);
15196       return;
15197    }
15198 
15199    /* Make a copy of the response and parse it */
15200    if (ast_str_set(&buf, 0, "%s", authtoken) == AST_DYNSTR_BUILD_FAILED) {
15201       __transmit_response(p, "403 Forbidden", &p->initreq, reliable);
15202       return;
15203    }
15204 
15205    c = buf->str;
15206 
15207    while (c && *(c = ast_skip_blanks(c))) { /* lookup for keys */
15208       for (i = keys; i->key != NULL; i++) {
15209          const char *separator = ",";  /* default */
15210 
15211          if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
15212             continue;
15213          }
15214          /* Found. Skip keyword, take text in quotes or up to the separator. */
15215          c += strlen(i->key);
15216          if (*c == '"') { /* in quotes. Skip first and look for last */
15217             c++;
15218             separator = "\"";
15219          }
15220          i->s = c;
15221          strsep(&c, separator);
15222          break;
15223       }
15224       if (i->key == NULL) { /* not found, jump after space or comma */
15225          strsep(&c, " ,");
15226       }
15227    }
15228 
15229    /* Verify nonce from request matches our nonce.  If not, send 401 with new nonce */
15230    if (strcasecmp(p->randdata, keys[K_NONCE].s)) {
15231       if (!req->ignore) {
15232          set_nonce_randdata(p, 1);
15233       }
15234       transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
15235 
15236       /* Schedule auto destroy in 32 seconds */
15237       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15238    } else {
15239       __transmit_response(p, "403 Forbidden", &p->initreq, reliable);
15240    }
15241 }
15242 
15243 /*!
15244  * Terminate the uri at the first ';' or space.
15245  * Technically we should ignore escaped space per RFC3261 (19.1.1 etc)
15246  * but don't do it for the time being. Remember the uri format is:
15247  * (User-parameters was added after RFC 3261)
15248  *\verbatim
15249  *
15250  * sip:user:password;user-parameters@host:port;uri-parameters?headers
15251  * sips:user:password;user-parameters@host:port;uri-parameters?headers
15252  *
15253  *\endverbatim
15254  * \todo As this function does not support user-parameters, it's considered broken
15255  * and needs fixing.
15256  */
15257 static char *terminate_uri(char *uri)
15258 {
15259    char *t = uri;
15260    while (*t && *t > ' ' && *t != ';') {
15261       t++;
15262    }
15263    *t = '\0';
15264    return uri;
15265 }
15266 
15267 /*! \brief Terminate a host:port at the ':'
15268  * \param hostport The address of the hostport string
15269  *
15270  * \note In the case of a bracket-enclosed IPv6 address, the hostport variable
15271  * will contain the non-bracketed host as a result of calling this function.
15272  */
15273 static void extract_host_from_hostport(char **hostport)
15274 {
15275    char *dont_care;
15276    ast_sockaddr_split_hostport(*hostport, hostport, &dont_care, PARSE_PORT_IGNORE);
15277 }
15278 
15279 /*! \internal \brief Helper function to update a peer's lastmsgssent value
15280  */
15281 static void update_peer_lastmsgssent(struct sip_peer *peer, int value, int locked)
15282 {
15283    if (!locked) {
15284       ao2_lock(peer);
15285    }
15286    peer->lastmsgssent = value;
15287    if (!locked) {
15288       ao2_unlock(peer);
15289    }
15290 }
15291 
15292 
15293 /*! \brief Verify registration of user
15294    - Registration is done in several steps, first a REGISTER without auth
15295      to get a challenge (nonce) then a second one with auth
15296    - Registration requests are only matched with peers that are marked as "dynamic"
15297  */
15298 static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
15299                      struct sip_request *req, const char *uri)
15300 {
15301    enum check_auth_result res = AUTH_NOT_FOUND;
15302    struct sip_peer *peer;
15303    char tmp[256];
15304    char *c, *name, *unused_password, *domain;
15305    char *uri2 = ast_strdupa(uri);
15306    int send_mwi = 0;
15307 
15308    terminate_uri(uri2);
15309 
15310    ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
15311 
15312    c = get_in_brackets(tmp);
15313    c = remove_uri_parameters(c);
15314 
15315    if (parse_uri_legacy_check(c, "sip:,sips:", &name, &unused_password, &domain, NULL)) {
15316       ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_sockaddr_stringify_addr(addr));
15317       return -1;
15318    }
15319 
15320    SIP_PEDANTIC_DECODE(name);
15321    SIP_PEDANTIC_DECODE(domain);
15322 
15323    extract_host_from_hostport(&domain);
15324 
15325    if (ast_strlen_zero(domain)) {
15326       /* <sip:name@[EMPTY]>, never good */
15327       transmit_response(p, "404 Not found", &p->initreq);
15328       return AUTH_UNKNOWN_DOMAIN;
15329    }
15330 
15331    if (ast_strlen_zero(name)) {
15332       /* <sip:[EMPTY][@]hostport>, unsure whether valid for
15333        * registration. RFC 3261, 10.2 states:
15334        * "The To header field and the Request-URI field typically
15335        * differ, as the former contains a user name."
15336        * But, Asterisk has always treated the domain-only uri as a
15337        * username: we allow admins to create accounts described by
15338        * domain name. */
15339       name = domain;
15340    }
15341 
15342    /* This here differs from 1.4 and 1.6: the domain matching ACLs were
15343     * skipped if it was a domain-only URI (used as username). Here we treat
15344     * <sip:hostport> as <sip:host@hostport> and won't forget to test the
15345     * domain ACLs against host. */
15346    if (!AST_LIST_EMPTY(&domain_list)) {
15347       if (!check_sip_domain(domain, NULL, 0)) {
15348          if (sip_cfg.alwaysauthreject) {
15349             transmit_fake_auth_response(p, &p->initreq, XMIT_UNRELIABLE);
15350          } else {
15351             transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
15352          }
15353          return AUTH_UNKNOWN_DOMAIN;
15354       }
15355    }
15356 
15357    ast_string_field_set(p, exten, name);
15358    build_contact(p);
15359    if (req->ignore) {
15360       /* Expires is a special case, where we only want to load the peer if this isn't a deregistration attempt */
15361       const char *expires = get_header(req, "Expires");
15362       int expire = atoi(expires);
15363 
15364       if (ast_strlen_zero(expires)) { /* No expires header; look in Contact */
15365          if ((expires = strcasestr(get_header(req, "Contact"), ";expires="))) {
15366             expire = atoi(expires + 9);
15367          }
15368       }
15369       if (!ast_strlen_zero(expires) && expire == 0) {
15370          transmit_response_with_date(p, "200 OK", req);
15371          return 0;
15372       }
15373    }
15374    peer = find_peer(name, NULL, TRUE, FINDPEERS, FALSE, 0);
15375 
15376    /* If we don't want username disclosure, use the bogus_peer when a user
15377     * is not found. */
15378    if (!peer && sip_cfg.alwaysauthreject && !sip_cfg.autocreatepeer) {
15379       peer = bogus_peer;
15380       ref_peer(peer, "register_verify: ref the bogus_peer");
15381    }
15382 
15383    if (!(peer && ast_apply_ha(peer->ha, addr))) {
15384       /* Peer fails ACL check */
15385       if (peer) {
15386          unref_peer(peer, "register_verify: unref_peer: from find_peer operation");
15387          peer = NULL;
15388          res = AUTH_ACL_FAILED;
15389       } else {
15390          res = AUTH_NOT_FOUND;
15391       }
15392    }
15393 
15394    if (peer) {
15395       ao2_lock(peer);
15396       if (!peer->host_dynamic) {
15397          ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
15398          res = AUTH_PEER_NOT_DYNAMIC;
15399       } else {
15400          ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT_FORCE_RPORT);
15401          if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri2, XMIT_UNRELIABLE, req->ignore))) {
15402             if (sip_cancel_destroy(p))
15403                ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
15404 
15405             if (check_request_transport(peer, req)) {
15406                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
15407                transmit_response_with_date(p, "403 Forbidden", req);
15408                res = AUTH_BAD_TRANSPORT;
15409             } else {
15410 
15411                /* We have a successful registration attempt with proper authentication,
15412                   now, update the peer */
15413                switch (parse_register_contact(p, peer, req)) {
15414                case PARSE_REGISTER_DENIED:
15415                   ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
15416                   transmit_response_with_date(p, "603 Denied", req);
15417                   res = 0;
15418                   break;
15419                case PARSE_REGISTER_FAILED:
15420                   ast_log(LOG_WARNING, "Failed to parse contact info\n");
15421                   transmit_response_with_date(p, "400 Bad Request", req);
15422                   res = 0;
15423                   break;
15424                case PARSE_REGISTER_QUERY:
15425                   ast_string_field_set(p, fullcontact, peer->fullcontact);
15426                   transmit_response_with_date(p, "200 OK", req);
15427                   res = 0;
15428                   break;
15429                case PARSE_REGISTER_UPDATE:
15430                   ast_string_field_set(p, fullcontact, peer->fullcontact);
15431                   /* If expiry is 0, peer has been unregistered already */
15432                   if (p->expiry != 0) {
15433                      update_peer(peer, p->expiry);
15434                   }
15435                   /* Say OK and ask subsystem to retransmit msg counter */
15436                   transmit_response_with_date(p, "200 OK", req);
15437                   send_mwi = 1;
15438                   res = 0;
15439                   break;
15440                }
15441             }
15442 
15443          }
15444       }
15445       ao2_unlock(peer);
15446    }
15447    if (!peer && sip_cfg.autocreatepeer) {
15448       /* Create peer if we have autocreate mode enabled */
15449       peer = temp_peer(name);
15450       if (peer) {
15451          ao2_t_link(peers, peer, "link peer into peer table");
15452          if (!ast_sockaddr_isnull(&peer->addr)) {
15453             ao2_t_link(peers_by_ip, peer, "link peer into peers-by-ip table");
15454          }
15455          ao2_lock(peer);
15456          if (sip_cancel_destroy(p))
15457             ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
15458          switch (parse_register_contact(p, peer, req)) {
15459          case PARSE_REGISTER_DENIED:
15460             ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
15461             transmit_response_with_date(p, "403 Forbidden", req);
15462             res = 0;
15463             break;
15464          case PARSE_REGISTER_FAILED:
15465             ast_log(LOG_WARNING, "Failed to parse contact info\n");
15466             transmit_response_with_date(p, "400 Bad Request", req);
15467             res = 0;
15468             break;
15469          case PARSE_REGISTER_QUERY:
15470             ast_string_field_set(p, fullcontact, peer->fullcontact);
15471             transmit_response_with_date(p, "200 OK", req);
15472             send_mwi = 1;
15473             res = 0;
15474             break;
15475          case PARSE_REGISTER_UPDATE:
15476             ast_string_field_set(p, fullcontact, peer->fullcontact);
15477             /* Say OK and ask subsystem to retransmit msg counter */
15478             transmit_response_with_date(p, "200 OK", req);
15479             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));
15480             send_mwi = 1;
15481             res = 0;
15482             break;
15483          }
15484          ao2_unlock(peer);
15485       }
15486    }
15487    if (!res) {
15488       if (send_mwi) {
15489          sip_pvt_unlock(p);
15490          sip_send_mwi_to_peer(peer, 0);
15491          sip_pvt_lock(p);
15492       } else {
15493          update_peer_lastmsgssent(peer, -1, 0);
15494       }
15495       ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", peer->name);
15496    }
15497    if (res < 0) {
15498       switch (res) {
15499       case AUTH_SECRET_FAILED:
15500          /* Wrong password in authentication. Go away, don't try again until you fixed it */
15501          transmit_response(p, "403 Forbidden", &p->initreq);
15502          if (global_authfailureevents) {
15503             const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
15504             const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
15505             manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
15506                      "ChannelType: SIP\r\n"
15507                      "Peer: SIP/%s\r\n"
15508                      "PeerStatus: Rejected\r\n"
15509                      "Cause: AUTH_SECRET_FAILED\r\n"
15510                      "Address: %s\r\n"
15511                      "Port: %s\r\n",
15512                      name, peer_addr, peer_port);
15513          }
15514          break;
15515       case AUTH_USERNAME_MISMATCH:
15516          /* Username and digest username does not match.
15517             Asterisk uses the From: username for authentication. We need the
15518             devices to use the same authentication user name until we support
15519             proper authentication by digest auth name */
15520       case AUTH_NOT_FOUND:
15521       case AUTH_PEER_NOT_DYNAMIC:
15522       case AUTH_ACL_FAILED:
15523          if (sip_cfg.alwaysauthreject) {
15524             transmit_fake_auth_response(p, &p->initreq, XMIT_UNRELIABLE);
15525             if (global_authfailureevents) {
15526                const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
15527                const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
15528                manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
15529                         "ChannelType: SIP\r\n"
15530                         "Peer: SIP/%s\r\n"
15531                         "PeerStatus: Rejected\r\n"
15532                         "Cause: %s\r\n"
15533                         "Address: %s\r\n"
15534                         "Port: %s\r\n",
15535                         name,
15536                         res == AUTH_PEER_NOT_DYNAMIC ? "AUTH_PEER_NOT_DYNAMIC" : "URI_NOT_FOUND",
15537                         peer_addr, peer_port);
15538             }
15539          } else {
15540             /* URI not found */
15541             if (res == AUTH_PEER_NOT_DYNAMIC) {
15542                transmit_response(p, "403 Forbidden", &p->initreq);
15543                if (global_authfailureevents) {
15544                   const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
15545                   const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
15546                   manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
15547                      "ChannelType: SIP\r\n"
15548                      "Peer: SIP/%s\r\n"
15549                      "PeerStatus: Rejected\r\n"
15550                      "Cause: AUTH_PEER_NOT_DYNAMIC\r\n"
15551                      "Address: %s\r\n"
15552                      "Port: %s\r\n",
15553                      name, peer_addr, peer_port);
15554                }
15555             } else {
15556                transmit_response(p, "404 Not found", &p->initreq);
15557                if (global_authfailureevents) {
15558                   const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
15559                   const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
15560                   manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
15561                      "ChannelType: SIP\r\n"
15562                      "Peer: SIP/%s\r\n"
15563                      "PeerStatus: Rejected\r\n"
15564                      "Cause: %s\r\n"
15565                      "Address: %s\r\n"
15566                      "Port: %s\r\n",
15567                      name,
15568                      (res == AUTH_USERNAME_MISMATCH) ? "AUTH_USERNAME_MISMATCH" : "URI_NOT_FOUND",
15569                      peer_addr, peer_port);
15570                }
15571             }
15572          }
15573          break;
15574       case AUTH_BAD_TRANSPORT:
15575       default:
15576          break;
15577       }
15578    }
15579    if (peer) {
15580       unref_peer(peer, "register_verify: unref_peer: tossing stack peer pointer at end of func");
15581    }
15582 
15583    return res;
15584 }
15585 
15586 /*! \brief Translate referring cause */
15587 static void sip_set_redirstr(struct sip_pvt *p, char *reason) {
15588 
15589    if (!strcmp(reason, "unknown")) {
15590       ast_string_field_set(p, redircause, "UNKNOWN");
15591    } else if (!strcmp(reason, "user-busy")) {
15592       ast_string_field_set(p, redircause, "BUSY");
15593    } else if (!strcmp(reason, "no-answer")) {
15594       ast_string_field_set(p, redircause, "NOANSWER");
15595    } else if (!strcmp(reason, "unavailable")) {
15596       ast_string_field_set(p, redircause, "UNREACHABLE");
15597    } else if (!strcmp(reason, "unconditional")) {
15598       ast_string_field_set(p, redircause, "UNCONDITIONAL");
15599    } else if (!strcmp(reason, "time-of-day")) {
15600       ast_string_field_set(p, redircause, "UNKNOWN");
15601    } else if (!strcmp(reason, "do-not-disturb")) {
15602       ast_string_field_set(p, redircause, "UNKNOWN");
15603    } else if (!strcmp(reason, "deflection")) {
15604       ast_string_field_set(p, redircause, "UNKNOWN");
15605    } else if (!strcmp(reason, "follow-me")) {
15606       ast_string_field_set(p, redircause, "UNKNOWN");
15607    } else if (!strcmp(reason, "out-of-service")) {
15608       ast_string_field_set(p, redircause, "UNREACHABLE");
15609    } else if (!strcmp(reason, "away")) {
15610       ast_string_field_set(p, redircause, "UNREACHABLE");
15611    } else {
15612       ast_string_field_set(p, redircause, "UNKNOWN");
15613    }
15614 }
15615 
15616 /*! \brief Parse the parts of the P-Asserted-Identity header
15617  * on an incoming packet. Returns 1 if a valid header is found
15618  * and it is different from the current caller id.
15619  */
15620 static int get_pai(struct sip_pvt *p, struct sip_request *req)
15621 {
15622    char pai[256];
15623    char privacy[64];
15624    char *cid_num = NULL;
15625    char *cid_name = NULL;
15626    char emptyname[1] = "";
15627    int callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
15628    char *uri = NULL;
15629    int is_anonymous = 0, do_update = 1, no_name = 0;
15630 
15631    ast_copy_string(pai, get_header(req, "P-Asserted-Identity"), sizeof(pai));
15632 
15633    if (ast_strlen_zero(pai)) {
15634       return 0;
15635    }
15636 
15637    /* use the reqresp_parser function get_name_and_number*/
15638    if (get_name_and_number(pai, &cid_name, &cid_num)) {
15639       return 0;
15640    }
15641 
15642    if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(cid_num)) {
15643       ast_shrink_phone_number(cid_num);
15644    }
15645 
15646    uri = get_in_brackets(pai);
15647    if (!strncasecmp(uri, "sip:anonymous@anonymous.invalid", 31)) {
15648       callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
15649       /*XXX Assume no change in cid_num. Perhaps it should be
15650        * blanked?
15651        */
15652       ast_free(cid_num);
15653       is_anonymous = 1;
15654       cid_num = (char *)p->cid_num;
15655    }
15656 
15657    ast_copy_string(privacy, get_header(req, "Privacy"), sizeof(privacy));
15658    if (!ast_strlen_zero(privacy) && !strncmp(privacy, "id", 2)) {
15659       callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
15660    }
15661    if (!cid_name) {
15662       no_name = 1;
15663       cid_name = (char *)emptyname;
15664    }  
15665    /* Only return true if the supplied caller id is different */
15666    if (!strcasecmp(p->cid_num, cid_num) && !strcasecmp(p->cid_name, cid_name) && p->callingpres == callingpres) {
15667       do_update = 0;
15668    } else {
15669 
15670       ast_string_field_set(p, cid_num, cid_num);
15671       ast_string_field_set(p, cid_name, cid_name);
15672       p->callingpres = callingpres;
15673 
15674       if (p->owner) {
15675          ast_set_callerid(p->owner, cid_num, cid_name, NULL);
15676          p->owner->caller.id.name.presentation = callingpres;
15677          p->owner->caller.id.number.presentation = callingpres;
15678       }
15679    }
15680 
15681    /* get_name_and_number allocates memory for cid_num and cid_name so we have to free it */
15682    if (!is_anonymous) {
15683       ast_free(cid_num);
15684    }
15685    if (!no_name) {
15686       ast_free(cid_name);
15687    }
15688 
15689    return do_update;
15690 }
15691 
15692 /*! \brief Get name, number and presentation from remote party id header,
15693  *  returns true if a valid header was found and it was different from the
15694  *  current caller id.
15695  */
15696 static int get_rpid(struct sip_pvt *p, struct sip_request *oreq)
15697 {
15698    char tmp[256];
15699    struct sip_request *req;
15700    char *cid_num = "";
15701    char *cid_name = "";
15702    int callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
15703    char *privacy = "";
15704    char *screen = "";
15705    char *start, *end;
15706 
15707    if (!ast_test_flag(&p->flags[0], SIP_TRUSTRPID))
15708       return 0;
15709    req = oreq;
15710    if (!req)
15711       req = &p->initreq;
15712    ast_copy_string(tmp, get_header(req, "Remote-Party-ID"), sizeof(tmp));
15713    if (ast_strlen_zero(tmp)) {
15714       return get_pai(p, req);
15715    }
15716 
15717    /*
15718     * RPID is not:
15719     *   rpid = (name-addr / addr-spec) *(SEMI rpi-token)
15720     * But it is:
15721     *   rpid = [display-name] LAQUOT addr-spec RAQUOT *(SEMI rpi-token)
15722     * Ergo, calling parse_name_andor_addr() on it wouldn't be
15723     * correct because that would allow addr-spec style too.
15724     */
15725    start = tmp;
15726    /* Quoted (note that we're not dealing with escapes properly) */
15727    if (*start == '"') {
15728       *start++ = '\0';
15729       end = strchr(start, '"');
15730       if (!end)
15731          return 0;
15732       *end++ = '\0';
15733       cid_name = start;
15734       start = ast_skip_blanks(end);
15735    /* Unquoted */
15736    } else {
15737       cid_name = start;
15738       start = end = strchr(start, '<');
15739       if (!start) {
15740          return 0;
15741       }
15742       /* trim blanks if there are any. the mandatory NUL is done below */
15743       while (--end >= cid_name && *end < 33) {
15744          *end = '\0';
15745       }
15746    }
15747 
15748    if (*start != '<')
15749       return 0;
15750    *start++ = '\0';
15751    end = strchr(start, '@');
15752    if (!end)
15753       return 0;
15754    *end++ = '\0';
15755    if (strncasecmp(start, "sip:", 4))
15756       return 0;
15757    cid_num = start + 4;
15758    if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(cid_num))
15759       ast_shrink_phone_number(cid_num);
15760    start = end;
15761 
15762    end = strchr(start, '>');
15763    if (!end)
15764       return 0;
15765    *end++ = '\0';
15766    if (*end) {
15767       start = end;
15768       if (*start != ';')
15769          return 0;
15770       *start++ = '\0';
15771       while (!ast_strlen_zero(start)) {
15772          end = strchr(start, ';');
15773          if (end)
15774             *end++ = '\0';
15775          if (!strncasecmp(start, "privacy=", 8))
15776             privacy = start + 8;
15777          else if (!strncasecmp(start, "screen=", 7))
15778             screen = start + 7;
15779          start = end;
15780       }
15781 
15782       if (!strcasecmp(privacy, "full")) {
15783          if (!strcasecmp(screen, "yes"))
15784             callingpres = AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN;
15785          else if (!strcasecmp(screen, "no"))
15786             callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
15787       } else {
15788          if (!strcasecmp(screen, "yes"))
15789             callingpres = AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
15790          else if (!strcasecmp(screen, "no"))
15791             callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
15792       }
15793    }
15794 
15795    /* Only return true if the supplied caller id is different */
15796    if (!strcasecmp(p->cid_num, cid_num) && !strcasecmp(p->cid_name, cid_name) && p->callingpres == callingpres)
15797       return 0;
15798 
15799    ast_string_field_set(p, cid_num, cid_num);
15800    ast_string_field_set(p, cid_name, cid_name);
15801    p->callingpres = callingpres;
15802 
15803    if (p->owner) {
15804       ast_set_callerid(p->owner, cid_num, cid_name, NULL);
15805       p->owner->caller.id.name.presentation = callingpres;
15806       p->owner->caller.id.number.presentation = callingpres;
15807    }
15808 
15809    return 1;
15810 }
15811 
15812 /*! \brief Get referring dnis */
15813 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason)
15814 {
15815    char tmp[256], *exten, *rexten, *rdomain, *rname = NULL;
15816    char *params, *reason_param = NULL;
15817    struct sip_request *req;
15818 
15819    req = oreq ? oreq : &p->initreq;
15820 
15821    ast_copy_string(tmp, get_header(req, "Diversion"), sizeof(tmp));
15822    if (ast_strlen_zero(tmp))
15823       return -1;
15824 
15825    if ((params = strchr(tmp, '>'))) {
15826       params = strchr(params, ';');
15827    }
15828 
15829    exten = get_in_brackets(tmp);
15830    if (!strncasecmp(exten, "sip:", 4)) {
15831       exten += 4;
15832    } else if (!strncasecmp(exten, "sips:", 5)) {
15833       exten += 5;
15834    } else {
15835       ast_log(LOG_WARNING, "Huh?  Not an RDNIS SIP header (%s)?\n", exten);
15836       return -1;
15837    }
15838 
15839    /* Get diversion-reason param if present */
15840    if (params) {
15841       *params = '\0';   /* Cut off parameters  */
15842       params++;
15843       while (*params == ';' || *params == ' ')
15844          params++;
15845       /* Check if we have a reason parameter */
15846       if ((reason_param = strcasestr(params, "reason="))) {
15847          char *end;
15848          reason_param+=7;
15849          if ((end = strchr(reason_param, ';'))) {
15850             *end = '\0';
15851          }
15852          /* Remove enclosing double-quotes */
15853          if (*reason_param == '"')
15854             reason_param = ast_strip_quoted(reason_param, "\"", "\"");
15855          if (!ast_strlen_zero(reason_param)) {
15856             sip_set_redirstr(p, reason_param);
15857             if (p->owner) {
15858                pbx_builtin_setvar_helper(p->owner, "__PRIREDIRECTREASON", p->redircause);
15859                pbx_builtin_setvar_helper(p->owner, "__SIPREDIRECTREASON", reason_param);
15860             }
15861          }
15862       }
15863    }
15864 
15865    rdomain = exten;
15866    rexten = strsep(&rdomain, "@");  /* trim anything after @ */
15867    if (p->owner)
15868       pbx_builtin_setvar_helper(p->owner, "__SIPRDNISDOMAIN", rdomain);
15869 
15870    if (sip_debug_test_pvt(p))
15871       ast_verbose("RDNIS for this call is %s (reason %s)\n", exten, S_OR(reason_param, ""));
15872 
15873    /*ast_string_field_set(p, rdnis, rexten);*/
15874 
15875    if (*tmp == '\"') {
15876       char *end_quote;
15877       rname = tmp + 1;
15878       end_quote = strchr(rname, '\"');
15879       if (end_quote) {
15880          *end_quote = '\0';
15881       }
15882    }
15883 
15884    if (number) {
15885       *number = ast_strdup(rexten);
15886    }
15887 
15888    if (name && rname) {
15889       *name = ast_strdup(rname);
15890    }
15891 
15892    if (reason && !ast_strlen_zero(reason_param)) {
15893       *reason = sip_reason_str_to_code(reason_param);
15894    }
15895 
15896    return 0;
15897 }
15898 
15899 /*!
15900  * \brief Find out who the call is for.
15901  *
15902  * \details
15903  * We use the request uri as a destination.
15904  * This code assumes authentication has been done, so that the
15905  * device (peer/user) context is already set.
15906  *
15907  * \return 0 on success (found a matching extension), non-zero on failure
15908  *
15909  * \note If the incoming uri is a SIPS: uri, we are required to carry this across
15910  * the dialplan, so that the outbound call also is a sips: call or encrypted
15911  * IAX2 call. If that's not available, the call should FAIL.
15912  */
15913 static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id)
15914 {
15915    char tmp[256] = "", *uri, *unused_password, *domain;
15916    RAII_VAR(char *, tmpf, NULL, ast_free);
15917    char *from = NULL;
15918    struct sip_request *req;
15919    char *decoded_uri;
15920 
15921    req = oreq;
15922    if (!req) {
15923       req = &p->initreq;
15924    }
15925 
15926    /* Find the request URI */
15927    if (req->rlPart2)
15928       ast_copy_string(tmp, REQ_OFFSET_TO_STR(req, rlPart2), sizeof(tmp));
15929    
15930    uri = ast_strdupa(get_in_brackets(tmp));
15931 
15932    if (parse_uri_legacy_check(uri, "sip:,sips:", &uri, &unused_password, &domain, NULL)) {
15933       ast_log(LOG_WARNING, "Not a SIP header (%s)?\n", uri);
15934       return SIP_GET_DEST_INVALID_URI;
15935    }
15936 
15937    SIP_PEDANTIC_DECODE(domain);
15938    SIP_PEDANTIC_DECODE(uri);
15939 
15940    extract_host_from_hostport(&domain);
15941 
15942    if (ast_strlen_zero(uri)) {
15943       /*
15944        * Either there really was no extension found or the request
15945        * URI had encoded nulls that made the string "empty".  Use "s"
15946        * as the extension.
15947        */
15948       uri = "s";
15949    }
15950 
15951    ast_string_field_set(p, domain, domain);
15952 
15953    /* Now find the From: caller ID and name */
15954    /* XXX Why is this done in get_destination? Isn't it already done?
15955       Needs to be checked
15956         */
15957    tmpf = ast_strdup(get_header(req, "From"));
15958    if (!ast_strlen_zero(tmpf)) {
15959       from = get_in_brackets(tmpf);
15960       if (parse_uri_legacy_check(from, "sip:,sips:", &from, NULL, &domain, NULL)) {
15961          ast_log(LOG_WARNING, "Not a SIP header (%s)?\n", from);
15962          return SIP_GET_DEST_INVALID_URI;
15963       }
15964 
15965       SIP_PEDANTIC_DECODE(from);
15966       SIP_PEDANTIC_DECODE(domain);
15967 
15968       extract_host_from_hostport(&domain);
15969 
15970       ast_string_field_set(p, fromdomain, domain);
15971    }
15972 
15973    if (!AST_LIST_EMPTY(&domain_list)) {
15974       char domain_context[AST_MAX_EXTENSION];
15975 
15976       domain_context[0] = '\0';
15977       if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
15978          if (!sip_cfg.allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
15979             ast_debug(1, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
15980             return SIP_GET_DEST_REFUSED;
15981          }
15982       }
15983       /* If we don't have a peer (i.e. we're a guest call),
15984        * overwrite the original context */
15985       if (!ast_test_flag(&p->flags[1], SIP_PAGE2_HAVEPEERCONTEXT) && !ast_strlen_zero(domain_context)) {
15986          ast_string_field_set(p, context, domain_context);
15987       }
15988    }
15989 
15990    /* If the request coming in is a subscription and subscribecontext has been specified use it */
15991    if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext)) {
15992       ast_string_field_set(p, context, p->subscribecontext);
15993    }
15994 
15995    if (sip_debug_test_pvt(p)) {
15996       ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
15997    }
15998 
15999    /* Since extensions.conf can have unescaped characters, try matching a
16000     * decoded uri in addition to the non-decoded uri. */
16001    decoded_uri = ast_strdupa(uri);
16002    ast_uri_decode(decoded_uri);
16003 
16004    /* If this is a subscription we actually just need to see if a hint exists for the extension */
16005    if (req->method == SIP_SUBSCRIBE) {
16006       char hint[AST_MAX_EXTENSION];
16007       int which = 0;
16008       if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, uri) ||
16009           (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, decoded_uri) && (which = 1))) {
16010          if (!oreq) {
16011             ast_string_field_set(p, exten, which ? decoded_uri : uri);
16012          }
16013          return SIP_GET_DEST_EXTEN_FOUND;
16014       } else {
16015          return SIP_GET_DEST_EXTEN_NOT_FOUND;
16016       }
16017    } else {
16018       struct ast_cc_agent *agent;
16019       /* Check the dialplan for the username part of the request URI,
16020          the domain will be stored in the SIPDOMAIN variable
16021          Return 0 if we have a matching extension */
16022       if (ast_exists_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from))) {
16023          if (!oreq) {
16024             ast_string_field_set(p, exten, uri);
16025          }
16026          return SIP_GET_DEST_EXTEN_FOUND;
16027       }
16028       if (ast_exists_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))
16029          || !strcmp(decoded_uri, ast_pickup_ext())) {
16030          if (!oreq) {
16031             ast_string_field_set(p, exten, decoded_uri);
16032          }
16033          return SIP_GET_DEST_EXTEN_FOUND;
16034       }
16035       if ((agent = find_sip_cc_agent_by_notify_uri(tmp))) {
16036          struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
16037          /* This is a CC recall. We can set p's extension to the exten from
16038           * the original INVITE
16039           */
16040          ast_string_field_set(p, exten, agent_pvt->original_exten);
16041          /* And we need to let the CC core know that the caller is attempting
16042           * his recall
16043           */
16044          ast_cc_agent_recalling(agent->core_id, "SIP caller %s is attempting recall",
16045                agent->device_name);
16046          if (cc_recall_core_id) {
16047             *cc_recall_core_id = agent->core_id;
16048          }
16049          ao2_ref(agent, -1);
16050          return SIP_GET_DEST_EXTEN_FOUND;
16051       }
16052    }
16053 
16054    if (ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)
16055       && (ast_canmatch_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from))
16056          || ast_canmatch_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))
16057          || !strncmp(decoded_uri, ast_pickup_ext(), strlen(decoded_uri)))) {
16058       /* Overlap dialing is enabled and we need more digits to match an extension. */
16059       return SIP_GET_DEST_EXTEN_MATCHMORE;
16060    }
16061 
16062    return SIP_GET_DEST_EXTEN_NOT_FOUND;
16063 }
16064 
16065 /*! \brief Lock dialog lock and find matching pvt lock
16066    \return a reference, remember to release it when done
16067 */
16068 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag)
16069 {
16070    struct sip_pvt *sip_pvt_ptr;
16071    struct sip_pvt tmp_dialog = {
16072       .callid = callid,
16073    };
16074 
16075    if (totag) {
16076       ast_debug(4, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
16077    }
16078 
16079    /* Search dialogs and find the match */
16080    
16081    sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find of dialog in dialogs table");
16082    if (sip_pvt_ptr) {
16083       /* Go ahead and lock it (and its owner) before returning */
16084       sip_pvt_lock(sip_pvt_ptr);
16085       if (sip_cfg.pedanticsipchecking) {
16086          unsigned char frommismatch = 0, tomismatch = 0;
16087 
16088          if (ast_strlen_zero(fromtag)) {
16089             sip_pvt_unlock(sip_pvt_ptr);
16090             ast_debug(4, "Matched %s call for callid=%s - no from tag specified, pedantic check fails\n",
16091                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
16092             return NULL;
16093          }
16094 
16095          if (ast_strlen_zero(totag)) {
16096             sip_pvt_unlock(sip_pvt_ptr);
16097             ast_debug(4, "Matched %s call for callid=%s - no to tag specified, pedantic check fails\n",
16098                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
16099             return NULL;
16100          }
16101          /* RFC 3891
16102           * > 3.  User Agent Server Behavior: Receiving a Replaces Header
16103           * > The Replaces header contains information used to match an existing
16104           * > SIP dialog (call-id, to-tag, and from-tag).  Upon receiving an INVITE
16105           * > with a Replaces header, the User Agent (UA) attempts to match this
16106           * > information with a confirmed or early dialog.  The User Agent Server
16107           * > (UAS) matches the to-tag and from-tag parameters as if they were tags
16108           * > present in an incoming request.  In other words, the to-tag parameter
16109           * > is compared to the local tag, and the from-tag parameter is compared
16110           * > to the remote tag.
16111           *
16112           * Thus, the totag is always compared to the local tag, regardless if
16113           * this our call is an incoming or outgoing call.
16114           */
16115          frommismatch = !!strcmp(fromtag, sip_pvt_ptr->theirtag);
16116          tomismatch = !!strcmp(totag, sip_pvt_ptr->tag);
16117 
16118                         /* Don't check from if the dialog is not established, due to multi forking the from
16119                          * can change when the call is not answered yet.
16120                          */
16121          if ((frommismatch && ast_test_flag(&sip_pvt_ptr->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) || tomismatch) {
16122             sip_pvt_unlock(sip_pvt_ptr);
16123             if (frommismatch) {
16124                ast_debug(4, "Matched %s call for callid=%s - pedantic from tag check fails; their tag is %s our tag is %s\n",
16125                     sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
16126                     fromtag, sip_pvt_ptr->theirtag);
16127             }
16128             if (tomismatch) {
16129                ast_debug(4, "Matched %s call for callid=%s - pedantic to tag check fails; their tag is %s our tag is %s\n",
16130                     sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
16131                     totag, sip_pvt_ptr->tag);
16132             }
16133             return NULL;
16134          }
16135       }
16136       
16137       if (totag)
16138          ast_debug(4, "Matched %s call - their tag is %s Our tag is %s\n",
16139                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING",
16140                  sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
16141 
16142       /* deadlock avoidance... */
16143       while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
16144          sip_pvt_unlock(sip_pvt_ptr);
16145          usleep(1);
16146          sip_pvt_lock(sip_pvt_ptr);
16147       }
16148    }
16149    
16150    return sip_pvt_ptr;
16151 }
16152 
16153 /*! \brief Call transfer support (the REFER method)
16154  *    Extracts Refer headers into pvt dialog structure
16155  *
16156  * \note If we get a SIPS uri in the refer-to header, we're required to set up a secure signalling path
16157  * to that extension. As a minimum, this needs to be added to a channel variable, if not a channel
16158  * flag.
16159  */
16160 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
16161 {
16162 
16163    const char *p_referred_by = NULL;
16164    char *h_refer_to = NULL;
16165    char *h_referred_by = NULL;
16166    char *refer_to;
16167    const char *p_refer_to;
16168    char *referred_by_uri = NULL;
16169    char *ptr;
16170    struct sip_request *req = NULL;
16171    const char *transfer_context = NULL;
16172    struct sip_refer *referdata;
16173 
16174 
16175    req = outgoing_req;
16176    referdata = transferer->refer;
16177 
16178    if (!req) {
16179       req = &transferer->initreq;
16180    }
16181 
16182    p_refer_to = get_header(req, "Refer-To");
16183    if (ast_strlen_zero(p_refer_to)) {
16184       ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
16185       return -2;  /* Syntax error */
16186    }
16187    h_refer_to = ast_strdupa(p_refer_to);
16188    refer_to = get_in_brackets(h_refer_to);
16189    if (!strncasecmp(refer_to, "sip:", 4)) {
16190       refer_to += 4;       /* Skip sip: */
16191    } else if (!strncasecmp(refer_to, "sips:", 5)) {
16192       refer_to += 5;
16193    } else {
16194       ast_log(LOG_WARNING, "Can't transfer to non-sip: URI.  (Refer-to: %s)?\n", refer_to);
16195       return -3;
16196    }
16197 
16198    /* Get referred by header if it exists */
16199    p_referred_by = get_header(req, "Referred-By");
16200 
16201    /* Give useful transfer information to the dialplan */
16202    if (transferer->owner) {
16203       struct ast_channel *peer = ast_bridged_channel(transferer->owner);
16204       if (peer) {
16205          pbx_builtin_setvar_helper(peer, "SIPREFERRINGCONTEXT", transferer->context);
16206          pbx_builtin_setvar_helper(peer, "SIPREFERREDBYHDR", p_referred_by);
16207       }
16208    }
16209 
16210    if (!ast_strlen_zero(p_referred_by)) {
16211       char *lessthan;
16212       h_referred_by = ast_strdupa(p_referred_by);
16213 
16214       /* Store referrer's caller ID name */
16215       ast_copy_string(referdata->referred_by_name, h_referred_by, sizeof(referdata->referred_by_name));
16216       if ((lessthan = strchr(referdata->referred_by_name, '<'))) {
16217          *(lessthan - 1) = '\0'; /* Space */
16218       }
16219 
16220       referred_by_uri = get_in_brackets(h_referred_by);
16221 
16222       if (!strncasecmp(referred_by_uri, "sip:", 4)) {
16223          referred_by_uri += 4;      /* Skip sip: */
16224       } else if (!strncasecmp(referred_by_uri, "sips:", 5)) {
16225          referred_by_uri += 5;      /* Skip sips: */
16226       } else {
16227          ast_log(LOG_WARNING, "Huh?  Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
16228          referred_by_uri = NULL;
16229       }
16230    }
16231 
16232    /* Check for arguments in the refer_to header */
16233    if ((ptr = strcasestr(refer_to, "replaces="))) {
16234       char *to = NULL, *from = NULL;
16235       
16236       /* This is an attended transfer */
16237       referdata->attendedtransfer = 1;
16238       ast_copy_string(referdata->replaces_callid, ptr+9, sizeof(referdata->replaces_callid));
16239       ast_uri_decode(referdata->replaces_callid);
16240       if ((ptr = strchr(referdata->replaces_callid, ';')))  /* Find options */ {
16241          *ptr++ = '\0';
16242       }
16243       
16244       if (ptr) {
16245          /* Find the different tags before we destroy the string */
16246          to = strcasestr(ptr, "to-tag=");
16247          from = strcasestr(ptr, "from-tag=");
16248       }
16249       
16250       /* Grab the to header */
16251       if (to) {
16252          ptr = to + 7;
16253          if ((to = strchr(ptr, '&'))) {
16254             *to = '\0';
16255          }
16256          if ((to = strchr(ptr, ';'))) {
16257             *to = '\0';
16258          }
16259          ast_copy_string(referdata->replaces_callid_totag, ptr, sizeof(referdata->replaces_callid_totag));
16260       }
16261       
16262       if (from) {
16263          ptr = from + 9;
16264          if ((to = strchr(ptr, '&'))) {
16265             *to = '\0';
16266          }
16267          if ((to = strchr(ptr, ';'))) {
16268             *to = '\0';
16269          }
16270          ast_copy_string(referdata->replaces_callid_fromtag, ptr, sizeof(referdata->replaces_callid_fromtag));
16271       }
16272 
16273       if (!strcmp(referdata->replaces_callid, transferer->callid) &&
16274          (!sip_cfg.pedanticsipchecking ||
16275          (!strcmp(referdata->replaces_callid_fromtag, transferer->theirtag) &&
16276          !strcmp(referdata->replaces_callid_totag, transferer->tag)))) {
16277             ast_log(LOG_WARNING, "Got an attempt to replace own Call-ID on %s\n", transferer->callid);
16278             return -4;
16279       }
16280 
16281       if (!sip_cfg.pedanticsipchecking) {
16282          ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata->replaces_callid );
16283       } else {
16284          ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s F-tag: %s T-tag: %s\n", referdata->replaces_callid, referdata->replaces_callid_fromtag ? referdata->replaces_callid_fromtag : "<none>", referdata->replaces_callid_totag ? referdata->replaces_callid_totag : "<none>" );
16285       }
16286    }
16287    
16288    if ((ptr = strchr(refer_to, '@'))) {   /* Separate domain */
16289       char *urioption = NULL, *domain;
16290       int bracket = 0;
16291       *ptr++ = '\0';
16292 
16293       if ((urioption = strchr(ptr, ';'))) { /* Separate urioptions */
16294          *urioption++ = '\0';
16295       }
16296 
16297       domain = ptr;
16298 
16299       /* Remove :port */
16300       for (; *ptr != '\0'; ++ptr) {
16301          if (*ptr == ':' && bracket == 0) {
16302             *ptr = '\0';
16303             break;
16304          } else if (*ptr == '[') {
16305             ++bracket;
16306          } else if (*ptr == ']') {
16307             --bracket;
16308          }
16309       }
16310 
16311       SIP_PEDANTIC_DECODE(domain);
16312       SIP_PEDANTIC_DECODE(urioption);
16313 
16314       /* Save the domain for the dial plan */
16315       ast_copy_string(referdata->refer_to_domain, domain, sizeof(referdata->refer_to_domain));
16316       if (urioption) {
16317          ast_copy_string(referdata->refer_to_urioption, urioption, sizeof(referdata->refer_to_urioption));
16318       }
16319    }
16320 
16321    if ((ptr = strchr(refer_to, ';')))  /* Remove options */
16322       *ptr = '\0';
16323 
16324    SIP_PEDANTIC_DECODE(refer_to);
16325    ast_copy_string(referdata->refer_to, refer_to, sizeof(referdata->refer_to));
16326    
16327    if (referred_by_uri) {
16328       if ((ptr = strchr(referred_by_uri, ';')))    /* Remove options */
16329          *ptr = '\0';
16330       SIP_PEDANTIC_DECODE(referred_by_uri);
16331       ast_copy_string(referdata->referred_by, referred_by_uri, sizeof(referdata->referred_by));
16332    } else {
16333       referdata->referred_by[0] = '\0';
16334    }
16335 
16336    /* Determine transfer context */
16337    if (transferer->owner) {
16338       /* By default, use the context in the channel sending the REFER */
16339       transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
16340       if (ast_strlen_zero(transfer_context)) {
16341          transfer_context = transferer->owner->macrocontext;
16342       }
16343    }
16344    if (ast_strlen_zero(transfer_context)) {
16345       transfer_context = S_OR(transferer->context, sip_cfg.default_context);
16346    }
16347 
16348    ast_copy_string(referdata->refer_to_context, transfer_context, sizeof(referdata->refer_to_context));
16349    
16350    /* Either an existing extension or the parking extension */
16351    if (referdata->attendedtransfer || ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL) ) {
16352       if (sip_debug_test_pvt(transferer)) {
16353          ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
16354       }
16355       /* We are ready to transfer to the extension */
16356       return 0;
16357    }
16358    if (sip_debug_test_pvt(transferer))
16359       ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
16360 
16361    /* Failure, we can't find this extension */
16362    return -1;
16363 }
16364 
16365 
16366 /*! \brief Call transfer support (old way, deprecated by the IETF)
16367  * \note does not account for SIPS: uri requirements, nor check transport
16368  */
16369 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
16370 {
16371    char tmp[256] = "", *c, *a;
16372    struct sip_request *req = oreq ? oreq : &p->initreq;
16373    struct sip_refer *referdata = NULL;
16374    const char *transfer_context = NULL;
16375    
16376    if (!p->refer && !sip_refer_allocate(p))
16377       return -1;
16378 
16379    referdata = p->refer;
16380 
16381    ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp));
16382    c = get_in_brackets(tmp);
16383 
16384    if (parse_uri_legacy_check(c, "sip:,sips:", &c, NULL, &a, NULL)) {
16385       ast_log(LOG_WARNING, "Huh?  Not a SIP header in Also: transfer (%s)?\n", c);
16386       return -1;
16387    }
16388    
16389    SIP_PEDANTIC_DECODE(c);
16390    SIP_PEDANTIC_DECODE(a);
16391 
16392    if (!ast_strlen_zero(a)) {
16393       ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain));
16394    }
16395 
16396    if (sip_debug_test_pvt(p))
16397       ast_verbose("Looking for %s in %s\n", c, p->context);
16398 
16399    /* Determine transfer context */
16400    if (p->owner) {
16401       /* By default, use the context in the channel sending the REFER */
16402       transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
16403       if (ast_strlen_zero(transfer_context)) {
16404          transfer_context = p->owner->macrocontext;
16405       }
16406    }
16407    if (ast_strlen_zero(transfer_context)) {
16408       transfer_context = S_OR(p->context, sip_cfg.default_context);
16409    }
16410 
16411    if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
16412       /* This is a blind transfer */
16413       ast_debug(1, "SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
16414       ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to));
16415       ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by));
16416       ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact));
16417       /* Set new context */
16418       ast_string_field_set(p, context, transfer_context);
16419       return 0;
16420    } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
16421       return 1;
16422    }
16423 
16424    return -1;
16425 }
16426 
16427 /*! \brief check received= and rport= in a SIP response.
16428  * If we get a response with received= and/or rport= in the Via:
16429  * line, use them as 'p->ourip' (see RFC 3581 for rport,
16430  * and RFC 3261 for received).
16431  * Using these two fields SIP can produce the correct
16432  * address and port in the SIP headers without the need for STUN.
16433  * The address part is also reused for the media sessions.
16434  * Note that ast_sip_ouraddrfor() still rewrites p->ourip
16435  * if you specify externaddr/seternaddr/.
16436  */
16437 static attribute_unused void check_via_response(struct sip_pvt *p, struct sip_request *req)
16438 {
16439    char via[256];
16440    char *cur, *opts;
16441 
16442    ast_copy_string(via, get_header(req, "Via"), sizeof(via));
16443 
16444    /* Work on the leftmost value of the topmost Via header */
16445    opts = strchr(via, ',');
16446    if (opts)
16447       *opts = '\0';
16448 
16449    /* parse all relevant options */
16450    opts = strchr(via, ';');
16451    if (!opts)
16452       return;  /* no options to parse */
16453    *opts++ = '\0';
16454    while ( (cur = strsep(&opts, ";")) ) {
16455       if (!strncmp(cur, "rport=", 6)) {
16456          int port = strtol(cur+6, NULL, 10);
16457          /* XXX add error checking */
16458          ast_sockaddr_set_port(&p->ourip, port);
16459       } else if (!strncmp(cur, "received=", 9)) {
16460          if (ast_parse_arg(cur + 9, PARSE_ADDR, &p->ourip))
16461             ;  /* XXX add error checking */
16462       }
16463    }
16464 }
16465 
16466 /*! \brief check Via: header for hostname, port and rport request/answer */
16467 static void check_via(struct sip_pvt *p, const struct sip_request *req)
16468 {
16469    char via[512];
16470    char *c, *maddr;
16471    struct ast_sockaddr tmp = { { 0, } };
16472    uint16_t port;
16473 
16474    ast_copy_string(via, get_header(req, "Via"), sizeof(via));
16475 
16476    /* Work on the leftmost value of the topmost Via header */
16477    c = strchr(via, ',');
16478    if (c)
16479       *c = '\0';
16480 
16481    /* Check for rport */
16482    c = strstr(via, ";rport");
16483    if (c && (c[6] != '=')) { /* rport query, not answer */
16484       ast_set_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT);
16485       ast_set_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT);
16486    }
16487 
16488    /* Check for maddr */
16489    maddr = strstr(via, "maddr=");
16490    if (maddr) {
16491       maddr += 6;
16492       c = maddr + strspn(maddr, "abcdefghijklmnopqrstuvwxyz"
16493                       "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-.:[]");
16494       *c = '\0';
16495    }
16496 
16497    c = strchr(via, ';');
16498    if (c)
16499       *c = '\0';
16500 
16501    c = strchr(via, ' ');
16502    if (c) {
16503       *c = '\0';
16504       c = ast_skip_blanks(c+1);
16505       if (strcasecmp(via, "SIP/2.0/UDP") && strcasecmp(via, "SIP/2.0/TCP") && strcasecmp(via, "SIP/2.0/TLS")) {
16506          ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
16507          return;
16508       }
16509 
16510       if (maddr && ast_sockaddr_resolve_first(&p->sa, maddr, 0)) {
16511          p->sa = p->recv;
16512       }
16513 
16514       if (ast_sockaddr_resolve_first(&tmp, c, 0)) {
16515          ast_log(LOG_WARNING, "Could not resolve socket address for '%s'\n", c);
16516          port = STANDARD_SIP_PORT;
16517       } else if (!(port = ast_sockaddr_port(&tmp))) {
16518          port = STANDARD_SIP_PORT;
16519       }
16520 
16521       ast_sockaddr_set_port(&p->sa, port);
16522 
16523       if (sip_debug_test_pvt(p)) {
16524          ast_verbose("Sending to %s (%s)\n",
16525                 ast_sockaddr_stringify(sip_real_dst(p)),
16526                 sip_nat_mode(p));
16527       }
16528    }
16529 }
16530 
16531 /*! \brief Validate device authentication */
16532 static enum check_auth_result check_peer_ok(struct sip_pvt *p, char *of,
16533    struct sip_request *req, int sipmethod, struct ast_sockaddr *addr,
16534    struct sip_peer **authpeer,
16535    enum xmittype reliable, char *calleridname, char *uri2)
16536 {
16537    enum check_auth_result res;
16538    int debug = sip_debug_test_addr(addr);
16539    struct sip_peer *peer;
16540 
16541    if (sipmethod == SIP_SUBSCRIBE) {
16542       /* For subscribes, match on device name only; for other methods,
16543       * match on IP address-port of the incoming request.
16544       */
16545       peer = find_peer(of, NULL, TRUE, FINDALLDEVICES, FALSE, 0);
16546    } else {
16547       /* First find devices based on username (avoid all type=peer's) */
16548       peer = find_peer(of, NULL, TRUE, FINDUSERS, FALSE, 0);
16549 
16550       /* Then find devices based on IP */
16551       if (!peer) {
16552          peer = find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
16553       }
16554    }
16555 
16556    if (!peer) {
16557       if (debug) {
16558          ast_verbose("No matching peer for '%s' from '%s'\n",
16559             of, ast_sockaddr_stringify(&p->recv));
16560       }
16561 
16562       /* If you don't mind, we can return 404s for devices that do
16563        * not exist: username disclosure. If we allow guests, there
16564        * is no way around that. */
16565       if (sip_cfg.allowguest || !sip_cfg.alwaysauthreject) {
16566          return AUTH_DONT_KNOW;
16567       }
16568 
16569       /* If you do mind, we use a peer that will never authenticate.
16570        * This ensures that we follow the same code path as regular
16571        * auth: less chance for username disclosure. */
16572       peer = bogus_peer;
16573       ref_peer(peer, "ref_peer: check_peer_ok: must ref bogus_peer so unreffing it does not fail");
16574    }
16575 
16576    if (!ast_apply_ha(peer->ha, addr)) {
16577       ast_debug(2, "Found peer '%s' for '%s', but fails host access\n", peer->name, of);
16578       unref_peer(peer, "unref_peer: check_peer_ok: from find_peer call, early return of AUTH_ACL_FAILED");
16579       return AUTH_ACL_FAILED;
16580    }
16581    if (debug && peer != bogus_peer) {
16582       ast_verbose("Found peer '%s' for '%s' from %s\n",
16583          peer->name, of, ast_sockaddr_stringify(&p->recv));
16584    }
16585 
16586    /* XXX what about p->prefs = peer->prefs; ? */
16587    /* Set Frame packetization */
16588    if (p->rtp) {
16589       ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &peer->prefs);
16590       p->autoframing = peer->autoframing;
16591    }
16592 
16593    /* Take the peer */
16594    ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
16595    ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
16596    ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
16597 
16598    if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && p->udptl) {
16599       p->t38_maxdatagram = peer->t38_maxdatagram;
16600       set_t38_capabilities(p);
16601    }
16602 
16603    /* Copy SIP extensions profile to peer */
16604    /* XXX is this correct before a successful auth ? */
16605    if (p->sipoptions)
16606       peer->sipoptions = p->sipoptions;
16607 
16608    do_setnat(p);
16609 
16610    ast_string_field_set(p, peersecret, peer->secret);
16611    ast_string_field_set(p, peermd5secret, peer->md5secret);
16612    ast_string_field_set(p, subscribecontext, peer->subscribecontext);
16613    ast_string_field_set(p, mohinterpret, peer->mohinterpret);
16614    ast_string_field_set(p, mohsuggest, peer->mohsuggest);
16615    if (!ast_strlen_zero(peer->parkinglot)) {
16616       ast_string_field_set(p, parkinglot, peer->parkinglot);
16617    }
16618    ast_string_field_set(p, engine, peer->engine);
16619    p->disallowed_methods = peer->disallowed_methods;
16620    set_pvt_allowed_methods(p, req);
16621    ast_cc_copy_config_params(p->cc_params, peer->cc_params);
16622    if (peer->callingpres)  /* Peer calling pres setting will override RPID */
16623       p->callingpres = peer->callingpres;
16624    if (peer->maxms && peer->lastms)
16625       p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
16626    else
16627       p->timer_t1 = peer->timer_t1;
16628 
16629    /* Set timer B to control transaction timeouts */
16630    if (peer->timer_b)
16631       p->timer_b = peer->timer_b;
16632    else
16633       p->timer_b = 64 * p->timer_t1;
16634 
16635    p->allowtransfer = peer->allowtransfer;
16636 
16637    if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
16638       /* Pretend there is no required authentication */
16639       ast_string_field_set(p, peersecret, NULL);
16640       ast_string_field_set(p, peermd5secret, NULL);
16641    }
16642    if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, req->ignore))) {
16643       ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
16644       ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
16645       ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
16646       /* If we have a call limit, set flag */
16647       if (peer->call_limit)
16648          ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
16649       ast_string_field_set(p, peername, peer->name);
16650       ast_string_field_set(p, authname, peer->name);
16651 
16652       if (sipmethod == SIP_INVITE) {
16653          /* destroy old channel vars and copy in new ones. */
16654          ast_variables_destroy(p->chanvars);
16655          p->chanvars = copy_vars(peer->chanvars);
16656       }
16657 
16658       if (authpeer) {
16659          ao2_t_ref(peer, 1, "copy pointer into (*authpeer)");
16660          (*authpeer) = peer;  /* Add a ref to the object here, to keep it in memory a bit longer if it is realtime */
16661       }
16662 
16663       if (!ast_strlen_zero(peer->username)) {
16664          ast_string_field_set(p, username, peer->username);
16665          /* Use the default username for authentication on outbound calls */
16666          /* XXX this takes the name from the caller... can we override ? */
16667          ast_string_field_set(p, authname, peer->username);
16668       }
16669       if (!get_rpid(p, req)) {
16670          if (!ast_strlen_zero(peer->cid_num)) {
16671             char *tmp = ast_strdupa(peer->cid_num);
16672             if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
16673                ast_shrink_phone_number(tmp);
16674             ast_string_field_set(p, cid_num, tmp);
16675          }
16676          if (!ast_strlen_zero(peer->cid_name))
16677             ast_string_field_set(p, cid_name, peer->cid_name);
16678          if (peer->callingpres)
16679             p->callingpres = peer->callingpres;
16680       }
16681       if (!ast_strlen_zero(peer->cid_tag)) {
16682          ast_string_field_set(p, cid_tag, peer->cid_tag);
16683       }
16684       ast_string_field_set(p, fullcontact, peer->fullcontact);
16685 
16686       if (!ast_strlen_zero(peer->context)) {
16687          ast_string_field_set(p, context, peer->context);
16688       }
16689       if (!ast_strlen_zero(peer->mwi_from)) {
16690          ast_string_field_set(p, mwi_from, peer->mwi_from);
16691       }
16692 
16693       ast_string_field_set(p, peersecret, peer->secret);
16694       ast_string_field_set(p, peermd5secret, peer->md5secret);
16695       ast_string_field_set(p, language, peer->language);
16696       ast_string_field_set(p, accountcode, peer->accountcode);
16697       p->amaflags = peer->amaflags;
16698       p->callgroup = peer->callgroup;
16699       p->pickupgroup = peer->pickupgroup;
16700       p->capability = peer->capability;
16701       p->prefs = peer->prefs;
16702       p->jointcapability = peer->capability;
16703       if (peer->maxforwards > 0) {
16704          p->maxforwards = peer->maxforwards;
16705       }
16706       if (p->peercapability)
16707          p->jointcapability &= p->peercapability;
16708       p->maxcallbitrate = peer->maxcallbitrate;
16709       if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
16710           (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
16711          p->noncodeccapability |= AST_RTP_DTMF;
16712       else
16713          p->noncodeccapability &= ~AST_RTP_DTMF;
16714       p->jointnoncodeccapability = p->noncodeccapability;
16715       p->rtptimeout = peer->rtptimeout;
16716       p->rtpholdtimeout = peer->rtpholdtimeout;
16717       p->rtpkeepalive = peer->rtpkeepalive;
16718       if (!dialog_initialize_rtp(p)) {
16719          if (p->rtp) {
16720             ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &peer->prefs);
16721             p->autoframing = peer->autoframing;
16722          }
16723       } else {
16724          res = AUTH_RTP_FAILED;
16725       }
16726    }
16727    unref_peer(peer, "check_peer_ok: unref_peer: tossing temp ptr to peer from find_peer");
16728    return res;
16729 }
16730 
16731 
16732 /*! \brief  Check if matching user or peer is defined
16733    Match user on From: user name and peer on IP/port
16734    This is used on first invite (not re-invites) and subscribe requests
16735     \return 0 on success, non-zero on failure
16736 */
16737 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
16738                      int sipmethod, const char *uri, enum xmittype reliable,
16739                      struct ast_sockaddr *addr, struct sip_peer **authpeer)
16740 {
16741    char *of, *name, *unused_password, *domain;
16742    RAII_VAR(char *, ofbuf, NULL, ast_free); /* beware, everyone starts pointing to this */
16743    RAII_VAR(char *, namebuf, NULL, ast_free);
16744    enum check_auth_result res = AUTH_DONT_KNOW;
16745    char calleridname[256];
16746    char *uri2 = ast_strdupa(uri);
16747 
16748    terminate_uri(uri2); /* trim extra stuff */
16749 
16750    ofbuf = ast_strdup(get_header(req, "From"));
16751    /* XXX here tries to map the username for invite things */
16752 
16753    /* strip the display-name portion off the beginning of the FROM header. */
16754    if (!(of = (char *) get_calleridname(ofbuf, calleridname, sizeof(calleridname)))) {
16755       ast_log(LOG_ERROR, "FROM header can not be parsed\n");
16756       return res;
16757    }
16758 
16759    if (calleridname[0]) {
16760       ast_string_field_set(p, cid_name, calleridname);
16761    }
16762 
16763    if (ast_strlen_zero(p->exten)) {
16764       char *t = uri2;
16765       if (!strncasecmp(t, "sip:", 4))
16766          t+= 4;
16767       else if (!strncasecmp(t, "sips:", 5))
16768          t += 5;
16769       ast_string_field_set(p, exten, t);
16770       t = strchr(p->exten, '@');
16771       if (t)
16772          *t = '\0';
16773 
16774       if (ast_strlen_zero(p->our_contact))
16775          build_contact(p);
16776    }
16777 
16778    of = get_in_brackets(of);
16779 
16780    /* save the URI part of the From header */
16781    ast_string_field_set(p, from, of);
16782 
16783    if (parse_uri_legacy_check(of, "sip:,sips:", &name, &unused_password, &domain, NULL)) {
16784       ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
16785    }
16786 
16787    SIP_PEDANTIC_DECODE(name);
16788    SIP_PEDANTIC_DECODE(domain);
16789 
16790    extract_host_from_hostport(&domain);
16791 
16792    if (ast_strlen_zero(domain)) {
16793       /* <sip:name@[EMPTY]>, never good */
16794       ast_log(LOG_ERROR, "Empty domain name in FROM header\n");
16795       return res;
16796    }
16797 
16798    if (ast_strlen_zero(name)) {
16799       /* <sip:[EMPTY][@]hostport>. Asterisk 1.4 and 1.6 have always
16800        * treated that as a username, so we continue the tradition:
16801        * uri is now <sip:host@hostport>. */
16802       name = domain;
16803    } else {
16804       /* Non-empty name, try to get caller id from it */
16805       char *tmp = ast_strdupa(name);
16806       /* We need to be able to handle from-headers looking like
16807          <sip:8164444422;phone-context=+1@1.2.3.4:5060;user=phone;tag=SDadkoa01-gK0c3bdb43>
16808       */
16809       tmp = strsep(&tmp, ";");
16810       if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp)) {
16811          ast_shrink_phone_number(tmp);
16812       }
16813       ast_string_field_set(p, cid_num, tmp);
16814    }
16815 
16816    if (global_match_auth_username) {
16817       /*
16818        * XXX This is experimental code to grab the search key from the
16819        * Auth header's username instead of the 'From' name, if available.
16820        * Do not enable this block unless you understand the side effects (if any!)
16821        * Note, the search for "username" should be done in a more robust way.
16822        * Note2, at the moment we check both fields, though maybe we should
16823        * pick one or another depending on the request ? XXX
16824        */
16825       const char *hdr = get_header(req, "Authorization");
16826       if (ast_strlen_zero(hdr)) {
16827          hdr = get_header(req, "Proxy-Authorization");
16828       }
16829 
16830       if (!ast_strlen_zero(hdr) && (hdr = strstr(hdr, "username=\""))) {
16831          namebuf = name = ast_strdup(hdr + strlen("username=\""));
16832          name = strsep(&name, "\"");
16833       }
16834    }
16835 
16836    res = check_peer_ok(p, name, req, sipmethod, addr,
16837          authpeer, reliable, calleridname, uri2);
16838    if (res != AUTH_DONT_KNOW) {
16839       return res;
16840    }
16841 
16842    /* Finally, apply the guest policy */
16843    if (sip_cfg.allowguest) {
16844       /* Ignore check_return warning from Coverity for get_rpid below. */
16845       get_rpid(p, req);
16846       p->rtptimeout = global_rtptimeout;
16847       p->rtpholdtimeout = global_rtpholdtimeout;
16848       p->rtpkeepalive = global_rtpkeepalive;
16849       if (!dialog_initialize_rtp(p)) {
16850          res = AUTH_SUCCESSFUL;
16851       } else {
16852          res = AUTH_RTP_FAILED;
16853       }
16854    } else {
16855       res = AUTH_SECRET_FAILED; /* we don't want any guests, authentication will fail */
16856    }
16857 
16858    if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT)) {
16859       ast_set_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT);
16860    }
16861 
16862    return res;
16863 }
16864 
16865 /*! \brief  Find user
16866    If we get a match, this will add a reference pointer to the user object in ASTOBJ, that needs to be unreferenced
16867 */
16868 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr)
16869 {
16870    return check_user_full(p, req, sipmethod, uri, reliable, addr, NULL);
16871 }
16872 
16873 /*! \brief Get message body from a SIP request
16874  * \param buf Destination buffer
16875  * \param len Destination buffer size
16876  * \param req The SIP request
16877  *
16878  * When parsing the request originally, the lines are split by LF or CRLF.
16879  * This function adds a single LF after every line.
16880  */
16881 static int get_msg_text(char *buf, int len, struct sip_request *req)
16882 {
16883    int x;
16884    int linelen;
16885 
16886    buf[0] = '\0';
16887    --len; /* reserve strncat null */
16888    for (x = 0; len && x < req->lines; ++x) {
16889       const char *line = REQ_OFFSET_TO_STR(req, line[x]);
16890       strncat(buf, line, len); /* safe */
16891       linelen = strlen(buf);
16892       buf += linelen;
16893       len -= linelen;
16894       if (len) {
16895          strcat(buf, "\n"); /* safe */
16896          ++buf;
16897          --len;
16898       }
16899    }
16900    return 0;
16901 }
16902 
16903 
16904 /*! \brief  Receive SIP MESSAGE method messages
16905 \note We only handle messages within current calls currently
16906    Reference: RFC 3428 */
16907 static void receive_message(struct sip_pvt *p, struct sip_request *req)
16908 {
16909    char buf[1400];   
16910    char *bufp;
16911    struct ast_frame f;
16912    const char *content_type = get_header(req, "Content-Type");
16913 
16914    if (strncmp(content_type, "text/plain", strlen("text/plain"))) { /* No text/plain attachment */
16915       transmit_response(p, "415 Unsupported Media Type", req); /* Good enough, or? */
16916       if (!p->owner)
16917          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16918       return;
16919    }
16920 
16921    if (get_msg_text(buf, sizeof(buf), req)) {
16922       ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
16923       transmit_response(p, "500 Internal Server Error", req);
16924       if (!p->owner) {
16925          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16926       }
16927       return;
16928    }
16929 
16930    /* Strip trailing line feeds from message body. (get_msg_text may add
16931     * a trailing linefeed and we don't need any at the end) */
16932    bufp = buf + strlen(buf);
16933    while (--bufp >= buf && *bufp == '\n') {
16934       *bufp = '\0';
16935    }
16936 
16937    if (p->owner) {
16938       if (sip_debug_test_pvt(p))
16939          ast_verbose("SIP Text message received: '%s'\n", buf);
16940       memset(&f, 0, sizeof(f));
16941       f.frametype = AST_FRAME_TEXT;
16942       f.subclass.integer = 0;
16943       f.offset = 0;
16944       f.data.ptr = buf;
16945       f.datalen = strlen(buf) + 1;
16946       ast_queue_frame(p->owner, &f);
16947       transmit_response(p, "202 Accepted", req); /* We respond 202 accepted, since we relay the message */
16948       return;
16949    }
16950 
16951    /* Message outside of a call, we do not support that */
16952    ast_log(LOG_WARNING, "Received message to %s from %s, dropped it...\n  Content-Type:%s\n  Message: %s\n", get_header(req, "To"), get_header(req, "From"), content_type, buf);
16953    transmit_response(p, "405 Method Not Allowed", req);
16954    sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16955    return;
16956 }
16957 
16958 /*! \brief  CLI Command to show calls within limits set by call_limit */
16959 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16960 {
16961 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
16962 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
16963    char ilimits[40];
16964    char iused[40];
16965    int showall = FALSE;
16966    struct ao2_iterator i;
16967    struct sip_peer *peer;
16968    
16969    switch (cmd) {
16970    case CLI_INIT:
16971       e->command = "sip show inuse";
16972       e->usage =
16973          "Usage: sip show inuse [all]\n"
16974          "       List all SIP devices usage counters and limits.\n"
16975          "       Add option \"all\" to show all devices, not only those with a limit.\n";
16976       return NULL;
16977    case CLI_GENERATE:
16978       return NULL;
16979    }
16980 
16981    if (a->argc < 3)
16982       return CLI_SHOWUSAGE;
16983 
16984    if (a->argc == 4 && !strcmp(a->argv[3], "all"))
16985       showall = TRUE;
16986    
16987    ast_cli(a->fd, FORMAT, "* Peer name", "In use", "Limit");
16988 
16989    i = ao2_iterator_init(peers, 0);
16990    while ((peer = ao2_t_iterator_next(&i, "iterate thru peer table"))) {
16991       ao2_lock(peer);
16992       if (peer->call_limit)
16993          snprintf(ilimits, sizeof(ilimits), "%d", peer->call_limit);
16994       else
16995          ast_copy_string(ilimits, "N/A", sizeof(ilimits));
16996       snprintf(iused, sizeof(iused), "%d/%d/%d", peer->inUse, peer->inRinging, peer->onHold);
16997       if (showall || peer->call_limit)
16998          ast_cli(a->fd, FORMAT2, peer->name, iused, ilimits);
16999       ao2_unlock(peer);
17000       unref_peer(peer, "toss iterator pointer");
17001    }
17002    ao2_iterator_destroy(&i);
17003 
17004    return CLI_SUCCESS;
17005 #undef FORMAT
17006 #undef FORMAT2
17007 }
17008 
17009 
17010 /*! \brief Convert transfer mode to text string */
17011 static char *transfermode2str(enum transfermodes mode)
17012 {
17013    if (mode == TRANSFER_OPENFORALL)
17014       return "open";
17015    else if (mode == TRANSFER_CLOSED)
17016       return "closed";
17017    return "strict";
17018 }
17019 
17020 /*! \brief  Report Peer status in character string
17021  *  \return 0 if peer is unreachable, 1 if peer is online, -1 if unmonitored
17022  */
17023 
17024 
17025 /* Session-Timer Modes */
17026 static const struct _map_x_s stmodes[] = {
17027         { SESSION_TIMER_MODE_ACCEPT,    "Accept"},
17028         { SESSION_TIMER_MODE_ORIGINATE, "Originate"},
17029         { SESSION_TIMER_MODE_REFUSE,    "Refuse"},
17030         { -1,                           NULL},
17031 };
17032 
17033 static const char *stmode2str(enum st_mode m)
17034 {
17035    return map_x_s(stmodes, m, "Unknown");
17036 }
17037 
17038 static enum st_mode str2stmode(const char *s)
17039 {
17040    return map_s_x(stmodes, s, -1);
17041 }
17042 
17043 /* Session-Timer Refreshers */
17044 static const struct _map_x_s strefresher_params[] = {
17045         { SESSION_TIMER_REFRESHER_PARAM_UNKNOWN, "unknown" },
17046         { SESSION_TIMER_REFRESHER_PARAM_UAC,     "uac"     },
17047         { SESSION_TIMER_REFRESHER_PARAM_UAS,     "uas"     },
17048         { -1,                                NULL  },
17049 };
17050 
17051 static const struct _map_x_s strefreshers[] = {
17052         { SESSION_TIMER_REFRESHER_AUTO, "auto" },
17053         { SESSION_TIMER_REFRESHER_US,   "us"   },
17054         { SESSION_TIMER_REFRESHER_THEM, "them" },
17055         { -1,                           NULL   },
17056 };
17057 
17058 static const char *strefresherparam2str(enum st_refresher r)
17059 {
17060    return map_x_s(strefresher_params, r, "Unknown");
17061 }
17062 
17063 static enum st_refresher str2strefresherparam(const char *s)
17064 {
17065    return map_s_x(strefresher_params, s, -1);
17066 }
17067 
17068 static const char *strefresher2str(enum st_refresher r)
17069 {
17070    return map_x_s(strefreshers, r, "Unknown");
17071 }
17072 
17073 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
17074 {
17075    int res = 0;
17076    if (peer->maxms) {
17077       if (peer->lastms < 0) {
17078          ast_copy_string(status, "UNREACHABLE", statuslen);
17079       } else if (peer->lastms > peer->maxms) {
17080          snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
17081          res = 1;
17082       } else if (peer->lastms) {
17083          snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
17084          res = 1;
17085       } else {
17086          ast_copy_string(status, "UNKNOWN", statuslen);
17087       }
17088    } else {
17089       ast_copy_string(status, "Unmonitored", statuslen);
17090       /* Checking if port is 0 */
17091       res = -1;
17092    }
17093    return res;
17094 }
17095 
17096 /*! \brief  Show active TCP connections */
17097 static char *sip_show_tcp(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17098 {
17099    struct sip_threadinfo *th;
17100    struct ao2_iterator i;
17101 
17102 #define FORMAT2 "%-47.47s %9.9s %6.6s\n"
17103 #define FORMAT  "%-47.47s %-9.9s %-6.6s\n"
17104 
17105    switch (cmd) {
17106    case CLI_INIT:
17107       e->command = "sip show tcp";
17108       e->usage =
17109          "Usage: sip show tcp\n"
17110          "       Lists all active TCP/TLS sessions.\n";
17111       return NULL;
17112    case CLI_GENERATE:
17113       return NULL;
17114    }
17115 
17116    if (a->argc != 3)
17117       return CLI_SHOWUSAGE;
17118 
17119    ast_cli(a->fd, FORMAT2, "Address", "Transport", "Type");
17120 
17121    i = ao2_iterator_init(threadt, 0);
17122    while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
17123       ast_cli(a->fd, FORMAT,
17124          ast_sockaddr_stringify(&th->tcptls_session->remote_address),
17125          get_transport(th->type),
17126          (th->tcptls_session->client ? "Client" : "Server"));
17127       ao2_t_ref(th, -1, "decrement ref from iterator");
17128    }
17129    ao2_iterator_destroy(&i);
17130 
17131    return CLI_SUCCESS;
17132 #undef FORMAT
17133 #undef FORMAT2
17134 }
17135 
17136 /*! \brief  CLI Command 'SIP Show Users' */
17137 static char *sip_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17138 {
17139    regex_t regexbuf;
17140    int havepattern = FALSE;
17141    struct ao2_iterator user_iter;
17142    struct sip_peer *user;
17143 
17144 #define FORMAT  "%-25.25s  %-15.15s  %-15.15s  %-15.15s  %-5.5s%-10.10s\n"
17145 
17146    switch (cmd) {
17147    case CLI_INIT:
17148       e->command = "sip show users";
17149       e->usage =
17150          "Usage: sip show users [like <pattern>]\n"
17151          "       Lists all known SIP users.\n"
17152          "       Optional regular expression pattern is used to filter the user list.\n";
17153       return NULL;
17154    case CLI_GENERATE:
17155       return NULL;
17156    }
17157 
17158    switch (a->argc) {
17159    case 5:
17160       if (!strcasecmp(a->argv[3], "like")) {
17161          if (regcomp(&regexbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
17162             return CLI_SHOWUSAGE;
17163          havepattern = TRUE;
17164       } else
17165          return CLI_SHOWUSAGE;
17166    case 3:
17167       break;
17168    default:
17169       return CLI_SHOWUSAGE;
17170    }
17171 
17172    ast_cli(a->fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "Forcerport");
17173 
17174    user_iter = ao2_iterator_init(peers, 0);
17175    while ((user = ao2_t_iterator_next(&user_iter, "iterate thru peers table"))) {
17176       ao2_lock(user);
17177       if (!(user->type & SIP_TYPE_USER)) {
17178          ao2_unlock(user);
17179          unref_peer(user, "sip show users");
17180          continue;
17181       }
17182 
17183       if (havepattern && regexec(&regexbuf, user->name, 0, NULL, 0)) {
17184          ao2_unlock(user);
17185          unref_peer(user, "sip show users");
17186          continue;
17187       }
17188 
17189       ast_cli(a->fd, FORMAT, user->name,
17190          user->secret,
17191          user->accountcode,
17192          user->context,
17193          AST_CLI_YESNO(user->ha != NULL),
17194          AST_CLI_YESNO(ast_test_flag(&user->flags[0], SIP_NAT_FORCE_RPORT)));
17195       ao2_unlock(user);
17196       unref_peer(user, "sip show users");
17197    }
17198    ao2_iterator_destroy(&user_iter);
17199 
17200    if (havepattern)
17201       regfree(&regexbuf);
17202 
17203    return CLI_SUCCESS;
17204 #undef FORMAT
17205 }
17206 
17207 /*! \brief Show SIP registrations in the manager API */
17208 static int manager_show_registry(struct mansession *s, const struct message *m)
17209 {
17210    const char *id = astman_get_header(m, "ActionID");
17211    char idtext[256] = "";
17212    int total = 0;
17213 
17214    if (!ast_strlen_zero(id))
17215       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
17216 
17217    astman_send_listack(s, m, "Registrations will follow", "start");
17218 
17219    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
17220       ASTOBJ_RDLOCK(iterator);
17221       astman_append(s,
17222          "Event: RegistryEntry\r\n"
17223          "%s"
17224          "Host: %s\r\n"
17225          "Port: %d\r\n"
17226          "Username: %s\r\n"
17227          "Domain: %s\r\n"
17228          "DomainPort: %d\r\n"
17229          "Refresh: %d\r\n"
17230          "State: %s\r\n"
17231          "RegistrationTime: %ld\r\n"
17232          "\r\n",
17233          idtext,
17234          iterator->hostname,
17235          iterator->portno ? iterator->portno : STANDARD_SIP_PORT,
17236          iterator->username,
17237          S_OR(iterator->regdomain,iterator->hostname),
17238          iterator->regdomainport ? iterator->regdomainport : STANDARD_SIP_PORT,
17239          iterator->refresh,
17240          regstate2str(iterator->regstate),
17241          (long) iterator->regtime.tv_sec);
17242       ASTOBJ_UNLOCK(iterator);
17243       total++;
17244    } while(0));
17245 
17246    astman_append(s,
17247       "Event: RegistrationsComplete\r\n"
17248       "EventList: Complete\r\n"
17249       "ListItems: %d\r\n"
17250       "%s"
17251       "\r\n", total, idtext);
17252    
17253    return 0;
17254 }
17255 
17256 /*! \brief  Show SIP peers in the manager API */
17257 /*    Inspired from chan_iax2 */
17258 static int manager_sip_show_peers(struct mansession *s, const struct message *m)
17259 {
17260    const char *id = astman_get_header(m, "ActionID");
17261    const char *a[] = {"sip", "show", "peers"};
17262    char idtext[256] = "";
17263    int total = 0;
17264 
17265    if (!ast_strlen_zero(id))
17266       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
17267 
17268    astman_send_listack(s, m, "Peer status list will follow", "start");
17269    /* List the peers in separate manager events */
17270    _sip_show_peers(-1, &total, s, m, 3, a);
17271    /* Send final confirmation */
17272    astman_append(s,
17273    "Event: PeerlistComplete\r\n"
17274    "EventList: Complete\r\n"
17275    "ListItems: %d\r\n"
17276    "%s"
17277    "\r\n", total, idtext);
17278    return 0;
17279 }
17280 
17281 /*! \brief  CLI Show Peers command */
17282 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17283 {
17284    switch (cmd) {
17285    case CLI_INIT:
17286       e->command = "sip show peers";
17287       e->usage =
17288          "Usage: sip show peers [like <pattern>]\n"
17289          "       Lists all known SIP peers.\n"
17290          "       Optional regular expression pattern is used to filter the peer list.\n";
17291       return NULL;
17292    case CLI_GENERATE:
17293       return NULL;
17294    }
17295 
17296    return _sip_show_peers(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
17297 }
17298 
17299 int peercomparefunc(const void *a, const void *b);
17300 
17301 int peercomparefunc(const void *a, const void *b)
17302 {
17303    struct sip_peer **ap = (struct sip_peer **)a;
17304    struct sip_peer **bp = (struct sip_peer **)b;
17305    return strcmp((*ap)->name, (*bp)->name);
17306 }
17307 
17308 /* the last argument is left-aligned, so we don't need a size anyways */
17309 #define PEERS_FORMAT2 "%-25.25s %-39.39s %-3.3s %-10.10s %-3.3s %-8s %-10s %s\n"
17310 
17311 /*! \brief Used in the sip_show_peers functions to pass parameters */
17312 struct show_peers_context {
17313    regex_t regexbuf;
17314    int havepattern;
17315    char idtext[256];
17316    int realtimepeers;
17317    int peers_mon_online;
17318    int peers_mon_offline;
17319    int peers_unmon_offline;
17320    int peers_unmon_online;
17321 };
17322 
17323 /*! \brief Execute sip show peers command */
17324 static char *_sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
17325 {
17326    struct show_peers_context cont = {
17327       .havepattern = FALSE,
17328       .idtext = "",
17329 
17330       .peers_mon_online = 0,
17331       .peers_mon_offline = 0,
17332       .peers_unmon_online = 0,
17333       .peers_unmon_offline = 0,
17334    };
17335    struct sip_peer *peer;
17336    struct ao2_iterator* it_peers;
17337 
17338    int total_peers = 0;
17339    const char *id;
17340    struct sip_peer **peerarray;
17341    int k;
17342 
17343    cont.realtimepeers = ast_check_realtime("sippeers");
17344 
17345    if (s) { /* Manager - get ActionID */
17346       id = astman_get_header(m, "ActionID");
17347       if (!ast_strlen_zero(id)) {
17348          snprintf(cont.idtext, sizeof(cont.idtext), "ActionID: %s\r\n", id);
17349       }
17350    }
17351 
17352    switch (argc) {
17353    case 5:
17354       if (!strcasecmp(argv[3], "like")) {
17355          if (regcomp(&cont.regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
17356             return CLI_SHOWUSAGE;
17357          cont.havepattern = TRUE;
17358       } else
17359          return CLI_SHOWUSAGE;
17360    case 3:
17361       break;
17362    default:
17363       return CLI_SHOWUSAGE;
17364    }
17365 
17366    if (!s) {
17367       /* Normal list */
17368       ast_cli(fd, PEERS_FORMAT2, "Name/username", "Host", "Dyn", "Forcerport", "ACL", "Port", "Status", (cont.realtimepeers ? "Realtime" : ""));
17369    }
17370 
17371    ao2_lock(peers);
17372    if (!(it_peers = ao2_callback(peers, OBJ_MULTIPLE, NULL, NULL))) {
17373       ast_log(AST_LOG_ERROR, "Unable to create iterator for peers container for sip show peers\n");
17374       ao2_unlock(peers);
17375       return CLI_FAILURE;
17376    }
17377    if (!(peerarray = ast_calloc(sizeof(struct sip_peer *), ao2_container_count(peers)))) {
17378       ast_log(AST_LOG_ERROR, "Unable to allocate peer array for sip show peers\n");
17379       ao2_iterator_destroy(it_peers);
17380       ao2_unlock(peers);
17381       return CLI_FAILURE;
17382    }
17383    ao2_unlock(peers);
17384 
17385    while ((peer = ao2_t_iterator_next(it_peers, "iterate thru peers table"))) {
17386       ao2_lock(peer);
17387 
17388       if (!(peer->type & SIP_TYPE_PEER)) {
17389          ao2_unlock(peer);
17390          unref_peer(peer, "unref peer because it's actually a user");
17391          continue;
17392       }
17393 
17394       if (cont.havepattern && regexec(&cont.regexbuf, peer->name, 0, NULL, 0)) {
17395          ao2_unlock(peer);
17396          unref_peer(peer, "toss iterator peer ptr before continue");
17397          continue;
17398       }
17399 
17400       peerarray[total_peers++] = peer;
17401       ao2_unlock(peer);
17402    }
17403    ao2_iterator_destroy(it_peers);
17404 
17405    qsort(peerarray, total_peers, sizeof(struct sip_peer *), peercomparefunc);
17406 
17407    for(k = 0; k < total_peers; k++) {
17408       peerarray[k] = _sip_show_peers_one(fd, s, &cont, peerarray[k]);
17409    }
17410 
17411    if (!s) {
17412       ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
17413               total_peers, cont.peers_mon_online, cont.peers_mon_offline, cont.peers_unmon_online, cont.peers_unmon_offline);
17414    }
17415 
17416    if (cont.havepattern) {
17417       regfree(&cont.regexbuf);
17418    }
17419 
17420    if (total) {
17421       *total = total_peers;
17422    }
17423 
17424    ast_free(peerarray);
17425 
17426    return CLI_SUCCESS;
17427 }
17428 
17429 /*! \brief Emit informations for one peer during sip show peers command */
17430 static struct sip_peer *_sip_show_peers_one(int fd, struct mansession *s, struct show_peers_context *cont, struct sip_peer *peer)
17431 {
17432    /* _sip_show_peers_one() is separated from _sip_show_peers() to properly free the ast_strdupa
17433     * (this is executed in a loop in _sip_show_peers() )
17434     */
17435 
17436    char name[256];
17437    char status[20] = "";
17438    char pstatus;
17439 
17440    /*
17441     * tmp_port and tmp_host store copies of ast_sockaddr_stringify strings since the
17442     * string pointers for that function aren't valid between subsequent calls to
17443     * ast_sockaddr_stringify functions
17444     */
17445    char *tmp_port;
17446    char *tmp_host;
17447 
17448    tmp_port = ast_sockaddr_isnull(&peer->addr) ?
17449       "0" : ast_strdupa(ast_sockaddr_stringify_port(&peer->addr));
17450 
17451    tmp_host = ast_sockaddr_isnull(&peer->addr) ?
17452       "(Unspecified)" : ast_strdupa(ast_sockaddr_stringify_addr(&peer->addr));
17453 
17454    ao2_lock(peer);
17455    if (cont->havepattern && regexec(&cont->regexbuf, peer->name, 0, NULL, 0)) {
17456       ao2_unlock(peer);
17457       return unref_peer(peer, "toss iterator peer ptr no match");
17458    }
17459 
17460    if (!ast_strlen_zero(peer->username) && !s) {
17461       snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
17462    } else {
17463       ast_copy_string(name, peer->name, sizeof(name));
17464    }
17465 
17466    pstatus = peer_status(peer, status, sizeof(status));
17467    if (pstatus == 1) {
17468       cont->peers_mon_online++;
17469    } else if (pstatus == 0) {
17470       cont->peers_mon_offline++;
17471    } else {
17472       if (ast_sockaddr_isnull(&peer->addr) ||
17473           !ast_sockaddr_port(&peer->addr)) {
17474          cont->peers_unmon_offline++;
17475       } else {
17476          cont->peers_unmon_online++;
17477       }
17478    }
17479 
17480    if (!s) { /* Normal CLI list */
17481       ast_cli(fd, PEERS_FORMAT2, name,
17482       tmp_host,
17483       peer->host_dynamic ? " D " : "   ", /* Dynamic or not? */
17484       ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? " N " : "   ", /* NAT=yes? */
17485       peer->ha ? " A " : "   ",       /* permit/deny */
17486       tmp_port, status,
17487       cont->realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
17488    } else { /* Manager format */
17489       /* The names here need to be the same as other channels */
17490       astman_append(s,
17491       "Event: PeerEntry\r\n%s"
17492       "Channeltype: SIP\r\n"
17493       "ObjectName: %s\r\n"
17494       "ChanObjectType: peer\r\n" /* "peer" or "user" */
17495       "IPaddress: %s\r\n"
17496       "IPport: %s\r\n"
17497       "Dynamic: %s\r\n"
17498       "Forcerport: %s\r\n"
17499       "VideoSupport: %s\r\n"
17500       "TextSupport: %s\r\n"
17501       "ACL: %s\r\n"
17502       "Status: %s\r\n"
17503       "RealtimeDevice: %s\r\n\r\n",
17504       cont->idtext,
17505       peer->name,
17506       ast_sockaddr_isnull(&peer->addr) ? "-none-" : tmp_host,
17507       ast_sockaddr_isnull(&peer->addr) ? "0" : tmp_port,
17508       peer->host_dynamic ? "yes" : "no",  /* Dynamic or not? */
17509       ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? "yes" : "no",  /* NAT=yes? */
17510       ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no",  /* VIDEOSUPPORT=yes? */
17511       ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "yes" : "no",   /* TEXTSUPPORT=yes? */
17512       peer->ha ? "yes" : "no",       /* permit/deny */
17513       status,
17514       cont->realtimepeers ? (peer->is_realtime ? "yes":"no") : "no");
17515    }
17516    ao2_unlock(peer);
17517 
17518    return unref_peer(peer, "toss iterator peer ptr");
17519 }
17520 #undef PEERS_FORMAT2
17521 
17522 static int peer_dump_func(void *userobj, void *arg, int flags)
17523 {
17524    struct sip_peer *peer = userobj;
17525    int refc = ao2_t_ref(userobj, 0, "");
17526    struct ast_cli_args *a = (struct ast_cli_args *) arg;
17527    
17528    ast_cli(a->fd, "name: %s\ntype: peer\nobjflags: %d\nrefcount: %d\n\n",
17529       peer->name, 0, refc);
17530    return 0;
17531 }
17532 
17533 static int dialog_dump_func(void *userobj, void *arg, int flags)
17534 {
17535    struct sip_pvt *pvt = userobj;
17536    int refc = ao2_t_ref(userobj, 0, "");
17537    struct ast_cli_args *a = (struct ast_cli_args *) arg;
17538    
17539    ast_cli(a->fd, "name: %s\ntype: dialog\nobjflags: %d\nrefcount: %d\n\n",
17540       pvt->callid, 0, refc);
17541    return 0;
17542 }
17543 
17544 
17545 /*! \brief List all allocated SIP Objects (realtime or static) */
17546 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17547 {
17548    char tmp[256];
17549    
17550    switch (cmd) {
17551    case CLI_INIT:
17552       e->command = "sip show objects";
17553       e->usage =
17554          "Usage: sip show objects\n"
17555          "       Lists status of known SIP objects\n";
17556       return NULL;
17557    case CLI_GENERATE:
17558       return NULL;
17559    }  
17560 
17561    if (a->argc != 3)
17562       return CLI_SHOWUSAGE;
17563    ast_cli(a->fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
17564    ao2_t_callback(peers, OBJ_NODATA, peer_dump_func, a, "initiate ao2_callback to dump peers");
17565    ast_cli(a->fd, "-= Peer objects by IP =-\n\n"); 
17566    ao2_t_callback(peers_by_ip, OBJ_NODATA, peer_dump_func, a, "initiate ao2_callback to dump peers_by_ip");
17567    ast_cli(a->fd, "-= Registry objects: %d =-\n\n", regobjs);
17568    ASTOBJ_CONTAINER_DUMP(a->fd, tmp, sizeof(tmp), &regl);
17569    ast_cli(a->fd, "-= Dialog objects:\n\n");
17570    ao2_t_callback(dialogs, OBJ_NODATA, dialog_dump_func, a, "initiate ao2_callback to dump dialogs");
17571    return CLI_SUCCESS;
17572 }
17573 /*! \brief Print call group and pickup group */
17574 static void print_group(int fd, ast_group_t group, int crlf)
17575 {
17576    char buf[256];
17577    ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
17578 }
17579 
17580 /*! \brief mapping between dtmf flags and strings */
17581 static const struct _map_x_s dtmfstr[] = {
17582    { SIP_DTMF_RFC2833,     "rfc2833" },
17583    { SIP_DTMF_INFO,        "info" },
17584    { SIP_DTMF_SHORTINFO,   "shortinfo" },
17585    { SIP_DTMF_INBAND,      "inband" },
17586    { SIP_DTMF_AUTO,        "auto" },
17587    { -1,                   NULL }, /* terminator */
17588 };
17589 
17590 /*! \brief Convert DTMF mode to printable string */
17591 static const char *dtmfmode2str(int mode)
17592 {
17593    return map_x_s(dtmfstr, mode, "<error>");
17594 }
17595 
17596 /*! \brief maps a string to dtmfmode, returns -1 on error */
17597 static int str2dtmfmode(const char *str)
17598 {
17599    return map_s_x(dtmfstr, str, -1);
17600 }
17601 
17602 static const struct _map_x_s insecurestr[] = {
17603    { SIP_INSECURE_PORT,    "port" },
17604    { SIP_INSECURE_INVITE,  "invite" },
17605    { SIP_INSECURE_PORT | SIP_INSECURE_INVITE, "port,invite" },
17606    { 0,                    "no" },
17607    { -1,                   NULL }, /* terminator */
17608 };
17609 
17610 /*! \brief Convert Insecure setting to printable string */
17611 static const char *insecure2str(int mode)
17612 {
17613    return map_x_s(insecurestr, mode, "<error>");
17614 }
17615 
17616 static const struct _map_x_s allowoverlapstr[] = {
17617    { SIP_PAGE2_ALLOWOVERLAP_YES,   "Yes" },
17618    { SIP_PAGE2_ALLOWOVERLAP_DTMF,  "DTMF" },
17619    { SIP_PAGE2_ALLOWOVERLAP_NO,    "No" },
17620    { -1,                           NULL }, /* terminator */
17621 };
17622 
17623 /*! \brief Convert AllowOverlap setting to printable string */
17624 static const char *allowoverlap2str(int mode)
17625 {
17626    return map_x_s(allowoverlapstr, mode, "<error>");
17627 }
17628 
17629 static const struct _map_x_s trust_id_outboundstr[] = {
17630    { SIP_PAGE2_TRUST_ID_OUTBOUND_LEGACY,  "Legacy" },
17631    { SIP_PAGE2_TRUST_ID_OUTBOUND_NO,      "No" },
17632    { SIP_PAGE2_TRUST_ID_OUTBOUND_YES,     "Yes" },
17633    { -1,                                  NULL }, /* terminator */
17634 };
17635 
17636 static const char *trust_id_outbound2str(int mode)
17637 {
17638    return map_x_s(trust_id_outboundstr, mode, "<error>");
17639 }
17640 
17641 /*! \brief Destroy disused contexts between reloads
17642    Only used in reload_config so the code for regcontext doesn't get ugly
17643 */
17644 static void cleanup_stale_contexts(char *new, char *old)
17645 {
17646    char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
17647 
17648    while ((oldcontext = strsep(&old, "&"))) {
17649       stalecontext = '\0';
17650       ast_copy_string(newlist, new, sizeof(newlist));
17651       stringp = newlist;
17652       while ((newcontext = strsep(&stringp, "&"))) {
17653          if (!strcmp(newcontext, oldcontext)) {
17654             /* This is not the context you're looking for */
17655             stalecontext = '\0';
17656             break;
17657          } else if (strcmp(newcontext, oldcontext)) {
17658             stalecontext = oldcontext;
17659          }
17660          
17661       }
17662       if (stalecontext)
17663          ast_context_destroy(ast_context_find(stalecontext), "SIP");
17664    }
17665 }
17666 
17667 /*!
17668  * \brief Match dialogs that need to be destroyed
17669  *
17670  * \details This is used with ao2_callback to unlink/delete all dialogs that
17671  * are marked needdestroy.
17672  *
17673  * \todo Re-work this to improve efficiency.  Currently, this function is called
17674  * on _every_ dialog after processing _every_ incoming SIP/UDP packet, or
17675  * potentially even more often when the scheduler has entries to run.
17676  */
17677 static int dialog_needdestroy(void *dialogobj, void *arg, int flags)
17678 {
17679    struct sip_pvt *dialog = dialogobj;
17680    time_t *t = arg;
17681 
17682    if (sip_pvt_trylock(dialog)) {
17683       /* Don't block the monitor thread.  This function is called often enough
17684        * that we can wait for the next time around. */
17685       return 0;
17686    }
17687 
17688    /* Check RTP timeouts and kill calls if we have a timeout set and do not get RTP */
17689    check_rtp_timeout(dialog, *t);
17690 
17691    /* We absolutely cannot destroy the rtp struct while a bridge is active or we WILL crash */
17692    if (dialog->rtp && ast_rtp_instance_get_bridged(dialog->rtp)) {
17693       ast_debug(2, "Bridge still active.  Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
17694       sip_pvt_unlock(dialog);
17695       return 0;
17696    }
17697 
17698    if (dialog->vrtp && ast_rtp_instance_get_bridged(dialog->vrtp)) {
17699       ast_debug(2, "Bridge still active.  Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
17700       sip_pvt_unlock(dialog);
17701       return 0;
17702    }
17703 
17704    /* If we have sessions that needs to be destroyed, do it now */
17705    /* Check if we have outstanding requests not responsed to or an active call
17706       - if that's the case, wait with destruction */
17707    if (dialog->needdestroy && !dialog->packets && !dialog->owner) {
17708       /* We absolutely cannot destroy the rtp struct while a bridge is active or we WILL crash */
17709       if (dialog->rtp && ast_rtp_instance_get_bridged(dialog->rtp)) {
17710          ast_debug(2, "Bridge still active.  Delaying destruction of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
17711          sip_pvt_unlock(dialog);
17712          return 0;
17713       }
17714       
17715       if (dialog->vrtp && ast_rtp_instance_get_bridged(dialog->vrtp)) {
17716          ast_debug(2, "Bridge still active.  Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
17717          sip_pvt_unlock(dialog);
17718          return 0;
17719       }
17720 
17721       sip_pvt_unlock(dialog);
17722 
17723       /* This dialog needs to be destroyed. */
17724       ao2_t_link(dialogs_to_destroy, dialog, "Link dialog for destruction");
17725       return 0;
17726    }
17727 
17728    sip_pvt_unlock(dialog);
17729 
17730    return 0;
17731 }
17732 
17733 /*!
17734  * \internal
17735  * \brief ao2_callback to unlink the specified dialog object.
17736  *
17737  * \param obj Ptr to dialog to unlink.
17738  * \param arg Don't care.
17739  * \param flags Don't care.
17740  *
17741  * \retval CMP_MATCH
17742  */
17743 static int dialog_unlink_callback(void *obj, void *arg, int flags)
17744 {
17745    struct sip_pvt *dialog = obj;
17746 
17747    dialog_unlink_all(dialog);
17748 
17749    return CMP_MATCH;
17750 }
17751 
17752 /*! \brief Remove temporary realtime objects from memory (CLI) */
17753 /*! \todo XXXX Propably needs an overhaul after removal of the devices */
17754 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17755 {
17756    struct sip_peer *peer, *pi;
17757    int prunepeer = FALSE;
17758    int multi = FALSE;
17759    const char *name = NULL;
17760    regex_t regexbuf;
17761    int havepattern = 0;
17762    struct ao2_iterator i;
17763    static const char * const choices[] = { "all", "like", NULL };
17764    char *cmplt;
17765    
17766    if (cmd == CLI_INIT) {
17767       e->command = "sip prune realtime [peer|all]";
17768       e->usage =
17769          "Usage: sip prune realtime [peer [<name>|all|like <pattern>]|all]\n"
17770          "       Prunes object(s) from the cache.\n"
17771          "       Optional regular expression pattern is used to filter the objects.\n";
17772       return NULL;
17773    } else if (cmd == CLI_GENERATE) {
17774       if (a->pos == 4 && !strcasecmp(a->argv[3], "peer")) {
17775          cmplt = ast_cli_complete(a->word, choices, a->n);
17776          if (!cmplt)
17777             cmplt = complete_sip_peer(a->word, a->n - sizeof(choices), SIP_PAGE2_RTCACHEFRIENDS);
17778          return cmplt;
17779       }
17780       if (a->pos == 5 && !strcasecmp(a->argv[4], "like"))
17781          return complete_sip_peer(a->word, a->n, SIP_PAGE2_RTCACHEFRIENDS);
17782       return NULL;
17783    }
17784    switch (a->argc) {
17785    case 4:
17786       name = a->argv[3];
17787       /* we accept a name in position 3, but keywords are not good. */
17788       if (!strcasecmp(name, "peer") || !strcasecmp(name, "like"))
17789          return CLI_SHOWUSAGE;
17790       prunepeer = TRUE;
17791       if (!strcasecmp(name, "all")) {
17792          multi = TRUE;
17793          name = NULL;
17794       }
17795       /* else a single name, already set */
17796       break;
17797    case 5:
17798       /* sip prune realtime {peer|like} name */
17799       name = a->argv[4];
17800       if (!strcasecmp(a->argv[3], "peer"))
17801          prunepeer = TRUE;
17802       else if (!strcasecmp(a->argv[3], "like")) {
17803          prunepeer = TRUE;
17804          multi = TRUE;
17805       } else
17806          return CLI_SHOWUSAGE;
17807       if (!strcasecmp(name, "like"))
17808          return CLI_SHOWUSAGE;
17809       if (!multi && !strcasecmp(name, "all")) {
17810          multi = TRUE;
17811          name = NULL;
17812       }
17813       break;
17814    case 6:
17815       name = a->argv[5];
17816       multi = TRUE;
17817       /* sip prune realtime {peer} like name */
17818       if (strcasecmp(a->argv[4], "like"))
17819          return CLI_SHOWUSAGE;
17820       if (!strcasecmp(a->argv[3], "peer")) {
17821          prunepeer = TRUE;
17822       } else
17823          return CLI_SHOWUSAGE;
17824       break;
17825    default:
17826       return CLI_SHOWUSAGE;
17827    }
17828 
17829    if (multi && name) {
17830       if (regcomp(&regexbuf, name, REG_EXTENDED | REG_NOSUB)) {
17831          return CLI_SHOWUSAGE;
17832       }
17833       havepattern = 1;
17834    }
17835 
17836    if (multi) {
17837       if (prunepeer) {
17838          int pruned = 0;
17839          
17840          i = ao2_iterator_init(peers, 0);
17841          while ((pi = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
17842             ao2_lock(pi);
17843             if (name && regexec(&regexbuf, pi->name, 0, NULL, 0)) {
17844                ao2_unlock(pi);
17845                unref_peer(pi, "toss iterator peer ptr before continue");
17846                continue;
17847             };
17848             if (ast_test_flag(&pi->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
17849                pi->the_mark = 1;
17850                pruned++;
17851             }
17852             ao2_unlock(pi);
17853             unref_peer(pi, "toss iterator peer ptr");
17854          }
17855          ao2_iterator_destroy(&i);
17856          if (pruned) {
17857             unlink_marked_peers_from_tables();
17858             ast_cli(a->fd, "%d peers pruned.\n", pruned);
17859          } else
17860             ast_cli(a->fd, "No peers found to prune.\n");
17861       }
17862    } else {
17863       if (prunepeer) {
17864          struct sip_peer tmp;
17865          ast_copy_string(tmp.name, name, sizeof(tmp.name));
17866          if ((peer = ao2_t_find(peers, &tmp, OBJ_POINTER | OBJ_UNLINK, "finding to unlink from peers"))) {
17867             if (!ast_sockaddr_isnull(&peer->addr)) {
17868                ao2_t_unlink(peers_by_ip, peer, "unlinking peer from peers_by_ip also");
17869             }
17870             if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
17871                ast_cli(a->fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
17872                /* put it back! */
17873                ao2_t_link(peers, peer, "link peer into peer table");
17874                if (!ast_sockaddr_isnull(&peer->addr)) {
17875                   ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
17876                }
17877             } else
17878                ast_cli(a->fd, "Peer '%s' pruned.\n", name);
17879             unref_peer(peer, "sip_prune_realtime: unref_peer: tossing temp peer ptr");
17880          } else
17881             ast_cli(a->fd, "Peer '%s' not found.\n", name);
17882       }
17883    }
17884 
17885    if (havepattern) {
17886       regfree(&regexbuf);
17887    }
17888 
17889    return CLI_SUCCESS;
17890 }
17891 
17892 /*! \brief Print codec list from preference to CLI/manager */
17893 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
17894 {
17895    int x;
17896    format_t codec;
17897 
17898    for(x = 0; x < 64 ; x++) {
17899       codec = ast_codec_pref_index(pref, x);
17900       if (!codec)
17901          break;
17902       ast_cli(fd, "%s", ast_getformatname(codec));
17903       ast_cli(fd, ":%d", pref->framing[x]);
17904       if (x < 31 && ast_codec_pref_index(pref, x + 1))
17905          ast_cli(fd, ",");
17906    }
17907    if (!x)
17908       ast_cli(fd, "none");
17909 }
17910 
17911 /*! \brief Print domain mode to cli */
17912 static const char *domain_mode_to_text(const enum domain_mode mode)
17913 {
17914    switch (mode) {
17915    case SIP_DOMAIN_AUTO:
17916       return "[Automatic]";
17917    case SIP_DOMAIN_CONFIG:
17918       return "[Configured]";
17919    }
17920 
17921    return "";
17922 }
17923 
17924 /*! \brief CLI command to list local domains */
17925 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17926 {
17927    struct domain *d;
17928 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
17929 
17930    switch (cmd) {
17931    case CLI_INIT:
17932       e->command = "sip show domains";
17933       e->usage =
17934          "Usage: sip show domains\n"
17935          "       Lists all configured SIP local domains.\n"
17936          "       Asterisk only responds to SIP messages to local domains.\n";
17937       return NULL;
17938    case CLI_GENERATE:
17939       return NULL;
17940    }
17941 
17942    if (AST_LIST_EMPTY(&domain_list)) {
17943       ast_cli(a->fd, "SIP Domain support not enabled.\n\n");
17944       return CLI_SUCCESS;
17945    } else {
17946       ast_cli(a->fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
17947       AST_LIST_LOCK(&domain_list);
17948       AST_LIST_TRAVERSE(&domain_list, d, list)
17949          ast_cli(a->fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
17950             domain_mode_to_text(d->mode));
17951       AST_LIST_UNLOCK(&domain_list);
17952       ast_cli(a->fd, "\n");
17953       return CLI_SUCCESS;
17954    }
17955 }
17956 #undef FORMAT
17957 
17958 /*! \brief Show SIP peers in the manager API  */
17959 static int manager_sip_show_peer(struct mansession *s, const struct message *m)
17960 {
17961    const char *a[4];
17962    const char *peer;
17963 
17964    peer = astman_get_header(m, "Peer");
17965    if (ast_strlen_zero(peer)) {
17966       astman_send_error(s, m, "Peer: <name> missing.");
17967       return 0;
17968    }
17969    a[0] = "sip";
17970    a[1] = "show";
17971    a[2] = "peer";
17972    a[3] = peer;
17973 
17974    _sip_show_peer(1, -1, s, m, 4, a);
17975    astman_append(s, "\r\n" );
17976    return 0;
17977 }
17978 
17979 /*! \brief Show one peer in detail */
17980 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17981 {
17982    switch (cmd) {
17983    case CLI_INIT:
17984       e->command = "sip show peer";
17985       e->usage =
17986          "Usage: sip show peer <name> [load]\n"
17987          "       Shows all details on one SIP peer and the current status.\n"
17988          "       Option \"load\" forces lookup of peer in realtime storage.\n";
17989       return NULL;
17990    case CLI_GENERATE:
17991       return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
17992    }
17993    return _sip_show_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
17994 }
17995 
17996 /*! \brief Send qualify message to peer from cli or manager. Mostly for debugging. */
17997 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
17998 {
17999    struct sip_peer *peer;
18000    int load_realtime;
18001 
18002    if (argc < 4)
18003       return CLI_SHOWUSAGE;
18004 
18005    load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
18006    if ((peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0))) {
18007       sip_poke_peer(peer, 1);
18008       unref_peer(peer, "qualify: done with peer");
18009    } else if (type == 0) {
18010       ast_cli(fd, "Peer '%s' not found\n", argv[3]);
18011    } else {
18012       astman_send_error(s, m, "Peer not found");
18013    }
18014    return CLI_SUCCESS;
18015 }
18016 
18017 /*! \brief Qualify SIP peers in the manager API  */
18018 static int manager_sip_qualify_peer(struct mansession *s, const struct message *m)
18019 {
18020    const char *a[4];
18021    const char *peer;
18022 
18023    peer = astman_get_header(m, "Peer");
18024    if (ast_strlen_zero(peer)) {
18025       astman_send_error(s, m, "Peer: <name> missing.");
18026       return 0;
18027    }
18028    a[0] = "sip";
18029    a[1] = "qualify";
18030    a[2] = "peer";
18031    a[3] = peer;
18032 
18033    _sip_qualify_peer(1, -1, s, m, 4, a);
18034    astman_append(s, "\r\n\r\n" );
18035    return 0;
18036 }
18037 
18038 /*! \brief Send an OPTIONS packet to a SIP peer */
18039 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18040 {
18041    switch (cmd) {
18042    case CLI_INIT:
18043       e->command = "sip qualify peer";
18044       e->usage =
18045          "Usage: sip qualify peer <name> [load]\n"
18046          "       Requests a response from one SIP peer and the current status.\n"
18047          "       Option \"load\" forces lookup of peer in realtime storage.\n";
18048       return NULL;
18049    case CLI_GENERATE:
18050       return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
18051    }
18052    return _sip_qualify_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
18053 }
18054 
18055 /*! \brief list peer mailboxes to CLI */
18056 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer)
18057 {
18058    struct sip_mailbox *mailbox;
18059 
18060    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
18061       ast_str_append(mailbox_str, 0, "%s%s%s%s",
18062          mailbox->mailbox,
18063          ast_strlen_zero(mailbox->context) ? "" : "@",
18064          S_OR(mailbox->context, ""),
18065          AST_LIST_NEXT(mailbox, entry) ? "," : "");
18066    }
18067 }
18068 
18069 static struct _map_x_s faxecmodes[] = {
18070    { SIP_PAGE2_T38SUPPORT_UDPTL,       "None"},
18071    { SIP_PAGE2_T38SUPPORT_UDPTL_FEC,      "FEC"},
18072    { SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY,  "Redundancy"},
18073    { -1,                NULL},
18074 };
18075 
18076 static const char *faxec2str(int faxec)
18077 {
18078    return map_x_s(faxecmodes, faxec, "Unknown");
18079 }
18080 
18081 /*! \brief Show one peer in detail (main function) */
18082 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
18083 {
18084    char status[30] = "";
18085    char cbuf[256];
18086    struct sip_peer *peer;
18087    char codec_buf[512];
18088    struct ast_codec_pref *pref;
18089    struct ast_variable *v;
18090    int x = 0, load_realtime;
18091    format_t codec = 0;
18092    int realtimepeers;
18093 
18094    realtimepeers = ast_check_realtime("sippeers");
18095 
18096    if (argc < 4)
18097       return CLI_SHOWUSAGE;
18098 
18099    load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
18100    peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0);
18101 
18102    if (s) {    /* Manager */
18103       if (peer) {
18104          const char *id = astman_get_header(m, "ActionID");
18105 
18106          astman_append(s, "Response: Success\r\n");
18107          if (!ast_strlen_zero(id))
18108             astman_append(s, "ActionID: %s\r\n", id);
18109       } else {
18110          snprintf (cbuf, sizeof(cbuf), "Peer %s not found.", argv[3]);
18111          astman_send_error(s, m, cbuf);
18112          return CLI_SUCCESS;
18113       }
18114    }
18115    if (peer && type==0 ) { /* Normal listing */
18116       struct ast_str *mailbox_str = ast_str_alloca(512);
18117       struct sip_auth_container *credentials;
18118 
18119       ao2_lock(peer);
18120       credentials = peer->auth;
18121       if (credentials) {
18122          ao2_t_ref(credentials, +1, "Ref peer auth for show");
18123       }
18124       ao2_unlock(peer);
18125 
18126       ast_cli(fd, "\n\n");
18127       ast_cli(fd, "  * Name       : %s\n", peer->name);
18128       if (realtimepeers) { /* Realtime is enabled */
18129          ast_cli(fd, "  Realtime peer: %s\n", peer->is_realtime ? "Yes, cached" : "No");
18130       }
18131       ast_cli(fd, "  Secret       : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
18132       ast_cli(fd, "  MD5Secret    : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
18133       ast_cli(fd, "  Remote Secret: %s\n", ast_strlen_zero(peer->remotesecret)?"<Not set>":"<Set>");
18134       if (credentials) {
18135          struct sip_auth *auth;
18136 
18137          AST_LIST_TRAVERSE(&credentials->list, auth, node) {
18138             ast_cli(fd, "  Realm-auth   : Realm %-15.15s User %-10.20s %s\n",
18139                auth->realm,
18140                auth->username,
18141                !ast_strlen_zero(auth->secret)
18142                   ? "<Secret set>"
18143                   : (!ast_strlen_zero(auth->md5secret)
18144                      ? "<MD5secret set>" : "<Not set>"));
18145          }
18146          ao2_t_ref(credentials, -1, "Unref peer auth for show");
18147       }
18148       ast_cli(fd, "  Context      : %s\n", peer->context);
18149       ast_cli(fd, "  Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
18150       ast_cli(fd, "  Language     : %s\n", peer->language);
18151       if (!ast_strlen_zero(peer->accountcode))
18152          ast_cli(fd, "  Accountcode  : %s\n", peer->accountcode);
18153       ast_cli(fd, "  AMA flags    : %s\n", ast_cdr_flags2str(peer->amaflags));
18154       ast_cli(fd, "  Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
18155       ast_cli(fd, "  CallingPres  : %s\n", ast_describe_caller_presentation(peer->callingpres));
18156       if (!ast_strlen_zero(peer->fromuser))
18157          ast_cli(fd, "  FromUser     : %s\n", peer->fromuser);
18158       if (!ast_strlen_zero(peer->fromdomain))
18159          ast_cli(fd, "  FromDomain   : %s Port %d\n", peer->fromdomain, (peer->fromdomainport) ? peer->fromdomainport : STANDARD_SIP_PORT);
18160       ast_cli(fd, "  Callgroup    : ");
18161       print_group(fd, peer->callgroup, 0);
18162       ast_cli(fd, "  Pickupgroup  : ");
18163       print_group(fd, peer->pickupgroup, 0);
18164       peer_mailboxes_to_str(&mailbox_str, peer);
18165       ast_cli(fd, "  MOH Suggest  : %s\n", peer->mohsuggest);
18166       ast_cli(fd, "  Mailbox      : %s\n", ast_str_buffer(mailbox_str));
18167       ast_cli(fd, "  VM Extension : %s\n", peer->vmexten);
18168       ast_cli(fd, "  LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
18169       ast_cli(fd, "  Call limit   : %d\n", peer->call_limit);
18170       ast_cli(fd, "  Max forwards : %d\n", peer->maxforwards);
18171       if (peer->busy_level)
18172          ast_cli(fd, "  Busy level   : %d\n", peer->busy_level);
18173       ast_cli(fd, "  Dynamic      : %s\n", AST_CLI_YESNO(peer->host_dynamic));
18174       ast_cli(fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
18175       ast_cli(fd, "  MaxCallBR    : %d kbps\n", peer->maxcallbitrate);
18176       ast_cli(fd, "  Expire       : %ld\n", ast_sched_when(sched, peer->expire));
18177       ast_cli(fd, "  Insecure     : %s\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
18178       ast_cli(fd, "  Force rport  : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT)));
18179       ast_cli(fd, "  ACL          : %s\n", AST_CLI_YESNO(peer->ha != NULL));
18180       ast_cli(fd, "  DirectMedACL : %s\n", AST_CLI_YESNO(peer->directmediaha != NULL));
18181       ast_cli(fd, "  T.38 support : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
18182       ast_cli(fd, "  T.38 EC mode : %s\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
18183       ast_cli(fd, "  T.38 MaxDtgrm: %u\n", peer->t38_maxdatagram);
18184       ast_cli(fd, "  DirectMedia  : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)));
18185       ast_cli(fd, "  PromiscRedir : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)));
18186       ast_cli(fd, "  User=Phone   : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)));
18187       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)));
18188       ast_cli(fd, "  Text Support : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)));
18189       ast_cli(fd, "  Ign SDP ver  : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_IGNORESDPVERSION)));
18190       ast_cli(fd, "  Trust RPID   : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_TRUSTRPID)));
18191       ast_cli(fd, "  Send RPID    : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_SENDRPID)));
18192       ast_cli(fd, "  TrustIDOutbnd: %s\n", trust_id_outbound2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND)));
18193       ast_cli(fd, "  Subscriptions: %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
18194       ast_cli(fd, "  Overlap dial : %s\n", allowoverlap2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP)));
18195       if (peer->outboundproxy)
18196          ast_cli(fd, "  Outb. proxy  : %s %s\n", ast_strlen_zero(peer->outboundproxy->name) ? "<not set>" : peer->outboundproxy->name,
18197                      peer->outboundproxy->force ? "(forced)" : "");
18198 
18199       /* - is enumerated */
18200       ast_cli(fd, "  DTMFmode     : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
18201       ast_cli(fd, "  Timer T1     : %d\n", peer->timer_t1);
18202       ast_cli(fd, "  Timer B      : %d\n", peer->timer_b);
18203       ast_cli(fd, "  ToHost       : %s\n", peer->tohost);
18204       ast_cli(fd, "  Addr->IP     : %s\n", ast_sockaddr_stringify(&peer->addr));
18205       ast_cli(fd, "  Defaddr->IP  : %s\n", ast_sockaddr_stringify(&peer->defaddr));
18206       ast_cli(fd, "  Prim.Transp. : %s\n", get_transport(peer->socket.type));
18207       ast_cli(fd, "  Allowed.Trsp : %s\n", get_transport_list(peer->transports));
18208       if (!ast_strlen_zero(sip_cfg.regcontext))
18209          ast_cli(fd, "  Reg. exten   : %s\n", peer->regexten);
18210       ast_cli(fd, "  Def. Username: %s\n", peer->username);
18211       ast_cli(fd, "  SIP Options  : ");
18212       if (peer->sipoptions) {
18213          int lastoption = -1;
18214          for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
18215             if (sip_options[x].id != lastoption) {
18216                if (peer->sipoptions & sip_options[x].id)
18217                   ast_cli(fd, "%s ", sip_options[x].text);
18218                lastoption = x;
18219             }
18220          }
18221       } else
18222          ast_cli(fd, "(none)");
18223 
18224       ast_cli(fd, "\n");
18225       ast_cli(fd, "  Codecs       : ");
18226       ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
18227       ast_cli(fd, "%s\n", codec_buf);
18228       ast_cli(fd, "  Codec Order  : (");
18229       print_codec_to_cli(fd, &peer->prefs);
18230       ast_cli(fd, ")\n");
18231 
18232       ast_cli(fd, "  Auto-Framing : %s\n", AST_CLI_YESNO(peer->autoframing));
18233       ast_cli(fd, "  Status       : ");
18234       peer_status(peer, status, sizeof(status));
18235       ast_cli(fd, "%s\n", status);
18236       ast_cli(fd, "  Useragent    : %s\n", peer->useragent);
18237       ast_cli(fd, "  Reg. Contact : %s\n", peer->fullcontact);
18238       ast_cli(fd, "  Qualify Freq : %d ms\n", peer->qualifyfreq);
18239       if (peer->chanvars) {
18240          ast_cli(fd, "  Variables    :\n");
18241          for (v = peer->chanvars ; v ; v = v->next)
18242             ast_cli(fd, "                 %s = %s\n", v->name, v->value);
18243       }
18244 
18245       ast_cli(fd, "  Sess-Timers  : %s\n", stmode2str(peer->stimer.st_mode_oper));
18246       ast_cli(fd, "  Sess-Refresh : %s\n", strefresherparam2str(peer->stimer.st_ref));
18247       ast_cli(fd, "  Sess-Expires : %d secs\n", peer->stimer.st_max_se);
18248       ast_cli(fd, "  Min-Sess     : %d secs\n", peer->stimer.st_min_se);
18249       ast_cli(fd, "  RTP Engine   : %s\n", peer->engine);
18250       ast_cli(fd, "  Parkinglot   : %s\n", peer->parkinglot);
18251       ast_cli(fd, "  Use Reason   : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_Q850_REASON)));
18252       ast_cli(fd, "  Encryption   : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP)));
18253       ast_cli(fd, "\n");
18254       peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer ptr");
18255    } else  if (peer && type == 1) { /* manager listing */
18256       char buffer[256];
18257       struct ast_str *mailbox_str = ast_str_alloca(512);
18258       astman_append(s, "Channeltype: SIP\r\n");
18259       astman_append(s, "ObjectName: %s\r\n", peer->name);
18260       astman_append(s, "ChanObjectType: peer\r\n");
18261       astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
18262       astman_append(s, "RemoteSecretExist: %s\r\n", ast_strlen_zero(peer->remotesecret)?"N":"Y");
18263       astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
18264       astman_append(s, "Context: %s\r\n", peer->context);
18265       astman_append(s, "Language: %s\r\n", peer->language);
18266       if (!ast_strlen_zero(peer->accountcode))
18267          astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
18268       astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
18269       astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
18270       if (!ast_strlen_zero(peer->fromuser))
18271          astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
18272       if (!ast_strlen_zero(peer->fromdomain))
18273          astman_append(s, "SIP-FromDomain: %s\r\nSip-FromDomain-Port: %d\r\n", peer->fromdomain, (peer->fromdomainport) ? peer->fromdomainport : STANDARD_SIP_PORT);
18274       astman_append(s, "Callgroup: ");
18275       astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->callgroup));
18276       astman_append(s, "Pickupgroup: ");
18277       astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->pickupgroup));
18278       astman_append(s, "MOHSuggest: %s\r\n", peer->mohsuggest);
18279       peer_mailboxes_to_str(&mailbox_str, peer);
18280       astman_append(s, "VoiceMailbox: %s\r\n", ast_str_buffer(mailbox_str));
18281       astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
18282       astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
18283       astman_append(s, "Maxforwards: %d\r\n", peer->maxforwards);
18284       astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
18285       astman_append(s, "Busy-level: %d\r\n", peer->busy_level);
18286       astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
18287       astman_append(s, "Dynamic: %s\r\n", peer->host_dynamic?"Y":"N");
18288       astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
18289       astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched, peer->expire));
18290       astman_append(s, "SIP-AuthInsecure: %s\r\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
18291       astman_append(s, "SIP-Forcerport: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT)?"Y":"N"));
18292       astman_append(s, "ACL: %s\r\n", (peer->ha?"Y":"N"));
18293       astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
18294       astman_append(s, "SIP-DirectMedia: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
18295       astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
18296       astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
18297       astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
18298       astman_append(s, "SIP-TextSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)?"Y":"N"));
18299       astman_append(s, "SIP-T.38Support: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)?"Y":"N"));
18300       astman_append(s, "SIP-T.38EC: %s\r\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
18301       astman_append(s, "SIP-T.38MaxDtgrm: %u\r\n", peer->t38_maxdatagram);
18302       astman_append(s, "SIP-Sess-Timers: %s\r\n", stmode2str(peer->stimer.st_mode_oper));
18303       astman_append(s, "SIP-Sess-Refresh: %s\r\n", strefresherparam2str(peer->stimer.st_ref));
18304       astman_append(s, "SIP-Sess-Expires: %d\r\n", peer->stimer.st_max_se);
18305       astman_append(s, "SIP-Sess-Min: %d\r\n", peer->stimer.st_min_se);
18306       astman_append(s, "SIP-RTP-Engine: %s\r\n", peer->engine);
18307       astman_append(s, "SIP-Encryption: %s\r\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP) ? "Y" : "N");
18308 
18309       /* - is enumerated */
18310       astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
18311       astman_append(s, "ToHost: %s\r\n", peer->tohost);
18312       astman_append(s, "Address-IP: %s\r\nAddress-Port: %d\r\n", ast_sockaddr_stringify_addr(&peer->addr), ast_sockaddr_port(&peer->addr));
18313       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));
18314       astman_append(s, "Default-Username: %s\r\n", peer->username);
18315       if (!ast_strlen_zero(sip_cfg.regcontext))
18316          astman_append(s, "RegExtension: %s\r\n", peer->regexten);
18317       astman_append(s, "Codecs: ");
18318       ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
18319       astman_append(s, "%s\r\n", codec_buf);
18320       astman_append(s, "CodecOrder: ");
18321       pref = &peer->prefs;
18322       for(x = 0; x < 64 ; x++) {
18323          codec = ast_codec_pref_index(pref, x);
18324          if (!codec)
18325             break;
18326          astman_append(s, "%s", ast_getformatname(codec));
18327          if (x < 63 && ast_codec_pref_index(pref, x+1))
18328             astman_append(s, ",");
18329       }
18330 
18331       astman_append(s, "\r\n");
18332       astman_append(s, "Status: ");
18333       peer_status(peer, status, sizeof(status));
18334       astman_append(s, "%s\r\n", status);
18335       astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
18336       astman_append(s, "Reg-Contact: %s\r\n", peer->fullcontact);
18337       astman_append(s, "QualifyFreq: %d ms\r\n", peer->qualifyfreq);
18338       astman_append(s, "Parkinglot: %s\r\n", peer->parkinglot);
18339       if (peer->chanvars) {
18340          for (v = peer->chanvars ; v ; v = v->next) {
18341             astman_append(s, "ChanVariable: %s=%s\r\n", v->name, v->value);
18342          }
18343       }
18344       astman_append(s, "SIP-Use-Reason-Header: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_Q850_REASON)) ? "Y" : "N");
18345 
18346       peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer");
18347 
18348    } else {
18349       ast_cli(fd, "Peer %s not found.\n", argv[3]);
18350       ast_cli(fd, "\n");
18351    }
18352 
18353    return CLI_SUCCESS;
18354 }
18355 
18356 /*! \brief Do completion on user name */
18357 static char *complete_sip_user(const char *word, int state)
18358 {
18359    char *result = NULL;
18360    int wordlen = strlen(word);
18361    int which = 0;
18362    struct ao2_iterator user_iter;
18363    struct sip_peer *user;
18364 
18365    user_iter = ao2_iterator_init(peers, 0);
18366    while ((user = ao2_t_iterator_next(&user_iter, "iterate thru peers table"))) {
18367       ao2_lock(user);
18368       if (!(user->type & SIP_TYPE_USER)) {
18369          ao2_unlock(user);
18370          unref_peer(user, "complete sip user");
18371          continue;
18372       }
18373       /* locking of the object is not required because only the name and flags are being compared */
18374       if (!strncasecmp(word, user->name, wordlen) && ++which > state) {
18375          result = ast_strdup(user->name);
18376       }
18377       ao2_unlock(user);
18378       unref_peer(user, "complete sip user");
18379       if (result) {
18380          break;
18381       }
18382    }
18383    ao2_iterator_destroy(&user_iter);
18384    return result;
18385 }
18386 /*! \brief Support routine for 'sip show user' CLI */
18387 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
18388 {
18389    if (pos == 3)
18390       return complete_sip_user(word, state);
18391 
18392    return NULL;
18393 }
18394 
18395 /*! \brief Show one user in detail */
18396 static char *sip_show_user(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18397 {
18398    char cbuf[256];
18399    struct sip_peer *user;
18400    struct ast_variable *v;
18401    int load_realtime;
18402 
18403    switch (cmd) {
18404    case CLI_INIT:
18405       e->command = "sip show user";
18406       e->usage =
18407          "Usage: sip show user <name> [load]\n"
18408          "       Shows all details on one SIP user and the current status.\n"
18409          "       Option \"load\" forces lookup of peer in realtime storage.\n";
18410       return NULL;
18411    case CLI_GENERATE:
18412       return complete_sip_show_user(a->line, a->word, a->pos, a->n);
18413    }
18414 
18415    if (a->argc < 4)
18416       return CLI_SHOWUSAGE;
18417 
18418    /* Load from realtime storage? */
18419    load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? TRUE : FALSE;
18420 
18421    if ((user = find_peer(a->argv[3], NULL, load_realtime, FINDUSERS, FALSE, 0))) {
18422       ao2_lock(user);
18423       ast_cli(a->fd, "\n\n");
18424       ast_cli(a->fd, "  * Name       : %s\n", user->name);
18425       ast_cli(a->fd, "  Secret       : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
18426       ast_cli(a->fd, "  MD5Secret    : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
18427       ast_cli(a->fd, "  Context      : %s\n", user->context);
18428       ast_cli(a->fd, "  Language     : %s\n", user->language);
18429       if (!ast_strlen_zero(user->accountcode))
18430          ast_cli(a->fd, "  Accountcode  : %s\n", user->accountcode);
18431       ast_cli(a->fd, "  AMA flags    : %s\n", ast_cdr_flags2str(user->amaflags));
18432       ast_cli(a->fd, "  Transfer mode: %s\n", transfermode2str(user->allowtransfer));
18433       ast_cli(a->fd, "  MaxCallBR    : %d kbps\n", user->maxcallbitrate);
18434       ast_cli(a->fd, "  CallingPres  : %s\n", ast_describe_caller_presentation(user->callingpres));
18435       ast_cli(a->fd, "  Call limit   : %d\n", user->call_limit);
18436       ast_cli(a->fd, "  Callgroup    : ");
18437       print_group(a->fd, user->callgroup, 0);
18438       ast_cli(a->fd, "  Pickupgroup  : ");
18439       print_group(a->fd, user->pickupgroup, 0);
18440       ast_cli(a->fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
18441       ast_cli(a->fd, "  ACL          : %s\n", AST_CLI_YESNO(user->ha != NULL));
18442       ast_cli(a->fd, "  Sess-Timers  : %s\n", stmode2str(user->stimer.st_mode_oper));
18443       ast_cli(a->fd, "  Sess-Refresh : %s\n", strefresherparam2str(user->stimer.st_ref));
18444       ast_cli(a->fd, "  Sess-Expires : %d secs\n", user->stimer.st_max_se);
18445       ast_cli(a->fd, "  Sess-Min-SE  : %d secs\n", user->stimer.st_min_se);
18446       ast_cli(a->fd, "  RTP Engine   : %s\n", user->engine);
18447 
18448       ast_cli(a->fd, "  Codec Order  : (");
18449       print_codec_to_cli(a->fd, &user->prefs);
18450       ast_cli(a->fd, ")\n");
18451 
18452       ast_cli(a->fd, "  Auto-Framing:  %s \n", AST_CLI_YESNO(user->autoframing));
18453       if (user->chanvars) {
18454          ast_cli(a->fd, "  Variables    :\n");
18455          for (v = user->chanvars ; v ; v = v->next)
18456             ast_cli(a->fd, "                 %s = %s\n", v->name, v->value);
18457       }
18458 
18459       ast_cli(a->fd, "\n");
18460 
18461       ao2_unlock(user);
18462       unref_peer(user, "sip show user");
18463    } else {
18464       ast_cli(a->fd, "User %s not found.\n", a->argv[3]);
18465       ast_cli(a->fd, "\n");
18466    }
18467 
18468    return CLI_SUCCESS;
18469 }
18470 
18471 
18472 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18473 {
18474    struct ast_str *cbuf;
18475    struct ast_cb_names cbnames = {9, { "retrans_pkt",
18476                                         "__sip_autodestruct",
18477                                         "expire_register",
18478                                         "auto_congest",
18479                                         "sip_reg_timeout",
18480                                         "sip_poke_peer_s",
18481                                         "sip_poke_noanswer",
18482                                         "sip_reregister",
18483                                         "sip_reinvite_retry"},
18484                            { retrans_pkt,
18485                                      __sip_autodestruct,
18486                                      expire_register,
18487                                      auto_congest,
18488                                      sip_reg_timeout,
18489                                      sip_poke_peer_s,
18490                                      sip_poke_noanswer,
18491                                      sip_reregister,
18492                                      sip_reinvite_retry}};
18493    
18494    switch (cmd) {
18495    case CLI_INIT:
18496       e->command = "sip show sched";
18497       e->usage =
18498          "Usage: sip show sched\n"
18499          "       Shows stats on what's in the sched queue at the moment\n";
18500       return NULL;
18501    case CLI_GENERATE:
18502       return NULL;
18503    }
18504 
18505    cbuf = ast_str_alloca(2048);
18506 
18507    ast_cli(a->fd, "\n");
18508    ast_sched_report(sched, &cbuf, &cbnames);
18509    ast_cli(a->fd, "%s", ast_str_buffer(cbuf));
18510 
18511    return CLI_SUCCESS;
18512 }
18513 
18514 /*! \brief  Show SIP Registry (registrations with other SIP proxies */
18515 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18516 {
18517 #define FORMAT2 "%-39.39s %-6.6s %-12.12s  %8.8s %-20.20s %-25.25s\n"
18518 #define FORMAT  "%-39.39s %-6.6s %-12.12s  %8d %-20.20s %-25.25s\n"
18519    char host[80];
18520    char user[80];
18521    char tmpdat[256];
18522    struct ast_tm tm;
18523    int counter = 0;
18524 
18525    switch (cmd) {
18526    case CLI_INIT:
18527       e->command = "sip show registry";
18528       e->usage =
18529          "Usage: sip show registry\n"
18530          "       Lists all registration requests and status.\n";
18531       return NULL;
18532    case CLI_GENERATE:
18533       return NULL;
18534    }
18535 
18536    if (a->argc != 3)
18537       return CLI_SHOWUSAGE;
18538    ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Refresh", "State", "Reg.Time");
18539    
18540    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
18541       ASTOBJ_RDLOCK(iterator);
18542       snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
18543       snprintf(user, sizeof(user), "%s", iterator->username);
18544       if (!ast_strlen_zero(iterator->regdomain)) {
18545          snprintf(tmpdat, sizeof(tmpdat), "%s", user);
18546          snprintf(user, sizeof(user), "%s@%s", tmpdat, iterator->regdomain);}
18547       if (iterator->regdomainport) {
18548          snprintf(tmpdat, sizeof(tmpdat), "%s", user);
18549          snprintf(user, sizeof(user), "%s:%d", tmpdat, iterator->regdomainport);}
18550       if (iterator->regtime.tv_sec) {
18551          ast_localtime(&iterator->regtime, &tm, NULL);
18552          ast_strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
18553       } else
18554          tmpdat[0] = '\0';
18555       ast_cli(a->fd, FORMAT, host, (iterator->dnsmgr) ? "Y" : "N", user, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
18556       ASTOBJ_UNLOCK(iterator);
18557       counter++;
18558    } while(0));
18559    ast_cli(a->fd, "%d SIP registrations.\n", counter);
18560    return CLI_SUCCESS;
18561 #undef FORMAT
18562 #undef FORMAT2
18563 }
18564 
18565 /*! \brief Unregister (force expiration) a SIP peer in the registry via CLI
18566    \note This function does not tell the SIP device what's going on,
18567    so use it with great care.
18568 */
18569 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18570 {
18571    struct sip_peer *peer;
18572    int load_realtime = 0;
18573 
18574    switch (cmd) {
18575    case CLI_INIT:
18576       e->command = "sip unregister";
18577       e->usage =
18578          "Usage: sip unregister <peer>\n"
18579          "       Unregister (force expiration) a SIP peer from the registry\n";
18580       return NULL;
18581    case CLI_GENERATE:
18582       return complete_sip_unregister(a->line, a->word, a->pos, a->n);
18583    }
18584    
18585    if (a->argc != 3)
18586       return CLI_SHOWUSAGE;
18587    
18588    if ((peer = find_peer(a->argv[2], NULL, load_realtime, FINDPEERS, TRUE, 0))) {
18589       if (peer->expire > 0) {
18590          AST_SCHED_DEL_UNREF(sched, peer->expire,
18591             unref_peer(peer, "remove register expire ref"));
18592          expire_register(ref_peer(peer, "ref for expire_register"));
18593          ast_cli(a->fd, "Unregistered peer \'%s\'\n\n", a->argv[2]);
18594       } else {
18595          ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
18596       }
18597       unref_peer(peer, "sip_unregister: unref_peer via sip_unregister: done with peer from find_peer call");
18598    } else {
18599       ast_cli(a->fd, "Peer unknown: \'%s\'. Not unregistered.\n", a->argv[2]);
18600    }
18601    
18602    return CLI_SUCCESS;
18603 }
18604 
18605 /*! \brief Callback for show_chanstats */
18606 static int show_chanstats_cb(void *__cur, void *__arg, int flags)
18607 {
18608 #define FORMAT2 "%-15.15s  %-11.11s  %-8.8s %-10.10s  %-10.10s (     %%) %-6.6s %-10.10s  %-10.10s (     %%) %-6.6s\n"
18609 #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"
18610    struct sip_pvt *cur = __cur;
18611    struct ast_rtp_instance_stats stats;
18612    char durbuf[10];
18613    int duration;
18614    int durh, durm, durs;
18615    struct ast_channel *c;
18616    struct __show_chan_arg *arg = __arg;
18617    int fd = arg->fd;
18618 
18619    sip_pvt_lock(cur);
18620    c = cur->owner;
18621 
18622    if (cur->subscribed != NONE) {
18623       /* Subscriptions */
18624       sip_pvt_unlock(cur);
18625       return 0;   /* don't care, we scan all channels */
18626    }
18627 
18628    if (!cur->rtp) {
18629       if (sipdebug) {
18630          ast_cli(fd, "%-15.15s  %-11.11s (inv state: %s) -- %s\n",
18631             ast_sockaddr_stringify_addr(&cur->sa), cur->callid,
18632             invitestate2string[cur->invitestate].desc,
18633             "-- No RTP active");
18634       }
18635       sip_pvt_unlock(cur);
18636       return 0;   /* don't care, we scan all channels */
18637    }
18638 
18639    if (ast_rtp_instance_get_stats(cur->rtp, &stats, AST_RTP_INSTANCE_STAT_ALL)) {
18640       sip_pvt_unlock(cur);
18641       ast_log(LOG_WARNING, "Could not get RTP stats.\n");
18642       return 0;
18643    }
18644 
18645    if (c && c->cdr && !ast_tvzero(c->cdr->start)) {
18646       duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
18647       durh = duration / 3600;
18648       durm = (duration % 3600) / 60;
18649       durs = duration % 60;
18650       snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
18651    } else {
18652       durbuf[0] = '\0';
18653    }
18654 
18655    ast_cli(fd, FORMAT,
18656       ast_sockaddr_stringify_addr(&cur->sa),
18657       cur->callid,
18658       durbuf,
18659       stats.rxcount > (unsigned int) 100000 ? (unsigned int) (stats.rxcount)/(unsigned int) 1000 : stats.rxcount,
18660       stats.rxcount > (unsigned int) 100000 ? "K":" ",
18661       stats.rxploss,
18662       (stats.rxcount + stats.rxploss) > 0 ? (double) stats.rxploss / (stats.rxcount + stats.rxploss) * 100 : 0,
18663       stats.rxjitter,
18664       stats.txcount > (unsigned int) 100000 ? (unsigned int) (stats.txcount)/(unsigned int) 1000 : stats.txcount,
18665       stats.txcount > (unsigned int) 100000 ? "K":" ",
18666       stats.txploss,
18667       stats.txcount > 0 ? (double) stats.txploss / stats.txcount * 100 : 0,
18668       stats.txjitter
18669    );
18670    arg->numchans++;
18671    sip_pvt_unlock(cur);
18672 
18673    return 0;   /* don't care, we scan all channels */
18674 }
18675 
18676 /*! \brief SIP show channelstats CLI (main function) */
18677 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18678 {
18679    struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
18680 
18681    switch (cmd) {
18682    case CLI_INIT:
18683       e->command = "sip show channelstats";
18684       e->usage =
18685          "Usage: sip show channelstats\n"
18686          "       Lists all currently active SIP channel's RTCP statistics.\n"
18687          "       Note that calls in the much optimized RTP P2P bridge mode will not show any packets here.";
18688       return NULL;
18689    case CLI_GENERATE:
18690       return NULL;
18691    }
18692 
18693    if (a->argc != 3)
18694       return CLI_SHOWUSAGE;
18695 
18696    ast_cli(a->fd, FORMAT2, "Peer", "Call ID", "Duration", "Recv: Pack", "Lost", "Jitter", "Send: Pack", "Lost", "Jitter");
18697    /* iterate on the container and invoke the callback on each item */
18698    ao2_t_callback(dialogs, OBJ_NODATA, show_chanstats_cb, &arg, "callback to sip show chanstats");
18699    ast_cli(a->fd, "%d active SIP channel%s\n", arg.numchans, (arg.numchans != 1) ? "s" : "");
18700    return CLI_SUCCESS;
18701 }
18702 #undef FORMAT
18703 #undef FORMAT2
18704 
18705 /*! \brief List global settings for the SIP channel */
18706 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18707 {
18708    int realtimepeers;
18709    int realtimeregs;
18710    char codec_buf[SIPBUFSIZE];
18711    const char *msg;  /* temporary msg pointer */
18712    struct sip_auth_container *credentials;
18713 
18714    switch (cmd) {
18715    case CLI_INIT:
18716       e->command = "sip show settings";
18717       e->usage =
18718          "Usage: sip show settings\n"
18719          "       Provides detailed list of the configuration of the SIP channel.\n";
18720       return NULL;
18721    case CLI_GENERATE:
18722       return NULL;
18723    }
18724 
18725    if (a->argc != 3)
18726       return CLI_SHOWUSAGE;
18727 
18728    realtimepeers = ast_check_realtime("sippeers");
18729    realtimeregs = ast_check_realtime("sipregs");
18730 
18731    ast_mutex_lock(&authl_lock);
18732    credentials = authl;
18733    if (credentials) {
18734       ao2_t_ref(credentials, +1, "Ref global auth for show");
18735    }
18736    ast_mutex_unlock(&authl_lock);
18737 
18738    ast_cli(a->fd, "\n\nGlobal Settings:\n");
18739    ast_cli(a->fd, "----------------\n");
18740    ast_cli(a->fd, "  UDP Bindaddress:        %s\n", ast_sockaddr_stringify(&bindaddr));
18741    if (ast_sockaddr_is_ipv6(&bindaddr) && ast_sockaddr_is_any(&bindaddr)) {
18742       ast_cli(a->fd, "  ** Additional Info:\n");
18743       ast_cli(a->fd, "     [::] may include IPv4 in addition to IPv6, if such a feature is enabled in the OS.\n");
18744    }
18745    ast_cli(a->fd, "  TCP SIP Bindaddress:    %s\n",
18746       sip_cfg.tcp_enabled != FALSE ?
18747             ast_sockaddr_stringify(&sip_tcp_desc.local_address) :
18748             "Disabled");
18749    ast_cli(a->fd, "  TLS SIP Bindaddress:    %s\n",
18750       default_tls_cfg.enabled != FALSE ?
18751             ast_sockaddr_stringify(&sip_tls_desc.local_address) :
18752             "Disabled");
18753    ast_cli(a->fd, "  Videosupport:           %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT)));
18754    ast_cli(a->fd, "  Textsupport:            %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT)));
18755    ast_cli(a->fd, "  Ignore SDP sess. ver.:  %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION)));
18756    ast_cli(a->fd, "  AutoCreate Peer:        %s\n", AST_CLI_YESNO(sip_cfg.autocreatepeer));
18757    ast_cli(a->fd, "  Match Auth Username:    %s\n", AST_CLI_YESNO(global_match_auth_username));
18758    ast_cli(a->fd, "  Allow unknown access:   %s\n", AST_CLI_YESNO(sip_cfg.allowguest));
18759    ast_cli(a->fd, "  Allow subscriptions:    %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
18760    ast_cli(a->fd, "  Allow overlap dialing:  %s\n", allowoverlap2str(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)));
18761    ast_cli(a->fd, "  Allow promisc. redir:   %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_PROMISCREDIR)));
18762    ast_cli(a->fd, "  Enable call counters:   %s\n", AST_CLI_YESNO(global_callcounter));
18763    ast_cli(a->fd, "  SIP domain support:     %s\n", AST_CLI_YESNO(!AST_LIST_EMPTY(&domain_list)));
18764    ast_cli(a->fd, "  Realm. auth:            %s\n", AST_CLI_YESNO(credentials != NULL));
18765    if (credentials) {
18766       struct sip_auth *auth;
18767 
18768       AST_LIST_TRAVERSE(&credentials->list, auth, node) {
18769          ast_cli(a->fd, "  Realm. auth entry:      Realm %-15.15s User %-10.20s %s\n",
18770             auth->realm,
18771             auth->username,
18772             !ast_strlen_zero(auth->secret)
18773                ? "<Secret set>"
18774                : (!ast_strlen_zero(auth->md5secret)
18775                   ? "<MD5secret set>" : "<Not set>"));
18776       }
18777       ao2_t_ref(credentials, -1, "Unref global auth for show");
18778    }
18779    ast_cli(a->fd, "  Our auth realm          %s\n", sip_cfg.realm);
18780    ast_cli(a->fd, "  Use domains as realms:  %s\n", AST_CLI_YESNO(sip_cfg.domainsasrealm));
18781    ast_cli(a->fd, "  Call to non-local dom.: %s\n", AST_CLI_YESNO(sip_cfg.allow_external_domains));
18782    ast_cli(a->fd, "  URI user is phone no:   %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_USEREQPHONE)));
18783    ast_cli(a->fd, "  Always auth rejects:    %s\n", AST_CLI_YESNO(sip_cfg.alwaysauthreject));
18784    ast_cli(a->fd, "  Direct RTP setup:       %s\n", AST_CLI_YESNO(sip_cfg.directrtpsetup));
18785    ast_cli(a->fd, "  User Agent:             %s\n", global_useragent);
18786    ast_cli(a->fd, "  SDP Session Name:       %s\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
18787    ast_cli(a->fd, "  SDP Owner Name:         %s\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner);
18788    ast_cli(a->fd, "  Reg. context:           %s\n", S_OR(sip_cfg.regcontext, "(not set)"));
18789    ast_cli(a->fd, "  Regexten on Qualify:    %s\n", AST_CLI_YESNO(sip_cfg.regextenonqualify));
18790    ast_cli(a->fd, "  Legacy userfield parse: %s\n", AST_CLI_YESNO(sip_cfg.legacy_useroption_parsing));
18791    ast_cli(a->fd, "  Caller ID:              %s\n", default_callerid);
18792    if ((default_fromdomainport) && (default_fromdomainport != STANDARD_SIP_PORT)) {
18793       ast_cli(a->fd, "  From: Domain:           %s:%d\n", default_fromdomain, default_fromdomainport);
18794    } else {
18795       ast_cli(a->fd, "  From: Domain:           %s\n", default_fromdomain);
18796    }
18797    ast_cli(a->fd, "  Record SIP history:     %s\n", AST_CLI_ONOFF(recordhistory));
18798    ast_cli(a->fd, "  Call Events:            %s\n", AST_CLI_ONOFF(sip_cfg.callevents));
18799    ast_cli(a->fd, "  Auth. Failure Events:   %s\n", AST_CLI_ONOFF(global_authfailureevents));
18800 
18801    ast_cli(a->fd, "  T.38 support:           %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
18802    ast_cli(a->fd, "  T.38 EC mode:           %s\n", faxec2str(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
18803    ast_cli(a->fd, "  T.38 MaxDtgrm:          %u\n", global_t38_maxdatagram);
18804    if (!realtimepeers && !realtimeregs)
18805       ast_cli(a->fd, "  SIP realtime:           Disabled\n" );
18806    else
18807       ast_cli(a->fd, "  SIP realtime:           Enabled\n" );
18808    ast_cli(a->fd, "  Qualify Freq :          %d ms\n", global_qualifyfreq);
18809    ast_cli(a->fd, "  Q.850 Reason header:    %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_Q850_REASON)));
18810    ast_cli(a->fd, "  Store SIP_CAUSE:        %s\n", AST_CLI_YESNO(global_store_sip_cause));
18811    ast_cli(a->fd, "\nNetwork QoS Settings:\n");
18812    ast_cli(a->fd, "---------------------------\n");
18813    ast_cli(a->fd, "  IP ToS SIP:             %s\n", ast_tos2str(global_tos_sip));
18814    ast_cli(a->fd, "  IP ToS RTP audio:       %s\n", ast_tos2str(global_tos_audio));
18815    ast_cli(a->fd, "  IP ToS RTP video:       %s\n", ast_tos2str(global_tos_video));
18816    ast_cli(a->fd, "  IP ToS RTP text:        %s\n", ast_tos2str(global_tos_text));
18817    ast_cli(a->fd, "  802.1p CoS SIP:         %u\n", global_cos_sip);
18818    ast_cli(a->fd, "  802.1p CoS RTP audio:   %u\n", global_cos_audio);
18819    ast_cli(a->fd, "  802.1p CoS RTP video:   %u\n", global_cos_video);
18820    ast_cli(a->fd, "  802.1p CoS RTP text:    %u\n", global_cos_text);
18821    ast_cli(a->fd, "  Jitterbuffer enabled:   %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_ENABLED)));
18822    if (ast_test_flag(&global_jbconf, AST_JB_ENABLED)) {
18823       ast_cli(a->fd, "  Jitterbuffer forced:    %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_FORCED)));
18824       ast_cli(a->fd, "  Jitterbuffer max size:  %ld\n", global_jbconf.max_size);
18825       ast_cli(a->fd, "  Jitterbuffer resync:    %ld\n", global_jbconf.resync_threshold);
18826       ast_cli(a->fd, "  Jitterbuffer impl:      %s\n", global_jbconf.impl);
18827       if (!strcasecmp(global_jbconf.impl, "adaptive")) {
18828          ast_cli(a->fd, "  Jitterbuffer tgt extra: %ld\n", global_jbconf.target_extra);
18829       }
18830       ast_cli(a->fd, "  Jitterbuffer log:       %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_LOG)));
18831    }
18832 
18833    ast_cli(a->fd, "\nNetwork Settings:\n");
18834    ast_cli(a->fd, "---------------------------\n");
18835    /* determine if/how SIP address can be remapped */
18836    if (localaddr == NULL)
18837       msg = "Disabled, no localnet list";
18838    else if (ast_sockaddr_isnull(&externaddr))
18839       msg = "Disabled";
18840    else if (!ast_strlen_zero(externhost))
18841       msg = "Enabled using externhost";
18842    else
18843       msg = "Enabled using externaddr";
18844    ast_cli(a->fd, "  SIP address remapping:  %s\n", msg);
18845    ast_cli(a->fd, "  Externhost:             %s\n", S_OR(externhost, "<none>"));
18846    ast_cli(a->fd, "  Externaddr:             %s\n", ast_sockaddr_stringify(&externaddr));
18847    ast_cli(a->fd, "  Externrefresh:          %d\n", externrefresh);
18848    {
18849       struct ast_ha *d;
18850       const char *prefix = "Localnet:";
18851 
18852       for (d = localaddr; d ; prefix = "", d = d->next) {
18853          const char *addr = ast_strdupa(ast_sockaddr_stringify_addr(&d->addr));
18854          const char *mask = ast_strdupa(ast_sockaddr_stringify_addr(&d->netmask));
18855          ast_cli(a->fd, "  %-24s%s/%s\n", prefix, addr, mask);
18856       }
18857    }
18858    ast_cli(a->fd, "\nGlobal Signalling Settings:\n");
18859    ast_cli(a->fd, "---------------------------\n");
18860    ast_cli(a->fd, "  Codecs:                 ");
18861    ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, sip_cfg.capability);
18862    ast_cli(a->fd, "%s\n", codec_buf);
18863    ast_cli(a->fd, "  Codec Order:            ");
18864    print_codec_to_cli(a->fd, &default_prefs);
18865    ast_cli(a->fd, "\n");
18866    ast_cli(a->fd, "  Relax DTMF:             %s\n", AST_CLI_YESNO(global_relaxdtmf));
18867    ast_cli(a->fd, "  RFC2833 Compensation:   %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE)));
18868    ast_cli(a->fd, "  Symmetric RTP:          %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_SYMMETRICRTP)));
18869    ast_cli(a->fd, "  Compact SIP headers:    %s\n", AST_CLI_YESNO(sip_cfg.compactheaders));
18870    ast_cli(a->fd, "  RTP Keepalive:          %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
18871    ast_cli(a->fd, "  RTP Timeout:            %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
18872    ast_cli(a->fd, "  RTP Hold Timeout:       %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
18873    ast_cli(a->fd, "  MWI NOTIFY mime type:   %s\n", default_notifymime);
18874    ast_cli(a->fd, "  DNS SRV lookup:         %s\n", AST_CLI_YESNO(sip_cfg.srvlookup));
18875    ast_cli(a->fd, "  Pedantic SIP support:   %s\n", AST_CLI_YESNO(sip_cfg.pedanticsipchecking));
18876    ast_cli(a->fd, "  Reg. min duration       %d secs\n", min_expiry);
18877    ast_cli(a->fd, "  Reg. max duration:      %d secs\n", max_expiry);
18878    ast_cli(a->fd, "  Reg. default duration:  %d secs\n", default_expiry);
18879    ast_cli(a->fd, "  Outbound reg. timeout:  %d secs\n", global_reg_timeout);
18880    ast_cli(a->fd, "  Outbound reg. attempts: %d\n", global_regattempts_max);
18881    ast_cli(a->fd, "  Outbound reg. retry 403:%d\n", global_reg_retry_403);
18882    ast_cli(a->fd, "  Notify ringing state:   %s\n", AST_CLI_YESNO(sip_cfg.notifyringing));
18883    if (sip_cfg.notifyringing) {
18884       ast_cli(a->fd, "    Include CID:          %s%s\n",
18885             AST_CLI_YESNO(sip_cfg.notifycid),
18886             sip_cfg.notifycid == IGNORE_CONTEXT ? " (Ignoring context)" : "");
18887    }
18888    ast_cli(a->fd, "  Notify hold state:      %s\n", AST_CLI_YESNO(sip_cfg.notifyhold));
18889    ast_cli(a->fd, "  SIP Transfer mode:      %s\n", transfermode2str(sip_cfg.allowtransfer));
18890    ast_cli(a->fd, "  Max Call Bitrate:       %d kbps\n", default_maxcallbitrate);
18891    ast_cli(a->fd, "  Auto-Framing:           %s\n", AST_CLI_YESNO(global_autoframing));
18892    ast_cli(a->fd, "  Outb. proxy:            %s %s\n", ast_strlen_zero(sip_cfg.outboundproxy.name) ? "<not set>" : sip_cfg.outboundproxy.name,
18893                      sip_cfg.outboundproxy.force ? "(forced)" : "");
18894    ast_cli(a->fd, "  Session Timers:         %s\n", stmode2str(global_st_mode));
18895    ast_cli(a->fd, "  Session Refresher:      %s\n", strefresherparam2str(global_st_refresher));
18896    ast_cli(a->fd, "  Session Expires:        %d secs\n", global_max_se);
18897    ast_cli(a->fd, "  Session Min-SE:         %d secs\n", global_min_se);
18898    ast_cli(a->fd, "  Timer T1:               %d\n", global_t1);
18899    ast_cli(a->fd, "  Timer T1 minimum:       %d\n", global_t1min);
18900    ast_cli(a->fd, "  Timer B:                %d\n", global_timer_b);
18901    ast_cli(a->fd, "  No premature media:     %s\n", AST_CLI_YESNO(global_prematuremediafilter));
18902    ast_cli(a->fd, "  Max forwards:           %d\n", sip_cfg.default_max_forwards);
18903 
18904    ast_cli(a->fd, "\nDefault Settings:\n");
18905    ast_cli(a->fd, "-----------------\n");
18906    ast_cli(a->fd, "  Allowed transports:     %s\n", get_transport_list(default_transports));
18907    ast_cli(a->fd, "  Outbound transport:    %s\n", get_transport(default_primary_transport));
18908    ast_cli(a->fd, "  Context:                %s\n", sip_cfg.default_context);
18909    ast_cli(a->fd, "  Force rport:            %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_NAT_FORCE_RPORT)));
18910    ast_cli(a->fd, "  DTMF:                   %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
18911    ast_cli(a->fd, "  Qualify:                %d\n", default_qualify);
18912    ast_cli(a->fd, "  Use ClientCode:         %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_USECLIENTCODE)));
18913    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)));
18914    ast_cli(a->fd, "  Language:               %s\n", default_language);
18915    ast_cli(a->fd, "  MOH Interpret:          %s\n", default_mohinterpret);
18916    ast_cli(a->fd, "  MOH Suggest:            %s\n", default_mohsuggest);
18917    ast_cli(a->fd, "  Voice Mail Extension:   %s\n", default_vmexten);
18918 
18919    
18920    if (realtimepeers || realtimeregs) {
18921       ast_cli(a->fd, "\nRealtime SIP Settings:\n");
18922       ast_cli(a->fd, "----------------------\n");
18923       ast_cli(a->fd, "  Realtime Peers:         %s\n", AST_CLI_YESNO(realtimepeers));
18924       ast_cli(a->fd, "  Realtime Regs:          %s\n", AST_CLI_YESNO(realtimeregs));
18925       ast_cli(a->fd, "  Cache Friends:          %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)));
18926       ast_cli(a->fd, "  Update:                 %s\n", AST_CLI_YESNO(sip_cfg.peer_rtupdate));
18927       ast_cli(a->fd, "  Ignore Reg. Expire:     %s\n", AST_CLI_YESNO(sip_cfg.ignore_regexpire));
18928       ast_cli(a->fd, "  Save sys. name:         %s\n", AST_CLI_YESNO(sip_cfg.rtsave_sysname));
18929       ast_cli(a->fd, "  Auto Clear:             %d (%s)\n", sip_cfg.rtautoclear, ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR) ? "Enabled" : "Disabled");
18930    }
18931    ast_cli(a->fd, "\n----\n");
18932    return CLI_SUCCESS;
18933 }
18934 
18935 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18936 {
18937 #define FORMAT  "%-30.30s  %-12.12s  %-10.10s  %-10.10s\n"
18938    char host[80];
18939    
18940    switch (cmd) {
18941    case CLI_INIT:
18942       e->command = "sip show mwi";
18943       e->usage =
18944          "Usage: sip show mwi\n"
18945          "       Provides a list of MWI subscriptions and status.\n";
18946       return NULL;
18947    case CLI_GENERATE:
18948       return NULL;
18949    }
18950    
18951    ast_cli(a->fd, FORMAT, "Host", "Username", "Mailbox", "Subscribed");
18952    
18953    ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
18954       ASTOBJ_RDLOCK(iterator);
18955       snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
18956       ast_cli(a->fd, FORMAT, host, iterator->username, iterator->mailbox, AST_CLI_YESNO(iterator->subscribed));
18957       ASTOBJ_UNLOCK(iterator);
18958    } while(0));
18959 
18960    return CLI_SUCCESS;
18961 #undef FORMAT
18962 }
18963 
18964 
18965 /*! \brief Show subscription type in string format */
18966 static const char *subscription_type2str(enum subscriptiontype subtype)
18967 {
18968    int i;
18969 
18970    for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
18971       if (subscription_types[i].type == subtype) {
18972          return subscription_types[i].text;
18973       }
18974    }
18975    return subscription_types[0].text;
18976 }
18977 
18978 /*! \brief Find subscription type in array */
18979 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
18980 {
18981    int i;
18982 
18983    for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
18984       if (subscription_types[i].type == subtype) {
18985          return &subscription_types[i];
18986       }
18987    }
18988    return &subscription_types[0];
18989 }
18990 
18991 /*
18992  * We try to structure all functions that loop on data structures as
18993  * a handler for individual entries, and a mainloop that iterates
18994  * on the main data structure. This way, moving the code to containers
18995  * that support iteration through callbacks will be a lot easier.
18996  */
18997 
18998 #define FORMAT4 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-13.13s  %-15.15s %-10.10s %-6.6d\n"
18999 #define FORMAT3 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-13.13s  %-15.15s %-10.10s %-6.6s\n"
19000 #define FORMAT2 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-7.7s  %-15.15s %-10.10s %-10.10s\n"
19001 #define FORMAT  "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-3.3s %-3.3s  %-15.15s %-10.10s %-10.10s\n"
19002 
19003 /*! \brief callback for show channel|subscription */
19004 static int show_channels_cb(void *__cur, void *__arg, int flags)
19005 {
19006    struct sip_pvt *cur = __cur;
19007    struct __show_chan_arg *arg = __arg;
19008    const struct ast_sockaddr *dst;
19009 
19010    sip_pvt_lock(cur);
19011    dst = sip_real_dst(cur);
19012 
19013    /* XXX indentation preserved to reduce diff. Will be fixed later */
19014    if (cur->subscribed == NONE && !arg->subscriptions) {
19015       /* set if SIP transfer in progress */
19016       const char *referstatus = cur->refer ? referstatus2str(cur->refer->status) : "";
19017       char formatbuf[SIPBUFSIZE/2];
19018       
19019       ast_cli(arg->fd, FORMAT, ast_sockaddr_stringify_addr(dst),
19020             S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
19021             cur->callid,
19022             ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0),
19023             AST_CLI_YESNO(ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD)),
19024             cur->needdestroy ? "(d)" : "",
19025             cur->lastmsg ,
19026             referstatus,
19027             cur->relatedpeer ? cur->relatedpeer->name : "<guest>"
19028          );
19029       arg->numchans++;
19030       if (cur->owner) { /* Count SIP dialog owned by a real channel */
19031          arg->usedchans++;
19032       }
19033    }
19034    if (cur->subscribed != NONE && arg->subscriptions) {
19035       struct ast_str *mailbox_str = ast_str_alloca(512);
19036       if (cur->subscribed == MWI_NOTIFICATION && cur->relatedpeer)
19037          peer_mailboxes_to_str(&mailbox_str, cur->relatedpeer);
19038       ast_cli(arg->fd, FORMAT4, ast_sockaddr_stringify_addr(dst),
19039             S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
19040                cur->callid,
19041             /* the 'complete' exten/context is hidden in the refer_to field for subscriptions */
19042             cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
19043             cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate),
19044             subscription_type2str(cur->subscribed),
19045             cur->subscribed == MWI_NOTIFICATION ? S_OR(ast_str_buffer(mailbox_str), "<none>") : "<none>",
19046             cur->expiry
19047          );
19048       arg->numchans++;
19049       if (cur->owner) { /* Count SIP dialog owned by a real channel */
19050          arg->usedchans++;
19051       }
19052    }
19053    sip_pvt_unlock(cur);
19054    return 0;   /* don't care, we scan all channels */
19055 }
19056 
19057 /*! \brief CLI for show channels or subscriptions.
19058  * This is a new-style CLI handler so a single function contains
19059  * the prototype for the function, the 'generator' to produce multiple
19060  * entries in case it is required, and the actual handler for the command.
19061  */
19062 static char *sip_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19063 {
19064    struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0, .usedchans = 0 };
19065 
19066 
19067    if (cmd == CLI_INIT) {
19068       e->command = "sip show {channels|subscriptions}";
19069       e->usage =
19070          "Usage: sip show channels\n"
19071          "       Lists all currently active SIP calls (dialogs).\n"
19072          "Usage: sip show subscriptions\n"
19073          "       Lists active SIP subscriptions.\n";
19074       return NULL;
19075    } else if (cmd == CLI_GENERATE)
19076       return NULL;
19077 
19078    if (a->argc != e->args)
19079       return CLI_SHOWUSAGE;
19080    arg.subscriptions = !strcasecmp(a->argv[e->args - 1], "subscriptions");
19081    if (!arg.subscriptions)
19082       ast_cli(arg.fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Format", "Hold", "Last Message", "Expiry", "Peer");
19083    else
19084       ast_cli(arg.fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox", "Expiry");
19085 
19086    /* iterate on the container and invoke the callback on each item */
19087    ao2_t_callback(dialogs, OBJ_NODATA, show_channels_cb, &arg, "callback to show channels");
19088    
19089    /* print summary information */
19090    ast_cli(arg.fd, "%d active SIP %s%s\n", arg.numchans,
19091       (arg.subscriptions ? "subscription" : "dialog"),
19092       ESS(arg.numchans));  /* ESS(n) returns an "s" if n>1 */
19093    ast_cli(arg.fd, "%d used SIP channel%s\n", arg.usedchans, ESS(arg.usedchans));
19094    return CLI_SUCCESS;
19095 #undef FORMAT
19096 #undef FORMAT2
19097 #undef FORMAT3
19098 }
19099 
19100 /*! \brief Support routine for 'sip show channel' and 'sip show history' CLI
19101  * This is in charge of generating all strings that match a prefix in the
19102  * given position. As many functions of this kind, each invokation has
19103  * O(state) time complexity so be careful in using it.
19104  */
19105 static char *complete_sipch(const char *line, const char *word, int pos, int state)
19106 {
19107    int which=0;
19108    struct sip_pvt *cur;
19109    char *c = NULL;
19110    int wordlen = strlen(word);
19111    struct ao2_iterator i;
19112 
19113    if (pos != 3) {
19114       return NULL;
19115    }
19116 
19117    i = ao2_iterator_init(dialogs, 0);
19118    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
19119       sip_pvt_lock(cur);
19120       if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
19121          c = ast_strdup(cur->callid);
19122          sip_pvt_unlock(cur);
19123          dialog_unref(cur, "drop ref in iterator loop break");
19124          break;
19125       }
19126       sip_pvt_unlock(cur);
19127       dialog_unref(cur, "drop ref in iterator loop");
19128    }
19129    ao2_iterator_destroy(&i);
19130    return c;
19131 }
19132 
19133 
19134 /*! \brief Do completion on peer name */
19135 static char *complete_sip_peer(const char *word, int state, int flags2)
19136 {
19137    char *result = NULL;
19138    int wordlen = strlen(word);
19139    int which = 0;
19140    struct ao2_iterator i = ao2_iterator_init(peers, 0);
19141    struct sip_peer *peer;
19142 
19143    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
19144       /* locking of the object is not required because only the name and flags are being compared */
19145       if (!strncasecmp(word, peer->name, wordlen) &&
19146             (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
19147             ++which > state)
19148          result = ast_strdup(peer->name);
19149       unref_peer(peer, "toss iterator peer ptr before break");
19150       if (result) {
19151          break;
19152       }
19153    }
19154    ao2_iterator_destroy(&i);
19155    return result;
19156 }
19157 
19158 /*! \brief Do completion on registered peer name */
19159 static char *complete_sip_registered_peer(const char *word, int state, int flags2)
19160 {
19161        char *result = NULL;
19162        int wordlen = strlen(word);
19163        int which = 0;
19164        struct ao2_iterator i;
19165        struct sip_peer *peer;
19166        
19167        i = ao2_iterator_init(peers, 0);
19168        while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
19169           if (!strncasecmp(word, peer->name, wordlen) &&
19170          (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
19171          ++which > state && peer->expire > 0)
19172              result = ast_strdup(peer->name);
19173           if (result) {
19174              unref_peer(peer, "toss iterator peer ptr before break");
19175              break;
19176           }
19177           unref_peer(peer, "toss iterator peer ptr");
19178        }
19179        ao2_iterator_destroy(&i);
19180        return result;
19181 }
19182 
19183 /*! \brief Support routine for 'sip show history' CLI */
19184 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state)
19185 {
19186    if (pos == 3)
19187       return complete_sipch(line, word, pos, state);
19188 
19189    return NULL;
19190 }
19191 
19192 /*! \brief Support routine for 'sip show peer' CLI */
19193 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
19194 {
19195    if (pos == 3) {
19196       return complete_sip_peer(word, state, 0);
19197    }
19198 
19199    return NULL;
19200 }
19201 
19202 /*! \brief Support routine for 'sip unregister' CLI */
19203 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state)
19204 {
19205        if (pos == 2)
19206                return complete_sip_registered_peer(word, state, 0);
19207 
19208        return NULL;
19209 }
19210 
19211 /*! \brief Support routine for 'sip notify' CLI */
19212 static char *complete_sipnotify(const char *line, const char *word, int pos, int state)
19213 {
19214    char *c = NULL;
19215 
19216    if (pos == 2) {
19217       int which = 0;
19218       char *cat = NULL;
19219       int wordlen = strlen(word);
19220 
19221       /* do completion for notify type */
19222 
19223       if (!notify_types)
19224          return NULL;
19225       
19226       while ( (cat = ast_category_browse(notify_types, cat)) ) {
19227          if (!strncasecmp(word, cat, wordlen) && ++which > state) {
19228             c = ast_strdup(cat);
19229             break;
19230          }
19231       }
19232       return c;
19233    }
19234 
19235    if (pos > 2)
19236       return complete_sip_peer(word, state, 0);
19237 
19238    return NULL;
19239 }
19240 
19241 static const char *transport2str(enum sip_transport transport)
19242 {
19243    switch (transport) {
19244    case SIP_TRANSPORT_TLS:
19245       return "TLS";
19246    case SIP_TRANSPORT_UDP:
19247       return "UDP";
19248    case SIP_TRANSPORT_TCP:
19249       return "TCP";
19250    }
19251 
19252    return "Undefined";
19253 }
19254 
19255 /*! \brief Show details of one active dialog */
19256 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19257 {
19258    struct sip_pvt *cur;
19259    size_t len;
19260    int found = 0;
19261    struct ao2_iterator i;
19262 
19263    switch (cmd) {
19264    case CLI_INIT:
19265       e->command = "sip show channel";
19266       e->usage =
19267          "Usage: sip show channel <call-id>\n"
19268          "       Provides detailed status on a given SIP dialog (identified by SIP call-id).\n";
19269       return NULL;
19270    case CLI_GENERATE:
19271       return complete_sipch(a->line, a->word, a->pos, a->n);
19272    }
19273 
19274    if (a->argc != 4)
19275       return CLI_SHOWUSAGE;
19276    len = strlen(a->argv[3]);
19277    
19278    i = ao2_iterator_init(dialogs, 0);
19279    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
19280       sip_pvt_lock(cur);
19281 
19282       if (!strncasecmp(cur->callid, a->argv[3], len)) {
19283          char formatbuf[SIPBUFSIZE/2];
19284          ast_cli(a->fd, "\n");
19285          if (cur->subscribed != NONE)
19286             ast_cli(a->fd, "  * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
19287          else
19288             ast_cli(a->fd, "  * SIP Call\n");
19289          ast_cli(a->fd, "  Curr. trans. direction:  %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
19290          ast_cli(a->fd, "  Call-ID:                %s\n", cur->callid);
19291          ast_cli(a->fd, "  Owner channel ID:       %s\n", cur->owner ? cur->owner->name : "<none>");
19292          ast_cli(a->fd, "  Our Codec Capability:   %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->capability));
19293          ast_cli(a->fd, "  Non-Codec Capability (DTMF):   %d\n", cur->noncodeccapability);
19294          ast_cli(a->fd, "  Their Codec Capability:   %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->peercapability));
19295          ast_cli(a->fd, "  Joint Codec Capability:   %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->jointcapability));
19296          ast_cli(a->fd, "  Format:                 %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0) );
19297          ast_cli(a->fd, "  T.38 support            %s\n", AST_CLI_YESNO(cur->udptl != NULL));
19298          ast_cli(a->fd, "  Video support           %s\n", AST_CLI_YESNO(cur->vrtp != NULL));
19299          ast_cli(a->fd, "  MaxCallBR:              %d kbps\n", cur->maxcallbitrate);
19300          ast_cli(a->fd, "  Theoretical Address:    %s\n", ast_sockaddr_stringify(&cur->sa));
19301          ast_cli(a->fd, "  Received Address:       %s\n", ast_sockaddr_stringify(&cur->recv));
19302          ast_cli(a->fd, "  SIP Transfer mode:      %s\n", transfermode2str(cur->allowtransfer));
19303          ast_cli(a->fd, "  Force rport:            %s\n", AST_CLI_YESNO(ast_test_flag(&cur->flags[0], SIP_NAT_FORCE_RPORT)));
19304          if (ast_sockaddr_isnull(&cur->redirip)) {
19305             ast_cli(a->fd,
19306                "  Audio IP:               %s (local)\n",
19307                ast_sockaddr_stringify_addr(&cur->ourip));
19308          } else {
19309             ast_cli(a->fd,
19310                "  Audio IP:               %s (Outside bridge)\n",
19311                ast_sockaddr_stringify_addr(&cur->redirip));
19312          }
19313          ast_cli(a->fd, "  Our Tag:                %s\n", cur->tag);
19314          ast_cli(a->fd, "  Their Tag:              %s\n", cur->theirtag);
19315          ast_cli(a->fd, "  SIP User agent:         %s\n", cur->useragent);
19316          if (!ast_strlen_zero(cur->username))
19317             ast_cli(a->fd, "  Username:               %s\n", cur->username);
19318          if (!ast_strlen_zero(cur->peername))
19319             ast_cli(a->fd, "  Peername:               %s\n", cur->peername);
19320          if (!ast_strlen_zero(cur->uri))
19321             ast_cli(a->fd, "  Original uri:           %s\n", cur->uri);
19322          if (!ast_strlen_zero(cur->cid_num))
19323             ast_cli(a->fd, "  Caller-ID:              %s\n", cur->cid_num);
19324          ast_cli(a->fd, "  Need Destroy:           %s\n", AST_CLI_YESNO(cur->needdestroy));
19325          ast_cli(a->fd, "  Last Message:           %s\n", cur->lastmsg);
19326          ast_cli(a->fd, "  Promiscuous Redir:      %s\n", AST_CLI_YESNO(ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR)));
19327          ast_cli(a->fd, "  Route:                  %s\n", cur->route ? cur->route->hop : "N/A");
19328          ast_cli(a->fd, "  DTMF Mode:              %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
19329          ast_cli(a->fd, "  SIP Options:            ");
19330          if (cur->sipoptions) {
19331             int x;
19332             for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
19333                if (cur->sipoptions & sip_options[x].id)
19334                   ast_cli(a->fd, "%s ", sip_options[x].text);
19335             }
19336             ast_cli(a->fd, "\n");
19337          } else
19338             ast_cli(a->fd, "(none)\n");
19339 
19340          if (!cur->stimer)
19341             ast_cli(a->fd, "  Session-Timer:          Uninitiallized\n");
19342          else {
19343             ast_cli(a->fd, "  Session-Timer:          %s\n", cur->stimer->st_active ? "Active" : "Inactive");
19344             if (cur->stimer->st_active == TRUE) {
19345                ast_cli(a->fd, "  S-Timer Interval:       %d\n", cur->stimer->st_interval);
19346                ast_cli(a->fd, "  S-Timer Refresher:      %s\n", strefresher2str(cur->stimer->st_ref));
19347                ast_cli(a->fd, "  S-Timer Sched Id:       %d\n", cur->stimer->st_schedid);
19348                ast_cli(a->fd, "  S-Timer Peer Sts:       %s\n", cur->stimer->st_active_peer_ua ? "Active" : "Inactive");
19349                ast_cli(a->fd, "  S-Timer Cached Min-SE:  %d\n", cur->stimer->st_cached_min_se);
19350                ast_cli(a->fd, "  S-Timer Cached SE:      %d\n", cur->stimer->st_cached_max_se);
19351                ast_cli(a->fd, "  S-Timer Cached Ref:     %s\n", strefresherparam2str(cur->stimer->st_cached_ref));
19352                ast_cli(a->fd, "  S-Timer Cached Mode:    %s\n", stmode2str(cur->stimer->st_cached_mode));
19353             }
19354          }
19355 
19356          /* add transport and media types */
19357          ast_cli(a->fd, "  Transport:              %s\n", transport2str(cur->socket.type));
19358          ast_cli(a->fd, "  Media:                  %s\n", cur->srtp ? "SRTP" : cur->rtp ? "RTP" : "None");
19359 
19360          ast_cli(a->fd, "\n\n");
19361 
19362          found++;
19363       }
19364 
19365       sip_pvt_unlock(cur);
19366 
19367       ao2_t_ref(cur, -1, "toss dialog ptr set by iterator_next");
19368    }
19369    ao2_iterator_destroy(&i);
19370 
19371    if (!found)
19372       ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
19373 
19374    return CLI_SUCCESS;
19375 }
19376 
19377 /*! \brief Show history details of one dialog */
19378 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19379 {
19380    struct sip_pvt *cur;
19381    size_t len;
19382    int found = 0;
19383    struct ao2_iterator i;
19384 
19385    switch (cmd) {
19386    case CLI_INIT:
19387       e->command = "sip show history";
19388       e->usage =
19389          "Usage: sip show history <call-id>\n"
19390          "       Provides detailed dialog history on a given SIP call (specified by call-id).\n";
19391       return NULL;
19392    case CLI_GENERATE:
19393       return complete_sip_show_history(a->line, a->word, a->pos, a->n);
19394    }
19395 
19396    if (a->argc != 4)
19397       return CLI_SHOWUSAGE;
19398 
19399    if (!recordhistory)
19400       ast_cli(a->fd, "\n***Note: History recording is currently DISABLED.  Use 'sip set history on' to ENABLE.\n");
19401 
19402    len = strlen(a->argv[3]);
19403 
19404    i = ao2_iterator_init(dialogs, 0);
19405    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
19406       sip_pvt_lock(cur);
19407       if (!strncasecmp(cur->callid, a->argv[3], len)) {
19408          struct sip_history *hist;
19409          int x = 0;
19410 
19411          ast_cli(a->fd, "\n");
19412          if (cur->subscribed != NONE)
19413             ast_cli(a->fd, "  * Subscription\n");
19414          else
19415             ast_cli(a->fd, "  * SIP Call\n");
19416          if (cur->history)
19417             AST_LIST_TRAVERSE(cur->history, hist, list)
19418                ast_cli(a->fd, "%d. %s\n", ++x, hist->event);
19419          if (x == 0)
19420             ast_cli(a->fd, "Call '%s' has no history\n", cur->callid);
19421          found++;
19422       }
19423       sip_pvt_unlock(cur);
19424       ao2_t_ref(cur, -1, "toss dialog ptr from iterator_next");
19425    }
19426    ao2_iterator_destroy(&i);
19427 
19428    if (!found)
19429       ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
19430 
19431    return CLI_SUCCESS;
19432 }
19433 
19434 /*! \brief Dump SIP history to debug log file at end of lifespan for SIP dialog */
19435 static void sip_dump_history(struct sip_pvt *dialog)
19436 {
19437    int x = 0;
19438    struct sip_history *hist;
19439    static int errmsg = 0;
19440 
19441    if (!dialog)
19442       return;
19443 
19444    if (!option_debug && !sipdebug) {
19445       if (!errmsg) {
19446          ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
19447          errmsg = 1;
19448       }
19449       return;
19450    }
19451 
19452    ast_debug(1, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
19453    if (dialog->subscribed)
19454       ast_debug(1, "  * Subscription\n");
19455    else
19456       ast_debug(1, "  * SIP Call\n");
19457    if (dialog->history)
19458       AST_LIST_TRAVERSE(dialog->history, hist, list)
19459          ast_debug(1, "  %-3.3d. %s\n", ++x, hist->event);
19460    if (!x)
19461       ast_debug(1, "Call '%s' has no history\n", dialog->callid);
19462    ast_debug(1, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
19463 }
19464 
19465 
19466 /*! \brief  Receive SIP INFO Message */
19467 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
19468 {
19469    char buf[1024] = "";
19470    unsigned int event;
19471    const char *c = get_header(req, "Content-Type");
19472 
19473    /* Need to check the media/type */
19474    if (!strcasecmp(c, "application/dtmf-relay") ||
19475        !strcasecmp(c, "application/vnd.nortelnetworks.digits") ||
19476        !strcasecmp(c, "application/dtmf")) {
19477       unsigned int duration = 0;
19478 
19479       if (!p->owner) {  /* not a PBX call */
19480          transmit_response(p, "481 Call leg/transaction does not exist", req);
19481          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19482          return;
19483       }
19484 
19485       /* If dtmf-relay or vnd.nortelnetworks.digits, parse the signal and duration;
19486        * otherwise use the body as the signal */
19487       if (strcasecmp(c, "application/dtmf")) {
19488          const char *msg_body;
19489 
19490          if (   ast_strlen_zero(msg_body = get_body(req, "Signal", '='))
19491             && ast_strlen_zero(msg_body = get_body(req, "d", '='))) {
19492             ast_log(LOG_WARNING, "Unable to retrieve DTMF signal for INFO message on "
19493                   "call %s\n", p->callid);
19494             transmit_response(p, "200 OK", req);
19495             return;
19496          }
19497          ast_copy_string(buf, msg_body, sizeof(buf));
19498 
19499          if (!ast_strlen_zero((msg_body = get_body(req, "Duration", '=')))) {
19500             sscanf(msg_body, "%30u", &duration);
19501          }
19502       } else {
19503          /* Type is application/dtmf, simply use what's in the message body */
19504          get_msg_text(buf, sizeof(buf), req);
19505       }
19506 
19507       /* An empty message body requires us to send a 200 OK */
19508       if (ast_strlen_zero(buf)) {
19509          transmit_response(p, "200 OK", req);
19510          return;
19511       }
19512 
19513       if (!duration) {
19514          duration = 100; /* 100 ms */
19515       }
19516 
19517       if (buf[0] == '*') {
19518          event = 10;
19519       } else if (buf[0] == '#') {
19520          event = 11;
19521       } else if (buf[0] == '!') {
19522          event = 16;
19523       } else if ('A' <= buf[0] && buf[0] <= 'D') {
19524          event = 12 + buf[0] - 'A';
19525       } else if ('a' <= buf[0] && buf[0] <= 'd') {
19526          event = 12 + buf[0] - 'a';
19527       } else if ((sscanf(buf, "%30u", &event) != 1) || event > 16) {
19528          ast_log(AST_LOG_WARNING, "Unable to convert DTMF event signal code to a valid "
19529                "value for INFO message on call %s\n", p->callid);
19530          transmit_response(p, "200 OK", req);
19531          return;
19532       }
19533 
19534       if (event == 16) {
19535          /* send a FLASH event */
19536          struct ast_frame f = { AST_FRAME_CONTROL, { AST_CONTROL_FLASH, } };
19537          ast_queue_frame(p->owner, &f);
19538          if (sipdebug) {
19539             ast_verbose("* DTMF-relay event received: FLASH\n");
19540          }
19541       } else {
19542          /* send a DTMF event */
19543          struct ast_frame f = { AST_FRAME_DTMF, };
19544          if (event < 10) {
19545             f.subclass.integer = '0' + event;
19546          } else if (event == 10) {
19547             f.subclass.integer = '*';
19548          } else if (event == 11) {
19549             f.subclass.integer = '#';
19550          } else {
19551             f.subclass.integer = 'A' + (event - 12);
19552          }
19553          f.len = duration;
19554          ast_queue_frame(p->owner, &f);
19555          if (sipdebug) {
19556             ast_verbose("* DTMF-relay event received: %c\n", (int) f.subclass.integer);
19557          }
19558       }
19559       transmit_response(p, "200 OK", req);
19560       return;
19561    } else if (!strcasecmp(c, "application/media_control+xml")) {
19562       /* Eh, we'll just assume it's a fast picture update for now */
19563       if (p->owner)
19564          ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
19565       transmit_response(p, "200 OK", req);
19566       return;
19567    } else if (!ast_strlen_zero(c = get_header(req, "X-ClientCode"))) {
19568       /* Client code (from SNOM phone) */
19569       if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
19570          if (p->owner && p->owner->cdr)
19571             ast_cdr_setuserfield(p->owner, c);
19572          if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr)
19573             ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
19574          transmit_response(p, "200 OK", req);
19575       } else {
19576          transmit_response(p, "403 Forbidden", req);
19577       }
19578       return;
19579    } else if (!ast_strlen_zero(c = get_header(req, "Record"))) {
19580       /* INFO messages generated by some phones to start/stop recording
19581          on phone calls.
19582          OEJ: I think this should be something that is enabled/disabled
19583          per device. I don't want incoming callers to record calls in my
19584          pbx.
19585       */
19586       
19587       struct ast_call_feature *feat;
19588       int j;
19589       struct ast_frame f = { AST_FRAME_DTMF, };
19590 
19591       if (!p->owner) {        /* not a PBX call */
19592          transmit_response(p, "481 Call leg/transaction does not exist", req);
19593          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19594          return;
19595       }
19596 
19597       /* first, get the feature string, if it exists */
19598       ast_rdlock_call_features();
19599       feat = ast_find_call_feature("automon");
19600       if (!feat || ast_strlen_zero(feat->exten)) {
19601          ast_log(LOG_WARNING, "Recording requested, but no One Touch Monitor registered. (See features.conf)\n");
19602          /* 403 means that we don't support this feature, so don't request it again */
19603          transmit_response(p, "403 Forbidden", req);
19604          ast_unlock_call_features();
19605          return;
19606       }
19607       /* Send the feature code to the PBX as DTMF, just like the handset had sent it */
19608       f.len = 100;
19609       for (j=0; j < strlen(feat->exten); j++) {
19610          f.subclass.integer = feat->exten[j];
19611          ast_queue_frame(p->owner, &f);
19612          if (sipdebug)
19613             ast_verbose("* DTMF-relay event faked: %c\n", f.subclass.integer);
19614       }
19615       ast_unlock_call_features();
19616 
19617       ast_debug(1, "Got a Request to Record the channel, state %s\n", c);
19618       transmit_response(p, "200 OK", req);
19619       return;
19620    } else if (ast_strlen_zero(c = get_header(req, "Content-Length")) || !strcasecmp(c, "0")) {
19621       /* This is probably just a packet making sure the signalling is still up, just send back a 200 OK */
19622       transmit_response(p, "200 OK", req);
19623       return;
19624    }
19625 
19626    /* Other type of INFO message, not really understood by Asterisk */
19627    /* if (get_msg_text(buf, sizeof(buf), req)) { */
19628 
19629    ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
19630    transmit_response(p, "415 Unsupported media type", req);
19631    return;
19632 }
19633 
19634 /*! \brief Enable SIP Debugging for a single IP */
19635 static char *sip_do_debug_ip(int fd, const char *arg)
19636 {
19637    if (ast_sockaddr_resolve_first_af(&debugaddr, arg, 0, 0)) {
19638       return CLI_SHOWUSAGE;
19639    }
19640 
19641    ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_sockaddr_stringify_addr(&debugaddr));
19642    sipdebug |= sip_debug_console;
19643 
19644    return CLI_SUCCESS;
19645 }
19646 
19647 /*! \brief  Turn on SIP debugging for a given peer */
19648 static char *sip_do_debug_peer(int fd, const char *arg)
19649 {
19650    struct sip_peer *peer = find_peer(arg, NULL, TRUE, FINDPEERS, FALSE, 0);
19651    if (!peer)
19652       ast_cli(fd, "No such peer '%s'\n", arg);
19653    else if (ast_sockaddr_isnull(&peer->addr))
19654       ast_cli(fd, "Unable to get IP address of peer '%s'\n", arg);
19655    else {
19656       ast_sockaddr_copy(&debugaddr, &peer->addr);
19657       ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_sockaddr_stringify_addr(&debugaddr));
19658       sipdebug |= sip_debug_console;
19659    }
19660    if (peer)
19661       unref_peer(peer, "sip_do_debug_peer: unref_peer, from find_peer call");
19662    return CLI_SUCCESS;
19663 }
19664 
19665 /*! \brief Turn on SIP debugging (CLI command) */
19666 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19667 {
19668    int oldsipdebug = sipdebug & sip_debug_console;
19669    const char *what;
19670 
19671    if (cmd == CLI_INIT) {
19672       e->command = "sip set debug {on|off|ip|peer}";
19673       e->usage =
19674          "Usage: sip set debug {off|on|ip addr[:port]|peer peername}\n"
19675          "       Globally disables dumping of SIP packets,\n"
19676          "       or enables it either globally or for a (single)\n"
19677          "       IP address or registered peer.\n";
19678       return NULL;
19679    } else if (cmd == CLI_GENERATE) {
19680       if (a->pos == 4 && !strcasecmp(a->argv[3], "peer"))
19681          return complete_sip_peer(a->word, a->n, 0);
19682       return NULL;
19683         }
19684 
19685    what = a->argv[e->args-1];      /* guaranteed to exist */
19686    if (a->argc == e->args) {       /* on/off */
19687       if (!strcasecmp(what, "on")) {
19688          sipdebug |= sip_debug_console;
19689          sipdebug_text = 1;   /*! \note this can be a special debug command - "sip debug text" or something */
19690          memset(&debugaddr, 0, sizeof(debugaddr));
19691          ast_cli(a->fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
19692          return CLI_SUCCESS;
19693       } else if (!strcasecmp(what, "off")) {
19694          sipdebug &= ~sip_debug_console;
19695          sipdebug_text = 0;
19696          ast_cli(a->fd, "SIP Debugging Disabled\n");
19697          return CLI_SUCCESS;
19698       }
19699    } else if (a->argc == e->args +1) {/* ip/peer */
19700       if (!strcasecmp(what, "ip"))
19701          return sip_do_debug_ip(a->fd, a->argv[e->args]);
19702       else if (!strcasecmp(what, "peer"))
19703          return sip_do_debug_peer(a->fd, a->argv[e->args]);
19704    }
19705    return CLI_SHOWUSAGE;   /* default, failure */
19706 }
19707 
19708 /*! \brief Cli command to send SIP notify to peer */
19709 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19710 {
19711    struct ast_variable *varlist;
19712    int i;
19713 
19714    switch (cmd) {
19715    case CLI_INIT:
19716       e->command = "sip notify";
19717       e->usage =
19718          "Usage: sip notify <type> <peer> [<peer>...]\n"
19719          "       Send a NOTIFY message to a SIP peer or peers\n"
19720          "       Message types are defined in sip_notify.conf\n";
19721       return NULL;
19722    case CLI_GENERATE:
19723       return complete_sipnotify(a->line, a->word, a->pos, a->n);
19724    }
19725 
19726    if (a->argc < 4)
19727       return CLI_SHOWUSAGE;
19728 
19729    if (!notify_types) {
19730       ast_cli(a->fd, "No %s file found, or no types listed there\n", notify_config);
19731       return CLI_FAILURE;
19732    }
19733 
19734    varlist = ast_variable_browse(notify_types, a->argv[2]);
19735 
19736    if (!varlist) {
19737       ast_cli(a->fd, "Unable to find notify type '%s'\n", a->argv[2]);
19738       return CLI_FAILURE;
19739    }
19740 
19741    for (i = 3; i < a->argc; i++) {
19742       struct sip_pvt *p;
19743       char buf[512];
19744       struct ast_variable *header, *var;
19745 
19746       if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
19747          ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
19748          return CLI_FAILURE;
19749       }
19750 
19751       if (create_addr(p, a->argv[i], NULL, 1)) {
19752          /* Maybe they're not registered, etc. */
19753          dialog_unlink_all(p);
19754          dialog_unref(p, "unref dialog inside for loop" );
19755          /* sip_destroy(p); */
19756          ast_cli(a->fd, "Could not create address for '%s'\n", a->argv[i]);
19757          continue;
19758       }
19759 
19760       /* Notify is outgoing call */
19761       ast_set_flag(&p->flags[0], SIP_OUTGOING);
19762       sip_notify_allocate(p);
19763       p->notify->headers = header = ast_variable_new("Subscription-State", "terminated", "");
19764 
19765       for (var = varlist; var; var = var->next) {
19766          ast_copy_string(buf, var->value, sizeof(buf));
19767          ast_unescape_semicolon(buf);
19768 
19769          if (!strcasecmp(var->name, "Content")) {
19770             if (ast_str_strlen(p->notify->content))
19771                ast_str_append(&p->notify->content, 0, "\r\n");
19772             ast_str_append(&p->notify->content, 0, "%s", buf);
19773          } else if (!strcasecmp(var->name, "Content-Length")) {
19774             ast_log(LOG_WARNING, "it is not necessary to specify Content-Length in sip_notify.conf, ignoring\n");
19775          } else {
19776             header->next = ast_variable_new(var->name, buf, "");
19777             header = header->next;
19778          }
19779       }
19780 
19781       /* Now that we have the peer's address, set our ip and change callid */
19782       ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
19783       build_via(p);
19784 
19785       change_callid_pvt(p, NULL);
19786 
19787       ast_cli(a->fd, "Sending NOTIFY of type '%s' to '%s'\n", a->argv[2], a->argv[i]);
19788       sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
19789       transmit_invite(p, SIP_NOTIFY, 0, 2, NULL);
19790       dialog_unref(p, "bump down the count of p since we're done with it.");
19791    }
19792 
19793    return CLI_SUCCESS;
19794 }
19795 
19796 /*! \brief Enable/Disable SIP History logging (CLI) */
19797 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19798 {
19799    switch (cmd) {
19800    case CLI_INIT:
19801       e->command = "sip set history {on|off}";
19802       e->usage =
19803          "Usage: sip set history {on|off}\n"
19804          "       Enables/Disables recording of SIP dialog history for debugging purposes.\n"
19805          "       Use 'sip show history' to view the history of a call number.\n";
19806       return NULL;
19807    case CLI_GENERATE:
19808       return NULL;
19809    }
19810 
19811    if (a->argc != e->args)
19812       return CLI_SHOWUSAGE;
19813 
19814    if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
19815       recordhistory = TRUE;
19816       ast_cli(a->fd, "SIP History Recording Enabled (use 'sip show history')\n");
19817    } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
19818       recordhistory = FALSE;
19819       ast_cli(a->fd, "SIP History Recording Disabled\n");
19820    } else {
19821       return CLI_SHOWUSAGE;
19822    }
19823    return CLI_SUCCESS;
19824 }
19825 
19826 /*! \brief Authenticate for outbound registration */
19827 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code)
19828 {
19829    char *header, *respheader;
19830    char digest[1024];
19831 
19832    p->authtries++;
19833    auth_headers(code, &header, &respheader);
19834    memset(digest, 0, sizeof(digest));
19835    if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
19836       /* There's nothing to use for authentication */
19837       /* No digest challenge in request */
19838       if (sip_debug_test_pvt(p) && p->registry)
19839          ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
19840          /* No old challenge */
19841       return -1;
19842    }
19843    if (p->do_history)
19844       append_history(p, "RegistryAuth", "Try: %d", p->authtries);
19845    if (sip_debug_test_pvt(p) && p->registry)
19846       ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
19847    return transmit_register(p->registry, SIP_REGISTER, digest, respheader);
19848 }
19849 
19850 /*! \brief Add authentication on outbound SIP packet */
19851 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code, int sipmethod, int init)
19852 {
19853    char *header, *respheader;
19854    char digest[1024];
19855 
19856    if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
19857       return -2;
19858 
19859    p->authtries++;
19860    auth_headers(code, &header, &respheader);
19861    ast_debug(2, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
19862    memset(digest, 0, sizeof(digest));
19863    if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
19864       /* No way to authenticate */
19865       return -1;
19866    }
19867    /* Now we have a reply digest */
19868    p->options->auth = digest;
19869    p->options->authheader = respheader;
19870    return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init, NULL);
19871 }
19872 
19873 /*! \brief  reply to authentication for outbound registrations
19874 \return  Returns -1 if we have no auth
19875 \note This is used for register= servers in sip.conf, SIP proxies we register
19876    with  for receiving calls from.  */
19877 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod,  char *digest, int digest_len)
19878 {
19879    char tmp[512];
19880    char *c;
19881    char oldnonce[256];
19882 
19883    /* table of recognised keywords, and places where they should be copied */
19884    const struct x {
19885       const char *key;
19886       const ast_string_field *field;
19887    } *i, keys[] = {
19888       { "realm=", &p->realm },
19889       { "nonce=", &p->nonce },
19890       { "opaque=", &p->opaque },
19891       { "qop=", &p->qop },
19892       { "domain=", &p->domain },
19893       { NULL, 0 },
19894    };
19895 
19896    ast_copy_string(tmp, get_header(req, header), sizeof(tmp));
19897    if (ast_strlen_zero(tmp))
19898       return -1;
19899    if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
19900       ast_log(LOG_WARNING, "missing Digest.\n");
19901       return -1;
19902    }
19903    c = tmp + strlen("Digest ");
19904    ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
19905    while (c && *(c = ast_skip_blanks(c))) {  /* lookup for keys */
19906       for (i = keys; i->key != NULL; i++) {
19907          char *src, *separator;
19908          if (strncasecmp(c, i->key, strlen(i->key)) != 0)
19909             continue;
19910          /* Found. Skip keyword, take text in quotes or up to the separator. */
19911          c += strlen(i->key);
19912          if (*c == '"') {
19913             src = ++c;
19914             separator = "\"";
19915          } else {
19916             src = c;
19917             separator = ",";
19918          }
19919          strsep(&c, separator); /* clear separator and move ptr */
19920          ast_string_field_ptr_set(p, i->field, src);
19921          break;
19922       }
19923       if (i->key == NULL) /* not found, try ',' */
19924          strsep(&c, ",");
19925    }
19926    /* Reset nonce count */
19927    if (strcmp(p->nonce, oldnonce))
19928       p->noncecount = 0;
19929 
19930    /* Save auth data for following registrations */
19931    if (p->registry) {
19932       struct sip_registry *r = p->registry;
19933 
19934       if (strcmp(r->nonce, p->nonce)) {
19935          ast_string_field_set(r, realm, p->realm);
19936          ast_string_field_set(r, nonce, p->nonce);
19937          ast_string_field_set(r, authdomain, p->domain);
19938          ast_string_field_set(r, opaque, p->opaque);
19939          ast_string_field_set(r, qop, p->qop);
19940          r->noncecount = 0;
19941       }
19942    }
19943    return build_reply_digest(p, sipmethod, digest, digest_len);
19944 }
19945 
19946 /*! \brief  Build reply digest
19947 \return  Returns -1 if we have no auth
19948 \note Build digest challenge for authentication of registrations and calls
19949    Also used for authentication of BYE
19950 */
19951 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
19952 {
19953    char a1[256];
19954    char a2[256];
19955    char a1_hash[256];
19956    char a2_hash[256];
19957    char resp[256];
19958    char resp_hash[256];
19959    char uri[256];
19960    char opaque[256] = "";
19961    char cnonce[80];
19962    const char *username;
19963    const char *secret;
19964    const char *md5secret;
19965    struct sip_auth *auth;  /* Realm authentication credential */
19966    struct sip_auth_container *credentials;
19967 
19968    if (!ast_strlen_zero(p->domain))
19969       snprintf(uri, sizeof(uri), "%s:%s", p->socket.type == SIP_TRANSPORT_TLS ? "sips" : "sip", p->domain);
19970    else if (!ast_strlen_zero(p->uri))
19971       ast_copy_string(uri, p->uri, sizeof(uri));
19972    else
19973       snprintf(uri, sizeof(uri), "%s:%s@%s", p->socket.type == SIP_TRANSPORT_TLS ? "sips" : "sip", p->username, ast_sockaddr_stringify_host_remote(&p->sa));
19974 
19975    snprintf(cnonce, sizeof(cnonce), "%08lx", (unsigned long)ast_random());
19976 
19977    /* Check if we have peer credentials */
19978    ao2_lock(p);
19979    credentials = p->peerauth;
19980    if (credentials) {
19981       ao2_t_ref(credentials, +1, "Ref peer auth for digest");
19982    }
19983    ao2_unlock(p);
19984    auth = find_realm_authentication(credentials, p->realm);
19985    if (!auth) {
19986       /* If not, check global credentials */
19987       if (credentials) {
19988          ao2_t_ref(credentials, -1, "Unref peer auth for digest");
19989       }
19990       ast_mutex_lock(&authl_lock);
19991       credentials = authl;
19992       if (credentials) {
19993          ao2_t_ref(credentials, +1, "Ref global auth for digest");
19994       }
19995       ast_mutex_unlock(&authl_lock);
19996       auth = find_realm_authentication(credentials, p->realm);
19997    }
19998 
19999    if (auth) {
20000       ast_debug(3, "use realm [%s] from peer [%s][%s]\n", auth->username, p->peername, p->username);
20001       username = auth->username;
20002       secret = auth->secret;
20003       md5secret = auth->md5secret;
20004       if (sipdebug)
20005          ast_debug(1, "Using realm %s authentication for call %s\n", p->realm, p->callid);
20006    } else {
20007       /* No authentication, use peer or register= config */
20008       username = p->authname;
20009       secret = p->relatedpeer 
20010          && !ast_strlen_zero(p->relatedpeer->remotesecret)
20011             ? p->relatedpeer->remotesecret : p->peersecret;
20012       md5secret = p->peermd5secret;
20013    }
20014    if (ast_strlen_zero(username)) {
20015       /* We have no authentication */
20016       if (credentials) {
20017          ao2_t_ref(credentials, -1, "Unref auth for digest");
20018       }
20019       return -1;
20020    }
20021 
20022    /* Calculate SIP digest response */
20023    snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
20024    snprintf(a2, sizeof(a2), "%s:%s", sip_methods[method].text, uri);
20025    if (!ast_strlen_zero(md5secret))
20026       ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
20027    else
20028       ast_md5_hash(a1_hash, a1);
20029    ast_md5_hash(a2_hash, a2);
20030 
20031    p->noncecount++;
20032    if (!ast_strlen_zero(p->qop))
20033       snprintf(resp, sizeof(resp), "%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, (unsigned)p->noncecount, cnonce, "auth", a2_hash);
20034    else
20035       snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, p->nonce, a2_hash);
20036    ast_md5_hash(resp_hash, resp);
20037 
20038    /* only include the opaque string if it's set */
20039    if (!ast_strlen_zero(p->opaque)) {
20040       snprintf(opaque, sizeof(opaque), ", opaque=\"%s\"", p->opaque);
20041    }
20042 
20043    /* XXX We hard code our qop to "auth" for now.  XXX */
20044    if (!ast_strlen_zero(p->qop))
20045       snprintf(digest, digest_len, "Digest username=\"%s\", realm=\"%s\", algorithm=MD5, uri=\"%s\", nonce=\"%s\", response=\"%s\"%s, qop=auth, cnonce=\"%s\", nc=%08x", username, p->realm, uri, p->nonce, resp_hash, opaque, cnonce, (unsigned)p->noncecount);
20046    else
20047       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);
20048 
20049    append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);
20050 
20051    if (credentials) {
20052       ao2_t_ref(credentials, -1, "Unref auth for digest");
20053    }
20054    return 0;
20055 }
20056    
20057 /*! \brief Read SIP header (dialplan function) */
20058 static int func_header_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len)
20059 {
20060    struct sip_pvt *p;
20061    const char *content = NULL;
20062    AST_DECLARE_APP_ARGS(args,
20063       AST_APP_ARG(header);
20064       AST_APP_ARG(number);
20065    );
20066    int i, number, start = 0;
20067 
20068    if (!chan) {
20069       ast_log(LOG_WARNING, "No channel was provided to %s function.\n", function);
20070       return -1;
20071    }
20072 
20073    if (ast_strlen_zero(data)) {
20074       ast_log(LOG_WARNING, "This function requires a header name.\n");
20075       return -1;
20076    }
20077 
20078    ast_channel_lock(chan);
20079    if (!IS_SIP_TECH(chan->tech)) {
20080       ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
20081       ast_channel_unlock(chan);
20082       return -1;
20083    }
20084 
20085    AST_STANDARD_APP_ARGS(args, data);
20086    if (!args.number) {
20087       number = 1;
20088    } else {
20089       sscanf(args.number, "%30d", &number);
20090       if (number < 1)
20091          number = 1;
20092    }
20093 
20094    p = chan->tech_pvt;
20095 
20096    /* If there is no private structure, this channel is no longer alive */
20097    if (!p) {
20098       ast_channel_unlock(chan);
20099       return -1;
20100    }
20101 
20102    for (i = 0; i < number; i++)
20103       content = __get_header(&p->initreq, args.header, &start);
20104 
20105    if (ast_strlen_zero(content)) {
20106       ast_channel_unlock(chan);
20107       return -1;
20108    }
20109 
20110    ast_copy_string(buf, content, len);
20111    ast_channel_unlock(chan);
20112 
20113    return 0;
20114 }
20115 
20116 static struct ast_custom_function sip_header_function = {
20117    .name = "SIP_HEADER",
20118    .read = func_header_read,
20119 };
20120 
20121 /*! \brief  Dial plan function to check if domain is local */
20122 static int func_check_sipdomain(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
20123 {
20124    if (ast_strlen_zero(data)) {
20125       ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
20126       return -1;
20127    }
20128    if (check_sip_domain(data, NULL, 0))
20129       ast_copy_string(buf, data, len);
20130    else
20131       buf[0] = '\0';
20132    return 0;
20133 }
20134 
20135 static struct ast_custom_function checksipdomain_function = {
20136    .name = "CHECKSIPDOMAIN",
20137    .read = func_check_sipdomain,
20138 };
20139 
20140 /*! \brief  ${SIPPEER()} Dialplan function - reads peer data */
20141 static int function_sippeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
20142 {
20143    struct sip_peer *peer;
20144    char *colname;
20145 
20146    if ((colname = strchr(data, ':'))) {   /*! \todo Will be deprecated after 1.4 */
20147       static int deprecation_warning = 0;
20148       *colname++ = '\0';
20149       if (deprecation_warning++ % 10 == 0)
20150          ast_log(LOG_WARNING, "SIPPEER(): usage of ':' to separate arguments is deprecated.  Please use ',' instead.\n");
20151    } else if ((colname = strchr(data, ',')))
20152       *colname++ = '\0';
20153    else
20154       colname = "ip";
20155 
20156    if (!(peer = find_peer(data, NULL, TRUE, FINDPEERS, FALSE, 0)))
20157       return -1;
20158 
20159    if (!strcasecmp(colname, "ip")) {
20160       ast_copy_string(buf, ast_sockaddr_stringify_addr(&peer->addr), len);
20161    } else  if (!strcasecmp(colname, "port")) {
20162       snprintf(buf, len, "%d", ast_sockaddr_port(&peer->addr));
20163    } else  if (!strcasecmp(colname, "status")) {
20164       peer_status(peer, buf, len);
20165    } else  if (!strcasecmp(colname, "language")) {
20166       ast_copy_string(buf, peer->language, len);
20167    } else  if (!strcasecmp(colname, "regexten")) {
20168       ast_copy_string(buf, peer->regexten, len);
20169    } else  if (!strcasecmp(colname, "limit")) {
20170       snprintf(buf, len, "%d", peer->call_limit);
20171    } else  if (!strcasecmp(colname, "busylevel")) {
20172       snprintf(buf, len, "%d", peer->busy_level);
20173    } else  if (!strcasecmp(colname, "curcalls")) {
20174       snprintf(buf, len, "%d", peer->inUse);
20175    } else if (!strcasecmp(colname, "maxforwards")) {
20176       snprintf(buf, len, "%d", peer->maxforwards);
20177    } else  if (!strcasecmp(colname, "accountcode")) {
20178       ast_copy_string(buf, peer->accountcode, len);
20179    } else  if (!strcasecmp(colname, "callgroup")) {
20180       ast_print_group(buf, len, peer->callgroup);
20181    } else  if (!strcasecmp(colname, "pickupgroup")) {
20182       ast_print_group(buf, len, peer->pickupgroup);
20183    } else  if (!strcasecmp(colname, "useragent")) {
20184       ast_copy_string(buf, peer->useragent, len);
20185    } else  if (!strcasecmp(colname, "mailbox")) {
20186       struct ast_str *mailbox_str = ast_str_alloca(512);
20187       peer_mailboxes_to_str(&mailbox_str, peer);
20188       ast_copy_string(buf, ast_str_buffer(mailbox_str), len);
20189    } else  if (!strcasecmp(colname, "context")) {
20190       ast_copy_string(buf, peer->context, len);
20191    } else  if (!strcasecmp(colname, "expire")) {
20192       snprintf(buf, len, "%d", peer->expire);
20193    } else  if (!strcasecmp(colname, "dynamic")) {
20194       ast_copy_string(buf, peer->host_dynamic ? "yes" : "no", len);
20195    } else  if (!strcasecmp(colname, "callerid_name")) {
20196       ast_copy_string(buf, peer->cid_name, len);
20197    } else  if (!strcasecmp(colname, "callerid_num")) {
20198       ast_copy_string(buf, peer->cid_num, len);
20199    } else  if (!strcasecmp(colname, "codecs")) {
20200       ast_getformatname_multiple(buf, len -1, peer->capability);
20201    } else if (!strcasecmp(colname, "encryption")) {
20202       snprintf(buf, len, "%u", ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP));
20203    } else  if (!strncasecmp(colname, "chanvar[", 8)) {
20204       char *chanvar=colname + 8;
20205       struct ast_variable *v;
20206    
20207       chanvar = strsep(&chanvar, "]");
20208       for (v = peer->chanvars ; v ; v = v->next) {
20209          if (!strcasecmp(v->name, chanvar)) {
20210             ast_copy_string(buf, v->value, len);
20211          }
20212       }
20213    } else  if (!strncasecmp(colname, "codec[", 6)) {
20214       char *codecnum;
20215       format_t codec = 0;
20216       
20217       codecnum = colname + 6; /* move past the '[' */
20218       codecnum = strsep(&codecnum, "]"); /* trim trailing ']' if any */
20219       if((codec = ast_codec_pref_index(&peer->prefs, atoi(codecnum)))) {
20220          ast_copy_string(buf, ast_getformatname(codec), len);
20221       } else {
20222          buf[0] = '\0';
20223       }
20224    } else {
20225       buf[0] = '\0';
20226    }
20227 
20228    unref_peer(peer, "unref_peer from function_sippeer, just before return");
20229 
20230    return 0;
20231 }
20232 
20233 /*! \brief Structure to declare a dialplan function: SIPPEER */
20234 static struct ast_custom_function sippeer_function = {
20235    .name = "SIPPEER",
20236    .read = function_sippeer,
20237 };
20238 
20239 /*! \brief ${SIPCHANINFO()} Dialplan function - reads sip channel data */
20240 static int function_sipchaninfo_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
20241 {
20242    struct sip_pvt *p;
20243    static int deprecated = 0;
20244 
20245    *buf = 0;
20246 
20247    if (!chan) {
20248       ast_log(LOG_WARNING, "No channel was provided to %s function.\n", cmd);
20249       return -1;
20250    }
20251 
20252    if (!data) {
20253       ast_log(LOG_WARNING, "This function requires a parameter name.\n");
20254       return -1;
20255    }
20256 
20257    ast_channel_lock(chan);
20258    if (!IS_SIP_TECH(chan->tech)) {
20259       ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
20260       ast_channel_unlock(chan);
20261       return -1;
20262    }
20263 
20264    if (deprecated++ % 20 == 0) {
20265       /* Deprecated in 1.6.1 */
20266       ast_log(LOG_WARNING, "SIPCHANINFO() is deprecated.  Please transition to using CHANNEL().\n");
20267    }
20268 
20269    p = chan->tech_pvt;
20270 
20271    /* If there is no private structure, this channel is no longer alive */
20272    if (!p) {
20273       ast_channel_unlock(chan);
20274       return -1;
20275    }
20276 
20277    if (!strcasecmp(data, "peerip")) {
20278       ast_copy_string(buf, ast_sockaddr_stringify_addr(&p->sa), len);
20279    } else  if (!strcasecmp(data, "recvip")) {
20280       ast_copy_string(buf, ast_sockaddr_stringify_addr(&p->recv), len);
20281    } else  if (!strcasecmp(data, "from")) {
20282       ast_copy_string(buf, p->from, len);
20283    } else  if (!strcasecmp(data, "uri")) {
20284       ast_copy_string(buf, p->uri, len);
20285    } else  if (!strcasecmp(data, "useragent")) {
20286       ast_copy_string(buf, p->useragent, len);
20287    } else  if (!strcasecmp(data, "peername")) {
20288       ast_copy_string(buf, p->peername, len);
20289    } else if (!strcasecmp(data, "t38passthrough")) {
20290       if (p->t38.state == T38_DISABLED) {
20291          ast_copy_string(buf, "0", len);
20292       } else { /* T38 is offered or enabled in this call */
20293          ast_copy_string(buf, "1", len);
20294       }
20295    } else {
20296       ast_channel_unlock(chan);
20297       return -1;
20298    }
20299    ast_channel_unlock(chan);
20300 
20301    return 0;
20302 }
20303 
20304 /*! \brief Structure to declare a dialplan function: SIPCHANINFO */
20305 static struct ast_custom_function sipchaninfo_function = {
20306    .name = "SIPCHANINFO",
20307    .read = function_sipchaninfo_read,
20308 };
20309 
20310 /*! \brief update redirecting information for a channel based on headers
20311  *
20312  */
20313 static void change_redirecting_information(struct sip_pvt *p, struct sip_request *req,
20314    struct ast_party_redirecting *redirecting,
20315    struct ast_set_party_redirecting *update_redirecting, int set_call_forward)
20316 {
20317    char *redirecting_from_name = NULL;
20318    char *redirecting_from_number = NULL;
20319    char *redirecting_to_name = NULL;
20320    char *redirecting_to_number = NULL;
20321    int reason = AST_REDIRECTING_REASON_UNCONDITIONAL;
20322    int is_response = req->method == SIP_RESPONSE;
20323    int res = 0;
20324 
20325    res = get_rdnis(p, req, &redirecting_from_name, &redirecting_from_number, &reason);
20326    if (res == -1) {
20327       if (is_response) {
20328          get_name_and_number(get_header(req, "TO"), &redirecting_from_name, &redirecting_from_number);
20329       } else {
20330          return;
20331       }
20332    }
20333 
20334    /* At this point, all redirecting "from" info should be filled in appropriately
20335     * on to the "to" info
20336     */
20337 
20338    if (is_response) {
20339       parse_moved_contact(p, req, &redirecting_to_name, &redirecting_to_number, set_call_forward);
20340    } else {
20341       get_name_and_number(get_header(req, "TO"), &redirecting_to_name, &redirecting_to_number);
20342    }
20343 
20344    if (!ast_strlen_zero(redirecting_from_number)) {
20345       ast_debug(3, "Got redirecting from number %s\n", redirecting_from_number);
20346       update_redirecting->from.number = 1;
20347       redirecting->from.number.valid = 1;
20348       ast_free(redirecting->from.number.str);
20349       redirecting->from.number.str = redirecting_from_number;
20350    }
20351    if (!ast_strlen_zero(redirecting_from_name)) {
20352       ast_debug(3, "Got redirecting from name %s\n", redirecting_from_name);
20353       update_redirecting->from.name = 1;
20354       redirecting->from.name.valid = 1;
20355       ast_free(redirecting->from.name.str);
20356       redirecting->from.name.str = redirecting_from_name;
20357    }
20358    if (!ast_strlen_zero(p->cid_tag)) {
20359       ast_free(redirecting->from.tag);
20360       redirecting->from.tag = ast_strdup(p->cid_tag);
20361       ast_free(redirecting->to.tag);
20362       redirecting->to.tag = ast_strdup(p->cid_tag);
20363    }
20364    if (!ast_strlen_zero(redirecting_to_number)) {
20365       ast_debug(3, "Got redirecting to number %s\n", redirecting_to_number);
20366       update_redirecting->to.number = 1;
20367       redirecting->to.number.valid = 1;
20368       ast_free(redirecting->to.number.str);
20369       redirecting->to.number.str = redirecting_to_number;
20370    }
20371    if (!ast_strlen_zero(redirecting_to_name)) {
20372       ast_debug(3, "Got redirecting to name %s\n", redirecting_from_number);
20373       update_redirecting->to.name = 1;
20374       redirecting->to.name.valid = 1;
20375       ast_free(redirecting->to.name.str);
20376       redirecting->to.name.str = redirecting_to_name;
20377    }
20378    redirecting->reason = reason;
20379 }
20380 
20381 /*! \brief Parse 302 Moved temporalily response
20382    \todo XXX Doesn't redirect over TLS on sips: uri's.
20383       If we get a redirect to a SIPS: uri, this needs to be going back to the
20384       dialplan (this is a request for a secure signalling path).
20385       Note that transport=tls is deprecated, but we need to support it on incoming requests.
20386 */
20387 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward)
20388 {
20389    char contact[SIPBUFSIZE];
20390    char *contact_name = NULL;
20391    char *contact_number = NULL;
20392    char *separator, *trans;
20393    char *domain;
20394    enum sip_transport transport = SIP_TRANSPORT_UDP;
20395 
20396    ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
20397    if ((separator = strchr(contact, ',')))
20398       *separator = '\0';
20399 
20400    contact_number = get_in_brackets(contact);
20401    if ((trans = strcasestr(contact_number, ";transport="))) {
20402       trans += 11;
20403 
20404       if ((separator = strchr(trans, ';')))
20405          *separator = '\0';
20406 
20407       if (!strncasecmp(trans, "tcp", 3))
20408          transport = SIP_TRANSPORT_TCP;
20409       else if (!strncasecmp(trans, "tls", 3))
20410          transport = SIP_TRANSPORT_TLS;
20411       else {
20412          if (strncasecmp(trans, "udp", 3))
20413             ast_debug(1, "received contact with an invalid transport, '%s'\n", contact_number);
20414          /* This will assume UDP for all unknown transports */
20415          transport = SIP_TRANSPORT_UDP;
20416       }
20417    }
20418    contact_number = remove_uri_parameters(contact_number);
20419 
20420    if (p->socket.tcptls_session) {
20421       ao2_ref(p->socket.tcptls_session, -1);
20422       p->socket.tcptls_session = NULL;
20423    }
20424 
20425    set_socket_transport(&p->socket, transport);
20426 
20427    if (set_call_forward && ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
20428       char *host = NULL;
20429       if (!strncasecmp(contact_number, "sip:", 4))
20430          contact_number += 4;
20431       else if (!strncasecmp(contact_number, "sips:", 5))
20432          contact_number += 5;
20433       separator = strchr(contact_number, '/');
20434       if (separator)
20435          *separator = '\0';
20436       if ((host = strchr(contact_number, '@'))) {
20437          *host++ = '\0';
20438          ast_debug(2, "Found promiscuous redirection to 'SIP/%s::::%s@%s'\n", contact_number, get_transport(transport), host);
20439          if (p->owner)
20440             ast_string_field_build(p->owner, call_forward, "SIP/%s::::%s@%s", contact_number, get_transport(transport), host);
20441       } else {
20442          ast_debug(2, "Found promiscuous redirection to 'SIP/::::%s@%s'\n", get_transport(transport), contact_number);
20443          if (p->owner)
20444             ast_string_field_build(p->owner, call_forward, "SIP/::::%s@%s", get_transport(transport), contact_number);
20445       }
20446    } else {
20447       separator = strchr(contact, '@');
20448       if (separator) {
20449          *separator++ = '\0';
20450          domain = separator;
20451       } else {
20452          /* No username part */
20453          domain = contact;
20454       }
20455       separator = strchr(contact, '/');   /* WHEN do we hae a forward slash in the URI? */
20456       if (separator)
20457          *separator = '\0';
20458 
20459       if (!strncasecmp(contact_number, "sip:", 4))
20460          contact_number += 4;
20461       else if (!strncasecmp(contact_number, "sips:", 5))
20462          contact_number += 5;
20463       separator = strchr(contact_number, ';');  /* And username ; parameters? */
20464       if (separator)
20465          *separator = '\0';
20466       ast_uri_decode(contact_number);
20467       if (set_call_forward) {
20468          ast_debug(2, "Received 302 Redirect to extension '%s' (domain %s)\n", contact_number, domain);
20469          if (p->owner) {
20470             pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
20471             ast_string_field_set(p->owner, call_forward, contact_number);
20472          }
20473       }
20474    }
20475 
20476    /* We've gotten the number for the contact, now get the name */
20477 
20478    if (*contact == '\"') {
20479       contact_name = contact + 1;
20480       if (!(separator = (char *)find_closing_quote(contact_name, NULL))) {
20481          ast_log(LOG_NOTICE, "No closing quote on name in Contact header? %s\n", contact);
20482       }
20483       *separator = '\0';
20484    }
20485 
20486    if (name && !ast_strlen_zero(contact_name)) {
20487       *name = ast_strdup(contact_name);
20488    }
20489    if (number) {
20490       *number = ast_strdup(contact_number);
20491    }
20492 }
20493 
20494 /*! \brief Check pending actions on SIP call 
20495  *
20496  * \note both sip_pvt and sip_pvt's owner channel (if present)
20497  *  must be locked for this function.
20498  */
20499 static void check_pendings(struct sip_pvt *p)
20500 {
20501    if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
20502       if (p->reinviteid > -1) {
20503          /* Outstanding p->reinviteid timeout, so wait... */
20504          return;
20505       } else if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA) {
20506          /* if we can't BYE, then this is really a pending CANCEL */
20507          p->invitestate = INV_CANCELLED;
20508          transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
20509          /* If the cancel occurred on an initial invite, cancel the pending BYE */
20510          if (!ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
20511             ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);
20512          }
20513          /* Actually don't destroy us yet, wait for the 487 on our original
20514             INVITE, but do set an autodestruct just in case we never get it. */
20515       } else {
20516          /* We have a pending outbound invite, don't send something
20517           * new in-transaction, unless it is a pending reinvite, then
20518           * by the time we are called here, we should probably just hang up. */
20519          if (p->pendinginvite && !p->ongoing_reinvite)
20520             return;
20521 
20522          if (p->owner) {
20523             ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
20524          }
20525          /* Perhaps there is an SD change INVITE outstanding */
20526          transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
20527          ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);
20528       }
20529       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20530    } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
20531       /* if we can't REINVITE, hold it for later */
20532       if (p->pendinginvite || p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA || p->waitid > 0) {
20533          ast_debug(2, "NOT Sending pending reinvite (yet) on '%s'\n", p->callid);
20534       } else {
20535          ast_debug(2, "Sending pending reinvite on '%s'\n", p->callid);
20536          /* Didn't get to reinvite yet, so do it now */
20537          transmit_reinvite_with_sdp(p, (p->t38.state == T38_LOCAL_REINVITE ? TRUE : FALSE), FALSE);
20538          ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE); 
20539       }
20540    }
20541 }
20542 
20543 /*! \brief Reset the NEEDREINVITE flag after waiting when we get 491 on a Re-invite
20544    to avoid race conditions between asterisk servers.
20545    Called from the scheduler.
20546 */
20547 static int sip_reinvite_retry(const void *data)
20548 {
20549    struct sip_pvt *p = (struct sip_pvt *) data;
20550    struct ast_channel *owner;
20551 
20552    sip_pvt_lock(p); /* called from schedule thread which requires a lock */
20553    while ((owner = p->owner) && ast_channel_trylock(owner)) {
20554       sip_pvt_unlock(p);
20555       usleep(1);
20556       sip_pvt_lock(p);
20557    }
20558    ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
20559    p->waitid = -1;
20560    check_pendings(p);
20561    sip_pvt_unlock(p);
20562    if (owner) {
20563       ast_channel_unlock(owner);
20564    }
20565    dialog_unref(p, "unref the dialog ptr from sip_reinvite_retry, because it held a dialog ptr");
20566    return 0;
20567 }
20568 
20569 /*!
20570  * \brief Handle authentication challenge for SIP UPDATE
20571  *
20572  * This function is only called upon the receipt of a 401/407 response to an UPDATE.
20573  */
20574 static void handle_response_update(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
20575 {
20576    if (p->options) {
20577       p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
20578    }
20579    if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, SIP_UPDATE, 1)) {
20580       ast_log(LOG_NOTICE, "Failed to authenticate on UPDATE to '%s'\n", get_header(&p->initreq, "From"));
20581    }
20582 }
20583 
20584 static void cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry)
20585 {
20586    struct cc_epa_entry *cc_entry = epa_entry->instance_data;
20587    struct sip_monitor_instance *monitor_instance = ao2_callback(sip_monitor_instances, 0,
20588          find_sip_monitor_instance_by_suspension_entry, epa_entry);
20589    const char *min_expires;
20590 
20591    if (!monitor_instance) {
20592       ast_log(LOG_WARNING, "Can't find monitor_instance corresponding to epa_entry %p.\n", epa_entry);
20593       return;
20594    }
20595 
20596    if (resp != 423) {
20597       ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
20598             "Received error response to our PUBLISH");
20599       ao2_ref(monitor_instance, -1);
20600       return;
20601    }
20602 
20603    /* Allrighty, the other end doesn't like our Expires value. They think it's
20604     * too small, so let's see if they've provided a more sensible value. If they
20605     * haven't, then we'll just double our Expires value and see if they like that
20606     * instead.
20607     *
20608     * XXX Ideally this logic could be placed into its own function so that SUBSCRIBE,
20609     * PUBLISH, and REGISTER could all benefit from the same shared code.
20610     */
20611    min_expires = get_header(req, "Min-Expires");
20612    if (ast_strlen_zero(min_expires)) {
20613       pvt->expiry *= 2;
20614       if (pvt->expiry < 0) {
20615          /* You dork! You overflowed! */
20616          ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
20617                "PUBLISH expiry overflowed");
20618          ao2_ref(monitor_instance, -1);
20619          return;
20620       }
20621    } else if (sscanf(min_expires, "%d", &pvt->expiry) != 1) {
20622       ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
20623             "Min-Expires has non-numeric value");
20624       ao2_ref(monitor_instance, -1);
20625       return;
20626    }
20627    /* At this point, we have most certainly changed pvt->expiry, so try transmitting
20628     * again
20629     */
20630    transmit_invite(pvt, SIP_PUBLISH, FALSE, 0, NULL);
20631    ao2_ref(monitor_instance, -1);
20632 }
20633 
20634 static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
20635 {
20636    struct sip_epa_entry *epa_entry = p->epa_entry;
20637    const char *etag = get_header(req, "Sip-ETag");
20638 
20639    ast_assert(epa_entry != NULL);
20640 
20641    if (resp == 401 || resp == 407) {
20642       ast_string_field_set(p, theirtag, NULL);
20643       if (p->options) {
20644          p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
20645       }
20646       if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, SIP_PUBLISH, 0)) {
20647          ast_log(LOG_NOTICE, "Failed to authenticate on PUBLISH to '%s'\n", get_header(&p->initreq, "From"));
20648          pvt_set_needdestroy(p, "Failed to authenticate on PUBLISH");
20649          sip_alreadygone(p);
20650       }
20651       return;
20652    }
20653 
20654    if (resp == 501 || resp == 405) {
20655       mark_method_unallowed(&p->allowed_methods, SIP_PUBLISH);
20656    }
20657 
20658    if (resp == 200) {
20659       p->authtries = 0;
20660       /* If I've read section 6, item 6 of RFC 3903 correctly,
20661        * an ESC will only generate a new etag when it sends a 200 OK
20662        */
20663       if (!ast_strlen_zero(etag)) {
20664          ast_copy_string(epa_entry->entity_tag, etag, sizeof(epa_entry->entity_tag));
20665       }
20666       /* The nominal case. Everything went well. Everybody is happy.
20667        * Each EPA will have a specific action to take as a result of this
20668        * development, so ... callbacks!
20669        */
20670       if (epa_entry->static_data->handle_ok) {
20671          epa_entry->static_data->handle_ok(p, req, epa_entry);
20672       }
20673    } else {
20674       /* Rather than try to make individual callbacks for each error
20675        * type, there is just a single error callback. The callback
20676        * can distinguish between error messages and do what it needs to
20677        */
20678       if (epa_entry->static_data->handle_error) {
20679          epa_entry->static_data->handle_error(p, resp, req, epa_entry);
20680       }
20681    }
20682 }
20683 
20684 /*!
20685  * \internal
20686  * \brief Set hangup source and cause.
20687  *
20688  * \param p SIP private.
20689  * \param cause Hangup cause to queue.  Zero if no cause.
20690  *
20691  * \pre p and p->owner are locked.
20692  *
20693  * \return Nothing
20694  */
20695 static void sip_queue_hangup_cause(struct sip_pvt *p, int cause)
20696 {
20697    struct ast_channel *owner = p->owner;
20698    const char *name = ast_strdupa(owner->name);
20699 
20700    /* Cannot hold any channel/private locks when calling. */
20701    ast_channel_ref(owner);
20702    ast_channel_unlock(owner);
20703    sip_pvt_unlock(p);
20704    ast_set_hangupsource(owner, name, 0);
20705    if (cause) {
20706       ast_queue_hangup_with_cause(owner, cause);
20707    } else {
20708       ast_queue_hangup(owner);
20709    }
20710    ast_channel_unref(owner);
20711 
20712    /* Relock things. */
20713    owner = sip_pvt_lock_full(p);
20714    if (owner) {
20715       ast_channel_unref(owner);
20716    }
20717 }
20718 
20719 /*! \brief Handle SIP response to INVITE dialogue */
20720 static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
20721 {
20722    int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
20723    int res = 0;
20724    int xmitres = 0;
20725    int reinvite = ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
20726    char *p_hdrval;
20727    int rtn;
20728    struct ast_party_connected_line connected;
20729    struct ast_set_party_connected_line update_connected;
20730 
20731    if (reinvite)
20732       ast_debug(4, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
20733    else
20734       ast_debug(4, "SIP response %d to standard invite\n", resp);
20735 
20736    if (p->alreadygone) { /* This call is already gone */
20737       ast_debug(1, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
20738       return;
20739    }
20740 
20741    /* Acknowledge sequence number - This only happens on INVITE from SIP-call */
20742    /* Don't auto congest anymore since we've gotten something useful back */
20743    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"));
20744 
20745    /* RFC3261 says we must treat every 1xx response (but not 100)
20746       that we don't recognize as if it was 183.
20747    */
20748    if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 181 && resp != 182 && resp != 183)
20749       resp = 183;
20750 
20751    /* Any response between 100 and 199 is PROCEEDING */
20752    if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING)
20753       p->invitestate = INV_PROCEEDING;
20754 
20755    /* Final response, not 200 ? */
20756    if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA ))
20757       p->invitestate = INV_COMPLETED;
20758    
20759    if ((resp >= 200 && reinvite)) {
20760       p->ongoing_reinvite = 0;
20761       if (p->reinviteid > -1) {
20762          AST_SCHED_DEL_UNREF(sched, p->reinviteid, dialog_unref(p, "unref dialog for reinvite timeout because of a final response"));
20763       }
20764    }
20765 
20766    /* Final response, clear out pending invite */
20767    if ((resp == 200 || resp >= 300) && p->pendinginvite && seqno == p->pendinginvite) {
20768       p->pendinginvite = 0;
20769    }
20770 
20771    /* If this is a response to our initial INVITE, we need to set what we can use
20772     * for this peer.
20773     */
20774    if (!reinvite) {
20775       set_pvt_allowed_methods(p, req);
20776    }
20777 
20778    switch (resp) {
20779    case 100:   /* Trying */
20780    case 101:   /* Dialog establishment */
20781       if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
20782          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
20783       check_pendings(p);
20784       break;
20785 
20786    case 180:   /* 180 Ringing */
20787    case 182:       /* 182 Queued */
20788       if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
20789          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
20790       /* Store Route-set from provisional SIP responses so
20791        * early-dialog request can be routed properly
20792        * */
20793       parse_ok_contact(p, req);
20794       if (!reinvite) {
20795          build_route(p, req, 1, resp);
20796       }
20797       if (!req->ignore && p->owner) {
20798          if (get_rpid(p, req)) {
20799             /* Queue a connected line update */
20800             ast_party_connected_line_init(&connected);
20801             memset(&update_connected, 0, sizeof(update_connected));
20802 
20803             update_connected.id.number = 1;
20804             connected.id.number.valid = 1;
20805             connected.id.number.str = (char *) p->cid_num;
20806             connected.id.number.presentation = p->callingpres;
20807 
20808             update_connected.id.name = 1;
20809             connected.id.name.valid = 1;
20810             connected.id.name.str = (char *) p->cid_name;
20811             connected.id.name.presentation = p->callingpres;
20812 
20813             connected.id.tag = (char *) p->cid_tag;
20814             connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
20815             ast_channel_queue_connected_line_update(p->owner, &connected,
20816                &update_connected);
20817          }
20818          sip_handle_cc(p, req, AST_CC_CCNR);
20819          ast_queue_control(p->owner, AST_CONTROL_RINGING);
20820          if (p->owner->_state != AST_STATE_UP) {
20821             ast_setstate(p->owner, AST_STATE_RINGING);
20822          }
20823       }
20824       if (find_sdp(req)) {
20825          if (p->invitestate != INV_CANCELLED)
20826             p->invitestate = INV_EARLY_MEDIA;
20827          res = process_sdp(p, req, SDP_T38_NONE);
20828          if (!req->ignore && p->owner) {
20829             /* Queue a progress frame only if we have SDP in 180 or 182 */
20830             ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
20831          }
20832          ast_rtp_instance_activate(p->rtp);
20833       }
20834       check_pendings(p);
20835       break;
20836 
20837    case 181:   /* Call Is Being Forwarded */
20838       if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
20839          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
20840       /* Store Route-set from provisional SIP responses so
20841        * early-dialog request can be routed properly
20842        * */
20843       parse_ok_contact(p, req);
20844       if (!reinvite) {
20845          build_route(p, req, 1, resp);
20846       }
20847       if (!req->ignore && p->owner) {
20848          struct ast_party_redirecting redirecting;
20849          struct ast_set_party_redirecting update_redirecting;
20850 
20851          ast_party_redirecting_init(&redirecting);
20852          memset(&update_redirecting, 0, sizeof(update_redirecting));
20853          change_redirecting_information(p, req, &redirecting, &update_redirecting,
20854             FALSE);
20855          ast_channel_queue_redirecting_update(p->owner, &redirecting,
20856             &update_redirecting);
20857          ast_party_redirecting_free(&redirecting);
20858          sip_handle_cc(p, req, AST_CC_CCNR);
20859       }
20860       check_pendings(p);
20861       break;
20862 
20863    case 183:   /* Session progress */
20864       if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
20865          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
20866       /* Store Route-set from provisional SIP responses so
20867        * early-dialog request can be routed properly
20868        * */
20869       parse_ok_contact(p, req);
20870       if (!reinvite) {
20871          build_route(p, req, 1, resp);
20872       }
20873       if (!req->ignore && p->owner) {
20874          if (get_rpid(p, req)) {
20875             /* Queue a connected line update */
20876             ast_party_connected_line_init(&connected);
20877             memset(&update_connected, 0, sizeof(update_connected));
20878 
20879             update_connected.id.number = 1;
20880             connected.id.number.valid = 1;
20881             connected.id.number.str = (char *) p->cid_num;
20882             connected.id.number.presentation = p->callingpres;
20883 
20884             update_connected.id.name = 1;
20885             connected.id.name.valid = 1;
20886             connected.id.name.str = (char *) p->cid_name;
20887             connected.id.name.presentation = p->callingpres;
20888 
20889             connected.id.tag = (char *) p->cid_tag;
20890             connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
20891             ast_channel_queue_connected_line_update(p->owner, &connected,
20892                &update_connected);
20893          }
20894          sip_handle_cc(p, req, AST_CC_CCNR);
20895       }
20896       if (find_sdp(req)) {
20897          if (p->invitestate != INV_CANCELLED)
20898             p->invitestate = INV_EARLY_MEDIA;
20899          res = process_sdp(p, req, SDP_T38_NONE);
20900          if (!req->ignore && p->owner) {
20901             /* Queue a progress frame */
20902             ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
20903          }
20904          ast_rtp_instance_activate(p->rtp);
20905       } else {
20906          /* Alcatel PBXs are known to send 183s with no SDP after sending
20907           * a 100 Trying response. We're just going to treat this sort of thing
20908           * the same as we would treat a 180 Ringing
20909           */
20910          if (!req->ignore && p->owner) {
20911             ast_queue_control(p->owner, AST_CONTROL_RINGING);
20912          }
20913       }
20914       check_pendings(p);
20915       break;
20916 
20917    case 200:   /* 200 OK on invite - someone's answering our call */
20918       if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
20919          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
20920       p->authtries = 0;
20921       if (find_sdp(req)) {
20922          if ((res = process_sdp(p, req, SDP_T38_ACCEPT)) && !req->ignore) {
20923             if (!reinvite) {
20924                /* This 200 OK's SDP is not acceptable, so we need to ack, then hangup */
20925                /* For re-invites, we try to recover */
20926                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
20927                p->hangupcause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
20928                if (p->owner) {
20929                   p->owner->hangupcause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
20930                   sip_queue_hangup_cause(p, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
20931                }
20932             }
20933          }
20934          ast_rtp_instance_activate(p->rtp);
20935       } else if (!reinvite) {
20936          struct ast_sockaddr remote_address = {{0,}};
20937 
20938          ast_rtp_instance_get_remote_address(p->rtp, &remote_address);
20939          if (ast_sockaddr_isnull(&remote_address) || (!ast_strlen_zero(p->theirprovtag) && strcmp(p->theirtag, p->theirprovtag))) {
20940             ast_log(LOG_WARNING, "Received response: \"200 OK\" from '%s' without SDP\n", p->relatedpeer->name);
20941             ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
20942             ast_rtp_instance_activate(p->rtp);
20943          }
20944       }
20945 
20946       if (!req->ignore && p->owner) {
20947          int rpid_changed;
20948 
20949          rpid_changed = get_rpid(p, req);
20950          if (rpid_changed || !reinvite) {
20951             /* Queue a connected line update */
20952             ast_party_connected_line_init(&connected);
20953             memset(&update_connected, 0, sizeof(update_connected));
20954             if (rpid_changed
20955                || !ast_strlen_zero(p->cid_num)
20956                || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
20957                update_connected.id.number = 1;
20958                connected.id.number.valid = 1;
20959                connected.id.number.str = (char *) p->cid_num;
20960                connected.id.number.presentation = p->callingpres;
20961             }
20962             if (rpid_changed
20963                || !ast_strlen_zero(p->cid_name)
20964                || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
20965                update_connected.id.name = 1;
20966                connected.id.name.valid = 1;
20967                connected.id.name.str = (char *) p->cid_name;
20968                connected.id.name.presentation = p->callingpres;
20969             }
20970             if (update_connected.id.number || update_connected.id.name) {
20971                connected.id.tag = (char *) p->cid_tag;
20972                connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
20973                ast_channel_queue_connected_line_update(p->owner, &connected,
20974                   &update_connected);
20975             }
20976          }
20977       }
20978 
20979       /* Parse contact header for continued conversation */
20980       /* When we get 200 OK, we know which device (and IP) to contact for this call */
20981       /* This is important when we have a SIP proxy between us and the phone */
20982       if (outgoing) {
20983          update_call_counter(p, DEC_CALL_RINGING);
20984          parse_ok_contact(p, req);
20985          /* Save Record-Route for any later requests we make on this dialogue */
20986          if (!reinvite) {
20987             build_route(p, req, 1, resp);
20988          }
20989          if(set_address_from_contact(p)) {
20990             /* Bad contact - we don't know how to reach this device */
20991             /* We need to ACK, but then send a bye */
20992             if (!p->route && !req->ignore)
20993                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
20994          }
20995 
20996       }
20997 
20998       if (!req->ignore && p->owner) {
20999          if (!reinvite && !res) {
21000             ast_queue_control(p->owner, AST_CONTROL_ANSWER);
21001             if (sip_cfg.callevents)
21002                manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
21003                   "Channel: %s\r\nChanneltype: %s\r\nUniqueid: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
21004                   p->owner->name, "SIP", p->owner->uniqueid, p->callid, p->fullcontact, p->peername);
21005          } else { /* RE-invite */
21006             if (p->t38.state == T38_DISABLED) {
21007                ast_queue_control(p->owner, AST_CONTROL_UPDATE_RTP_PEER);
21008             } else {
21009                ast_queue_frame(p->owner, &ast_null_frame);
21010             }
21011          }
21012       } else {
21013           /* It's possible we're getting an 200 OK after we've tried to disconnect
21014               by sending CANCEL */
21015          /* First send ACK, then send bye */
21016          if (!req->ignore)
21017             ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
21018       }
21019 
21020       /* Check for Session-Timers related headers */
21021       if (st_get_mode(p, 0) != SESSION_TIMER_MODE_REFUSE) {
21022          p_hdrval = (char*)get_header(req, "Session-Expires");
21023          if (!ast_strlen_zero(p_hdrval)) {
21024             /* UAS supports Session-Timers */
21025             enum st_refresher_param st_ref_param;
21026             int tmp_st_interval = 0;
21027             rtn = parse_session_expires(p_hdrval, &tmp_st_interval, &st_ref_param);
21028             if (rtn != 0) {
21029                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
21030             } else if (tmp_st_interval < st_get_se(p, FALSE)) {
21031                ast_log(LOG_WARNING, "Got Session-Expires less than local Min-SE in 200 OK, tearing down call\n");
21032                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
21033             }
21034             if (st_ref_param == SESSION_TIMER_REFRESHER_PARAM_UAC) {
21035                p->stimer->st_ref = SESSION_TIMER_REFRESHER_US;
21036             } else if (st_ref_param == SESSION_TIMER_REFRESHER_PARAM_UAS) {
21037                p->stimer->st_ref = SESSION_TIMER_REFRESHER_THEM;
21038             } else {
21039                ast_log(LOG_WARNING, "Unknown refresher on %s\n", p->callid);
21040             }
21041             if (tmp_st_interval) {
21042                p->stimer->st_interval = tmp_st_interval;
21043             }
21044             p->stimer->st_active = TRUE;
21045             p->stimer->st_active_peer_ua = TRUE;
21046             start_session_timer(p);
21047          } else {
21048             /* UAS doesn't support Session-Timers */
21049             if (st_get_mode(p, 0) == SESSION_TIMER_MODE_ORIGINATE) {
21050                p->stimer->st_ref = SESSION_TIMER_REFRESHER_US;
21051                p->stimer->st_active_peer_ua = FALSE;
21052                start_session_timer(p);
21053             }
21054          }
21055       }
21056 
21057 
21058       /* If I understand this right, the branch is different for a non-200 ACK only */
21059       p->invitestate = INV_TERMINATED;
21060       ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21061       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
21062       check_pendings(p);
21063       break;
21064 
21065    case 407: /* Proxy authentication */
21066    case 401: /* Www auth */
21067       /* First we ACK */
21068       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
21069       if (p->options)
21070          p->options->auth_type = resp;
21071 
21072       /* Then we AUTH */
21073       ast_string_field_set(p, theirtag, NULL);  /* forget their old tag, so we don't match tags when getting response */
21074       if (!req->ignore) {
21075          if (p->authtries < MAX_AUTHTRIES)
21076             p->invitestate = INV_CALLING;
21077          if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, SIP_INVITE, 1)) {
21078             ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
21079             pvt_set_needdestroy(p, "failed to authenticate on INVITE");
21080             sip_alreadygone(p);
21081             if (p->owner)
21082                ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
21083          }
21084       }
21085       break;
21086 
21087    case 403: /* Forbidden */
21088       /* First we ACK */
21089       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
21090       ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", get_header(&p->initreq, "From"));
21091       if (!req->ignore && p->owner) {
21092          sip_queue_hangup_cause(p, hangup_sip2cause(resp));
21093       }
21094       break;
21095 
21096    case 414: /* Bad request URI */
21097    case 493: /* Undecipherable */
21098    case 404: /* Not found */
21099       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
21100       if (p->owner && !req->ignore) {
21101          sip_queue_hangup_cause(p, hangup_sip2cause(resp));
21102       }
21103       break;
21104 
21105    case 481: /* Call leg does not exist */
21106       /* Could be REFER caused INVITE with replaces */
21107       ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
21108       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
21109       if (p->owner) {
21110          ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
21111       }
21112       break;
21113 
21114    case 422: /* Session-Timers: Session interval too small */
21115       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
21116       ast_string_field_set(p, theirtag, NULL);
21117       proc_422_rsp(p, req);
21118       break;
21119 
21120    case 428: /* Use identity header - rfc 4474 - not supported by Asterisk yet */
21121       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
21122       append_history(p, "Identity", "SIP identity is required. Not supported by Asterisk.");
21123       ast_log(LOG_WARNING, "SIP identity required by proxy. SIP dialog '%s'. Giving up.\n", p->callid);
21124       if (p->owner && !req->ignore) {
21125          ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
21126       }
21127       break;
21128 
21129    case 487: /* Cancelled transaction */
21130       /* We have sent CANCEL on an outbound INVITE
21131          This transaction is already scheduled to be killed by sip_hangup().
21132       */
21133       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
21134       if (p->owner && !req->ignore) {
21135          ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_CLEARING);
21136          append_history(p, "Hangup", "Got 487 on CANCEL request from us. Queued AST hangup request");
21137       } else if (!req->ignore) {
21138          update_call_counter(p, DEC_CALL_LIMIT);
21139          append_history(p, "Hangup", "Got 487 on CANCEL request from us on call without owner. Killing this dialog.");
21140       }
21141       check_pendings(p);
21142       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21143       break;
21144    case 415: /* Unsupported media type */
21145    case 488: /* Not acceptable here */
21146    case 606: /* Not Acceptable */
21147       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
21148       if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
21149          change_t38_state(p, T38_DISABLED);
21150          /* Try to reset RTP timers */
21151          //ast_rtp_set_rtptimers_onhold(p->rtp);
21152 
21153          /* Trigger a reinvite back to audio */
21154          transmit_reinvite_with_sdp(p, FALSE, FALSE);
21155       } else {
21156          /* We can't set up this call, so give up */
21157          if (p->owner && !req->ignore) {
21158             ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
21159          }
21160       }
21161       break;
21162    case 491: /* Pending */
21163       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
21164       if (p->owner && !req->ignore) {
21165          if (p->owner->_state != AST_STATE_UP) {
21166             ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
21167          } else {
21168             /* This is a re-invite that failed. */
21169             /* Reset the flag after a while
21170              */
21171             int wait;
21172             /* RFC 3261, if owner of call, wait between 2.1 to 4 seconds,
21173              * if not owner of call, wait 0 to 2 seconds */
21174             if (p->outgoing_call) {
21175                wait = 2100 + ast_random() % 2000;
21176             } else {
21177                wait = ast_random() % 2000;
21178             }
21179             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."));
21180             ast_debug(2, "Reinvite race. Scheduled sip_reinvite_retry in %d secs in handle_response_invite (waitid %d, dialog '%s')\n",
21181                   wait, p->waitid, p->callid);
21182          }
21183       }
21184       break;
21185 
21186    case 408: /* Request timeout */
21187    case 405: /* Not allowed */
21188    case 501: /* Not implemented */
21189       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
21190       if (p->owner) {
21191          ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
21192       }
21193       break;
21194    }
21195    if (xmitres == XMIT_ERROR)
21196       ast_log(LOG_WARNING, "Could not transmit message in dialog %s\n", p->callid);
21197 }
21198 
21199 /* \brief Handle SIP response in NOTIFY transaction
21200        We've sent a NOTIFY, now handle responses to it
21201   */
21202 static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
21203 {
21204    switch (resp) {
21205    case 200:   /* Notify accepted */
21206       /* They got the notify, this is the end */
21207       if (p->owner) {
21208          if (p->refer) {
21209             ast_log(LOG_NOTICE, "Got OK on REFER Notify message\n");
21210          } else {
21211             ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", p->owner->name);
21212          }
21213       } else {
21214          if (p->subscribed == NONE && !p->refer) {
21215             ast_debug(4, "Got 200 accepted on NOTIFY %s\n", p->callid);
21216             pvt_set_needdestroy(p, "received 200 response");
21217          }
21218          if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
21219             /* Ready to send the next state we have on queue */
21220             ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
21221             cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
21222          }
21223       }
21224       break;
21225    case 401:   /* Not www-authorized on SIP method */
21226    case 407:   /* Proxy auth */
21227       if (!p->notify) {
21228          break; /* Only device notify can use NOTIFY auth */
21229       }
21230       ast_string_field_set(p, theirtag, NULL);
21231       if (ast_strlen_zero(p->authname)) {
21232          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));
21233          pvt_set_needdestroy(p, "unable to authenticate NOTIFY");
21234       }
21235       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_NOTIFY, 0)) {
21236          ast_log(LOG_NOTICE, "Failed to authenticate on NOTIFY to '%s'\n", get_header(&p->initreq, "From"));
21237          pvt_set_needdestroy(p, "failed to authenticate NOTIFY");
21238       }
21239       break;
21240    case 481: /* Call leg does not exist */
21241       pvt_set_needdestroy(p, "Received 481 response for NOTIFY");
21242       break;
21243    }
21244 }
21245 
21246 /* \brief Handle SIP response in SUBSCRIBE transaction */
21247 static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
21248 {
21249    if (p->subscribed == CALL_COMPLETION) {
21250       struct sip_monitor_instance *monitor_instance;
21251 
21252       if (resp < 300) {
21253          return;
21254       }
21255 
21256       /* Final failure response received. */
21257       monitor_instance = ao2_callback(sip_monitor_instances, 0,
21258          find_sip_monitor_instance_by_subscription_pvt, p);
21259       if (monitor_instance) {
21260          ast_cc_monitor_failed(monitor_instance->core_id,
21261             monitor_instance->device_name,
21262             "Received error response to our SUBSCRIBE");
21263       }
21264       return;
21265    }
21266 
21267    if (p->subscribed != MWI_NOTIFICATION) {
21268       return;
21269    }
21270    if (!p->mwi) {
21271       return;
21272    }
21273 
21274    switch (resp) {
21275    case 200: /* Subscription accepted */
21276       ast_debug(3, "Got 200 OK on subscription for MWI\n");
21277       set_pvt_allowed_methods(p, req);
21278       if (p->options) {
21279          if (p->options->outboundproxy) {
21280             ao2_ref(p->options->outboundproxy, -1);
21281          }
21282          ast_free(p->options);
21283          p->options = NULL;
21284       }
21285       p->mwi->subscribed = 1;
21286       if ((p->mwi->resub = ast_sched_add(sched, mwi_expiry * 1000, sip_subscribe_mwi_do, ASTOBJ_REF(p->mwi))) < 0) {
21287          ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
21288       }
21289       break;
21290    case 401:
21291    case 407:
21292       ast_string_field_set(p, theirtag, NULL);
21293       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_SUBSCRIBE, 0)) {
21294          ast_log(LOG_NOTICE, "Failed to authenticate on SUBSCRIBE to '%s'\n", get_header(&p->initreq, "From"));
21295          p->mwi->call = NULL;
21296          ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
21297          pvt_set_needdestroy(p, "failed to authenticate SUBSCRIBE");
21298       }
21299       break;
21300    case 403:
21301       transmit_response_with_date(p, "200 OK", req);
21302       ast_log(LOG_WARNING, "Authentication failed while trying to subscribe for MWI.\n");
21303       p->mwi->call = NULL;
21304       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
21305       pvt_set_needdestroy(p, "received 403 response");
21306       sip_alreadygone(p);
21307       break;
21308    case 404:
21309       ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that a mailbox may not have been configured.\n");
21310       p->mwi->call = NULL;
21311       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
21312       pvt_set_needdestroy(p, "received 404 response");
21313       break;
21314    case 481:
21315       ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that our dialog did not exist.\n");
21316       p->mwi->call = NULL;
21317       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
21318       pvt_set_needdestroy(p, "received 481 response");
21319       break;
21320 
21321    case 400: /* Bad Request */
21322    case 414: /* Request URI too long */
21323    case 493: /* Undecipherable */
21324    case 500:
21325    case 501:
21326       ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side may have suffered a heart attack.\n");
21327       p->mwi->call = NULL;
21328       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
21329       pvt_set_needdestroy(p, "received serious error (500/501/493/414/400) response");
21330       break;
21331    }
21332 }
21333 
21334 /* \brief Handle SIP response in REFER transaction
21335    We've sent a REFER, now handle responses to it
21336   */
21337 static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
21338 {
21339    enum ast_control_transfer message = AST_TRANSFER_FAILED;
21340 
21341    /* If no refer structure exists, then do nothing */
21342    if (!p->refer)
21343       return;
21344 
21345    switch (resp) {
21346    case 202:   /* Transfer accepted */
21347       /* We need  to do something here */
21348       /* The transferee is now sending INVITE to target */
21349       p->refer->status = REFER_ACCEPTED;
21350       /* Now wait for next message */
21351       ast_debug(3, "Got 202 accepted on transfer\n");
21352       /* We should hang along, waiting for NOTIFY's here */
21353       break;
21354 
21355    case 401:   /* Not www-authorized on SIP method */
21356    case 407:   /* Proxy auth */
21357       if (ast_strlen_zero(p->authname)) {
21358          ast_log(LOG_WARNING, "Asked to authenticate REFER to %s but we have no matching peer or realm auth!\n",
21359             ast_sockaddr_stringify(&p->recv));
21360          if (p->owner) {
21361             ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
21362          }
21363          pvt_set_needdestroy(p, "unable to authenticate REFER");
21364       }
21365       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_REFER, 0)) {
21366          ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", get_header(&p->initreq, "From"));
21367          p->refer->status = REFER_NOAUTH;
21368          if (p->owner) {
21369             ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
21370          }
21371          pvt_set_needdestroy(p, "failed to authenticate REFER");
21372       }
21373       break;
21374    
21375    case 405:   /* Method not allowed */
21376       /* Return to the current call onhold */
21377       /* Status flag needed to be reset */
21378       ast_log(LOG_NOTICE, "SIP transfer to %s failed, REFER not allowed. \n", p->refer->refer_to);
21379       pvt_set_needdestroy(p, "received 405 response");
21380       p->refer->status = REFER_FAILED;
21381       if (p->owner) {
21382          ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
21383       }
21384       break;
21385 
21386    case 481: /* Call leg does not exist */
21387 
21388       /* A transfer with Replaces did not work */
21389       /* OEJ: We should Set flag, cancel the REFER, go back
21390       to original call - but right now we can't */
21391       ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
21392       if (p->owner)
21393          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
21394       pvt_set_needdestroy(p, "received 481 response");
21395       break;
21396 
21397    case 500:   /* Server error */
21398    case 501:   /* Method not implemented */
21399       /* Return to the current call onhold */
21400       /* Status flag needed to be reset */
21401       ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
21402       pvt_set_needdestroy(p, "received 500/501 response");
21403       p->refer->status = REFER_FAILED;
21404       if (p->owner) {
21405          ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
21406       }
21407       break;
21408    case 603:   /* Transfer declined */
21409       ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
21410       p->refer->status = REFER_FAILED;
21411       pvt_set_needdestroy(p, "received 603 response");
21412       if (p->owner) {
21413          ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
21414       }
21415       break;
21416    default:
21417       /* We should treat unrecognized 9xx as 900.  400 is actually
21418          specified as a possible response, but any 4-6xx is 
21419          theoretically possible. */
21420 
21421       if (resp < 299) { /* 1xx cases don't get here */
21422          ast_log(LOG_WARNING, "SIP transfer to %s had unxpected 2xx response (%d), confusion is possible. \n", p->refer->refer_to, resp);
21423       } else {
21424          ast_log(LOG_WARNING, "SIP transfer to %s with response (%d). \n", p->refer->refer_to, resp);
21425       }
21426 
21427       p->refer->status = REFER_FAILED;
21428       pvt_set_needdestroy(p, "received failure response");
21429       if (p->owner) {
21430          ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
21431       }
21432       break;
21433    }
21434 }
21435 
21436 /*! \brief Handle responses on REGISTER to services */
21437 static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
21438 {
21439    int expires, expires_ms;
21440    struct sip_registry *r;
21441    r=p->registry;
21442    
21443    switch (resp) {
21444    case 401:   /* Unauthorized */
21445       if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
21446          ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
21447          pvt_set_needdestroy(p, "failed to authenticate REGISTER");
21448       }
21449       break;
21450    case 403:   /* Forbidden */
21451       if (global_reg_retry_403) {
21452          ast_log(LOG_NOTICE, "Treating 403 response to REGISTER as non-fatal for %s@%s\n",
21453             p->registry->username, p->registry->hostname);
21454          ast_string_field_set(r, nonce, "");
21455          ast_string_field_set(p, nonce, "");
21456          break;
21457       }
21458       ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
21459       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 403"));
21460       r->regstate = REG_STATE_NOAUTH;
21461       pvt_set_needdestroy(p, "received 403 response");
21462       break;
21463    case 404:   /* Not found */
21464       ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username, p->registry->hostname);
21465       pvt_set_needdestroy(p, "received 404 response");
21466       if (r->call)
21467          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 404");
21468       r->regstate = REG_STATE_REJECTED;
21469       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 404"));
21470       break;
21471    case 407:   /* Proxy auth */
21472       if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
21473          ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
21474          pvt_set_needdestroy(p, "failed to authenticate REGISTER");
21475       }
21476       break;
21477    case 408:   /* Request timeout */
21478       /* Got a timeout response, so reset the counter of failed responses */
21479       if (r) {
21480          r->regattempts = 0;
21481       } else {
21482          ast_log(LOG_WARNING, "Got a 408 response to our REGISTER on call %s after we had destroyed the registry object\n", p->callid);
21483       }
21484       break;
21485    case 423:   /* Interval too brief */
21486       r->expiry = atoi(get_header(req, "Min-Expires"));
21487       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);
21488       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 423"));
21489       if (r->call) {
21490          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 423");
21491          pvt_set_needdestroy(p, "received 423 response");
21492       }
21493       if (r->expiry > max_expiry) {
21494          ast_log(LOG_WARNING, "Required expiration time from %s@%s is too high, giving up\n", p->registry->username, p->registry->hostname);
21495          r->expiry = r->configured_expiry;
21496          r->regstate = REG_STATE_REJECTED;
21497       } else {
21498          r->regstate = REG_STATE_UNREGISTERED;
21499          transmit_register(r, SIP_REGISTER, NULL, NULL);
21500       }
21501       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));
21502       break;
21503    case 400:   /* Bad request */
21504    case 414:   /* Request URI too long */
21505    case 493:   /* Undecipherable */
21506    case 479:   /* Kamailio/OpenSIPS: Not able to process the URI - address is wrong in register*/
21507       ast_log(LOG_WARNING, "Got error %d on register to %s@%s, giving up (check config)\n", resp, p->registry->username, p->registry->hostname);
21508       pvt_set_needdestroy(p, "received 4xx response");
21509       if (r->call)
21510          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 4xx");
21511       r->regstate = REG_STATE_REJECTED;
21512       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 479"));
21513       break;
21514    case 200:   /* 200 OK */
21515       if (!r) {
21516          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));
21517          pvt_set_needdestroy(p, "received erroneous 200 response");
21518          return 0;
21519       }
21520       
21521       r->regstate = REG_STATE_REGISTERED;
21522       r->regtime = ast_tvnow();     /* Reset time of last successful registration */
21523       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));
21524       r->regattempts = 0;
21525       ast_debug(1, "Registration successful\n");
21526       if (r->timeout > -1) {
21527          ast_debug(1, "Cancelling timeout %d\n", r->timeout);
21528       }
21529       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 200"));
21530       if (r->call)
21531          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 200");
21532       p->registry = registry_unref(p->registry, "unref registry entry p->registry");
21533 
21534       /* destroy dialog now to avoid interference with next register */
21535       pvt_set_needdestroy(p, "Registration successfull");
21536       
21537       /* set us up for re-registering
21538        * figure out how long we got registered for
21539        * according to section 6.13 of RFC, contact headers override
21540        * expires headers, so check those first */
21541       expires = 0;
21542 
21543       /* XXX todo: try to save the extra call */
21544       if (!ast_strlen_zero(get_header(req, "Contact"))) {
21545          const char *contact = NULL;
21546          const char *tmptmp = NULL;
21547          int start = 0;
21548          for(;;) {
21549             contact = __get_header(req, "Contact", &start);
21550             /* this loop ensures we get a contact header about our register request */
21551             if(!ast_strlen_zero(contact)) {
21552                if( (tmptmp=strstr(contact, p->our_contact))) {
21553                   contact=tmptmp;
21554                   break;
21555                }
21556             } else
21557                break;
21558          }
21559          tmptmp = strcasestr(contact, "expires=");
21560          if (tmptmp) {
21561             if (sscanf(tmptmp + 8, "%30d", &expires) != 1) {
21562                expires = 0;
21563             }
21564          }
21565          
21566       }
21567       if (!expires)
21568          expires=atoi(get_header(req, "expires"));
21569       if (!expires)
21570          expires=default_expiry;
21571       
21572       expires_ms = expires * 1000;
21573       if (expires <= EXPIRY_GUARD_LIMIT)
21574          expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT), EXPIRY_GUARD_MIN);
21575       else
21576          expires_ms -= EXPIRY_GUARD_SECS * 1000;
21577       if (sipdebug)
21578          ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000);
21579       
21580       r->refresh= (int) expires_ms / 1000;
21581       
21582       /* Schedule re-registration before we expire */
21583       AST_SCHED_REPLACE_UNREF(r->expire, sched, expires_ms, sip_reregister, r,
21584                         registry_unref(_data,"unref in REPLACE del fail"),
21585                         registry_unref(r,"unref in REPLACE add fail"),
21586                         registry_addref(r,"The Addition side of REPLACE"));
21587    }
21588    return 1;
21589 }
21590 
21591 /*! \brief Handle qualification responses (OPTIONS) */
21592 static void handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
21593 {
21594    struct sip_peer *peer = /* ref_peer( */ p->relatedpeer /* , "bump refcount on p, as it is being used in this function(handle_response_peerpoke)")*/ ; /* hope this is already refcounted! */
21595    int statechanged, is_reachable, was_reachable;
21596    int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);
21597 
21598    /*
21599     * Compute the response time to a ping (goes in peer->lastms.)
21600     * -1 means did not respond, 0 means unknown,
21601     * 1..maxms is a valid response, >maxms means late response.
21602     */
21603    if (pingtime < 1) {  /* zero = unknown, so round up to 1 */
21604       pingtime = 1;
21605    }
21606 
21607    if (!peer->maxms) { /* this should never happens */
21608       pvt_set_needdestroy(p, "got OPTIONS response but qualify is not enabled");
21609       return;
21610    }
21611 
21612    /* Now determine new state and whether it has changed.
21613     * Use some helper variables to simplify the writing
21614     * of the expressions.
21615     */
21616    was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
21617    is_reachable = pingtime <= peer->maxms;
21618    statechanged = peer->lastms == 0 /* yes, unknown before */
21619       || was_reachable != is_reachable;
21620 
21621    peer->lastms = pingtime;
21622    peer->call = dialog_unref(peer->call, "unref dialog peer->call");
21623    if (statechanged) {
21624       const char *s = is_reachable ? "Reachable" : "Lagged";
21625       char str_lastms[20];
21626       snprintf(str_lastms, sizeof(str_lastms), "%d", pingtime);
21627 
21628       ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
21629          peer->name, s, pingtime, peer->maxms);
21630       ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", peer->name);
21631       if (sip_cfg.peer_rtupdate) {
21632          ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", str_lastms, SENTINEL);
21633       }
21634       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
21635          "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
21636          peer->name, s, pingtime);
21637       if (is_reachable && sip_cfg.regextenonqualify)
21638          register_peer_exten(peer, TRUE);
21639    }
21640 
21641    pvt_set_needdestroy(p, "got OPTIONS response");
21642 
21643    /* Try again eventually */
21644    AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
21645          is_reachable ? peer->qualifyfreq : DEFAULT_FREQ_NOTOK,
21646          sip_poke_peer_s, peer,
21647          unref_peer(_data, "removing poke peer ref"),
21648          unref_peer(peer, "removing poke peer ref"),
21649          ref_peer(peer, "adding poke peer ref"));
21650 }
21651 
21652 /*!
21653  * \internal
21654  * \brief Handle responses to INFO messages
21655  *
21656  * \note The INFO method MUST NOT change the state of calls or
21657  * related sessions (RFC 2976).
21658  */
21659 static void handle_response_info(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
21660 {
21661    int sipmethod = SIP_INFO;
21662 
21663    switch (resp) {
21664    case 401: /* Not www-authorized on SIP method */
21665    case 407: /* Proxy auth required */
21666       ast_log(LOG_WARNING, "Host '%s' requests authentication (%d) for '%s'\n",
21667          ast_sockaddr_stringify(&p->sa), resp, sip_methods[sipmethod].text);
21668       break;
21669    case 405: /* Method not allowed */
21670    case 501: /* Not Implemented */
21671       mark_method_unallowed(&p->allowed_methods, sipmethod);
21672       if (p->relatedpeer) {
21673          mark_method_allowed(&p->relatedpeer->disallowed_methods, sipmethod);
21674       }
21675       ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n",
21676          ast_sockaddr_stringify(&p->sa), sip_methods[sipmethod].text);
21677       break;
21678    default:
21679       if (300 <= resp && resp < 700) {
21680          ast_verb(3, "Got SIP %s response %d \"%s\" back from host '%s'\n",
21681             sip_methods[sipmethod].text, resp, rest, ast_sockaddr_stringify(&p->sa));
21682       }
21683       break;
21684    }
21685 }
21686 
21687 /*!
21688  * \internal
21689  * \brief Handle responses to MESSAGE messages
21690  *
21691  * \note The MESSAGE method should not change the state of calls
21692  * or related sessions if associated with a dialog. (Implied by
21693  * RFC 3428 Section 2).
21694  */
21695 static void handle_response_message(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
21696 {
21697    int sipmethod = SIP_MESSAGE;
21698    /* Out-of-dialog MESSAGE currently not supported. */
21699    //int in_dialog = ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21700 
21701    switch (resp) {
21702    case 401: /* Not www-authorized on SIP method */
21703    case 407: /* Proxy auth required */
21704       ast_log(LOG_WARNING, "Host '%s' requests authentication (%d) for '%s'\n",
21705          ast_sockaddr_stringify(&p->sa), resp, sip_methods[sipmethod].text);
21706       break;
21707    case 405: /* Method not allowed */
21708    case 501: /* Not Implemented */
21709       mark_method_unallowed(&p->allowed_methods, sipmethod);
21710       if (p->relatedpeer) {
21711          mark_method_allowed(&p->relatedpeer->disallowed_methods, sipmethod);
21712       }
21713       ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n",
21714          ast_sockaddr_stringify(&p->sa), sip_methods[sipmethod].text);
21715       break;
21716    default:
21717       if (100 <= resp && resp < 200) {
21718          /* Must allow provisional responses for out-of-dialog requests. */
21719       } else if (200 <= resp && resp < 300) {
21720          p->authtries = 0; /* Reset authentication counter */
21721       } else if (300 <= resp && resp < 700) {
21722          ast_verb(3, "Got SIP %s response %d \"%s\" back from host '%s'\n",
21723             sip_methods[sipmethod].text, resp, rest, ast_sockaddr_stringify(&p->sa));
21724       }
21725       break;
21726    }
21727 }
21728 
21729 /*! \brief Immediately stop RTP, VRTP and UDPTL as applicable */
21730 static void stop_media_flows(struct sip_pvt *p)
21731 {
21732    /* Immediately stop RTP, VRTP and UDPTL as applicable */
21733    if (p->rtp)
21734       ast_rtp_instance_stop(p->rtp);
21735    if (p->vrtp)
21736       ast_rtp_instance_stop(p->vrtp);
21737    if (p->trtp)
21738       ast_rtp_instance_stop(p->trtp);
21739    if (p->udptl)
21740       ast_udptl_stop(p->udptl);
21741 }
21742 
21743 /*! \brief Handle SIP response in dialogue
21744    \note only called by handle_incoming */
21745 static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
21746 {
21747    struct ast_channel *owner;
21748    int sipmethod;
21749    const char *c = get_header(req, "Cseq");
21750    /* 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 */
21751    char *c_copy = ast_strdupa(c);
21752    /* Skip the Cseq and its subsequent spaces */
21753    const char *msg = ast_skip_blanks(ast_skip_nonblanks(c_copy));
21754 
21755    if (!msg)
21756       msg = "";
21757 
21758    sipmethod = find_sip_method(msg);
21759 
21760    owner = p->owner;
21761    if (owner) {
21762       const char *rp = NULL, *rh = NULL;
21763 
21764       owner->hangupcause = 0;
21765       if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON) && (rh = get_header(req, "Reason"))) {
21766          rh = ast_skip_blanks(rh);
21767          if (!strncasecmp(rh, "Q.850", 5)) {
21768             rp = strstr(rh, "cause=");
21769             if (rp && sscanf(rp + 6, "%30d", &owner->hangupcause) == 1) {
21770                owner->hangupcause &= 0x7f;
21771                if (req->debug)
21772                   ast_verbose("Using Reason header for cause code: %d\n", owner->hangupcause);
21773             }
21774          }
21775       }
21776 
21777       if (!owner->hangupcause)
21778          owner->hangupcause = hangup_sip2cause(resp);
21779    }
21780 
21781    if (p->socket.type == SIP_TRANSPORT_UDP) {
21782       int ack_res = FALSE;
21783 
21784       /* Acknowledge whatever it is destined for */
21785       if ((resp >= 100) && (resp <= 199)) {
21786          /* NON-INVITE messages do not ack a 1XX response. RFC 3261 section 17.1.2.2 */
21787          if (sipmethod == SIP_INVITE) {
21788             ack_res = __sip_semi_ack(p, seqno, 0, sipmethod);
21789          }
21790       } else {
21791          ack_res = __sip_ack(p, seqno, 0, sipmethod);
21792       }
21793 
21794       if (ack_res == FALSE) {
21795          /* RFC 3261 13.2.2.4 and 17.1.1.2 - We must re-send ACKs to re-transmitted final responses */
21796          if (sipmethod == SIP_INVITE && resp >= 200) {
21797             transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, resp < 300 ? TRUE: FALSE);
21798          }
21799 
21800          append_history(p, "Ignore", "Ignoring this retransmit\n");
21801          return;
21802       }
21803    }
21804 
21805    /* If this is a NOTIFY for a subscription clear the flag that indicates that we have a NOTIFY pending */
21806    if (!p->owner && sipmethod == SIP_NOTIFY && p->pendinginvite) {
21807       p->pendinginvite = 0;
21808    }
21809 
21810    /* Get their tag if we haven't already */
21811    if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
21812       char tag[128];
21813 
21814       gettag(req, "To", tag, sizeof(tag));
21815       ast_string_field_set(p, theirtag, tag);
21816    } else {
21817       /* Store theirtag to track for changes when 200 responses to invites are received without SDP */
21818       ast_string_field_set(p, theirprovtag, p->theirtag);
21819    }
21820 
21821    /* This needs to be configurable on a channel/peer level,
21822       not mandatory for all communication. Sadly enough, NAT implementations
21823       are not so stable so we can always rely on these headers.
21824       Temporarily disabled, while waiting for fix.
21825       Fix assigned to Rizzo :-)
21826    */
21827    /* check_via_response(p, req); */
21828 
21829    /* RFC 3261 Section 15 specifies that if we receive a 408 or 481
21830     * in response to a BYE, then we should end the current dialog
21831     * and session.  It is known that at least one phone manufacturer
21832     * potentially will send a 404 in response to a BYE, so we'll be
21833     * liberal in what we accept and end the dialog and session if we
21834     * receive any of those responses to a BYE.
21835     */
21836    if ((resp == 404 || resp == 408 || resp == 481) && sipmethod == SIP_BYE) {
21837       pvt_set_needdestroy(p, "received 4XX response to a BYE");
21838       return;
21839    }
21840 
21841    if (p->relatedpeer && sipmethod == SIP_OPTIONS) {
21842       /* We don't really care what the response is, just that it replied back.
21843          Well, as long as it's not a 100 response...  since we might
21844          need to hang around for something more "definitive" */
21845       if (resp != 100)
21846          handle_response_peerpoke(p, resp, req);
21847    } else if (sipmethod == SIP_REFER && resp >= 200) {
21848       handle_response_refer(p, resp, rest, req, seqno);
21849    } else if (sipmethod == SIP_PUBLISH) {
21850       /* SIP PUBLISH transcends this morass of doodoo and instead
21851        * we just always call the response handler. Good gravy!
21852        */
21853       handle_response_publish(p, resp, rest, req, seqno);
21854    } else if (sipmethod == SIP_INFO) {
21855       /* More good gravy! */
21856       handle_response_info(p, resp, rest, req, seqno);
21857    } else if (sipmethod == SIP_MESSAGE) {
21858       /* More good gravy! */
21859       handle_response_message(p, resp, rest, req, seqno);
21860    } else if (sipmethod == SIP_NOTIFY) {
21861       /* The gravy train continues to roll */
21862       handle_response_notify(p, resp, rest, req, seqno);
21863    } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
21864       switch(resp) {
21865       case 100:   /* 100 Trying */
21866       case 101:   /* 101 Dialog establishment */
21867       case 183:   /* 183 Session Progress */
21868       case 180:   /* 180 Ringing */
21869       case 182:   /* 182 Queued */
21870       case 181:   /* 181 Call Is Being Forwarded */
21871          if (sipmethod == SIP_INVITE)
21872             handle_response_invite(p, resp, rest, req, seqno);
21873          break;
21874       case 200:   /* 200 OK */
21875          p->authtries = 0; /* Reset authentication counter */
21876          if (sipmethod == SIP_INVITE) {
21877             handle_response_invite(p, resp, rest, req, seqno);
21878          } else if (sipmethod == SIP_REGISTER) {
21879             handle_response_register(p, resp, rest, req, seqno);
21880          } else if (sipmethod == SIP_SUBSCRIBE) {
21881             ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21882             handle_response_subscribe(p, resp, rest, req, seqno);
21883          } else if (sipmethod == SIP_BYE) {     /* Ok, we're ready to go */
21884             pvt_set_needdestroy(p, "received 200 response");
21885             ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21886          }
21887          break;
21888       case 401: /* Not www-authorized on SIP method */
21889       case 407: /* Proxy auth required */
21890          if (sipmethod == SIP_INVITE)
21891             handle_response_invite(p, resp, rest, req, seqno);
21892          else if (sipmethod == SIP_SUBSCRIBE)
21893             handle_response_subscribe(p, resp, rest, req, seqno);
21894          else if (p->registry && sipmethod == SIP_REGISTER)
21895             handle_response_register(p, resp, rest, req, seqno);
21896          else if (sipmethod == SIP_UPDATE) {
21897             handle_response_update(p, resp, rest, req, seqno);
21898          } else if (sipmethod == SIP_BYE) {
21899             if (p->options)
21900                p->options->auth_type = resp;
21901             if (ast_strlen_zero(p->authname)) {
21902                ast_log(LOG_WARNING, "Asked to authenticate %s, to %s but we have no matching peer!\n",
21903                      msg, ast_sockaddr_stringify(&p->recv));
21904                pvt_set_needdestroy(p, "unable to authenticate BYE");
21905             } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp,  sipmethod, 0)) {
21906                ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
21907                pvt_set_needdestroy(p, "failed to authenticate BYE");
21908             }
21909          } else {
21910             ast_log(LOG_WARNING, "Got authentication request (%d) on %s to '%s'\n", resp, sip_methods[sipmethod].text, get_header(req, "To"));
21911             pvt_set_needdestroy(p, "received 407 response");
21912          }
21913          break;
21914       case 403: /* Forbidden - we failed authentication */
21915          if (sipmethod == SIP_INVITE)
21916             handle_response_invite(p, resp, rest, req, seqno);
21917          else if (sipmethod == SIP_SUBSCRIBE)
21918             handle_response_subscribe(p, resp, rest, req, seqno);
21919          else if (p->registry && sipmethod == SIP_REGISTER)
21920             handle_response_register(p, resp, rest, req, seqno);
21921          else {
21922             ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
21923             pvt_set_needdestroy(p, "received 403 response");
21924          }
21925          break;
21926       case 400: /* Bad Request */
21927       case 414: /* Request URI too long */
21928       case 493: /* Undecipherable */
21929       case 404: /* Not found */
21930          if (p->registry && sipmethod == SIP_REGISTER)
21931             handle_response_register(p, resp, rest, req, seqno);
21932          else if (sipmethod == SIP_INVITE)
21933             handle_response_invite(p, resp, rest, req, seqno);
21934          else if (sipmethod == SIP_SUBSCRIBE)
21935             handle_response_subscribe(p, resp, rest, req, seqno);
21936          else if (owner)
21937             ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
21938          break;
21939       case 423: /* Interval too brief */
21940          if (sipmethod == SIP_REGISTER)
21941             handle_response_register(p, resp, rest, req, seqno);
21942          break;
21943       case 408: /* Request timeout - terminate dialog */
21944          if (sipmethod == SIP_INVITE)
21945             handle_response_invite(p, resp, rest, req, seqno);
21946          else if (sipmethod == SIP_REGISTER)
21947             handle_response_register(p, resp, rest, req, seqno);
21948          else if (sipmethod == SIP_BYE) {
21949             pvt_set_needdestroy(p, "received 408 response");
21950             ast_debug(4, "Got timeout on bye. Thanks for the answer. Now, kill this call\n");
21951          } else {
21952             if (owner)
21953                ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
21954             pvt_set_needdestroy(p, "received 408 response");
21955          }
21956          break;
21957 
21958       case 428:
21959       case 422: /* Session-Timers: Session Interval Too Small */
21960          if (sipmethod == SIP_INVITE) {
21961             handle_response_invite(p, resp, rest, req, seqno);
21962          }
21963          break;
21964 
21965       case 481: /* Call leg does not exist */
21966          if (sipmethod == SIP_INVITE) {
21967             handle_response_invite(p, resp, rest, req, seqno);
21968          } else if (sipmethod == SIP_SUBSCRIBE) {
21969             handle_response_subscribe(p, resp, rest, req, seqno);
21970          } else if (sipmethod == SIP_BYE) {
21971             /* The other side has no transaction to bye,
21972             just assume it's all right then */
21973             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
21974          } else if (sipmethod == SIP_CANCEL) {
21975             /* The other side has no transaction to cancel,
21976             just assume it's all right then */
21977             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
21978          } else {
21979             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
21980             /* Guessing that this is not an important request */
21981          }
21982          break;
21983       case 487:
21984          if (sipmethod == SIP_INVITE)
21985             handle_response_invite(p, resp, rest, req, seqno);
21986          break;
21987       case 415: /* Unsupported media type */
21988       case 488: /* Not acceptable here - codec error */
21989       case 606: /* Not Acceptable */
21990          if (sipmethod == SIP_INVITE)
21991             handle_response_invite(p, resp, rest, req, seqno);
21992          break;
21993       case 491: /* Pending */
21994          if (sipmethod == SIP_INVITE)
21995             handle_response_invite(p, resp, rest, req, seqno);
21996          else {
21997             ast_debug(1, "Got 491 on %s, unsupported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
21998             pvt_set_needdestroy(p, "received 491 response");
21999          }
22000          break;
22001       case 405: /* Method not allowed */
22002       case 501: /* Not Implemented */
22003          mark_method_unallowed(&p->allowed_methods, sipmethod);
22004          if (p->relatedpeer) {
22005             mark_method_allowed(&p->relatedpeer->disallowed_methods, sipmethod);
22006          }
22007          if (sipmethod == SIP_INVITE)
22008             handle_response_invite(p, resp, rest, req, seqno);
22009          else
22010             ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_sockaddr_stringify(&p->sa), msg);
22011          break;
22012       default:
22013          if ((resp >= 300) && (resp < 700)) {
22014             /* Fatal response */
22015             if ((resp != 487))
22016                ast_verb(3, "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_sockaddr_stringify(&p->sa));
22017    
22018             if (sipmethod == SIP_INVITE)
22019                stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
22020 
22021             /* XXX Locking issues?? XXX */
22022             switch(resp) {
22023             case 300: /* Multiple Choices */
22024             case 301: /* Moved permanently */
22025             case 302: /* Moved temporarily */
22026             case 305: /* Use Proxy */
22027                if (p->owner) {
22028                   struct ast_party_redirecting redirecting;
22029                   struct ast_set_party_redirecting update_redirecting;
22030 
22031                   ast_party_redirecting_init(&redirecting);
22032                   memset(&update_redirecting, 0, sizeof(update_redirecting));
22033                   change_redirecting_information(p, req, &redirecting,
22034                      &update_redirecting, TRUE);
22035                   ast_channel_set_redirecting(p->owner, &redirecting,
22036                      &update_redirecting);
22037                   ast_party_redirecting_free(&redirecting);
22038                }
22039                /* Fall through */
22040             case 486: /* Busy here */
22041             case 600: /* Busy everywhere */
22042             case 603: /* Decline */
22043                if (p->owner) {
22044                   sip_handle_cc(p, req, AST_CC_CCBS);
22045                   ast_queue_control(p->owner, AST_CONTROL_BUSY);
22046                }
22047                break;
22048             case 482: /* Loop Detected */
22049             case 480: /* Temporarily Unavailable */
22050             case 404: /* Not Found */
22051             case 410: /* Gone */
22052             case 400: /* Bad Request */
22053             case 500: /* Server error */
22054                if (sipmethod == SIP_SUBSCRIBE) {
22055                   handle_response_subscribe(p, resp, rest, req, seqno);
22056                   break;
22057                }
22058                /* Fall through */
22059             case 502: /* Bad gateway */
22060             case 503: /* Service Unavailable */
22061             case 504: /* Server Timeout */
22062                if (owner)
22063                   ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
22064                break;
22065             case 484: /* Address Incomplete */
22066                if (owner && sipmethod != SIP_BYE) {
22067                   switch (ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)) {
22068                   case SIP_PAGE2_ALLOWOVERLAP_YES:
22069                      ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
22070                      break;
22071                   default:
22072                      ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(404));
22073                      break;
22074                   }
22075                }
22076                break;
22077             default:
22078                /* Send hangup */ 
22079                if (owner && sipmethod != SIP_BYE)
22080                   ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
22081                break;
22082             }
22083             /* ACK on invite */
22084             if (sipmethod == SIP_INVITE)
22085                transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
22086             sip_alreadygone(p);
22087             if (!p->owner) {
22088                pvt_set_needdestroy(p, "transaction completed");
22089             }
22090          } else if ((resp >= 100) && (resp < 200)) {
22091             if (sipmethod == SIP_INVITE) {
22092                if (!req->ignore && sip_cancel_destroy(p))
22093                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
22094                if (find_sdp(req))
22095                   process_sdp(p, req, SDP_T38_NONE);
22096                if (p->owner) {
22097                   /* Queue a progress frame */
22098                   ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
22099                }
22100             }
22101          } else
22102             ast_log(LOG_NOTICE, "Don't know how to handle a %d %s response from %s\n", resp, rest, p->owner ? p->owner->name : ast_sockaddr_stringify(&p->sa));
22103       }
22104    } else { 
22105       /* Responses to OUTGOING SIP requests on INCOMING calls
22106          get handled here. As well as out-of-call message responses */
22107       if (req->debug)
22108          ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
22109 
22110       if (sipmethod == SIP_INVITE && resp == 200) {
22111          /* Tags in early session is replaced by the tag in 200 OK, which is
22112          the final reply to our INVITE */
22113          char tag[128];
22114 
22115          gettag(req, "To", tag, sizeof(tag));
22116          ast_string_field_set(p, theirtag, tag);
22117       }
22118 
22119       switch(resp) {
22120       case 200:
22121          if (sipmethod == SIP_INVITE) {
22122             handle_response_invite(p, resp, rest, req, seqno);
22123          } else if (sipmethod == SIP_CANCEL) {
22124             ast_debug(1, "Got 200 OK on CANCEL\n");
22125 
22126             /* Wait for 487, then destroy */
22127          } else if (sipmethod == SIP_BYE) {
22128             pvt_set_needdestroy(p, "transaction completed");
22129          }
22130          break;
22131       case 401:   /* www-auth */
22132       case 407:
22133          if (sipmethod == SIP_INVITE)
22134             handle_response_invite(p, resp, rest, req, seqno);
22135          else if (sipmethod == SIP_BYE) {
22136             if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, sipmethod, 0)) {
22137                ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
22138                pvt_set_needdestroy(p, "failed to authenticate BYE");
22139             }
22140          }
22141          break;
22142       case 481:   /* Call leg does not exist */
22143          if (sipmethod == SIP_INVITE) {
22144             /* Re-invite failed */
22145             handle_response_invite(p, resp, rest, req, seqno);
22146          } else if (sipmethod == SIP_BYE) {
22147             pvt_set_needdestroy(p, "received 481 response");
22148          } else if (sipdebug) {
22149             ast_debug(1, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
22150          }
22151          break;
22152       case 501: /* Not Implemented */
22153          if (sipmethod == SIP_INVITE)
22154             handle_response_invite(p, resp, rest, req, seqno);
22155          break;
22156       default: /* Errors without handlers */
22157          if ((resp >= 100) && (resp < 200)) {
22158             if (sipmethod == SIP_INVITE) {   /* re-invite */
22159                if (!req->ignore && sip_cancel_destroy(p))
22160                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
22161             }
22162          }
22163          if ((resp >= 300) && (resp < 700)) {
22164             if ((resp != 487))
22165                ast_verb(3, "Incoming call: Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_sockaddr_stringify(&p->sa));
22166             switch(resp) {
22167             case 415: /* Unsupported media type */
22168             case 488: /* Not acceptable here - codec error */
22169             case 603: /* Decline */
22170             case 500: /* Server error */
22171             case 502: /* Bad gateway */
22172             case 503: /* Service Unavailable */
22173             case 504: /* Server timeout */
22174 
22175                /* re-invite failed */
22176                if (sipmethod == SIP_INVITE && sip_cancel_destroy(p))
22177                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
22178                break;
22179             }
22180          }
22181          break;
22182       }
22183    }
22184 }
22185 
22186 
22187 /*! \brief Park SIP call support function
22188    Starts in a new thread, then parks the call
22189    XXX Should we add a wait period after streaming audio and before hangup?? Sometimes the
22190       audio can't be heard before hangup
22191 */
22192 static void *sip_park_thread(void *stuff)
22193 {
22194    struct ast_channel *transferee, *transferer; /* Chan1: The transferee, Chan2: The transferer */
22195    struct sip_pvt *transferer_pvt;
22196    struct sip_dual *d;
22197    int ext;
22198    int res;
22199 
22200    d = stuff;
22201    transferee = d->chan1;
22202    transferer = d->chan2;
22203    transferer_pvt = transferer->tech_pvt;
22204 
22205    ast_debug(4, "SIP Park: Transferer channel %s, Transferee %s\n", transferer->name, transferee->name);
22206 
22207    res = ast_park_call_exten(transferee, transferer, d->park_exten, d->park_context, 0, &ext);
22208 
22209 #ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
22210    if (res) {
22211       transmit_message_with_text(transferer_pvt, "Unable to park call.\n");
22212    } else {
22213       /* Then tell the transferer what happened */
22214       sprintf(buf, "Call parked on extension '%d'", ext);
22215       transmit_message_with_text(transferer_pvt, buf);
22216    }
22217 #endif
22218 
22219    /* Any way back to the current call??? */
22220    /* Transmit response to the REFER request */
22221    ast_set_flag(&transferer_pvt->flags[0], SIP_DEFER_BYE_ON_TRANSFER);  
22222    if (!res)   {
22223       /* Transfer succeeded */
22224       append_history(transferer_pvt, "SIPpark", "Parked call on %d", ext);
22225       transmit_notify_with_sipfrag(transferer_pvt, d->seqno, "200 OK", TRUE);
22226       transferer->hangupcause = AST_CAUSE_NORMAL_CLEARING;
22227       ast_debug(1, "SIP Call parked on extension '%d'\n", ext);
22228    } else {
22229       transmit_notify_with_sipfrag(transferer_pvt, d->seqno, "503 Service Unavailable", TRUE);
22230       append_history(transferer_pvt, "SIPpark", "Parking failed\n");
22231       ast_log(AST_LOG_NOTICE, "SIP Call parked failed for %s\n", transferee->name);
22232       ast_hangup(transferee);
22233    }
22234    ast_hangup(transferer);
22235    deinit_req(&d->req);
22236    ast_free(d->park_exten);
22237    ast_free(d->park_context);
22238    ast_free(d);
22239    return NULL;
22240 }
22241 
22242 /*! DO NOT hold any locks while calling sip_park */
22243 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)
22244 {
22245    struct sip_dual *d;
22246    struct ast_channel *transferee, *transferer;
22247    pthread_t th;
22248 
22249    transferee = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan1->accountcode, chan1->exten, chan1->context, chan1->linkedid, chan1->amaflags, "Parking/%s", chan1->name);
22250    transferer = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->linkedid, chan2->amaflags, "SIPPeer/%s", chan2->name);
22251    d = ast_calloc(1, sizeof(*d));
22252    if (!transferee || !transferer || !d) {
22253       if (transferee) {
22254          ast_hangup(transferee);
22255       }
22256       if (transferer) {
22257          ast_hangup(transferer);
22258       }
22259       ast_free(d);
22260       return -1;
22261    }
22262    d->park_exten = ast_strdup(park_exten);
22263    d->park_context = ast_strdup(park_context);
22264    if (!d->park_exten || !d->park_context) {
22265       ast_hangup(transferee);
22266       ast_hangup(transferer);
22267       ast_free(d->park_exten);
22268       ast_free(d->park_context);
22269       ast_free(d);
22270       return -1;
22271    }
22272 
22273    /* Make formats okay */
22274    transferee->readformat = chan1->readformat;
22275    transferee->writeformat = chan1->writeformat;
22276 
22277    /* Prepare for taking over the channel */
22278    if (ast_channel_masquerade(transferee, chan1)) {
22279       ast_hangup(transferee);
22280       ast_hangup(transferer);
22281       ast_free(d->park_exten);
22282       ast_free(d->park_context);
22283       ast_free(d);
22284       return -1;
22285    }
22286 
22287    /* Setup the extensions and such */
22288    ast_copy_string(transferee->context, chan1->context, sizeof(transferee->context));
22289    ast_copy_string(transferee->exten, chan1->exten, sizeof(transferee->exten));
22290    transferee->priority = chan1->priority;
22291 
22292    ast_do_masquerade(transferee);
22293 
22294    /* We make a clone of the peer channel too, so we can play
22295       back the announcement */
22296 
22297    /* Make formats okay */
22298    transferer->readformat = chan2->readformat;
22299    transferer->writeformat = chan2->writeformat;
22300    ast_string_field_set(transferer, parkinglot, chan2->parkinglot);
22301 
22302    /* Prepare for taking over the channel */
22303    if (ast_channel_masquerade(transferer, chan2)) {
22304       ast_hangup(transferee);
22305       ast_hangup(transferer);
22306       ast_free(d->park_exten);
22307       ast_free(d->park_context);
22308       ast_free(d);
22309       return -1;
22310    }
22311 
22312    /* Setup the extensions and such */
22313    ast_copy_string(transferer->context, chan2->context, sizeof(transferer->context));
22314    ast_copy_string(transferer->exten, chan2->exten, sizeof(transferer->exten));
22315    transferer->priority = chan2->priority;
22316 
22317    ast_do_masquerade(transferer);
22318 
22319    /* Save original request for followup */
22320    copy_request(&d->req, req);
22321    d->chan1 = transferee;  /* Transferee */
22322    d->chan2 = transferer;  /* Transferer */
22323    d->seqno = seqno;
22324    if (ast_pthread_create_detached_background(&th, NULL, sip_park_thread, d) < 0) {
22325       /* Could not start thread */
22326       ast_hangup(transferer);
22327       ast_hangup(transferee);
22328       deinit_req(&d->req);
22329       ast_free(d->park_exten);
22330       ast_free(d->park_context);
22331       ast_free(d);   /* We don't need it anymore. If thread is created, d will be free'd
22332                by sip_park_thread() */
22333       return -1;
22334    }
22335    return 0;
22336 }
22337 
22338 
22339 /*! \brief SIP pickup support function
22340  * Starts in a new thread, then pickup the call
22341  */
22342 static void *sip_pickup_thread(void *stuff)
22343 {
22344    struct ast_channel *chan;
22345    chan = stuff;
22346 
22347    if (ast_pickup_call(chan)) {
22348       chan->hangupcause = AST_CAUSE_CALL_REJECTED;
22349    } else {
22350       chan->hangupcause = AST_CAUSE_NORMAL_CLEARING;
22351    }
22352    ast_hangup(chan);
22353    ast_channel_unref(chan);
22354    chan = NULL;
22355    return NULL;
22356 }
22357 
22358 /*! \brief Pickup a call using the subsystem in features.c
22359  * This is executed in a separate thread
22360  */
22361 static int sip_pickup(struct ast_channel *chan)
22362 {
22363    pthread_t threadid;
22364 
22365    ast_channel_ref(chan);
22366 
22367    if (ast_pthread_create_detached_background(&threadid, NULL, sip_pickup_thread, chan)) {
22368       ast_debug(1, "Unable to start Group pickup thread on channel %s\n", chan->name);
22369       ast_channel_unref(chan);
22370       return -1;
22371    }
22372    ast_debug(1, "Started Group pickup thread on channel %s\n", chan->name);
22373    return 0;
22374 }
22375 
22376 
22377 /*! \brief Turn off generator data
22378    XXX Does this function belong in the SIP channel?
22379 */
22380 static void ast_quiet_chan(struct ast_channel *chan)
22381 {
22382    if (chan && chan->_state == AST_STATE_UP) {
22383       if (ast_test_flag(chan, AST_FLAG_MOH))
22384          ast_moh_stop(chan);
22385       else if (chan->generatordata)
22386          ast_deactivate_generator(chan);
22387    }
22388 }
22389 
22390 /*! \brief Attempt transfer of SIP call
22391    This fix for attended transfers on a local PBX */
22392 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target)
22393 {
22394    int res = 0;
22395    struct ast_channel *peera = NULL,   
22396       *peerb = NULL,
22397       *peerc = NULL,
22398       *peerd = NULL;
22399 
22400 
22401    /* We will try to connect the transferee with the target and hangup
22402       all channels to the transferer */   
22403    ast_debug(4, "Sip transfer:--------------------\n");
22404    if (transferer->chan1)
22405       ast_debug(4, "-- Transferer to PBX channel: %s State %s\n", transferer->chan1->name, ast_state2str(transferer->chan1->_state));
22406    else
22407       ast_debug(4, "-- No transferer first channel - odd??? \n");
22408    if (target->chan1)
22409       ast_debug(4, "-- Transferer to PBX second channel (target): %s State %s\n", target->chan1->name, ast_state2str(target->chan1->_state));
22410    else
22411       ast_debug(4, "-- No target first channel ---\n");
22412    if (transferer->chan2)
22413       ast_debug(4, "-- Bridged call to transferee: %s State %s\n", transferer->chan2->name, ast_state2str(transferer->chan2->_state));
22414    else
22415       ast_debug(4, "-- No bridged call to transferee\n");
22416    if (target->chan2)
22417       ast_debug(4, "-- Bridged call to transfer target: %s State %s\n", target->chan2 ? target->chan2->name : "<none>", target->chan2 ? ast_state2str(target->chan2->_state) : "(none)");
22418    else
22419       ast_debug(4, "-- No target second channel ---\n");
22420    ast_debug(4, "-- END Sip transfer:--------------------\n");
22421    if (transferer->chan2) { /* We have a bridge on the transferer's channel */
22422       peera = transferer->chan1; /* Transferer - PBX -> transferee channel * the one we hangup */
22423       peerb = target->chan1;     /* Transferer - PBX -> target channel - This will get lost in masq */
22424       peerc = transferer->chan2; /* Asterisk to Transferee */
22425       peerd = target->chan2;     /* Asterisk to Target */
22426       ast_debug(3, "SIP transfer: Four channels to handle\n");
22427    } else if (target->chan2) {   /* Transferer has no bridge (IVR), but transferee */
22428       peera = target->chan1;     /* Transferer to PBX -> target channel */
22429       peerb = transferer->chan1; /* Transferer to IVR*/
22430       peerc = target->chan2;     /* Asterisk to Target */
22431       peerd = transferer->chan2; /* Nothing */
22432       ast_debug(3, "SIP transfer: Three channels to handle\n");
22433    }
22434 
22435    if (peera && peerb && peerc && (peerb != peerc)) {
22436       ast_quiet_chan(peera);     /* Stop generators */
22437       /* no need to quiet peerb since it should be hungup after the
22438          transfer and the masquerade needs to be able to see if MOH is
22439          playing on it */
22440       ast_quiet_chan(peerc);
22441       if (peerd)
22442          ast_quiet_chan(peerd);
22443 
22444       ast_debug(4, "SIP transfer: trying to masquerade %s into %s\n", peerc->name, peerb->name);
22445       if (ast_channel_masquerade(peerb, peerc)) {
22446          ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
22447          res = -1;
22448       } else
22449          ast_debug(4, "SIP transfer: Succeeded to masquerade channels.\n");
22450       return res;
22451    } else {
22452       ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
22453       if (transferer->chan1)
22454          ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
22455       if (target->chan1)
22456          ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
22457       return -1;
22458    }
22459    return 0;
22460 }
22461 
22462 /*! \brief Get tag from packet
22463  *
22464  * \return Returns the pointer to the provided tag buffer,
22465  *         or NULL if the tag was not found.
22466  */
22467 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
22468 {
22469    const char *thetag;
22470 
22471    if (!tagbuf)
22472       return NULL;
22473    tagbuf[0] = '\0';    /* reset the buffer */
22474    thetag = get_header(req, header);
22475    thetag = strcasestr(thetag, ";tag=");
22476    if (thetag) {
22477       thetag += 5;
22478       ast_copy_string(tagbuf, thetag, tagbufsize);
22479       return strsep(&tagbuf, ";");
22480    }
22481    return NULL;
22482 }
22483 
22484 static int handle_cc_notify(struct sip_pvt *pvt, struct sip_request *req)
22485 {
22486    struct sip_monitor_instance *monitor_instance = ao2_callback(sip_monitor_instances, 0,
22487          find_sip_monitor_instance_by_subscription_pvt, pvt);
22488    const char *status = get_body(req, "cc-state", ':');
22489    struct cc_epa_entry *cc_entry;
22490    char *uri;
22491 
22492    if (!monitor_instance) {
22493       transmit_response(pvt, "400 Bad Request", req);
22494       return -1;
22495    }
22496 
22497    if (ast_strlen_zero(status)) {
22498       ao2_ref(monitor_instance, -1);
22499       transmit_response(pvt, "400 Bad Request", req);
22500       return -1;
22501    }
22502 
22503    if (!strcmp(status, "queued")) {
22504       /* We've been told that we're queued. This is the endpoint's way of telling
22505        * us that it has accepted our CC request. We need to alert the core of this
22506        * development
22507        */
22508       ast_cc_monitor_request_acked(monitor_instance->core_id, "SIP endpoint %s accepted request", monitor_instance->device_name);
22509       transmit_response(pvt, "200 OK", req);
22510       ao2_ref(monitor_instance, -1);
22511       return 0;
22512    }
22513 
22514    /* It's open! Yay! */
22515    uri = get_body(req, "cc-URI", ':');
22516    if (ast_strlen_zero(uri)) {
22517       uri = get_in_brackets((char *)get_header(req, "From"));
22518    }
22519 
22520    ast_string_field_set(monitor_instance, notify_uri, uri);
22521    if (monitor_instance->suspension_entry) {
22522       cc_entry = monitor_instance->suspension_entry->instance_data;
22523       if (cc_entry->current_state == CC_CLOSED) {
22524          /* If we've created a suspension entry and the current state is closed, then that means
22525           * we got a notice from the CC core earlier to suspend monitoring, but because this particular
22526           * call leg had not yet notified us that it was ready for recall, it meant that we
22527           * could not yet send a PUBLISH. Now, however, we can.
22528           */
22529          construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body,
22530                sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
22531          transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_INITIAL, monitor_instance->notify_uri);
22532       } else {
22533          ast_cc_monitor_callee_available(monitor_instance->core_id, "SIP monitored callee has become available");
22534       }
22535    } else {
22536       ast_cc_monitor_callee_available(monitor_instance->core_id, "SIP monitored callee has become available");
22537    }
22538    ao2_ref(monitor_instance, -1);
22539    transmit_response(pvt, "200 OK", req);
22540 
22541    return 0;
22542 }
22543 
22544 /*! \brief Handle incoming notifications */
22545 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e)
22546 {
22547    /* This is mostly a skeleton for future improvements */
22548    /* Mostly created to return proper answers on notifications on outbound REFER's */
22549    int res = 0;
22550    const char *event = get_header(req, "Event");
22551    char *sep;
22552 
22553    if( (sep = strchr(event, ';')) ) {  /* XXX bug here - overwriting string ? */
22554       *sep++ = '\0';
22555    }
22556    
22557    if (sipdebug)
22558       ast_debug(2, "Got NOTIFY Event: %s\n", event);
22559 
22560    if (!strcmp(event, "refer")) {
22561       /* Save nesting depth for now, since there might be other events we will
22562          support in the future */
22563 
22564       /* Handle REFER notifications */
22565 
22566       char buf[1024];
22567       char *cmd, *code;
22568       int respcode;
22569       int success = TRUE;
22570 
22571       /* EventID for each transfer... EventID is basically the REFER cseq
22572 
22573        We are getting notifications on a call that we transferred
22574        We should hangup when we are getting a 200 OK in a sipfrag
22575        Check if we have an owner of this event */
22576       
22577       /* Check the content type */
22578       if (strncasecmp(get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
22579          /* We need a sipfrag */
22580          transmit_response(p, "400 Bad request", req);
22581          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22582          return -1;
22583       }
22584 
22585       /* Get the text of the attachment */
22586       if (get_msg_text(buf, sizeof(buf), req)) {
22587          ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
22588          transmit_response(p, "400 Bad request", req);
22589          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22590          return -1;
22591       }
22592 
22593       /*
22594       From the RFC...
22595       A minimal, but complete, implementation can respond with a single
22596       NOTIFY containing either the body:
22597          SIP/2.0 100 Trying
22598       
22599       if the subscription is pending, the body:
22600          SIP/2.0 200 OK
22601       if the reference was successful, the body:
22602          SIP/2.0 503 Service Unavailable
22603       if the reference failed, or the body:
22604          SIP/2.0 603 Declined
22605 
22606       if the REFER request was accepted before approval to follow the
22607       reference could be obtained and that approval was subsequently denied
22608       (see Section 2.4.7).
22609       
22610       If there are several REFERs in the same dialog, we need to
22611       match the ID of the event header...
22612       */
22613       ast_debug(3, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
22614       cmd = ast_skip_blanks(buf);
22615       code = cmd;
22616       /* We are at SIP/2.0 */
22617       while(*code && (*code > 32)) {   /* Search white space */
22618          code++;
22619       }
22620       *code++ = '\0';
22621       code = ast_skip_blanks(code);
22622       sep = code;
22623       sep++;
22624       while(*sep && (*sep > 32)) {  /* Search white space */
22625          sep++;
22626       }
22627       *sep++ = '\0';       /* Response string */
22628       respcode = atoi(code);
22629       switch (respcode) {
22630       case 200:   /* OK: The new call is up, hangup this call */
22631          /* Hangup the call that we are replacing */
22632          break;
22633       case 301: /* Moved permenantly */
22634       case 302: /* Moved temporarily */
22635          /* Do we get the header in the packet in this case? */
22636          success = FALSE;
22637          break;
22638       case 503:   /* Service Unavailable: The new call failed */
22639       case 603:   /* Declined: Not accepted */
22640             /* Cancel transfer, continue the current call */
22641          success = FALSE;
22642          break;
22643       case 0:     /* Parse error */
22644             /* Cancel transfer, continue the current call */
22645          ast_log(LOG_NOTICE, "Error parsing sipfrag in NOTIFY in response to REFER.\n");
22646          success = FALSE;
22647          break;
22648       default:
22649          if (respcode < 200) {
22650             /* ignore provisional responses */
22651             success = -1;
22652          } else {
22653             ast_log(LOG_NOTICE, "Got unknown code '%d' in NOTIFY in response to REFER.\n", respcode);
22654             success = FALSE;
22655          }
22656          break;
22657       }
22658       if (success == FALSE) {
22659          ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
22660       }
22661 
22662       if (p->owner && success != -1) {
22663          enum ast_control_transfer message = success ? AST_TRANSFER_SUCCESS : AST_TRANSFER_FAILED;
22664          ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
22665       }
22666       /* Confirm that we received this packet */
22667       transmit_response(p, "200 OK", req);
22668    } else if (!strcmp(event, "message-summary")) {
22669       const char *mailbox = NULL;
22670       char *c = ast_strdupa(get_body(req, "Voice-Message", ':'));
22671 
22672       if (!p->mwi) {
22673          struct sip_peer *peer = find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
22674 
22675          if (peer) {
22676             mailbox = ast_strdupa(peer->unsolicited_mailbox);
22677             unref_peer(peer, "removing unsolicited mwi ref");
22678          }
22679       } else {
22680          mailbox = p->mwi->mailbox;
22681       }
22682 
22683       if (!ast_strlen_zero(mailbox) && !ast_strlen_zero(c)) {
22684          char *old = strsep(&c, " ");
22685          char *new = strsep(&old, "/");
22686          struct ast_event *event;
22687 
22688          if ((event = ast_event_new(AST_EVENT_MWI,
22689                      AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
22690                      AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, "SIP_Remote",
22691                      AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(new),
22692                      AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(old),
22693                      AST_EVENT_IE_END))) {
22694             ast_event_queue_and_cache(event);
22695          }
22696          transmit_response(p, "200 OK", req);
22697       } else {
22698          transmit_response(p, "489 Bad event", req);
22699          res = -1;
22700       }
22701    } else if (!strcmp(event, "keep-alive")) {
22702        /* Used by Sipura/Linksys for NAT pinhole,
22703         * just confirm that we received the packet. */
22704       transmit_response(p, "200 OK", req);
22705    } else if (!strcmp(event, "call-completion")) {
22706       res = handle_cc_notify(p, req);
22707    } else {
22708       /* We don't understand this event. */
22709       transmit_response(p, "489 Bad event", req);
22710       res = -1;
22711    }
22712 
22713    if (!p->lastinvite)
22714       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22715 
22716    return res;
22717 }
22718 
22719 /*! \brief Handle incoming OPTIONS request
22720    An OPTIONS request should be answered like an INVITE from the same UA, including SDP
22721 */
22722 static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e)
22723 {
22724    const char *msg;
22725    enum sip_get_dest_result gotdest;
22726    int res;
22727 
22728    if (p->lastinvite) {
22729       /* if this is a request in an active dialog, just confirm that the dialog exists. */
22730       transmit_response_with_allow(p, "200 OK", req, 0);
22731       return 0;
22732    }
22733 
22734    if (sip_cfg.auth_options_requests) {
22735       /* Do authentication if this OPTIONS request began the dialog */
22736       copy_request(&p->initreq, req);
22737       set_pvt_allowed_methods(p, req);
22738       res = check_user(p, req, SIP_OPTIONS, e, XMIT_UNRELIABLE, addr);
22739       if (res == AUTH_CHALLENGE_SENT) {
22740          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22741          return 0;
22742       }
22743       if (res < 0) { /* Something failed in authentication */
22744          ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
22745          transmit_response(p, "403 Forbidden", req);
22746          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22747          return 0;
22748       }
22749    }
22750 
22751    /* must go through authentication before getting here */
22752    gotdest = get_destination(p, req, NULL);
22753    build_contact(p);
22754 
22755    if (ast_strlen_zero(p->context))
22756       ast_string_field_set(p, context, sip_cfg.default_context);
22757 
22758    if (ast_shutting_down()) {
22759       msg = "503 Unavailable";
22760    } else {
22761       msg = "404 Not Found";
22762       switch (gotdest) {
22763       case SIP_GET_DEST_INVALID_URI:
22764          msg = "416 Unsupported URI scheme";
22765          break;
22766       case SIP_GET_DEST_EXTEN_MATCHMORE:
22767       case SIP_GET_DEST_REFUSED:
22768       case SIP_GET_DEST_EXTEN_NOT_FOUND:
22769          //msg = "404 Not Found";
22770          break;
22771       case SIP_GET_DEST_EXTEN_FOUND:
22772          msg = "200 OK";
22773          break;
22774       }
22775    }
22776    transmit_response_with_allow(p, msg, req, 0);
22777 
22778    /* Destroy if this OPTIONS was the opening request, but not if
22779       it's in the middle of a normal call flow. */
22780    sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22781 
22782    return 0;
22783 }
22784 
22785 /*! \brief Handle the transfer part of INVITE with a replaces: header,
22786     meaning a target pickup or an attended transfer.
22787     Used only once.
22788    XXX 'ignore' is unused.
22789 
22790    \note this function is called by handle_request_invite(). Four locks
22791    held at the beginning of this function, p, p->owner, p->refer->refer_call and
22792    p->refere->refer_call->owner.  only p's lock should remain at the end of this
22793    function.  p's lock as well as the channel p->owner's lock are held by
22794    handle_request_do(), we unlock p->owner before the masq.  By setting nounlock
22795    we are indicating to handle_request_do() that we have already unlocked the owner.
22796  */
22797 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, struct ast_sockaddr *addr, int *nounlock)
22798 {
22799    int earlyreplace = 0;
22800    int oneleggedreplace = 0;     /* Call with no bridge, propably IVR or voice message */
22801    struct ast_channel *c = p->owner;   /* Our incoming call */
22802    struct ast_channel *replacecall = p->refer->refer_call->owner; /* The channel we're about to take over */
22803    struct ast_channel *targetcall;     /* The bridge to the take-over target */
22804 
22805    /* Check if we're in ring state */
22806    if (replacecall->_state == AST_STATE_RING)
22807       earlyreplace = 1;
22808 
22809    /* Check if we have a bridge */
22810    if (!(targetcall = ast_bridged_channel(replacecall))) {
22811       /* We have no bridge */
22812       if (!earlyreplace) {
22813          ast_debug(2, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", replacecall->name);
22814          oneleggedreplace = 1;
22815       }
22816    }
22817    if (targetcall && targetcall->_state == AST_STATE_RINGING)
22818       ast_debug(4, "SIP transfer: Target channel is in ringing state\n");
22819 
22820    if (targetcall)
22821       ast_debug(4, "SIP transfer: Invite Replace incoming channel should bridge to channel %s while hanging up channel %s\n", targetcall->name, replacecall->name);
22822    else
22823       ast_debug(4, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", replacecall->name);
22824 
22825    if (req->ignore) {
22826       ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
22827       /* We should answer something here. If we are here, the
22828          call we are replacing exists, so an accepted
22829          can't harm */
22830       transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE, FALSE);
22831       /* Do something more clever here */
22832       if (c) {
22833          *nounlock = 1;
22834          ast_channel_unlock(c);
22835       }
22836       ast_channel_unlock(replacecall);
22837       sip_pvt_unlock(p->refer->refer_call);
22838       return 1;
22839    }
22840    if (!c) {
22841       /* What to do if no channel ??? */
22842       ast_log(LOG_ERROR, "Unable to create new channel.  Invite/replace failed.\n");
22843       transmit_response_reliable(p, "503 Service Unavailable", req);
22844       append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
22845       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22846       ast_channel_unlock(replacecall);
22847       sip_pvt_unlock(p->refer->refer_call);
22848       return 1;
22849    }
22850    append_history(p, "Xfer", "INVITE/Replace received");
22851    /* We have three channels to play with
22852       channel c: New incoming call
22853       targetcall: Call from PBX to target
22854       p->refer->refer_call: SIP pvt dialog from transferer to pbx.
22855       replacecall: The owner of the previous
22856       We need to masq C into refer_call to connect to
22857       targetcall;
22858       If we are talking to internal audio stream, target call is null.
22859    */
22860 
22861    /* Fake call progress */
22862    transmit_response(p, "100 Trying", req);
22863    ast_setstate(c, AST_STATE_RING);
22864 
22865    /* Masquerade the new call into the referred call to connect to target call
22866       Targetcall is not touched by the masq */
22867 
22868    /* Answer the incoming call and set channel to UP state */
22869    transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE, FALSE);
22870 
22871    /* Is this a call pickup? */
22872    if (earlyreplace || oneleggedreplace) {
22873       /* Report pickup event, in this order: PICKUP, CHAN_UP, ANSWER */
22874       ast_cel_report_event(replacecall, AST_CEL_PICKUP, NULL, NULL, c);
22875       ast_setstate(c, AST_STATE_UP);
22876       ast_cel_report_event(c, AST_CEL_ANSWER, NULL, NULL, NULL);
22877    } else {
22878       ast_setstate(c, AST_STATE_UP);
22879    }
22880 
22881    /* Stop music on hold and other generators */
22882    ast_quiet_chan(replacecall);
22883    ast_quiet_chan(targetcall);
22884    ast_debug(4, "Invite/Replaces: preparing to masquerade %s into %s\n", c->name, replacecall->name);
22885 
22886    /* Make sure that the masq does not free our PVT for the old call */
22887    if (! earlyreplace && ! oneleggedreplace )
22888       ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER);  /* Delay hangup */
22889 
22890    /* Prepare the masquerade - if this does not happen, we will be gone */
22891    if(ast_channel_masquerade(replacecall, c))
22892       ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
22893    else
22894       ast_debug(4, "Invite/Replaces: Going to masquerade %s into %s\n", c->name, replacecall->name);
22895 
22896    /* C should now be in place of replacecall. all channel locks and pvt locks should be removed
22897     * before issuing the masq.  Since we are unlocking both the pvt (p) and its owner channel (c)
22898     * it is possible for channel c to be destroyed on us.  To prevent this, we must give c a reference
22899     * before any unlocking takes place and remove it only once we are completely done with it */
22900    ast_channel_ref(c);
22901    ast_channel_unlock(replacecall);
22902    ast_channel_unlock(c);
22903    sip_pvt_unlock(p->refer->refer_call);
22904    sip_pvt_unlock(p);
22905    if (ast_do_masquerade(replacecall)) {
22906       ast_log(LOG_WARNING, "Failed to perform masquerade with INVITE replaces\n");
22907    }
22908    if (earlyreplace || oneleggedreplace ) {
22909       ast_channel_lock(c);
22910       c->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
22911       ast_channel_unlock(c);
22912    }
22913 
22914    /* The call should be down with no ast_channel, so hang it up */
22915    c->tech_pvt = dialog_unref(c->tech_pvt, "unref dialog c->tech_pvt");
22916 
22917    /* c and c's tech pvt must be unlocked at this point for ast_hangup */
22918    ast_hangup(c);
22919    /* this indicates to handle_request_do that the owner channel has already been unlocked */
22920    *nounlock = 1;
22921    /* lock PVT structure again after hangup */
22922    sip_pvt_lock(p);
22923    ast_channel_unref(c);
22924    return 0;
22925 }
22926 
22927 /*! \note No channel or pvt locks should be held while calling this function. */
22928 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context)
22929 {
22930    struct ast_str *str = ast_str_alloca(AST_MAX_EXTENSION + AST_MAX_CONTEXT + 2);
22931    struct ast_app *pickup = pbx_findapp("Pickup");
22932 
22933    if (!pickup) {
22934       ast_log(LOG_ERROR, "Unable to perform pickup: Application 'Pickup' not loaded (app_directed_pickup.so).\n");
22935       return -1;
22936    }
22937 
22938    ast_str_set(&str, 0, "%s@%s", extension, sip_cfg.notifycid == IGNORE_CONTEXT ? "PICKUPMARK" : context);
22939 
22940    ast_debug(2, "About to call Pickup(%s)\n", ast_str_buffer(str));
22941 
22942    /* There is no point in capturing the return value since pickup_exec
22943       doesn't return anything meaningful unless the passed data is an empty
22944       string (which in our case it will not be) */
22945    pbx_exec(channel, pickup, ast_str_buffer(str));
22946 
22947    return 0;
22948 }
22949 
22950 /*! \brief Called to deny a T38 reinvite if the core does not respond to our request */
22951 static int sip_t38_abort(const void *data)
22952 {
22953    struct sip_pvt *p = (struct sip_pvt *) data;
22954 
22955    sip_pvt_lock(p);
22956    /* an application may have taken ownership of the T.38 negotiation on this
22957     * channel while we were waiting to grab the lock... if it did, the scheduler
22958     * id will have been reset to -1, which is our indication that we do *not*
22959     * want to abort the negotiation process
22960     */
22961    if (p->t38id != -1) {
22962       change_t38_state(p, T38_DISABLED);
22963       transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
22964       p->t38id = -1;
22965       dialog_unref(p, "unref the dialog ptr from sip_t38_abort, because it held a dialog ptr");
22966    }
22967    sip_pvt_unlock(p);
22968    return 0;
22969 }
22970 
22971 /*!
22972  * \brief bare-bones support for SIP UPDATE
22973  *
22974  * XXX This is not even close to being RFC 3311-compliant. We don't advertise
22975  * that we support the UPDATE method, so no one should ever try sending us
22976  * an UPDATE anyway. However, Asterisk can send an UPDATE to change connected
22977  * line information, so we need to be prepared to handle this. The way we distinguish
22978  * such an UPDATE is through the X-Asterisk-rpid-update header.
22979  *
22980  * Actually updating the media session may be some future work.
22981  */
22982 static int handle_request_update(struct sip_pvt *p, struct sip_request *req)
22983 {
22984    if (ast_strlen_zero(get_header(req, "X-Asterisk-rpid-update"))) {
22985       transmit_response(p, "501 Method Not Implemented", req);
22986       return 0;
22987    }
22988    if (!p->owner) {
22989       transmit_response(p, "481 Call/Transaction Does Not Exist", req);
22990       return 0;
22991    }
22992    if (get_rpid(p, req)) {
22993       struct ast_party_connected_line connected;
22994       struct ast_set_party_connected_line update_connected;
22995 
22996       ast_party_connected_line_init(&connected);
22997       memset(&update_connected, 0, sizeof(update_connected));
22998 
22999       update_connected.id.number = 1;
23000       connected.id.number.valid = 1;
23001       connected.id.number.str = (char *) p->cid_num;
23002       connected.id.number.presentation = p->callingpres;
23003 
23004       update_connected.id.name = 1;
23005       connected.id.name.valid = 1;
23006       connected.id.name.str = (char *) p->cid_name;
23007       connected.id.name.presentation = p->callingpres;
23008 
23009       connected.id.tag = (char *) p->cid_tag;
23010       connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
23011       ast_channel_queue_connected_line_update(p->owner, &connected, &update_connected);
23012    }
23013    transmit_response(p, "200 OK", req);
23014    return 0;
23015 }
23016 
23017 /*
23018  * \internal \brief Check Session Timers for an INVITE request
23019  *
23020  * \retval 0 ok
23021  * \retval -1 failure
23022  */
23023 static int handle_request_invite_st(struct sip_pvt *p, struct sip_request *req,
23024       const char *required, int reinvite)
23025 {
23026    const char *p_uac_se_hdr;       /* UAC's Session-Expires header string                      */
23027    const char *p_uac_min_se;       /* UAC's requested Min-SE interval (char string)            */
23028    int uac_max_se = -1;            /* UAC's Session-Expires in integer format                  */
23029    int uac_min_se = -1;            /* UAC's Min-SE in integer format                           */
23030    int st_active = FALSE;          /* Session-Timer on/off boolean                             */
23031    int st_interval = 0;            /* Session-Timer negotiated refresh interval                */
23032    enum st_refresher tmp_st_ref = SESSION_TIMER_REFRESHER_AUTO; /* Session-Timer refresher     */
23033    int dlg_min_se = -1;
23034    int dlg_max_se = global_max_se;
23035    int rtn;
23036 
23037    /* Session-Timers */
23038    if ((p->sipoptions & SIP_OPT_TIMER)) {
23039       enum st_refresher_param st_ref_param = SESSION_TIMER_REFRESHER_PARAM_UNKNOWN;
23040 
23041       /* The UAC has requested session-timers for this session. Negotiate
23042       the session refresh interval and who will be the refresher */
23043       ast_debug(2, "Incoming INVITE with 'timer' option supported\n");
23044 
23045       /* Allocate Session-Timers struct w/in the dialog */
23046       if (!p->stimer) {
23047          sip_st_alloc(p);
23048       }
23049 
23050       /* Parse the Session-Expires header */
23051       p_uac_se_hdr = get_header(req, "Session-Expires");
23052       if (!ast_strlen_zero(p_uac_se_hdr)) {
23053          ast_debug(2, "INVITE also has \"Session-Expires\" header.\n");
23054          rtn = parse_session_expires(p_uac_se_hdr, &uac_max_se, &st_ref_param);
23055          tmp_st_ref = (st_ref_param == SESSION_TIMER_REFRESHER_PARAM_UAC) ? SESSION_TIMER_REFRESHER_THEM : SESSION_TIMER_REFRESHER_US;
23056          if (rtn != 0) {
23057             transmit_response_reliable(p, "400 Session-Expires Invalid Syntax", req);
23058             return -1;
23059          }
23060       }
23061 
23062       /* Parse the Min-SE header */
23063       p_uac_min_se = get_header(req, "Min-SE");
23064       if (!ast_strlen_zero(p_uac_min_se)) {
23065          ast_debug(2, "INVITE also has \"Min-SE\" header.\n");
23066          rtn = parse_minse(p_uac_min_se, &uac_min_se);
23067          if (rtn != 0) {
23068             transmit_response_reliable(p, "400 Min-SE Invalid Syntax", req);
23069             return -1;
23070          }
23071       }
23072 
23073       dlg_min_se = st_get_se(p, FALSE);
23074       switch (st_get_mode(p, 1)) {
23075       case SESSION_TIMER_MODE_ACCEPT:
23076       case SESSION_TIMER_MODE_ORIGINATE:
23077          if (uac_max_se > 0 && uac_max_se < dlg_min_se) {
23078             transmit_response_with_minse(p, "422 Session Interval Too Small", req, dlg_min_se);
23079             return -1;
23080          }
23081 
23082          p->stimer->st_active_peer_ua = TRUE;
23083          st_active = TRUE;
23084          if (st_ref_param == SESSION_TIMER_REFRESHER_PARAM_UNKNOWN) {
23085             tmp_st_ref = st_get_refresher(p);
23086          }
23087 
23088          dlg_max_se = st_get_se(p, TRUE);
23089          if (uac_max_se > 0) {
23090             if (dlg_max_se >= uac_min_se) {
23091                st_interval = (uac_max_se < dlg_max_se) ? uac_max_se : dlg_max_se;
23092             } else {
23093                st_interval = uac_max_se;
23094             }
23095          } else if (uac_min_se > 0) {
23096             st_interval = MAX(dlg_max_se, uac_min_se);
23097          } else {
23098             st_interval = dlg_max_se;
23099          }
23100          break;
23101 
23102       case SESSION_TIMER_MODE_REFUSE:
23103          if (p->reqsipoptions & SIP_OPT_TIMER) {
23104             transmit_response_with_unsupported(p, "420 Option Disabled", req, required);
23105             ast_log(LOG_WARNING, "Received SIP INVITE with supported but disabled option: %s\n", required);
23106             return -1;
23107          }
23108          break;
23109 
23110       default:
23111          ast_log(LOG_ERROR, "Internal Error %u at %s:%d\n", st_get_mode(p, 1), __FILE__, __LINE__);
23112          break;
23113       }
23114    } else {
23115       /* The UAC did not request session-timers.  Asterisk (UAS), will now decide
23116       (based on session-timer-mode in sip.conf) whether to run session-timers for
23117       this session or not. */
23118       switch (st_get_mode(p, 1)) {
23119       case SESSION_TIMER_MODE_ORIGINATE:
23120          st_active = TRUE;
23121          st_interval = st_get_se(p, TRUE);
23122          tmp_st_ref = SESSION_TIMER_REFRESHER_US;
23123          p->stimer->st_active_peer_ua = (p->sipoptions & SIP_OPT_TIMER) ? TRUE : FALSE;
23124          break;
23125 
23126       default:
23127          break;
23128       }
23129    }
23130 
23131    if (reinvite == 0) {
23132       /* Session-Timers: Start session refresh timer based on negotiation/config */
23133       if (st_active == TRUE) {
23134          p->stimer->st_active = TRUE;
23135          p->stimer->st_interval = st_interval;
23136          p->stimer->st_ref = tmp_st_ref;
23137       }
23138    } else {
23139       if (p->stimer->st_active == TRUE) {
23140          /* Session-Timers:  A re-invite request sent within a dialog will serve as
23141          a refresh request, no matter whether the re-invite was sent for refreshing
23142          the session or modifying it.*/
23143          ast_debug (2, "Restarting session-timers on a refresh - %s\n", p->callid);
23144 
23145          /* The UAC may be adjusting the session-timers mid-session */
23146          if (st_interval > 0) {
23147             p->stimer->st_interval = st_interval;
23148             p->stimer->st_ref      = tmp_st_ref;
23149          }
23150       }
23151    }
23152 
23153    return 0;
23154 }
23155 
23156 /*!
23157  * \brief Handle incoming INVITE request
23158  * \note If the INVITE has a Replaces header, it is part of an
23159  * attended transfer. If so, we do not go through the dial
23160  * plan but try to find the active call and masquerade
23161  * into it
23162  */
23163 static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, struct ast_sockaddr *addr, int *recount, const char *e, int *nounlock)
23164 {
23165    int res = 1;
23166    int gotdest;
23167    const char *p_replaces;
23168    char *replace_id = NULL;
23169    int refer_locked = 0;
23170    const char *required;
23171    unsigned int required_profile = 0;
23172    struct ast_channel *c = NULL;    /* New channel */
23173    struct sip_peer *authpeer = NULL;   /* Matching Peer */
23174    int reinvite = 0;
23175    struct ast_party_redirecting redirecting;
23176    struct ast_set_party_redirecting update_redirecting;
23177    int supported_start = 0;
23178    int require_start = 0;
23179    char unsupported[256] = { 0, };
23180    struct {
23181       char exten[AST_MAX_EXTENSION];
23182       char context[AST_MAX_CONTEXT];
23183    } pickup = {
23184          .exten = "",
23185    };
23186 
23187    /* Find out what they support */
23188    if (!p->sipoptions) {
23189       const char *supported = NULL;
23190       do {
23191          supported = __get_header(req, "Supported", &supported_start);
23192          if (!ast_strlen_zero(supported)) {
23193             p->sipoptions |= parse_sip_options(supported, NULL, 0);
23194          }
23195       } while (!ast_strlen_zero(supported));
23196    }
23197 
23198    /* Find out what they require */
23199    do {
23200       required = __get_header(req, "Require", &require_start);
23201       if (!ast_strlen_zero(required)) {
23202          required_profile |= parse_sip_options(required, unsupported, ARRAY_LEN(unsupported));
23203       }
23204    } while (!ast_strlen_zero(required));
23205 
23206    /* If there are any options required that we do not support,
23207     * then send a 420 with only those unsupported options listed */
23208    if (!ast_strlen_zero(unsupported)) {
23209       transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, unsupported);
23210       ast_log(LOG_WARNING, "Received SIP INVITE with unsupported required extension: required:%s unsupported:%s\n", required, unsupported);
23211       p->invitestate = INV_COMPLETED;
23212       if (!p->lastinvite) {
23213          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23214       }
23215       res = -1;
23216       goto request_invite_cleanup;
23217    }
23218 
23219 
23220    /* The option tags may be present in Supported: or Require: headers.
23221    Include the Require: option tags for further processing as well */
23222    p->sipoptions |= required_profile;
23223    p->reqsipoptions = required_profile;
23224 
23225    /* Check if this is a loop */
23226    if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && p->owner && (p->invitestate != INV_TERMINATED && p->invitestate != INV_CONFIRMED) && p->owner->_state != AST_STATE_UP) {
23227       /* This is a call to ourself.  Send ourselves an error code and stop
23228          processing immediately, as SIP really has no good mechanism for
23229          being able to call yourself */
23230       /* If pedantic is on, we need to check the tags. If they're different, this is
23231          in fact a forked call through a SIP proxy somewhere. */
23232       int different;
23233       const char *initial_rlPart2 = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
23234       const char *this_rlPart2 = REQ_OFFSET_TO_STR(req, rlPart2);
23235       if (sip_cfg.pedanticsipchecking)
23236          different = sip_uri_cmp(initial_rlPart2, this_rlPart2);
23237       else
23238          different = strcmp(initial_rlPart2, this_rlPart2);
23239       if (!different) {
23240          transmit_response(p, "482 Loop Detected", req);
23241          p->invitestate = INV_COMPLETED;
23242          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23243          res = 0;
23244          goto request_invite_cleanup;
23245       } else {
23246          /*! This is a spiral. What we need to do is to just change the outgoing INVITE
23247           * so that it now routes to the new Request URI. Since we created the INVITE ourselves
23248           * that should be all we need to do.
23249           *
23250           * \todo XXX This needs to be reviewed.  YOu don't change the request URI really, you route the packet
23251           * correctly instead...
23252           */
23253          char *uri = ast_strdupa(this_rlPart2);
23254          char *at = strchr(uri, '@');
23255          char *peerorhost;
23256          ast_debug(2, "Potential spiral detected. Original RURI was %s, new RURI is %s\n", initial_rlPart2, this_rlPart2);
23257          transmit_response(p, "100 Trying", req);
23258          if (at) {
23259             *at = '\0';
23260          }
23261          /* Parse out "sip:" */
23262          if ((peerorhost = strchr(uri, ':'))) {
23263             *peerorhost++ = '\0';
23264          }
23265          ast_string_field_set(p, theirtag, NULL);
23266          /* Treat this as if there were a call forward instead...
23267           */
23268          ast_string_field_set(p->owner, call_forward, peerorhost);
23269          ast_queue_control(p->owner, AST_CONTROL_BUSY);
23270          res = 0;
23271          goto request_invite_cleanup;
23272       }
23273    }
23274 
23275    if (!req->ignore && p->pendinginvite) {
23276       if (!ast_test_flag(&p->flags[0], SIP_OUTGOING) && (p->invitestate == INV_COMPLETED || p->invitestate == INV_TERMINATED)) {
23277          /* What do these circumstances mean? We have received an INVITE for an "incoming" dialog for which we
23278           * have sent a final response. We have not yet received an ACK, though (which is why p->pendinginvite is non-zero).
23279           * We also know that the INVITE is not a retransmission, because otherwise the "ignore" flag would be set.
23280           * This means that either we are receiving a reinvite for a terminated dialog, or we are receiving an INVITE with
23281           * credentials based on one we challenged earlier.
23282           *
23283           * The action to take in either case is to treat the INVITE as though it contains an implicit ACK for the previous
23284           * transaction. Calling __sip_ack will take care of this by clearing the p->pendinginvite and removing the response
23285           * from the previous transaction from the list of outstanding packets.
23286           */
23287          __sip_ack(p, p->pendinginvite, 1, 0);
23288       } else {
23289          /* We already have a pending invite. Sorry. You are on hold. */
23290          p->glareinvite = seqno;
23291          if (p->rtp && find_sdp(req)) {
23292             struct ast_sockaddr addr;
23293             if (get_ip_and_port_from_sdp(req, SDP_AUDIO, &addr)) {
23294                ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Audio may not work properly on this call.\n");
23295             } else {
23296                ast_rtp_instance_set_alt_remote_address(p->rtp, &addr);
23297             }
23298             if (p->vrtp) {
23299                if (get_ip_and_port_from_sdp(req, SDP_VIDEO, &addr)) {
23300                   ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Video may not work properly on this call.\n");
23301                } else {
23302                   ast_rtp_instance_set_alt_remote_address(p->vrtp, &addr);
23303                }
23304             }
23305          }
23306          transmit_response_reliable(p, "491 Request Pending", req);
23307          check_via(p, req);
23308          ast_debug(1, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
23309          /* Don't destroy dialog here */
23310          res = 0;
23311          goto request_invite_cleanup;
23312       }
23313    }
23314 
23315    p_replaces = get_header(req, "Replaces");
23316    if (!ast_strlen_zero(p_replaces)) {
23317       /* We have a replaces header */
23318       char *ptr;
23319       char *fromtag = NULL;
23320       char *totag = NULL;
23321       char *start, *to;
23322       int error = 0;
23323 
23324       if (p->owner) {
23325          ast_debug(3, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
23326          transmit_response_reliable(p, "400 Bad request", req);   /* The best way to not not accept the transfer */
23327          check_via(p, req);
23328          copy_request(&p->initreq, req);
23329          /* Do not destroy existing call */
23330          res = -1;
23331          goto request_invite_cleanup;
23332       }
23333 
23334       if (sipdebug)
23335          ast_debug(3, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
23336       /* Create a buffer we can manipulate */
23337       replace_id = ast_strdupa(p_replaces);
23338       ast_uri_decode(replace_id);
23339 
23340       if (!p->refer && !sip_refer_allocate(p)) {
23341          transmit_response_reliable(p, "500 Server Internal Error", req);
23342          append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
23343          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23344          p->invitestate = INV_COMPLETED;
23345          check_via(p, req);
23346          copy_request(&p->initreq, req);
23347          res = -1;
23348          goto request_invite_cleanup;
23349       }
23350 
23351       /*  Todo: (When we find phones that support this)
23352          if the replaces header contains ";early-only"
23353          we can only replace the call in early
23354          stage, not after it's up.
23355 
23356          If it's not in early mode, 486 Busy.
23357       */
23358 
23359       /* Skip leading whitespace */
23360       replace_id = ast_skip_blanks(replace_id);
23361 
23362       start = replace_id;
23363       while ( (ptr = strsep(&start, ";")) ) {
23364          ptr = ast_skip_blanks(ptr); /* XXX maybe unnecessary ? */
23365          if ( (to = strcasestr(ptr, "to-tag=") ) )
23366             totag = to + 7;   /* skip the keyword */
23367          else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
23368             fromtag = to + 9; /* skip the keyword */
23369             fromtag = strsep(&fromtag, "&"); /* trim what ? */
23370          }
23371       }
23372 
23373       if (sipdebug)
23374          ast_debug(4, "Invite/replaces: Will use Replace-Call-ID : %s Fromtag: %s Totag: %s\n",
23375                  replace_id,
23376                  fromtag ? fromtag : "<no from tag>",
23377                  totag ? totag : "<no to tag>");
23378 
23379       /* Try to find call that we are replacing.
23380          If we have a Replaces header, we need to cancel that call if we succeed with this call.
23381          First we cheat a little and look for a magic call-id from phones that support
23382          dialog-info+xml so we can do technology independent pickup... */
23383       if (strncmp(replace_id, "pickup-", 7) == 0) {
23384          struct sip_pvt *subscription = NULL;
23385          replace_id += 7; /* Worst case we are looking at \0 */
23386 
23387          if ((subscription = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
23388             ast_log(LOG_NOTICE, "Unable to find subscription with call-id: %s\n", replace_id);
23389             transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
23390             error = 1;
23391          } else {
23392             ast_log(LOG_NOTICE, "Trying to pick up %s@%s\n", subscription->exten, subscription->context);
23393             ast_copy_string(pickup.exten, subscription->exten, sizeof(pickup.exten));
23394             ast_copy_string(pickup.context, subscription->context, sizeof(pickup.context));
23395             sip_pvt_unlock(subscription);
23396             if (subscription->owner) {
23397                ast_channel_unlock(subscription->owner);
23398             }
23399             subscription = dialog_unref(subscription, "unref dialog subscription");
23400          }
23401       }
23402 
23403       /* This locks both refer_call pvt and refer_call pvt's owner!!!*/
23404       if (!error && ast_strlen_zero(pickup.exten) && (p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
23405          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
23406          transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
23407          error = 1;
23408       } else {
23409          refer_locked = 1;
23410       }
23411 
23412       /* The matched call is the call from the transferer to Asterisk .
23413          We want to bridge the bridged part of the call to the
23414          incoming invite, thus taking over the refered call */
23415 
23416       if (p->refer->refer_call == p) {
23417          ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
23418          transmit_response_reliable(p, "400 Bad request", req);   /* The best way to not not accept the transfer */
23419          error = 1;
23420       }
23421 
23422       if (!error && ast_strlen_zero(pickup.exten) && !p->refer->refer_call->owner) {
23423          /* Oops, someting wrong anyway, no owner, no call */
23424          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
23425          /* Check for better return code */
23426          transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replace)", req);
23427          error = 1;
23428       }
23429 
23430       if (!error && ast_strlen_zero(pickup.exten) && p->refer->refer_call->owner->_state != AST_STATE_RINGING && p->refer->refer_call->owner->_state != AST_STATE_RING && p->refer->refer_call->owner->_state != AST_STATE_UP) {
23431          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
23432          transmit_response_reliable(p, "603 Declined (Replaces)", req);
23433          error = 1;
23434       }
23435 
23436       if (error) {   /* Give up this dialog */
23437          append_history(p, "Xfer", "INVITE/Replace Failed.");
23438          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23439          sip_pvt_unlock(p);
23440          if (p->refer->refer_call) {
23441             sip_pvt_unlock(p->refer->refer_call);
23442             if (p->refer->refer_call->owner) {
23443                ast_channel_unlock(p->refer->refer_call->owner);
23444             }
23445             p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
23446          }
23447          refer_locked = 0;
23448          p->invitestate = INV_COMPLETED;
23449          check_via(p, req);
23450          copy_request(&p->initreq, req);
23451          res = -1;
23452          goto request_invite_cleanup;
23453       }
23454    }
23455 
23456    /* Check if this is an INVITE that sets up a new dialog or
23457       a re-invite in an existing dialog */
23458 
23459    if (!req->ignore) {
23460       int newcall = (p->initreq.headers ? TRUE : FALSE);
23461 
23462       if (sip_cancel_destroy(p))
23463          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
23464       /* This also counts as a pending invite */
23465       p->pendinginvite = seqno;
23466       check_via(p, req);
23467 
23468       copy_request(&p->initreq, req);     /* Save this INVITE as the transaction basis */
23469       if (sipdebug)
23470          ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
23471       if (!p->owner) {  /* Not a re-invite */
23472          if (debug)
23473             ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
23474          if (newcall)
23475             append_history(p, "Invite", "New call: %s", p->callid);
23476          parse_ok_contact(p, req);
23477       } else { /* Re-invite on existing call */
23478          ast_clear_flag(&p->flags[0], SIP_OUTGOING);  /* This is now an inbound dialog */
23479          if (get_rpid(p, req)) {
23480             struct ast_party_connected_line connected;
23481             struct ast_set_party_connected_line update_connected;
23482 
23483             ast_party_connected_line_init(&connected);
23484             memset(&update_connected, 0, sizeof(update_connected));
23485 
23486             update_connected.id.number = 1;
23487             connected.id.number.valid = 1;
23488             connected.id.number.str = (char *) p->cid_num;
23489             connected.id.number.presentation = p->callingpres;
23490 
23491             update_connected.id.name = 1;
23492             connected.id.name.valid = 1;
23493             connected.id.name.str = (char *) p->cid_name;
23494             connected.id.name.presentation = p->callingpres;
23495 
23496             connected.id.tag = (char *) p->cid_tag;
23497             connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
23498             ast_channel_queue_connected_line_update(p->owner, &connected,
23499                &update_connected);
23500          }
23501          /* Handle SDP here if we already have an owner */
23502          if (find_sdp(req)) {
23503             if (process_sdp(p, req, SDP_T38_INITIATE)) {
23504                if (!ast_strlen_zero(get_header(req, "Content-Encoding"))) {
23505                   /* Asterisk does not yet support any Content-Encoding methods.  Always
23506                    * attempt to process the sdp, but return a 415 if a Content-Encoding header
23507                    * was present after processing failed.  */
23508                   transmit_response_reliable(p, "415 Unsupported Media type", req);
23509                } else {
23510                   transmit_response_reliable(p, "488 Not acceptable here", req);
23511                }
23512                if (!p->lastinvite)
23513                   sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23514                res = -1;
23515                goto request_invite_cleanup;
23516             }
23517             ast_queue_control(p->owner, AST_CONTROL_SRCUPDATE);
23518          } else {
23519             p->jointcapability = p->capability;
23520             ast_debug(1, "Hm....  No sdp for the moment\n");
23521             /* Some devices signal they want to be put off hold by sending a re-invite
23522                *without* an SDP, which is supposed to mean "Go back to your state"
23523                and since they put os on remote hold, we go back to off hold */
23524             if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
23525                ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
23526                /* Activate a re-invite */
23527                ast_queue_frame(p->owner, &ast_null_frame);
23528                change_hold_state(p, req, FALSE, 0);
23529             }
23530          }
23531          if (p->do_history) /* This is a response, note what it was for */
23532             append_history(p, "ReInv", "Re-invite received");
23533       }
23534    } else if (debug)
23535       ast_verbose("Ignoring this INVITE request\n");
23536 
23537    if (!p->lastinvite && !req->ignore && !p->owner) {
23538       /* This is a new invite */
23539       /* Handle authentication if this is our first invite */
23540       int cc_recall_core_id = -1;
23541       set_pvt_allowed_methods(p, req);
23542       res = check_user_full(p, req, SIP_INVITE, e, XMIT_RELIABLE, addr, &authpeer);
23543       if (res == AUTH_CHALLENGE_SENT) {
23544          p->invitestate = INV_COMPLETED;     /* Needs to restart in another INVITE transaction */
23545          res = 0;
23546          goto request_invite_cleanup;
23547       }
23548       if (res < 0) { /* Something failed in authentication */
23549          ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
23550          transmit_response_reliable(p, "403 Forbidden", req);
23551          p->invitestate = INV_COMPLETED;
23552          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23553          res = 0;
23554          goto request_invite_cleanup;
23555       }
23556 
23557       /* Successful authentication and peer matching so record the peer related to this pvt (for easy access to peer settings) */
23558       if (p->relatedpeer) {
23559          p->relatedpeer = unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
23560       }
23561       if (authpeer) {
23562          p->relatedpeer = ref_peer(authpeer, "setting dialog's relatedpeer pointer");
23563       }
23564 
23565       req->authenticated = 1;
23566 
23567       /* We have a successful authentication, process the SDP portion if there is one */
23568       if (find_sdp(req)) {
23569          if (process_sdp(p, req, SDP_T38_INITIATE)) {
23570             /* Asterisk does not yet support any Content-Encoding methods.  Always
23571              * attempt to process the sdp, but return a 415 if a Content-Encoding header
23572              * was present after processing fails. */
23573             if (!ast_strlen_zero(get_header(req, "Content-Encoding"))) {
23574                transmit_response_reliable(p, "415 Unsupported Media type", req);
23575             } else {
23576                /* Unacceptable codecs */
23577                transmit_response_reliable(p, "488 Not acceptable here", req);
23578             }
23579             p->invitestate = INV_COMPLETED;
23580             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23581             ast_debug(1, "No compatible codecs for this SIP call.\n");
23582             res = -1;
23583             goto request_invite_cleanup;
23584          }
23585       } else { /* No SDP in invite, call control session */
23586          p->jointcapability = p->capability;
23587          ast_debug(2, "No SDP in Invite, third party call control\n");
23588       }
23589 
23590       /* Initialize the context if it hasn't been already */
23591       if (ast_strlen_zero(p->context))
23592          ast_string_field_set(p, context, sip_cfg.default_context);
23593 
23594 
23595       /* Check number of concurrent calls -vs- incoming limit HERE */
23596       ast_debug(1, "Checking SIP call limits for device %s\n", p->username);
23597       if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
23598          if (res < 0) {
23599             ast_log(LOG_NOTICE, "Failed to place call for device %s, too many calls\n", p->username);
23600             transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
23601             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23602             p->invitestate = INV_COMPLETED;
23603          }
23604          res = 0;
23605          goto request_invite_cleanup;
23606       }
23607       gotdest = get_destination(p, NULL, &cc_recall_core_id);  /* Get destination right away */
23608       extract_uri(p, req);       /* Get the Contact URI */
23609       build_contact(p);       /* Build our contact header */
23610 
23611       if (p->rtp) {
23612          ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
23613          ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
23614       }
23615 
23616       if (!replace_id && (gotdest != SIP_GET_DEST_EXTEN_FOUND)) { /* No matching extension found */
23617          switch(gotdest) {
23618          case SIP_GET_DEST_INVALID_URI:
23619             transmit_response_reliable(p, "416 Unsupported URI scheme", req);
23620             break;
23621          case SIP_GET_DEST_EXTEN_MATCHMORE:
23622             if (ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)
23623                == SIP_PAGE2_ALLOWOVERLAP_YES) {
23624                transmit_response_reliable(p, "484 Address Incomplete", req);
23625                break;
23626             }
23627             /*
23628              * XXX We would have to implement collecting more digits in
23629              * chan_sip for any other schemes of overlap dialing.
23630              *
23631              * For SIP_PAGE2_ALLOWOVERLAP_DTMF it is better to do this in
23632              * the dialplan using the Incomplete application rather than
23633              * having the channel driver do it.
23634              */
23635             /* Fall through */
23636          case SIP_GET_DEST_EXTEN_NOT_FOUND:
23637             {
23638                char *decoded_exten = ast_strdupa(p->exten);
23639                transmit_response_reliable(p, "404 Not Found", req);
23640                ast_uri_decode(decoded_exten);
23641                ast_log(LOG_NOTICE, "Call from '%s' (%s) to extension"
23642                   " '%s' rejected because extension not found in context '%s'.\n",
23643                   S_OR(p->username, p->peername), ast_sockaddr_stringify(&p->recv), decoded_exten, p->context);
23644             }
23645             break;
23646          case SIP_GET_DEST_REFUSED:
23647          default:
23648             transmit_response_reliable(p, "403 Forbidden", req);
23649          } /* end switch */
23650 
23651          p->invitestate = INV_COMPLETED;
23652          update_call_counter(p, DEC_CALL_LIMIT);
23653          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23654          res = 0;
23655          goto request_invite_cleanup;
23656       } else {
23657 
23658          /* If no extension was specified, use the s one */
23659          /* Basically for calling to IP/Host name only */
23660          if (ast_strlen_zero(p->exten))
23661             ast_string_field_set(p, exten, "s");
23662          /* Initialize our tag */
23663 
23664          make_our_tag(p);
23665 
23666          if (handle_request_invite_st(p, req, required, reinvite)) {
23667             p->invitestate = INV_COMPLETED;
23668             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23669             res = -1;
23670             goto request_invite_cleanup;
23671          }
23672 
23673          /* First invitation - create the channel.  Allocation
23674           * failures are handled below. */
23675          c = sip_new(p, AST_STATE_DOWN, S_OR(p->peername, NULL), NULL);
23676          if (cc_recall_core_id != -1) {
23677             ast_setup_cc_recall_datastore(c, cc_recall_core_id);
23678             ast_cc_agent_set_interfaces_chanvar(c);
23679          }
23680          *recount = 1;
23681 
23682          /* Save Record-Route for any later requests we make on this dialogue */
23683          build_route(p, req, 0, 0);
23684 
23685          if (c) {
23686             ast_party_redirecting_init(&redirecting);
23687             memset(&update_redirecting, 0, sizeof(update_redirecting));
23688             change_redirecting_information(p, req, &redirecting, &update_redirecting,
23689                FALSE); /*Will return immediately if no Diversion header is present */
23690             ast_channel_set_redirecting(c, &redirecting, &update_redirecting);
23691             ast_party_redirecting_free(&redirecting);
23692          }
23693       }
23694    } else {
23695       ast_party_redirecting_init(&redirecting);
23696       memset(&update_redirecting, 0, sizeof(update_redirecting));
23697       if (sipdebug) {
23698          if (!req->ignore)
23699             ast_debug(2, "Got a SIP re-invite for call %s\n", p->callid);
23700          else
23701             ast_debug(2, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
23702       }
23703       if (!req->ignore)
23704          reinvite = 1;
23705 
23706       if (handle_request_invite_st(p, req, required, reinvite)) {
23707          p->invitestate = INV_COMPLETED;
23708          if (!p->lastinvite) {
23709             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23710          }
23711          res = -1;
23712          goto request_invite_cleanup;
23713       }
23714 
23715       c = p->owner;
23716       change_redirecting_information(p, req, &redirecting, &update_redirecting, FALSE); /*Will return immediately if no Diversion header is present */
23717       if (c) {
23718          ast_channel_set_redirecting(c, &redirecting, &update_redirecting);
23719       }
23720       ast_party_redirecting_free(&redirecting);
23721    }
23722 
23723    if (reinvite && p->stimer->st_active == TRUE) {
23724       restart_session_timer(p);
23725    }
23726 
23727    if (!req->ignore && p)
23728       p->lastinvite = seqno;
23729 
23730    if (c && replace_id) {  /* Attended transfer or call pickup - we're the target */
23731       if (!ast_strlen_zero(pickup.exten)) {
23732          append_history(p, "Xfer", "INVITE/Replace received");
23733 
23734          /* Let the caller know we're giving it a shot */
23735          transmit_response(p, "100 Trying", req);
23736          p->invitestate = INV_PROCEEDING;
23737          ast_setstate(c, AST_STATE_RING);
23738 
23739          /* Do the pickup itself */
23740          ast_channel_unlock(c);
23741          *nounlock = 1;
23742 
23743          /* since p->owner (c) is unlocked, we need to go ahead and unlock pvt for both
23744           * magic pickup and ast_hangup.  Both of these functions will attempt to lock
23745           * p->owner again, which can cause a deadlock if we already hold a lock on p.
23746           * Locking order is, channel then pvt.  Dead lock avoidance must be used if
23747           * called the other way around. */
23748          sip_pvt_unlock(p);
23749          do_magic_pickup(c, pickup.exten, pickup.context);
23750          /* Now we're either masqueraded or we failed to pickup, in either case we... */
23751          ast_hangup(c);
23752          sip_pvt_lock(p); /* pvt is expected to remain locked on return, so re-lock it */
23753 
23754          res = 0;
23755          goto request_invite_cleanup;
23756       } else {
23757          /* Go and take over the target call */
23758          if (sipdebug)
23759             ast_debug(4, "Sending this call to the invite/replcaes handler %s\n", p->callid);
23760          res = handle_invite_replaces(p, req, debug, seqno, addr, nounlock);
23761          refer_locked = 0;
23762          goto request_invite_cleanup;
23763       }
23764    }
23765 
23766 
23767    if (c) { /* We have a call  -either a new call or an old one (RE-INVITE) */
23768       enum ast_channel_state c_state = c->_state;
23769 
23770       if (c_state != AST_STATE_UP && reinvite &&
23771          (p->invitestate == INV_TERMINATED || p->invitestate == INV_CONFIRMED)) {
23772          /* If these conditions are true, and the channel is still in the 'ringing'
23773           * state, then this likely means that we have a situation where the initial
23774           * INVITE transaction has completed *but* the channel's state has not yet been
23775           * changed to UP. The reason this could happen is if the reinvite is received
23776           * on the SIP socket prior to an application calling ast_read on this channel
23777           * to read the answer frame we earlier queued on it. In this case, the reinvite
23778           * is completely legitimate so we need to handle this the same as if the channel
23779           * were already UP. Thus we are purposely falling through to the AST_STATE_UP case.
23780           */
23781          c_state = AST_STATE_UP;
23782       }
23783 
23784       switch(c_state) {
23785       case AST_STATE_DOWN:
23786          ast_debug(2, "%s: New call is still down.... Trying... \n", c->name);
23787          transmit_provisional_response(p, "100 Trying", req, 0);
23788          p->invitestate = INV_PROCEEDING;
23789          ast_setstate(c, AST_STATE_RING);
23790          if (strcmp(p->exten, ast_pickup_ext())) { /* Call to extension -start pbx on this call */
23791             enum ast_pbx_result result;
23792 
23793             result = ast_pbx_start(c);
23794 
23795             switch(result) {
23796             case AST_PBX_FAILED:
23797                ast_log(LOG_WARNING, "Failed to start PBX :(\n");
23798                p->invitestate = INV_COMPLETED;
23799                transmit_response_reliable(p, "503 Unavailable", req);
23800                break;
23801             case AST_PBX_CALL_LIMIT:
23802                ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
23803                p->invitestate = INV_COMPLETED;
23804                transmit_response_reliable(p, "480 Temporarily Unavailable", req);
23805                break;
23806             case AST_PBX_SUCCESS:
23807                /* nothing to do */
23808                break;
23809             }
23810 
23811             if (result) {
23812 
23813                /* Unlock locks so ast_hangup can do its magic */
23814                ast_channel_unlock(c);
23815                *nounlock = 1;
23816                sip_pvt_unlock(p);
23817                ast_hangup(c);
23818                sip_pvt_lock(p);
23819                c = NULL;
23820             }
23821          } else { /* Pickup call in call group */
23822             if (sip_pickup(c)) {
23823                ast_log(LOG_WARNING, "Failed to start Group pickup by %s\n", c->name);
23824                transmit_response_reliable(p, "480 Temporarily Unavailable", req);
23825                sip_alreadygone(p);
23826                c->hangupcause = AST_CAUSE_FAILURE;
23827 
23828                /* Unlock locks so ast_hangup can do its magic */
23829                ast_channel_unlock(c);
23830                *nounlock = 1;
23831 
23832                p->invitestate = INV_COMPLETED;
23833                sip_pvt_unlock(p);
23834                ast_hangup(c);
23835                sip_pvt_lock(p);
23836                c = NULL;
23837             }
23838          }
23839          break;
23840       case AST_STATE_RING:
23841          transmit_provisional_response(p, "100 Trying", req, 0);
23842          p->invitestate = INV_PROCEEDING;
23843          break;
23844       case AST_STATE_RINGING:
23845          transmit_provisional_response(p, "180 Ringing", req, 0);
23846          p->invitestate = INV_PROCEEDING;
23847          break;
23848       case AST_STATE_UP:
23849          ast_debug(2, "%s: This call is UP.... \n", c->name);
23850 
23851          transmit_response(p, "100 Trying", req);
23852 
23853          if (p->t38.state == T38_PEER_REINVITE) {
23854             if (p->t38id > -1) {
23855                /* reset t38 abort timer */
23856                AST_SCHED_DEL_UNREF(sched, p->t38id, dialog_unref(p, "remove ref for t38id"));
23857             }
23858             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."));
23859          } else if (p->t38.state == T38_ENABLED) {
23860             ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
23861             transmit_response_with_t38_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ?  XMIT_UNRELIABLE : XMIT_CRITICAL)));
23862          } else if (p->t38.state == T38_DISABLED) {
23863             /* If this is not a re-invite or something to ignore - it's critical */
23864             if (p->srtp && !ast_test_flag(p->srtp, SRTP_CRYPTO_OFFER_OK)) {
23865                ast_log(LOG_WARNING, "Target does not support required crypto\n");
23866                transmit_response_reliable(p, "488 Not Acceptable Here (crypto)", req);
23867             } else {
23868                ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
23869                transmit_response_with_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ?  XMIT_UNRELIABLE : XMIT_CRITICAL)), p->session_modify == TRUE ? FALSE : TRUE, FALSE);
23870                ast_queue_control(p->owner, AST_CONTROL_UPDATE_RTP_PEER);
23871             }
23872          }
23873 
23874          p->invitestate = INV_TERMINATED;
23875          break;
23876       default:
23877          ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %u\n", c->_state);
23878          transmit_response(p, "100 Trying", req);
23879          break;
23880       }
23881    } else {
23882       if (!req->ignore && p && (p->autokillid == -1)) {
23883          const char *msg;
23884 
23885          if (!p->jointcapability)
23886             msg = "488 Not Acceptable Here (codec error)";
23887          else {
23888             ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
23889             msg = "503 Unavailable";
23890          }
23891          transmit_response_reliable(p, msg, req);
23892          p->invitestate = INV_COMPLETED;
23893          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23894       }
23895    }
23896 
23897 request_invite_cleanup:
23898 
23899    if (refer_locked && p->refer && p->refer->refer_call) {
23900       sip_pvt_unlock(p->refer->refer_call);
23901       if (p->refer->refer_call->owner) {
23902          ast_channel_unlock(p->refer->refer_call->owner);
23903       }
23904       p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
23905    }
23906    if (authpeer) {
23907       authpeer = unref_peer(authpeer, "unref_peer, from handle_request_invite authpeer");
23908    }
23909 
23910    return res;
23911 }
23912 
23913 /*! \brief  Find all call legs and bridge transferee with target
23914  * called from handle_request_refer
23915  *
23916  * \note this function assumes two locks to begin with, sip_pvt transferer and current.chan1 (the pvt's owner)... 
23917  * 2 additional locks are held at the beginning of the function, targetcall_pvt, and targetcall_pvt's owner
23918  * channel (which is stored in target.chan1).  These 2 locks _MUST_ be let go by the end of the function.  Do
23919  * not be confused into thinking a pvt's owner is the same thing as the channels locked at the beginning of
23920  * this function, after the masquerade this may not be true.  Be consistent and unlock only the exact same
23921  * pointers that were locked to begin with.
23922  *
23923  * If this function is successful, only the transferer pvt lock will remain on return.  Setting nounlock indicates
23924  * to handle_request_do() that the pvt's owner it locked does not require an unlock.
23925  */
23926 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, uint32_t seqno, int *nounlock)
23927 {
23928    struct sip_dual target;    /* Chan 1: Call from tranferer to Asterisk */
23929                /* Chan 2: Call from Asterisk to target */
23930    int res = 0;
23931    struct sip_pvt *targetcall_pvt;
23932    struct ast_party_connected_line connected_to_transferee;
23933    struct ast_party_connected_line connected_to_target;
23934    char transferer_linkedid[32];
23935    struct ast_channel *chans[2];
23936 
23937    /* Check if the call ID of the replaces header does exist locally */
23938    if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag,
23939       transferer->refer->replaces_callid_fromtag))) {
23940       if (transferer->refer->localtransfer) {
23941          /* We did not find the refered call. Sorry, can't accept then */
23942          /* Let's fake a response from someone else in order
23943             to follow the standard */
23944          transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
23945          append_history(transferer, "Xfer", "Refer failed");
23946          ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
23947          transferer->refer->status = REFER_FAILED;
23948          return -1;
23949       }
23950       /* Fall through for remote transfers that we did not find locally */
23951       ast_debug(3, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
23952       return 0;
23953    }
23954 
23955    /* Ok, we can accept this transfer */
23956    append_history(transferer, "Xfer", "Refer accepted");
23957    if (!targetcall_pvt->owner) { /* No active channel */
23958       ast_debug(4, "SIP attended transfer: Error: No owner of target call\n");
23959       /* Cancel transfer */
23960       transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
23961       append_history(transferer, "Xfer", "Refer failed");
23962       ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
23963       transferer->refer->status = REFER_FAILED;
23964       sip_pvt_unlock(targetcall_pvt);
23965       if (targetcall_pvt)
23966          ao2_t_ref(targetcall_pvt, -1, "Drop targetcall_pvt pointer");
23967       return -1;
23968    }
23969 
23970    /* We have a channel, find the bridge */
23971    target.chan1 = ast_channel_ref(targetcall_pvt->owner);            /* Transferer to Asterisk */
23972    target.chan2 = ast_bridged_channel(targetcall_pvt->owner);  /* Asterisk to target */
23973    if (target.chan2) {
23974       ast_channel_ref(target.chan2);
23975    }
23976 
23977    if (!target.chan2 || !(target.chan2->_state == AST_STATE_UP || target.chan2->_state == AST_STATE_RINGING) ) {
23978       /* Wrong state of new channel */
23979       if (target.chan2)
23980          ast_debug(4, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(target.chan2->_state));
23981       else if (target.chan1->_state != AST_STATE_RING)
23982          ast_debug(4, "SIP attended transfer: Error: No target channel\n");
23983       else
23984          ast_debug(4, "SIP attended transfer: Attempting transfer in ringing state\n");
23985    }
23986 
23987    /* Transfer */
23988    if (sipdebug) {
23989       if (current->chan2)  /* We have two bridges */
23990          ast_debug(4, "SIP attended transfer: trying to bridge %s and %s\n", target.chan1->name, current->chan2->name);
23991       else        /* One bridge, propably transfer of IVR/voicemail etc */
23992          ast_debug(4, "SIP attended transfer: trying to make %s take over (masq) %s\n", target.chan1->name, current->chan1->name);
23993    }
23994 
23995    ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);   /* Delay hangup */
23996 
23997    ast_copy_string(transferer_linkedid, transferer->owner->linkedid, sizeof(transferer_linkedid));
23998 
23999    /* Perform the transfer */
24000    chans[0] = transferer->owner;
24001    chans[1] = target.chan1;
24002    ast_manager_event_multichan(EVENT_FLAG_CALL, "Transfer", 2, chans,
24003       "TransferMethod: SIP\r\n"
24004       "TransferType: Attended\r\n"
24005       "Channel: %s\r\n"
24006       "Uniqueid: %s\r\n"
24007       "SIP-Callid: %s\r\n"
24008       "TargetChannel: %s\r\n"
24009       "TargetUniqueid: %s\r\n",
24010       transferer->owner->name,
24011       transferer->owner->uniqueid,
24012       transferer->callid,
24013       target.chan1->name,
24014       target.chan1->uniqueid);
24015    ast_party_connected_line_init(&connected_to_transferee);
24016    ast_party_connected_line_init(&connected_to_target);
24017    /* No need to lock current->chan1 here since it was locked in sipsock_read */
24018    ast_party_connected_line_copy(&connected_to_transferee, &current->chan1->connected);
24019    /* No need to lock target.chan1 here since it was locked in get_sip_pvt_byid_locked */
24020    ast_party_connected_line_copy(&connected_to_target, &target.chan1->connected);
24021    connected_to_target.source = connected_to_transferee.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
24022    res = attempt_transfer(current, &target);
24023    if (res) {
24024       /* Failed transfer */
24025       transmit_notify_with_sipfrag(transferer, seqno, "486 Busy Here", TRUE);
24026       append_history(transferer, "Xfer", "Refer failed");
24027       ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
24028       /* if transfer failed, go ahead and unlock targetcall_pvt and it's owner channel */
24029       sip_pvt_unlock(targetcall_pvt);
24030       ast_channel_unlock(target.chan1);
24031    } else {
24032       /* Transfer succeeded! */
24033       const char *xfersound = pbx_builtin_getvar_helper(target.chan1, "ATTENDED_TRANSFER_COMPLETE_SOUND");
24034 
24035       /* target.chan1 was locked in get_sip_pvt_byid_locked, do not unlock target.chan1 before this */
24036       ast_cel_report_event(target.chan1, AST_CEL_ATTENDEDTRANSFER, NULL, transferer_linkedid, target.chan2);
24037 
24038       /* Tell transferer that we're done. */
24039       transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
24040       append_history(transferer, "Xfer", "Refer succeeded");
24041       transferer->refer->status = REFER_200OK;
24042       if (target.chan2 && !ast_strlen_zero(xfersound) && ast_streamfile(target.chan2, xfersound, target.chan2->language) >= 0) {
24043          ast_waitstream(target.chan2, "");
24044       }
24045 
24046       /* By forcing the masquerade, we know that target.chan1 and target.chan2 are bridged. We then
24047        * can queue connected line updates where they need to go.
24048        *
24049        * before a masquerade, all channel and pvt locks must be unlocked.  Any recursive
24050        * channel locks held before this function invalidates channel container locking order.
24051        * Since we are unlocking both the pvt (transferer) and its owner channel (current.chan1)
24052        * it is possible for current.chan1 to be destroyed in the pbx thread.  To prevent this
24053        * we must give c a reference before any unlocking takes place.
24054        */
24055 
24056       ast_channel_ref(current->chan1);
24057       ast_channel_unlock(current->chan1); /* current.chan1 is p->owner before the masq, it was locked by socket_read()*/
24058       ast_channel_unlock(target.chan1);
24059       *nounlock = 1;  /* we just unlocked the dialog's channel and have no plans of locking it again. */
24060       sip_pvt_unlock(targetcall_pvt);
24061       sip_pvt_unlock(transferer);
24062 
24063       ast_do_masquerade(target.chan1);
24064 
24065       if (target.chan2) {
24066          ast_indicate(target.chan2, AST_CONTROL_UNHOLD);
24067       }
24068 
24069       if (current->chan2 && current->chan2->_state == AST_STATE_RING) {
24070          ast_indicate(target.chan1, AST_CONTROL_RINGING);
24071       }
24072 
24073       if (target.chan2) {
24074          ast_channel_queue_connected_line_update(target.chan1, &connected_to_transferee, NULL);
24075          ast_channel_queue_connected_line_update(target.chan2, &connected_to_target, NULL);
24076       } else {
24077          /* Since target.chan1 isn't actually connected to another channel, there is no way for us
24078           * to queue a frame so that its connected line status will be updated.
24079           *
24080           * Instead, we use the somewhat hackish approach of using a special control frame type that
24081           * instructs ast_read to perform a specific action. In this case, the frame we queue tells
24082           * ast_read to call the connected line interception macro configured for target.chan1.
24083           */
24084          struct ast_control_read_action_payload *frame_payload;
24085          int payload_size;
24086          int frame_size;
24087          unsigned char connected_line_data[1024];
24088          payload_size = ast_connected_line_build_data(connected_line_data,
24089             sizeof(connected_line_data), &connected_to_target, NULL);
24090          frame_size = payload_size + sizeof(*frame_payload);
24091          if (payload_size != -1) {
24092             frame_payload = ast_alloca(frame_size);
24093             frame_payload->payload_size = payload_size;
24094             memcpy(frame_payload->payload, connected_line_data, payload_size);
24095             frame_payload->action = AST_FRAME_READ_ACTION_CONNECTED_LINE_MACRO;
24096             ast_queue_control_data(target.chan1, AST_CONTROL_READ_ACTION, frame_payload, frame_size);
24097          }
24098          /* In addition to queueing the read action frame so that target.chan1's connected line info
24099           * will be updated, we also are going to queue a plain old connected line update on target.chan1. This
24100           * way, either Dial or Queue can apply this connected line update to the outgoing ringing channel.
24101           */
24102          ast_channel_queue_connected_line_update(target.chan1, &connected_to_transferee, NULL);
24103 
24104       }
24105       sip_pvt_lock(transferer); /* the transferer pvt is expected to remain locked on return */
24106 
24107       ast_channel_unref(current->chan1);
24108    }
24109 
24110    /* at this point if the transfer is successful only the transferer pvt should be locked. */
24111    ast_party_connected_line_free(&connected_to_target);
24112    ast_party_connected_line_free(&connected_to_transferee);
24113    ast_channel_unref(target.chan1);
24114    if (target.chan2) {
24115       ast_channel_unref(target.chan2);
24116    }
24117    if (targetcall_pvt)
24118       ao2_t_ref(targetcall_pvt, -1, "drop targetcall_pvt");
24119    return 1;
24120 }
24121 
24122 
24123 /*! \brief Handle incoming REFER request */
24124 /*! \page SIP_REFER SIP transfer Support (REFER)
24125 
24126    REFER is used for call transfer in SIP. We get a REFER
24127    to place a new call with an INVITE somwhere and then
24128    keep the transferor up-to-date of the transfer. If the
24129    transfer fails, get back on line with the orginal call.
24130 
24131    - REFER can be sent outside or inside of a dialog.
24132      Asterisk only accepts REFER inside of a dialog.
24133 
24134    - If we get a replaces header, it is an attended transfer
24135 
24136    \par Blind transfers
24137    The transferor provides the transferee
24138    with the transfer targets contact. The signalling between
24139    transferer or transferee should not be cancelled, so the
24140    call is recoverable if the transfer target can not be reached
24141    by the transferee.
24142 
24143    In this case, Asterisk receives a TRANSFER from
24144    the transferor, thus is the transferee. We should
24145    try to set up a call to the contact provided
24146    and if that fails, re-connect the current session.
24147    If the new call is set up, we issue a hangup.
24148    In this scenario, we are following section 5.2
24149    in the SIP CC Transfer draft. (Transfer without
24150    a GRUU)
24151 
24152    \par Transfer with consultation hold
24153    In this case, the transferor
24154    talks to the transfer target before the transfer takes place.
24155    This is implemented with SIP hold and transfer.
24156    Note: The invite From: string could indicate a transfer.
24157    (Section 6. Transfer with consultation hold)
24158    The transferor places the transferee on hold, starts a call
24159    with the transfer target to alert them to the impending
24160    transfer, terminates the connection with the target, then
24161    proceeds with the transfer (as in Blind transfer above)
24162 
24163    \par Attended transfer
24164    The transferor places the transferee
24165    on hold, calls the transfer target to alert them,
24166    places the target on hold, then proceeds with the transfer
24167    using a Replaces header field in the Refer-to header. This
24168    will force the transfee to send an Invite to the target,
24169    with a replaces header that instructs the target to
24170    hangup the call between the transferor and the target.
24171    In this case, the Refer/to: uses the AOR address. (The same
24172    URI that the transferee used to establish the session with
24173    the transfer target (To: ). The Require: replaces header should
24174    be in the INVITE to avoid the wrong UA in a forked SIP proxy
24175    scenario to answer and have no call to replace with.
24176 
24177    The referred-by header is *NOT* required, but if we get it,
24178    can be copied into the INVITE to the transfer target to
24179    inform the target about the transferor
24180 
24181    "Any REFER request has to be appropriately authenticated.".
24182    
24183    We can't destroy dialogs, since we want the call to continue.
24184    
24185    */
24186 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, int *nounlock)
24187 {
24188    /*!
24189     * Chan1: Call between asterisk and transferer
24190     * Chan2: Call between asterisk and transferee
24191     */
24192    struct sip_dual current = { 0, };
24193    struct ast_channel *chans[2] = { 0, };
24194    char *refer_to = NULL;
24195    char *refer_to_domain = NULL;
24196    char *refer_to_context = NULL;
24197    char *referred_by = NULL;
24198    char *callid = NULL;
24199    int localtransfer = 0;
24200    int attendedtransfer = 0;
24201    int res = 0;
24202 
24203    if (req->debug) {
24204       ast_verbose("Call %s got a SIP call transfer from %s: (REFER)!\n",
24205          p->callid,
24206          ast_test_flag(&p->flags[0], SIP_OUTGOING) ? "callee" : "caller");
24207    }
24208 
24209    if (!p->owner) {
24210       /* This is a REFER outside of an existing SIP dialog */
24211       /* We can't handle that, so decline it */
24212       ast_debug(3, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
24213       transmit_response(p, "603 Declined (No dialog)", req);
24214       if (!req->ignore) {
24215          append_history(p, "Xfer", "Refer failed. Outside of dialog.");
24216          sip_alreadygone(p);
24217          pvt_set_needdestroy(p, "outside of dialog");
24218       }
24219       res = 0;
24220       goto handle_refer_cleanup;
24221    }
24222 
24223    /* Check if transfer is allowed from this device */
24224    if (p->allowtransfer == TRANSFER_CLOSED ) {
24225       /* Transfer not allowed, decline */
24226       transmit_response(p, "603 Declined (policy)", req);
24227       append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
24228       /* Do not destroy SIP session */
24229       res = 0;
24230       goto handle_refer_cleanup;
24231    }
24232 
24233    if (!req->ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
24234       /* Already have a pending REFER */
24235       transmit_response(p, "491 Request pending", req);
24236       append_history(p, "Xfer", "Refer failed. Request pending.");
24237       res = 0;
24238       goto handle_refer_cleanup;
24239    }
24240 
24241    /* Allocate memory for call transfer data */
24242    if (!p->refer && !sip_refer_allocate(p)) {
24243       transmit_response(p, "500 Internal Server Error", req);
24244       append_history(p, "Xfer", "Refer failed. Memory allocation error.");
24245       res = -3;
24246       goto handle_refer_cleanup;
24247    }
24248 
24249    res = get_refer_info(p, req); /* Extract headers */
24250 
24251    p->refer->status = REFER_SENT;
24252 
24253    if (res != 0) {
24254       switch (res) {
24255       case -2: /* Syntax error */
24256          transmit_response(p, "400 Bad Request (Refer-to missing)", req);
24257          append_history(p, "Xfer", "Refer failed. Refer-to missing.");
24258          if (req->debug) {
24259             ast_debug(1, "SIP transfer to black hole can't be handled (no refer-to: )\n");
24260          }
24261          break;
24262       case -3:
24263          transmit_response(p, "603 Declined (Non sip: uri)", req);
24264          append_history(p, "Xfer", "Refer failed. Non SIP uri");
24265          if (req->debug) {
24266             ast_debug(1, "SIP transfer to non-SIP uri denied\n");
24267          }
24268          break;
24269       default:
24270          /* Refer-to extension not found, fake a failed transfer */
24271          transmit_response(p, "202 Accepted", req);
24272          append_history(p, "Xfer", "Refer failed. Bad extension.");
24273          transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
24274          ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
24275          if (req->debug) {
24276             ast_debug(1, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
24277          }
24278          break;
24279       }
24280       res = 0;
24281       goto handle_refer_cleanup;
24282    }
24283    if (ast_strlen_zero(p->context)) {
24284       ast_string_field_set(p, context, sip_cfg.default_context);
24285    }
24286 
24287    /* If we do not support SIP domains, all transfers are local */
24288    if (sip_cfg.allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
24289       p->refer->localtransfer = 1;
24290       if (sipdebug) {
24291          ast_debug(3, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
24292       }
24293    } else if (AST_LIST_EMPTY(&domain_list) || check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
24294       /* This PBX doesn't bother with SIP domains or domain is local, so this transfer is local */
24295       p->refer->localtransfer = 1;
24296    } else if (sipdebug) {
24297       ast_debug(3, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
24298    }
24299 
24300    /* Is this a repeat of a current request? Ignore it */
24301    /* Don't know what else to do right now. */
24302    if (req->ignore) {
24303       goto handle_refer_cleanup;
24304    }
24305 
24306    /* If this is a blind transfer, we have the following
24307    channels to work with:
24308    - chan1, chan2: The current call between transferer and transferee (2 channels)
24309    - target_channel: A new call from the transferee to the target (1 channel)
24310    We need to stay tuned to what happens in order to be able
24311    to bring back the call to the transferer */
24312 
24313    /* If this is a attended transfer, we should have all call legs within reach:
24314    - chan1, chan2: The call between the transferer and transferee (2 channels)
24315    - target_channel, targetcall_pvt: The call between the transferer and the target (2 channels)
24316    We want to bridge chan2 with targetcall_pvt!
24317    
24318    The replaces call id in the refer message points
24319    to the call leg between Asterisk and the transferer.
24320    So we need to connect the target and the transferee channel
24321    and hangup the two other channels silently
24322    
24323    If the target is non-local, the call ID could be on a remote
24324    machine and we need to send an INVITE with replaces to the
24325    target. We basically handle this as a blind transfer
24326    and let the sip_call function catch that we need replaces
24327    header in the INVITE.
24328    */
24329 
24330    /* Get the transferer's channel */
24331    chans[0] = current.chan1 = p->owner;
24332 
24333    /* Find the other part of the bridge (2) - transferee */
24334    chans[1] = current.chan2 = ast_bridged_channel(current.chan1);
24335 
24336    ast_channel_ref(current.chan1);
24337    if (current.chan2) {
24338       ast_channel_ref(current.chan2);
24339    }
24340 
24341    if (sipdebug) {
24342       ast_debug(3, "SIP %s transfer: Transferer channel %s, transferee channel %s\n",
24343          p->refer->attendedtransfer ? "attended" : "blind",
24344          current.chan1->name,
24345          current.chan2 ? current.chan2->name : "<none>");
24346    }
24347 
24348    if (!current.chan2 && !p->refer->attendedtransfer) {
24349       /* No bridged channel, propably IVR or echo or similar... */
24350       /* Guess we should masquerade or something here */
24351       /* Until we figure it out, refuse transfer of such calls */
24352       if (sipdebug) {
24353          ast_debug(3, "Refused SIP transfer on non-bridged channel.\n");
24354       }
24355       p->refer->status = REFER_FAILED;
24356       append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
24357       transmit_response(p, "603 Declined", req);
24358       res = -1;
24359       goto handle_refer_cleanup;
24360    }
24361 
24362    if (current.chan2) {
24363       if (sipdebug) {
24364          ast_debug(4, "Got SIP transfer, applying to bridged peer '%s'\n", current.chan2->name);
24365       }
24366       ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
24367    }
24368 
24369    ast_set_flag(&p->flags[0], SIP_GOTREFER);
24370 
24371    /* From here on failures will be indicated with NOTIFY requests */
24372    transmit_response(p, "202 Accepted", req);
24373 
24374    /* Attended transfer: Find all call legs and bridge transferee with target*/
24375    if (p->refer->attendedtransfer) {
24376       /* both p and p->owner _MUST_ be locked while calling local_attended_transfer */
24377       if ((res = local_attended_transfer(p, &current, req, seqno, nounlock))) {
24378          goto handle_refer_cleanup; /* We're done with the transfer */
24379       }
24380       /* Fall through for remote transfers that we did not find locally */
24381       if (sipdebug) {
24382          ast_debug(4, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
24383       }
24384       /* Fallthrough if we can't find the call leg internally */
24385    }
24386 
24387    /* Copy data we can not safely access after letting the pvt lock go. */
24388    refer_to = ast_strdupa(p->refer->refer_to);
24389    refer_to_domain = ast_strdupa(p->refer->refer_to_domain);
24390    refer_to_context = ast_strdupa(p->refer->refer_to_context);
24391    referred_by = ast_strdupa(p->refer->referred_by);
24392    callid = ast_strdupa(p->callid);
24393    localtransfer = p->refer->localtransfer;
24394    attendedtransfer = p->refer->attendedtransfer;
24395 
24396    if (!*nounlock) {
24397       ast_channel_unlock(p->owner);
24398       *nounlock = 1;
24399    }
24400    sip_pvt_unlock(p);
24401 
24402    /* Parking a call.  DO NOT hold any locks while calling ast_parking_ext_valid() */
24403    if (localtransfer && ast_parking_ext_valid(refer_to, current.chan1, refer_to_context)) {
24404       sip_pvt_lock(p);
24405       ast_clear_flag(&p->flags[0], SIP_GOTREFER);
24406       p->refer->status = REFER_200OK;
24407       append_history(p, "Xfer", "REFER to call parking.");
24408       sip_pvt_unlock(p);
24409 
24410       ast_manager_event_multichan(EVENT_FLAG_CALL, "Transfer", 2, chans,
24411          "TransferMethod: SIP\r\n"
24412          "TransferType: Blind\r\n"
24413          "Channel: %s\r\n"
24414          "Uniqueid: %s\r\n"
24415          "SIP-Callid: %s\r\n"
24416          "TargetChannel: %s\r\n"
24417          "TargetUniqueid: %s\r\n"
24418          "TransferExten: %s\r\n"
24419          "Transfer2Parking: Yes\r\n",
24420          current.chan1->name,
24421          current.chan1->uniqueid,
24422          callid,
24423          current.chan2->name,
24424          current.chan2->uniqueid,
24425          refer_to);
24426 
24427       if (sipdebug) {
24428          ast_debug(4, "SIP transfer to parking: trying to park %s. Parked by %s\n", current.chan2->name, current.chan1->name);
24429       }
24430 
24431       /* DO NOT hold any locks while calling sip_park */
24432       if (sip_park(current.chan2, current.chan1, req, seqno, refer_to, refer_to_context)) {
24433          sip_pvt_lock(p);
24434          transmit_notify_with_sipfrag(p, seqno, "500 Internal Server Error", TRUE);
24435       } else {
24436          sip_pvt_lock(p);
24437       }
24438       goto handle_refer_cleanup;
24439    }
24440 
24441    /* Blind transfers and remote attended xfers.
24442     * Locks should not be held while calling pbx_builtin_setvar_helper. This function
24443     * locks the channel being passed into it.*/
24444    if (current.chan1 && current.chan2) {
24445       ast_debug(3, "chan1->name: %s\n", current.chan1->name);
24446       pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", current.chan2->name);
24447    }
24448 
24449    if (current.chan2) {
24450       pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", current.chan1->name);
24451       pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", refer_to_domain);
24452       pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
24453       /* One for the new channel */
24454       pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
24455       /* Attended transfer to remote host, prepare headers for the INVITE */
24456       if (!ast_strlen_zero(referred_by)) {
24457          pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", referred_by);
24458       }
24459    }
24460 
24461    sip_pvt_lock(p);
24462    /* Generate a Replaces string to be used in the INVITE during attended transfer */
24463    if (!ast_strlen_zero(p->refer->replaces_callid)) {
24464       char tempheader[SIPBUFSIZE];
24465       snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid,
24466          p->refer->replaces_callid_totag ? ";to-tag=" : "",
24467          p->refer->replaces_callid_totag,
24468          p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
24469          p->refer->replaces_callid_fromtag);
24470 
24471       if (current.chan2) {
24472          sip_pvt_unlock(p);
24473          pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader);
24474          sip_pvt_lock(p);
24475       }
24476    }
24477 
24478    /* Connect the call */
24479 
24480    /* FAKE ringing if not attended transfer */
24481    if (!p->refer->attendedtransfer) {
24482       transmit_notify_with_sipfrag(p, seqno, "180 Ringing", FALSE);
24483    }
24484 
24485    /* For blind transfer, this will lead to a new call */
24486    /* For attended transfer to remote host, this will lead to
24487       a new SIP call with a replaces header, if the dial plan allows it
24488    */
24489    if (!current.chan2) {
24490       /* We have no bridge, so we're talking with Asterisk somehow */
24491       /* We need to masquerade this call */
24492       /* What to do to fix this situation:
24493          * Set up the new call in a new channel
24494          * Let the new channel masq into this channel
24495          Please add that code here :-)
24496       */
24497       p->refer->status = REFER_FAILED;
24498       transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
24499       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
24500       append_history(p, "Xfer", "Refer failed (only bridged calls).");
24501       res = -1;
24502       goto handle_refer_cleanup;
24503    }
24504    ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);   /* Delay hangup */
24505 
24506    /* Do not hold the pvt lock during the indicate and async_goto. Those functions
24507     * lock channels which will invalidate locking order if the pvt lock is held.*/
24508    /* For blind transfers, move the call to the new extensions. For attended transfers on multiple
24509     * servers - generate an INVITE with Replaces. Either way, let the dial plan decided
24510     * indicate before masquerade so the indication actually makes it to the real channel
24511     * when using local channels with MOH passthru */
24512    sip_pvt_unlock(p);
24513    ast_indicate(current.chan2, AST_CONTROL_UNHOLD);
24514    res = ast_async_goto(current.chan2, refer_to_context, refer_to, 1);
24515 
24516    if (!res) {
24517       ast_manager_event_multichan(EVENT_FLAG_CALL, "Transfer", 2, chans,
24518          "TransferMethod: SIP\r\n"
24519          "TransferType: Blind\r\n"
24520          "Channel: %s\r\n"
24521          "Uniqueid: %s\r\n"
24522          "SIP-Callid: %s\r\n"
24523          "TargetChannel: %s\r\n"
24524          "TargetUniqueid: %s\r\n"
24525          "TransferExten: %s\r\n"
24526          "TransferContext: %s\r\n",
24527          current.chan1->name,
24528          current.chan1->uniqueid,
24529          callid,
24530          current.chan2->name,
24531          current.chan2->uniqueid,
24532          refer_to,
24533          refer_to_context);
24534       /* Success  - we have a new channel */
24535       ast_debug(3, "%s transfer succeeded. Telling transferer.\n", attendedtransfer? "Attended" : "Blind");
24536 
24537       /* XXX - what to we put in CEL 'extra' for attended transfers to external systems? NULL for now */
24538       ast_channel_lock(current.chan1);
24539       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);
24540       ast_channel_unlock(current.chan1);
24541 
24542       sip_pvt_lock(p);
24543       transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
24544       if (p->refer->localtransfer) {
24545          p->refer->status = REFER_200OK;
24546       }
24547       if (p->owner) {
24548          p->owner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
24549       }
24550       append_history(p, "Xfer", "Refer succeeded.");
24551       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
24552       /* Do not hangup call, the other side do that when we say 200 OK */
24553       /* We could possibly implement a timer here, auto congestion */
24554       res = 0;
24555    } else {
24556       sip_pvt_lock(p);
24557       ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Don't delay hangup */
24558       ast_debug(3, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
24559       append_history(p, "Xfer", "Refer failed.");
24560       /* Failure of some kind */
24561       p->refer->status = REFER_FAILED;
24562       transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
24563       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
24564       res = -1;
24565    }
24566 
24567 handle_refer_cleanup:
24568    if (current.chan1) {
24569       ast_channel_unref(current.chan1);
24570    }
24571    if (current.chan2) {
24572       ast_channel_unref(current.chan2);
24573    }
24574 
24575    /* Make sure we exit with the pvt locked */
24576    return res;
24577 }
24578 
24579 /*! \brief Handle incoming CANCEL request */
24580 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
24581 {
24582 
24583    check_via(p, req);
24584    sip_alreadygone(p);
24585 
24586    if (p->owner && p->owner->_state == AST_STATE_UP) {
24587       /* This call is up, cancel is ignored, we need a bye */
24588       transmit_response(p, "200 OK", req);
24589       ast_debug(1, "Got CANCEL on an answered call. Ignoring... \n");
24590       return 0;
24591    }
24592 
24593    /* At this point, we could have cancelled the invite at the same time
24594       as the other side sends a CANCEL. Our final reply with error code
24595       might not have been received by the other side before the CANCEL
24596       was sent, so let's just give up retransmissions and waiting for
24597       ACK on our error code. The call is hanging up any way. */
24598    if (p->invitestate == INV_TERMINATED || p->invitestate == INV_COMPLETED) {
24599       __sip_pretend_ack(p);
24600    }
24601    if (p->invitestate != INV_TERMINATED)
24602       p->invitestate = INV_CANCELLED;
24603 
24604    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD))
24605       update_call_counter(p, DEC_CALL_LIMIT);
24606 
24607    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
24608    if (p->owner) {
24609       sip_queue_hangup_cause(p, 0);
24610    } else {
24611       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
24612    }
24613    if (ast_str_strlen(p->initreq.data) > 0) {
24614       struct sip_pkt *pkt, *prev_pkt;
24615       /* If the CANCEL we are receiving is a retransmission, and we already have scheduled
24616        * a reliable 487, then we don't want to schedule another one on top of the previous
24617        * one.
24618        *
24619        * As odd as this may sound, we can't rely on the previously-transmitted "reliable"
24620        * response in this situation. What if we've sent all of our reliable responses
24621        * already and now all of a sudden, we get this second CANCEL?
24622        *
24623        * The only way to do this correctly is to cancel our previously-scheduled reliably-
24624        * transmitted response and send a new one in its place.
24625        */
24626       for (pkt = p->packets, prev_pkt = NULL; pkt; prev_pkt = pkt, pkt = pkt->next) {
24627          if (pkt->seqno == p->lastinvite && pkt->response_code == 487) {
24628             AST_SCHED_DEL(sched, pkt->retransid);
24629             UNLINK(pkt, p->packets, prev_pkt);
24630             dialog_unref(pkt->owner, "unref packet->owner from dialog");
24631             if (pkt->data) {
24632                ast_free(pkt->data);
24633             }
24634             ast_free(pkt);
24635             break;
24636          }
24637       }
24638       transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
24639       transmit_response(p, "200 OK", req);
24640       return 1;
24641    } else {
24642       transmit_response(p, "481 Call Leg Does Not Exist", req);
24643       return 0;
24644    }
24645 }
24646 
24647 /*! \brief Handle incoming BYE request */
24648 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
24649 {
24650    struct ast_channel *c=NULL;
24651    int res;
24652    struct ast_channel *bridged_to;
24653    const char *required;
24654 
24655    /* If we have an INCOMING invite that we haven't answered, terminate that transaction */
24656    if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !req->ignore) {
24657       transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
24658    }
24659 
24660    __sip_pretend_ack(p);
24661 
24662    p->invitestate = INV_TERMINATED;
24663 
24664    copy_request(&p->initreq, req);
24665    if (sipdebug)
24666       ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
24667    check_via(p, req);
24668    sip_alreadygone(p);
24669 
24670    /* Get RTCP quality before end of call */
24671    if (p->do_history || p->owner) {
24672       char quality_buf[AST_MAX_USER_FIELD], *quality;
24673       struct ast_channel *bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
24674 
24675       /* We need to get the lock on bridge because ast_rtp_instance_set_stats_vars will attempt
24676        * to lock the bridge. This may get hairy...
24677        */
24678       while (bridge && ast_channel_trylock(bridge)) {
24679          ast_channel_unlock(p->owner);
24680          do {
24681             /* Can't use DEADLOCK_AVOIDANCE since p is an ao2 object */
24682             sip_pvt_unlock(p);
24683             usleep(1);
24684             sip_pvt_lock(p);
24685          } while (p->owner && ast_channel_trylock(p->owner));
24686          bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
24687       }
24688 
24689 
24690       if (p->rtp && (quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
24691          if (p->do_history) {
24692             append_history(p, "RTCPaudio", "Quality:%s", quality);
24693 
24694             if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_JITTER, quality_buf, sizeof(quality_buf)))) {
24695                append_history(p, "RTCPaudioJitter", "Quality:%s", quality);
24696             }
24697             if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_LOSS, quality_buf, sizeof(quality_buf)))) {
24698                append_history(p, "RTCPaudioLoss", "Quality:%s", quality);
24699             }
24700             if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_RTT, quality_buf, sizeof(quality_buf)))) {
24701                append_history(p, "RTCPaudioRTT", "Quality:%s", quality);
24702             }
24703          }
24704 
24705          if (p->owner) {
24706             ast_rtp_instance_set_stats_vars(p->owner, p->rtp);
24707          }
24708 
24709       }
24710 
24711       if (bridge) {
24712          struct sip_pvt *q = bridge->tech_pvt;
24713 
24714          if (IS_SIP_TECH(bridge->tech) && q && q->rtp) {
24715             ast_rtp_instance_set_stats_vars(bridge, q->rtp);
24716          }
24717          ast_channel_unlock(bridge);
24718       }
24719 
24720       if (p->vrtp && (quality = ast_rtp_instance_get_quality(p->vrtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
24721          if (p->do_history) {
24722             append_history(p, "RTCPvideo", "Quality:%s", quality);
24723          }
24724          if (p->owner) {
24725             pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", quality);
24726          }
24727       }
24728       if (p->trtp && (quality = ast_rtp_instance_get_quality(p->trtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
24729          if (p->do_history) {
24730             append_history(p, "RTCPtext", "Quality:%s", quality);
24731          }
24732          if (p->owner) {
24733             pbx_builtin_setvar_helper(p->owner, "RTPTEXTQOS", quality);
24734          }
24735       }
24736    }
24737 
24738    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
24739    if (p->stimer) {
24740       stop_session_timer(p); /* Stop Session-Timer */
24741    }
24742 
24743    if (!ast_strlen_zero(get_header(req, "Also"))) {
24744       ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method.  Ask vendor to support REFER instead\n",
24745          ast_sockaddr_stringify(&p->recv));
24746       if (ast_strlen_zero(p->context))
24747          ast_string_field_set(p, context, sip_cfg.default_context);
24748       res = get_also_info(p, req);
24749       if (!res) {
24750          c = p->owner;
24751          if (c) {
24752             bridged_to = ast_bridged_channel(c);
24753             if (bridged_to) {
24754                /* Don't actually hangup here... */
24755                ast_queue_control(c, AST_CONTROL_UNHOLD);
24756                ast_channel_unlock(c);  /* async_goto can do a masquerade, no locks can be held during a masq */
24757                ast_async_goto(bridged_to, p->context, p->refer->refer_to, 1);
24758                ast_channel_lock(c);
24759             } else
24760                ast_queue_hangup(p->owner);
24761          }
24762       } else {
24763          ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_sockaddr_stringify(&p->recv));
24764          if (p->owner)
24765             ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
24766       }
24767    } else if (p->owner) {
24768       sip_queue_hangup_cause(p, 0);
24769       sip_scheddestroy_final(p, DEFAULT_TRANS_TIMEOUT);
24770       ast_debug(3, "Received bye, issuing owner hangup\n");
24771    } else {
24772       sip_scheddestroy_final(p, DEFAULT_TRANS_TIMEOUT);
24773       ast_debug(3, "Received bye, no owner, selfdestruct soon.\n");
24774    }
24775    ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
24776 
24777    /* Find out what they require */
24778    required = get_header(req, "Require");
24779    if (!ast_strlen_zero(required)) {
24780       char unsupported[256] = { 0, };
24781       parse_sip_options(required, unsupported, ARRAY_LEN(unsupported));
24782       /* If there are any options required that we do not support,
24783        * then send a 420 with only those unsupported options listed */
24784       if (!ast_strlen_zero(unsupported)) {
24785          transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, unsupported);
24786          ast_log(LOG_WARNING, "Received SIP BYE with unsupported required extension: required:%s unsupported:%s\n", required, unsupported);
24787       } else {
24788          transmit_response(p, "200 OK", req);
24789       }
24790    } else {
24791       transmit_response(p, "200 OK", req);
24792    }
24793 
24794    /* Destroy any pending invites so we won't try to do another
24795     * scheduled reINVITE. */
24796    AST_SCHED_DEL_UNREF(sched, p->waitid, dialog_unref(p, "decrement refcount from sip_destroy because waitid won't be scheduled"));
24797 
24798    return 1;
24799 }
24800 
24801 /*! \brief Handle incoming MESSAGE request */
24802 static int handle_request_message(struct sip_pvt *p, struct sip_request *req)
24803 {
24804    if (!req->ignore) {
24805       if (req->debug)
24806          ast_verbose("Receiving message!\n");
24807       receive_message(p, req);
24808    } else
24809       transmit_response(p, "202 Accepted", req);
24810    return 1;
24811 }
24812 
24813 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)
24814 {
24815    int etag_present = !ast_strlen_zero(etag);
24816    int body_present = req->lines > 0;
24817 
24818    ast_assert(expires_int != NULL);
24819 
24820    if (ast_strlen_zero(expires)) {
24821       /* Section 6, item 4, second bullet point of RFC 3903 says to
24822        * use a locally-configured default expiration if none is provided
24823        * in the request
24824        */
24825       *expires_int = DEFAULT_PUBLISH_EXPIRES;
24826    } else if (sscanf(expires, "%30d", expires_int) != 1) {
24827       return SIP_PUBLISH_UNKNOWN;
24828    }
24829 
24830    if (*expires_int == 0) {
24831       return SIP_PUBLISH_REMOVE;
24832    } else if (!etag_present && body_present) {
24833       return SIP_PUBLISH_INITIAL;
24834    } else if (etag_present && !body_present) {
24835       return SIP_PUBLISH_REFRESH;
24836    } else if (etag_present && body_present) {
24837       return SIP_PUBLISH_MODIFY;
24838    }
24839 
24840    return SIP_PUBLISH_UNKNOWN;
24841 }
24842 
24843 #ifdef HAVE_LIBXML2
24844 static void get_pidf_body(struct sip_request *req, char *pidf_body, size_t size)
24845 {
24846    int i;
24847    struct ast_str *str = ast_str_alloca(size);
24848    for (i = 0; i < req->lines; ++i) {
24849       ast_str_append(&str, 0, "%s", REQ_OFFSET_TO_STR(req, line[i]));
24850    }
24851    ast_copy_string(pidf_body, ast_str_buffer(str), size);
24852 }
24853 
24854 static int pidf_validate_tuple(struct ast_xml_node *tuple_node)
24855 {
24856    const char *id;
24857    int status_found = FALSE;
24858    struct ast_xml_node *tuple_children;
24859    struct ast_xml_node *tuple_children_iterator;
24860    /* Tuples have to have an id attribute or they're invalid */
24861    if (!(id = ast_xml_get_attribute(tuple_node, "id"))) {
24862       ast_log(LOG_WARNING, "Tuple XML element has no attribute 'id'\n");
24863       return FALSE;
24864    }
24865    /* We don't care what it actually is, just that it's there */
24866    ast_xml_free_attr(id);
24867    /* This is a tuple. It must have a status element */
24868    if (!(tuple_children = ast_xml_node_get_children(tuple_node))) {
24869       /* The tuple has no children. It sucks */
24870       ast_log(LOG_WARNING, "Tuple XML element has no child elements\n");
24871       return FALSE;
24872    }
24873    for (tuple_children_iterator = tuple_children; tuple_children_iterator;
24874          tuple_children_iterator = ast_xml_node_get_next(tuple_children_iterator)) {
24875       /* Similar to the wording used regarding tuples, the status element should appear
24876        * first. However, we will once again relax things and accept the status at any
24877        * position. We will enforce that only a single status element can be present.
24878        */
24879       if (strcmp(ast_xml_node_get_name(tuple_children_iterator), "status")) {
24880          /* Not the status, we don't care */
24881          continue;
24882       }
24883       if (status_found == TRUE) {
24884          /* THERE CAN BE ONLY ONE!!! */
24885          ast_log(LOG_WARNING, "Multiple status elements found in tuple. Only one allowed\n");
24886          return FALSE;
24887       }
24888       status_found = TRUE;
24889    }
24890    return status_found;
24891 }
24892 
24893 
24894 static int pidf_validate_presence(struct ast_xml_doc *doc)
24895 {
24896    struct ast_xml_node *presence_node = ast_xml_get_root(doc);
24897    struct ast_xml_node *child_nodes;
24898    struct ast_xml_node *node_iterator;
24899    struct ast_xml_ns *ns;
24900    const char *entity;
24901    const char *namespace;
24902    const char presence_namespace[] = "urn:ietf:params:xml:ns:pidf";
24903 
24904    if (!presence_node) {
24905       ast_log(LOG_WARNING, "Unable to retrieve root node of the XML document\n");
24906       return FALSE;
24907    }
24908    /* Okay, we managed to open the document! YAY! Now, let's start making sure it's all PIDF-ified
24909     * correctly.
24910     */
24911    if (strcmp(ast_xml_node_get_name(presence_node), "presence")) {
24912       ast_log(LOG_WARNING, "Root node of PIDF document is not 'presence'. Invalid\n");
24913       return FALSE;
24914    }
24915 
24916    /* The presence element must have an entity attribute and an xmlns attribute. Furthermore
24917     * the xmlns attribute must be "urn:ietf:params:xml:ns:pidf"
24918     */
24919    if (!(entity = ast_xml_get_attribute(presence_node, "entity"))) {
24920       ast_log(LOG_WARNING, "Presence element of PIDF document has no 'entity' attribute\n");
24921       return FALSE;
24922    }
24923    /* We're not interested in what the entity is, just that it exists */
24924    ast_xml_free_attr(entity);
24925 
24926    if (!(ns = ast_xml_find_namespace(doc, presence_node, NULL))) {
24927       ast_log(LOG_WARNING, "Couldn't find default namespace...\n");
24928       return FALSE;
24929    }
24930 
24931    namespace = ast_xml_get_ns_href(ns);
24932    if (ast_strlen_zero(namespace) || strcmp(namespace, presence_namespace)) {
24933       ast_log(LOG_WARNING, "PIDF document has invalid namespace value %s\n", namespace);
24934       return FALSE;
24935    }
24936 
24937    if (!(child_nodes = ast_xml_node_get_children(presence_node))) {
24938       ast_log(LOG_WARNING, "PIDF document has no elements as children of 'presence'. Invalid\n");
24939       return FALSE;
24940    }
24941 
24942    /* Check for tuple elements. RFC 3863 says that PIDF documents can have any number of
24943     * tuples, including 0. The big thing here is that if there are tuple elements present,
24944     * they have to have a single status element within.
24945     *
24946     * The RFC is worded such that tuples should appear as the first elements as children of
24947     * the presence element. However, we'll be accepting of documents which may place other elements
24948     * before the tuple(s).
24949     */
24950    for (node_iterator = child_nodes; node_iterator;
24951          node_iterator = ast_xml_node_get_next(node_iterator)) {
24952       if (strcmp(ast_xml_node_get_name(node_iterator), "tuple")) {
24953          /* Not a tuple. We don't give a rat's hind quarters */
24954          continue;
24955       }
24956       if (pidf_validate_tuple(node_iterator) == FALSE) {
24957          ast_log(LOG_WARNING, "Unable to validate tuple\n");
24958          return FALSE;
24959       }
24960    }
24961 
24962    return TRUE;
24963 }
24964 
24965 /*!
24966  * \brief Makes sure that body is properly formatted PIDF
24967  *
24968  * Specifically, we check that the document has a "presence" element
24969  * at the root and that within that, there is at least one "tuple" element
24970  * that contains a "status" element.
24971  *
24972  * XXX This function currently assumes a default namespace is used. Of course
24973  * if you're not using a default namespace, you're probably a stupid jerk anyway.
24974  *
24975  * \param req The SIP request to check
24976  * \param[out] pidf_doc The validated PIDF doc.
24977  * \retval FALSE The XML was malformed or the basic PIDF structure was marred
24978  * \retval TRUE The PIDF document is of a valid format
24979  */
24980 static int sip_pidf_validate(struct sip_request *req, struct ast_xml_doc **pidf_doc)
24981 {
24982    struct ast_xml_doc *doc;
24983    int content_length;
24984    const char *content_length_str = get_header(req, "Content-Length");
24985    const char *content_type = get_header(req, "Content-Type");
24986    char pidf_body[SIPBUFSIZE];
24987    int res;
24988 
24989    if (ast_strlen_zero(content_type) || strcmp(content_type, "application/pidf+xml")) {
24990       ast_log(LOG_WARNING, "Content type is not PIDF\n");
24991       return FALSE;
24992    }
24993 
24994    if (ast_strlen_zero(content_length_str)) {
24995       ast_log(LOG_WARNING, "No content length. Can't determine bounds of PIDF document\n");
24996       return FALSE;
24997    }
24998 
24999    if (sscanf(content_length_str, "%30d", &content_length) != 1) {
25000       ast_log(LOG_WARNING, "Invalid content length provided\n");
25001       return FALSE;
25002    }
25003 
25004    if (content_length > sizeof(pidf_body)) {
25005       ast_log(LOG_WARNING, "Content length of PIDF document truncated to %d bytes\n", (int) sizeof(pidf_body));
25006       content_length = sizeof(pidf_body);
25007    }
25008 
25009    get_pidf_body(req, pidf_body, content_length);
25010 
25011    if (!(doc = ast_xml_read_memory(pidf_body, content_length))) {
25012       ast_log(LOG_WARNING, "Unable to open XML PIDF document. Is it malformed?\n");
25013       return FALSE;
25014    }
25015 
25016    res = pidf_validate_presence(doc);
25017    if (res == TRUE) {
25018       *pidf_doc = doc;
25019    } else {
25020       ast_xml_close(doc);
25021    }
25022    return res;
25023 }
25024 
25025 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)
25026 {
25027    const char *uri = REQ_OFFSET_TO_STR(req, rlPart2);
25028    struct ast_cc_agent *agent;
25029    struct sip_cc_agent_pvt *agent_pvt;
25030    struct ast_xml_doc *pidf_doc = NULL;
25031    const char *basic_status = NULL;
25032    struct ast_xml_node *presence_node;
25033    struct ast_xml_node *presence_children;
25034    struct ast_xml_node *tuple_node;
25035    struct ast_xml_node *tuple_children;
25036    struct ast_xml_node *status_node;
25037    struct ast_xml_node *status_children;
25038    struct ast_xml_node *basic_node;
25039    int res = 0;
25040 
25041    if (!((agent = find_sip_cc_agent_by_notify_uri(uri)) || (agent = find_sip_cc_agent_by_subscribe_uri(uri)))) {
25042       ast_log(LOG_WARNING, "Could not find agent using uri '%s'\n", uri);
25043       transmit_response(pvt, "412 Conditional Request Failed", req);
25044       return -1;
25045    }
25046 
25047    agent_pvt = agent->private_data;
25048 
25049    if (sip_pidf_validate(req, &pidf_doc) == FALSE) {
25050       res = -1;
25051       goto cc_publish_cleanup;
25052    }
25053 
25054    /* It's important to note that the PIDF validation routine has no knowledge
25055     * of what we specifically want in this instance. A valid PIDF document could
25056     * have no tuples, or it could have tuples whose status element has no basic
25057     * element contained within. While not violating the PIDF spec, these are
25058     * insufficient for our needs in this situation
25059     */
25060    presence_node = ast_xml_get_root(pidf_doc);
25061    if (!(presence_children = ast_xml_node_get_children(presence_node))) {
25062       ast_log(LOG_WARNING, "No tuples within presence element.\n");
25063       res = -1;
25064       goto cc_publish_cleanup;
25065    }
25066 
25067    if (!(tuple_node = ast_xml_find_element(presence_children, "tuple", NULL, NULL))) {
25068       ast_log(LOG_NOTICE, "Couldn't find tuple node?\n");
25069       res = -1;
25070       goto cc_publish_cleanup;
25071    }
25072 
25073    /* We already made sure that the tuple has a status node when we validated the PIDF
25074     * document earlier. So there's no need to enclose this operation in an if statement.
25075     */
25076    tuple_children = ast_xml_node_get_children(tuple_node);
25077    /* coverity[null_returns: FALSE] */
25078    status_node = ast_xml_find_element(tuple_children, "status", NULL, NULL);
25079 
25080    if (!(status_children = ast_xml_node_get_children(status_node))) {
25081       ast_log(LOG_WARNING, "No basic elements within status element.\n");
25082       res = -1;
25083       goto cc_publish_cleanup;
25084    }
25085 
25086    if (!(basic_node = ast_xml_find_element(status_children, "basic", NULL, NULL))) {
25087       ast_log(LOG_WARNING, "Couldn't find basic node?\n");
25088       res = -1;
25089       goto cc_publish_cleanup;
25090    }
25091 
25092    basic_status = ast_xml_get_text(basic_node);
25093 
25094    if (ast_strlen_zero(basic_status)) {
25095       ast_log(LOG_NOTICE, "NOthing in basic node?\n");
25096       res = -1;
25097       goto cc_publish_cleanup;
25098    }
25099 
25100    if (!strcmp(basic_status, "open")) {
25101       agent_pvt->is_available = TRUE;
25102       ast_cc_agent_caller_available(agent->core_id, "Received PUBLISH stating SIP caller %s is available",
25103             agent->device_name);
25104    } else if (!strcmp(basic_status, "closed")) {
25105       agent_pvt->is_available = FALSE;
25106       ast_cc_agent_caller_busy(agent->core_id, "Received PUBLISH stating SIP caller %s is busy",
25107             agent->device_name);
25108    } else {
25109       ast_log(LOG_NOTICE, "Invalid content in basic element: %s\n", basic_status);
25110    }
25111 
25112 cc_publish_cleanup:
25113    if (basic_status) {
25114       ast_xml_free_text(basic_status);
25115    }
25116    if (pidf_doc) {
25117       ast_xml_close(pidf_doc);
25118    }
25119    ao2_ref(agent, -1);
25120    if (res) {
25121       transmit_response(pvt, "400 Bad Request", req);
25122    }
25123    return res;
25124 }
25125 
25126 #endif /* HAVE_LIBXML2 */
25127 
25128 static int handle_sip_publish_initial(struct sip_pvt *p, struct sip_request *req, struct event_state_compositor *esc, const int expires)
25129 {
25130    struct sip_esc_entry *esc_entry = create_esc_entry(esc, req, expires);
25131    int res = 0;
25132 
25133    if (!esc_entry) {
25134       transmit_response(p, "503 Internal Server Failure", req);
25135       return -1;
25136    }
25137 
25138    if (esc->callbacks->initial_handler) {
25139       res = esc->callbacks->initial_handler(p, req, esc, esc_entry);
25140    }
25141 
25142    if (!res) {
25143       transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 0);
25144    }
25145 
25146    ao2_ref(esc_entry, -1);
25147    return res;
25148 }
25149 
25150 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)
25151 {
25152    struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
25153    int expires_ms = expires * 1000;
25154    int res = 0;
25155 
25156    if (!esc_entry) {
25157       transmit_response(p, "412 Conditional Request Failed", req);
25158       return -1;
25159    }
25160 
25161    AST_SCHED_REPLACE_UNREF(esc_entry->sched_id, sched, expires_ms, publish_expire, esc_entry,
25162          ao2_ref(_data, -1),
25163          ao2_ref(esc_entry, -1),
25164          ao2_ref(esc_entry, +1));
25165 
25166    if (esc->callbacks->refresh_handler) {
25167       res = esc->callbacks->refresh_handler(p, req, esc, esc_entry);
25168    }
25169 
25170    if (!res) {
25171       transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
25172    }
25173 
25174    ao2_ref(esc_entry, -1);
25175    return res;
25176 }
25177 
25178 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)
25179 {
25180    struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
25181    int expires_ms = expires * 1000;
25182    int res = 0;
25183 
25184    if (!esc_entry) {
25185       transmit_response(p, "412 Conditional Request Failed", req);
25186       return -1;
25187    }
25188 
25189    AST_SCHED_REPLACE_UNREF(esc_entry->sched_id, sched, expires_ms, publish_expire, esc_entry,
25190          ao2_ref(_data, -1),
25191          ao2_ref(esc_entry, -1),
25192          ao2_ref(esc_entry, +1));
25193 
25194    if (esc->callbacks->modify_handler) {
25195       res = esc->callbacks->modify_handler(p, req, esc, esc_entry);
25196    }
25197 
25198    if (!res) {
25199       transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
25200    }
25201 
25202    ao2_ref(esc_entry, -1);
25203    return res;
25204 }
25205 
25206 static int handle_sip_publish_remove(struct sip_pvt *p, struct sip_request *req, struct event_state_compositor *esc, const char * const etag)
25207 {
25208    struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
25209    int res = 0;
25210 
25211    if (!esc_entry) {
25212       transmit_response(p, "412 Conditional Request Failed", req);
25213       return -1;
25214    }
25215 
25216    AST_SCHED_DEL(sched, esc_entry->sched_id);
25217    /* Scheduler's ref of the esc_entry */
25218    ao2_ref(esc_entry, -1);
25219 
25220    if (esc->callbacks->remove_handler) {
25221       res = esc->callbacks->remove_handler(p, req, esc, esc_entry);
25222    }
25223 
25224    if (!res) {
25225       transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
25226    }
25227 
25228    /* Ref from finding the esc_entry earlier in function */
25229    ao2_unlink(esc->compositor, esc_entry);
25230    ao2_ref(esc_entry, -1);
25231    return res;
25232 }
25233 
25234 static int handle_request_publish(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const uint32_t seqno, const char *uri)
25235 {
25236    const char *etag = get_header(req, "SIP-If-Match");
25237    const char *event = get_header(req, "Event");
25238    struct event_state_compositor *esc;
25239    enum sip_publish_type publish_type;
25240    const char *expires_str = get_header(req, "Expires");
25241    int expires_int;
25242    int auth_result;
25243    int handler_result = -1;
25244 
25245    if (ast_strlen_zero(event)) {
25246       transmit_response(p, "489 Bad Event", req);
25247       pvt_set_needdestroy(p, "missing Event: header");
25248       return -1;
25249    }
25250 
25251    if (!(esc = get_esc(event))) {
25252       transmit_response(p, "489 Bad Event", req);
25253       pvt_set_needdestroy(p, "unknown event package in publish");
25254       return -1;
25255    }
25256 
25257    auth_result = check_user(p, req, SIP_PUBLISH, uri, XMIT_UNRELIABLE, addr);
25258    if (auth_result == AUTH_CHALLENGE_SENT) {
25259       p->lastinvite = seqno;
25260       return 0;
25261    } else if (auth_result < 0) {
25262       ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
25263       transmit_response(p, "403 Forbidden", req);
25264       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25265       ast_string_field_set(p, theirtag, NULL);
25266       return 0;
25267    } else if (auth_result == AUTH_SUCCESSFUL && p->lastinvite) {
25268       /* We need to stop retransmitting the 401 */
25269       __sip_ack(p, p->lastinvite, 1, 0);
25270    }
25271 
25272    publish_type = determine_sip_publish_type(req, event, etag, expires_str, &expires_int);
25273 
25274    if (expires_int > max_expiry) {
25275       expires_int = max_expiry;
25276    } else if (expires_int < min_expiry && expires_int > 0) {
25277       transmit_response_with_minexpires(p, "423 Interval too small", req);
25278       pvt_set_needdestroy(p, "Expires is less that the min expires allowed.");
25279       return 0;
25280    }
25281    p->expiry = expires_int;
25282 
25283    /* It is the responsibility of these handlers to formulate any response
25284     * sent for a PUBLISH
25285     */
25286    switch (publish_type) {
25287    case SIP_PUBLISH_UNKNOWN:
25288       transmit_response(p, "400 Bad Request", req);
25289       break;
25290    case SIP_PUBLISH_INITIAL:
25291       handler_result = handle_sip_publish_initial(p, req, esc, expires_int);
25292       break;
25293    case SIP_PUBLISH_REFRESH:
25294       handler_result = handle_sip_publish_refresh(p, req, esc, etag, expires_int);
25295       break;
25296    case SIP_PUBLISH_MODIFY:
25297       handler_result = handle_sip_publish_modify(p, req, esc, etag, expires_int);
25298       break;
25299    case SIP_PUBLISH_REMOVE:
25300       handler_result = handle_sip_publish_remove(p, req, esc, etag);
25301       break;
25302    default:
25303       transmit_response(p, "400 Impossible Condition", req);
25304       break;
25305    }
25306    if (!handler_result && p->expiry > 0) {
25307       sip_scheddestroy(p, (p->expiry + 10) * 1000);
25308    } else {
25309       pvt_set_needdestroy(p, "forcing expiration");
25310    }
25311 
25312    return handler_result;
25313 }
25314 
25315 /*! \internal \brief Subscribe to MWI events for the specified peer
25316  * \note The peer cannot be locked during this method.  sip_send_mwi_peer will
25317  * attempt to lock the peer after the event subscription lock is held; if the peer is locked during
25318  * this method then we will attempt to lock the event subscription lock but after the peer, creating
25319  * a locking inversion.
25320  */
25321 static void add_peer_mwi_subs(struct sip_peer *peer)
25322 {
25323    struct sip_mailbox *mailbox;
25324 
25325    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
25326       if (mailbox->event_sub) {
25327          ast_event_unsubscribe(mailbox->event_sub);
25328       }
25329 
25330       mailbox->event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, "SIP mbox event", peer,
25331          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
25332          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
25333          AST_EVENT_IE_END);
25334    }
25335 }
25336 
25337 static int handle_cc_subscribe(struct sip_pvt *p, struct sip_request *req)
25338 {
25339    const char *uri = REQ_OFFSET_TO_STR(req, rlPart2);
25340    char *param_separator;
25341    struct ast_cc_agent *agent;
25342    struct sip_cc_agent_pvt *agent_pvt;
25343    const char *expires_str = get_header(req, "Expires");
25344    int expires = -1; /* Just need it to be non-zero */
25345 
25346    if (!ast_strlen_zero(expires_str)) {
25347       sscanf(expires_str, "%d", &expires);
25348    }
25349 
25350    if ((param_separator = strchr(uri, ';'))) {
25351       *param_separator = '\0';
25352    }
25353 
25354    p->subscribed = CALL_COMPLETION;
25355 
25356    if (!(agent = find_sip_cc_agent_by_subscribe_uri(uri))) {
25357       if (!expires) {
25358          /* Typically, if a 0 Expires reaches us and we can't find
25359           * the corresponding agent, it means that the CC transaction
25360           * has completed and so the calling side is just trying to
25361           * clean up its subscription. We'll just respond with a
25362           * 200 OK and be done with it
25363           */
25364          transmit_response(p, "200 OK", req);
25365          return 0;
25366       }
25367       ast_log(LOG_WARNING, "Invalid URI '%s' in CC subscribe\n", uri);
25368       transmit_response(p, "404 Not Found", req);
25369       return -1;
25370    }
25371 
25372    agent_pvt = agent->private_data;
25373 
25374    if (!expires) {
25375       /* We got sent a SUBSCRIBE and found an agent. This means that CC
25376        * is being canceled.
25377        */
25378       ast_cc_failed(agent->core_id, "CC is being canceled by %s", agent->device_name);
25379       transmit_response(p, "200 OK", req);
25380       ao2_ref(agent, -1);
25381       return 0;
25382    }
25383 
25384    agent_pvt->subscribe_pvt = dialog_ref(p, "SIP CC agent gains reference to subscription dialog");
25385    ast_cc_agent_accept_request(agent->core_id, "SIP caller %s has requested CC via SUBSCRIBE",
25386          agent->device_name);
25387 
25388    /* We don't send a response here. That is done in the agent's ack callback or in the
25389     * agent destructor, should a failure occur before we have responded
25390     */
25391    ao2_ref(agent, -1);
25392    return 0;
25393 }
25394 
25395 /*! \brief  Handle incoming SUBSCRIBE request */
25396 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e)
25397 {
25398    int gotdest = 0;
25399    int res = 0;
25400    int firststate;
25401    struct sip_peer *authpeer = NULL;
25402    const char *eventheader = get_header(req, "Event");   /* Get Event package name */
25403    int resubscribe = (p->subscribed != NONE) && !req->ignore;
25404    char *event_end;
25405    ptrdiff_t event_len = 0;
25406 
25407    if (p->initreq.headers) {  
25408       /* We already have a dialog */
25409       if (p->initreq.method != SIP_SUBSCRIBE) {
25410          /* This is a SUBSCRIBE within another SIP dialog, which we do not support */
25411          /* For transfers, this could happen, but since we haven't seen it happening, let us just refuse this */
25412          transmit_response(p, "403 Forbidden (within dialog)", req);
25413          /* Do not destroy session, since we will break the call if we do */
25414          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);
25415          return 0;
25416       } else if (req->debug) {
25417          if (resubscribe)
25418             ast_debug(1, "Got a re-subscribe on existing subscription %s\n", p->callid);
25419          else
25420             ast_debug(1, "Got a new subscription %s (possibly with auth) or retransmission\n", p->callid);
25421       }
25422    }
25423 
25424    /* Check if we have a global disallow setting on subscriptions.
25425       if so, we don't have to check peer settings after auth, which saves a lot of processing
25426    */
25427    if (!sip_cfg.allowsubscribe) {
25428       transmit_response(p, "403 Forbidden (policy)", req);
25429       pvt_set_needdestroy(p, "forbidden");
25430       return 0;
25431    }
25432 
25433    if (!req->ignore && !resubscribe) { /* Set up dialog, new subscription */
25434       const char *to = get_header(req, "To");
25435       char totag[128];
25436       set_pvt_allowed_methods(p, req);
25437 
25438       /* Check to see if a tag was provided, if so this is actually a resubscription of a dialog we no longer know about */
25439       if (!ast_strlen_zero(to) && gettag(req, "To", totag, sizeof(totag))) {
25440          if (req->debug)
25441             ast_verbose("Received resubscription for a dialog we no longer know about. Telling remote side to subscribe again.\n");
25442          transmit_response(p, "481 Subscription does not exist", req);
25443          pvt_set_needdestroy(p, "subscription does not exist");
25444          return 0;
25445       }
25446 
25447       /* Use this as the basis */
25448       if (req->debug)
25449          ast_verbose("Creating new subscription\n");
25450 
25451       copy_request(&p->initreq, req);
25452       if (sipdebug)
25453          ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
25454       check_via(p, req);
25455       build_route(p, req, 0, 0);
25456    } else if (req->debug && req->ignore)
25457       ast_verbose("Ignoring this SUBSCRIBE request\n");
25458 
25459    /* Find parameters to Event: header value and remove them for now */
25460    if (ast_strlen_zero(eventheader)) {
25461       transmit_response(p, "489 Bad Event", req);
25462       ast_debug(2, "Received SIP subscribe for unknown event package: <none>\n");
25463       pvt_set_needdestroy(p, "unknown event package in subscribe");
25464       return 0;
25465    }
25466 
25467    event_end = strchr(eventheader, ';');
25468    if (event_end) {
25469       event_len = event_end - eventheader;
25470    }
25471 
25472    /* Handle authentication if we're new and not a retransmission. We can't just
25473     * use if !req->ignore, because then we'll end up sending
25474     * a 200 OK if someone retransmits without sending auth */
25475    if (p->subscribed == NONE || resubscribe) {
25476       res = check_user_full(p, req, SIP_SUBSCRIBE, e, XMIT_UNRELIABLE, addr, &authpeer);
25477 
25478       /* if an authentication response was sent, we are done here */
25479       if (res == AUTH_CHALLENGE_SENT)  /* authpeer = NULL here */
25480          return 0;
25481       if (res != AUTH_SUCCESSFUL) {
25482          ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
25483          transmit_response(p, "403 Forbidden", req);
25484 
25485          pvt_set_needdestroy(p, "authentication failed");
25486          return 0;
25487       }
25488    }
25489 
25490    /* At this point, we hold a reference to authpeer (if not NULL).  It
25491     * must be released when done.
25492     */
25493 
25494    /* Check if this device  is allowed to subscribe at all */
25495    if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
25496       transmit_response(p, "403 Forbidden (policy)", req);
25497       pvt_set_needdestroy(p, "subscription not allowed");
25498       if (authpeer) {
25499          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 1)");
25500       }
25501       return 0;
25502    }
25503 
25504    if (strncmp(eventheader, "message-summary", MAX(event_len, 15)) && strncmp(eventheader, "call-completion", MAX(event_len, 15))) {
25505       /* Get destination right away */
25506       gotdest = get_destination(p, NULL, NULL);
25507    }
25508 
25509    /* Get full contact header - this needs to be used as a request URI in NOTIFY's */
25510    parse_ok_contact(p, req);
25511 
25512    build_contact(p);
25513    if (gotdest != SIP_GET_DEST_EXTEN_FOUND) {
25514       if (gotdest == SIP_GET_DEST_INVALID_URI) {
25515          transmit_response(p, "416 Unsupported URI scheme", req);
25516       } else {
25517          transmit_response(p, "404 Not Found", req);
25518       }
25519       pvt_set_needdestroy(p, "subscription target not found");
25520       if (authpeer) {
25521          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
25522       }
25523       return 0;
25524    }
25525 
25526    /* Initialize tag for new subscriptions */   
25527    if (ast_strlen_zero(p->tag))
25528       make_our_tag(p);
25529 
25530    if (!strncmp(eventheader, "presence", MAX(event_len, 8)) || !strncmp(eventheader, "dialog", MAX(event_len, 6))) { /* Presence, RFC 3842 */
25531       unsigned int pidf_xml;
25532       const char *accept;
25533       int start = 0;
25534       enum subscriptiontype subscribed = NONE;
25535       const char *unknown_acceptheader = NULL;
25536 
25537       /* Header from Xten Eye-beam Accept: multipart/related, application/rlmi+xml, application/pidf+xml, application/xpidf+xml */
25538       accept = __get_header(req, "Accept", &start);
25539       while ((subscribed == NONE) && !ast_strlen_zero(accept)) {
25540          pidf_xml = strstr(accept, "application/pidf+xml") ? 1 : 0;
25541 
25542          /* Older versions of Polycom firmware will claim pidf+xml, but really
25543           * they only support xpidf+xml. */
25544          if (pidf_xml && strstr(p->useragent, "Polycom")) {
25545             subscribed = XPIDF_XML;
25546          } else if (pidf_xml) {
25547             subscribed = PIDF_XML;         /* RFC 3863 format */
25548          } else if (strstr(accept, "application/dialog-info+xml")) {
25549             subscribed = DIALOG_INFO_XML;
25550             /* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
25551          } else if (strstr(accept, "application/cpim-pidf+xml")) {
25552             subscribed = CPIM_PIDF_XML;    /* RFC 3863 format */
25553          } else if (strstr(accept, "application/xpidf+xml")) {
25554             subscribed = XPIDF_XML;        /* Early pre-RFC 3863 format with MSN additions (Microsoft Messenger) */
25555          } else {
25556             unknown_acceptheader = accept;
25557          }
25558          /* check to see if there is another Accept header present */
25559          accept = __get_header(req, "Accept", &start);
25560       }
25561 
25562       if (!start) {
25563          if (p->subscribed == NONE) { /* if the subscribed field is not already set, and there is no accept header... */
25564             transmit_response(p, "489 Bad Event", req);
25565             ast_log(LOG_WARNING,"SUBSCRIBE failure: no Accept header: pvt: "
25566                "stateid: %d, laststate: %d, dialogver: %u, subscribecont: "
25567                "'%s', subscribeuri: '%s'\n",
25568                p->stateid,
25569                p->laststate,
25570                p->dialogver,
25571                p->subscribecontext,
25572                p->subscribeuri);
25573             pvt_set_needdestroy(p, "no Accept header");
25574             if (authpeer) {
25575                unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
25576             }
25577             return 0;
25578          }
25579          /* if p->subscribed is non-zero, then accept is not obligatory; according to rfc 3265 section 3.1.3, at least.
25580             so, we'll just let it ride, keeping the value from a previous subscription, and not abort the subscription */
25581       } else if (subscribed == NONE) {
25582          /* Can't find a format for events that we know about */
25583          char mybuf[200];
25584          if (!ast_strlen_zero(unknown_acceptheader)) {
25585             snprintf(mybuf, sizeof(mybuf), "489 Bad Event (format %s)", unknown_acceptheader);
25586          } else {
25587             snprintf(mybuf, sizeof(mybuf), "489 Bad Event");
25588          }
25589          transmit_response(p, mybuf, req);
25590          ast_log(LOG_WARNING,"SUBSCRIBE failure: unrecognized format:"
25591             "'%s' pvt: subscribed: %d, stateid: %d, laststate: %d,"
25592             "dialogver: %u, subscribecont: '%s', subscribeuri: '%s'\n",
25593             unknown_acceptheader,
25594             (int)p->subscribed,
25595             p->stateid,
25596             p->laststate,
25597             p->dialogver,
25598             p->subscribecontext,
25599             p->subscribeuri);
25600          pvt_set_needdestroy(p, "unrecognized format");
25601          if (authpeer) {
25602             unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
25603          }
25604          return 0;
25605       } else {
25606          p->subscribed = subscribed;
25607       }
25608    } else if (!strncmp(eventheader, "message-summary", MAX(event_len, 15))) {
25609       int start = 0;
25610       int found_supported = 0;
25611       const char *acceptheader;
25612 
25613       acceptheader = __get_header(req, "Accept", &start);
25614       while (!found_supported && !ast_strlen_zero(acceptheader)) {
25615          found_supported = strcmp(acceptheader, "application/simple-message-summary") ? 0 : 1;
25616          if (!found_supported && (option_debug > 2)) {
25617             ast_log(LOG_DEBUG, "Received SIP mailbox subscription for unknown format: %s\n", acceptheader);
25618          }
25619          acceptheader = __get_header(req, "Accept", &start);
25620       }
25621       if (start && !found_supported) {
25622          /* Format requested that we do not support */
25623          transmit_response(p, "406 Not Acceptable", req);
25624          ast_debug(2, "Received SIP mailbox subscription for unknown format: %s\n", acceptheader);
25625          pvt_set_needdestroy(p, "unknown format");
25626          if (authpeer) {
25627             unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 3)");
25628          }
25629          return 0;
25630       }
25631       /* Looks like they actually want a mailbox status
25632         This version of Asterisk supports mailbox subscriptions
25633         The subscribed URI needs to exist in the dial plan
25634         In most devices, this is configurable to the voicemailmain extension you use
25635       */
25636       if (!authpeer || AST_LIST_EMPTY(&authpeer->mailboxes)) {
25637          if (!authpeer) {
25638             transmit_response(p, "404 Not found", req);
25639          } else {
25640             transmit_response(p, "404 Not found (no mailbox)", req);
25641             ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", S_OR(authpeer->name, ""));
25642          }
25643          pvt_set_needdestroy(p, "received 404 response");
25644          if (authpeer) {
25645             unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 3)");
25646          }
25647          return 0;
25648       }
25649 
25650       p->subscribed = MWI_NOTIFICATION;
25651       if (ast_test_flag(&authpeer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY)) {
25652          ao2_unlock(p);
25653          add_peer_mwi_subs(authpeer);
25654          ao2_lock(p);
25655       }
25656       if (authpeer->mwipvt != p) {  /* Destroy old PVT if this is a new one */
25657          /* We only allow one subscription per peer */
25658          if (authpeer->mwipvt) {
25659             dialog_unlink_all(authpeer->mwipvt);
25660             authpeer->mwipvt = dialog_unref(authpeer->mwipvt, "unref dialog authpeer->mwipvt");
25661          }
25662          authpeer->mwipvt = dialog_ref(p, "setting peers' mwipvt to p");
25663       }
25664       if (p->relatedpeer != authpeer) {
25665          if (p->relatedpeer) {
25666             unref_peer(p->relatedpeer, "Unref previously stored relatedpeer ptr");
25667          }
25668          p->relatedpeer = ref_peer(authpeer, "setting dialog's relatedpeer pointer");
25669       }
25670       /* Do not release authpeer here */
25671    } else if (!strncmp(eventheader, "call-completion", MAX(event_len, 15))) {
25672       handle_cc_subscribe(p, req);
25673    } else { /* At this point, Asterisk does not understand the specified event */
25674       transmit_response(p, "489 Bad Event", req);
25675       ast_debug(2, "Received SIP subscribe for unknown event package: %s\n", eventheader);
25676       pvt_set_needdestroy(p, "unknown event package");
25677       if (authpeer) {
25678          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 5)");
25679       }
25680       return 0;
25681    }
25682 
25683    /* Add subscription for extension state from the PBX core */
25684    if (p->subscribed != MWI_NOTIFICATION  && p->subscribed != CALL_COMPLETION && !resubscribe) {
25685       if (p->stateid != -1) {
25686          ast_extension_state_del(p->stateid, cb_extensionstate);
25687       }
25688       dialog_ref(p, "copying dialog ptr into extension state struct");
25689       p->stateid = ast_extension_state_add_destroy(p->context, p->exten,
25690          cb_extensionstate, cb_extensionstate_destroy, p);
25691       if (p->stateid == -1) {
25692          dialog_unref(p, "copying dialog ptr into extension state struct failed");
25693       }
25694    }
25695 
25696    if (!req->ignore) {
25697       p->lastinvite = seqno;
25698    }
25699    if (!p->needdestroy) {
25700       p->expiry = atoi(get_header(req, "Expires"));
25701 
25702       /* check if the requested expiry-time is within the approved limits from sip.conf */
25703       if (p->expiry > max_expiry) {
25704          p->expiry = max_expiry;
25705       } else if (p->expiry < min_expiry && p->expiry > 0) {
25706          transmit_response_with_minexpires(p, "423 Interval too small", req);
25707          ast_log(LOG_WARNING, "Received subscription for extension \"%s\" context \"%s\" "
25708             "with Expire header less that 'minexpire' limit. Received \"Expire: %d\" min is %d\n",
25709             p->exten, p->context, p->expiry, min_expiry);
25710          pvt_set_needdestroy(p, "Expires is less that the min expires allowed.");
25711          if (authpeer) {
25712             unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 6)");
25713          }
25714          return 0;
25715       }
25716 
25717       if (sipdebug) {
25718          const char *action = p->expiry > 0 ? "Adding" : "Removing";
25719          if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer) {
25720             ast_debug(2, "%s subscription for mailbox notification - peer %s\n",
25721                   action, p->relatedpeer->name);
25722          } else if (p->subscribed == CALL_COMPLETION) {
25723             ast_debug(2, "%s CC subscription for peer %s\n", action, p->username);
25724          } else {
25725             ast_debug(2, "%s subscription for extension %s context %s for peer %s\n",
25726                   action, p->exten, p->context, p->username);
25727          }
25728       }
25729       if (p->autokillid > -1 && sip_cancel_destroy(p))   /* Remove subscription expiry for renewals */
25730          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
25731       if (p->expiry > 0)
25732          sip_scheddestroy(p, (p->expiry + 10) * 1000);   /* Set timer for destruction of call at expiration */
25733 
25734       if (p->subscribed == MWI_NOTIFICATION) {
25735          ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
25736          transmit_response(p, "200 OK", req);
25737          if (p->relatedpeer) {   /* Send first notification */
25738             struct sip_peer *peer = p->relatedpeer;
25739             ref_peer(peer, "ensure a peer ref is held during MWI sending");
25740             ao2_unlock(p);
25741             sip_send_mwi_to_peer(peer, 0);
25742             ao2_lock(p);
25743             unref_peer(peer, "release a peer ref now that MWI is sent");
25744          }
25745       } else if (p->subscribed != CALL_COMPLETION) {
25746          sip_pvt_unlock(p);
25747          firststate = ast_extension_state(NULL, p->context, p->exten);
25748          sip_pvt_lock(p);
25749 
25750          if (firststate < 0) {
25751             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));
25752             transmit_response(p, "404 Not found", req);
25753             pvt_set_needdestroy(p, "no extension for SUBSCRIBE");
25754             if (authpeer) {
25755                unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 6)");
25756             }
25757             return 0;
25758          }
25759          ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
25760          transmit_response(p, "200 OK", req);
25761          transmit_state_notify(p, firststate, 1, FALSE); /* Send first notification */
25762          append_history(p, "Subscribestatus", "%s", ast_extension_state2str(firststate));
25763          /* hide the 'complete' exten/context in the refer_to field for later display */
25764          ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
25765          /* Deleted the slow iteration of all sip dialogs to find old subscribes from this peer for exten@context */
25766 
25767       }
25768       if (!p->expiry) {
25769          pvt_set_needdestroy(p, "forcing expiration");
25770       }
25771    }
25772 
25773    if (authpeer) {
25774       unref_peer(authpeer, "unref pointer into (*authpeer)");
25775    }
25776    return 1;
25777 }
25778 
25779 /*! \brief Handle incoming REGISTER request */
25780 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e)
25781 {
25782    enum check_auth_result res;
25783 
25784    /* If this is not the intial request, and the initial request isn't
25785     * a register, something screwy happened, so bail */
25786    if (p->initreq.headers && p->initreq.method != SIP_REGISTER) {
25787       ast_log(LOG_WARNING, "Ignoring spurious REGISTER with Call-ID: %s\n", p->callid);
25788       return -1;
25789    }
25790 
25791    /* Use this as the basis */
25792    copy_request(&p->initreq, req);
25793    if (sipdebug)
25794       ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
25795    check_via(p, req);
25796    if ((res = register_verify(p, addr, req, e)) < 0) {
25797       const char *reason;
25798 
25799       switch (res) {
25800       case AUTH_SECRET_FAILED:
25801          reason = "Wrong password";
25802          break;
25803       case AUTH_USERNAME_MISMATCH:
25804          reason = "Username/auth name mismatch";
25805          break;
25806       case AUTH_NOT_FOUND:
25807          reason = "No matching peer found";
25808          break;
25809       case AUTH_UNKNOWN_DOMAIN:
25810          reason = "Not a local domain";
25811          break;
25812       case AUTH_PEER_NOT_DYNAMIC:
25813          reason = "Peer is not supposed to register";
25814          break;
25815       case AUTH_ACL_FAILED:
25816          reason = "Device does not match ACL";
25817          break;
25818       case AUTH_BAD_TRANSPORT:
25819          reason = "Device not configured to use this transport type";
25820          break;
25821       default:
25822          reason = "Unknown failure";
25823          break;
25824       }
25825       ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
25826          get_header(req, "To"), ast_sockaddr_stringify(addr),
25827          reason);
25828       append_history(p, "RegRequest", "Failed : Account %s : %s", get_header(req, "To"), reason);
25829    } else {
25830       req->authenticated = 1;
25831       append_history(p, "RegRequest", "Succeeded : Account %s", get_header(req, "To"));
25832    }
25833 
25834    if (res < 1) {
25835       /* Destroy the session, but keep us around for just a bit in case they don't
25836          get our 200 OK */
25837       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25838    }
25839    return res;
25840 }
25841 
25842 /*!
25843  * \brief Handle incoming SIP requests (methods)
25844  * \note
25845  * This is where all incoming requests go first.
25846  * \note
25847  * called with p and p->owner locked
25848  */
25849 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock)
25850 {
25851    /* Called with p->lock held, as well as p->owner->lock if appropriate, keeping things
25852       relatively static */
25853    const char *cmd;
25854    const char *cseq;
25855    const char *useragent;
25856    const char *via;
25857    const char *callid;
25858    int via_pos = 0;
25859    uint32_t seqno;
25860    int len;
25861    int respid;
25862    int res = 0;
25863    int debug = sip_debug_test_pvt(p);
25864    const char *e;
25865    int error = 0;
25866    int oldmethod = p->method;
25867    int acked = 0;
25868 
25869    /* RFC 3261 - 8.1.1 A valid SIP request must contain To, From, CSeq, Call-ID and Via.
25870     * 8.2.6.2 Response must have To, From, Call-ID CSeq, and Via related to the request,
25871     * so we can check to make sure these fields exist for all requests and responses */
25872    cseq = get_header(req, "Cseq");
25873    cmd = REQ_OFFSET_TO_STR(req, header[0]);
25874    /* Save the via_pos so we can check later that responses only have 1 Via header */
25875    via = __get_header(req, "Via", &via_pos);
25876    /* This must exist already because we've called find_call by now */
25877    callid = get_header(req, "Call-ID");
25878 
25879    /* Must have Cseq */
25880    if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq) || ast_strlen_zero(via)) {
25881       ast_log(LOG_ERROR, "Dropping this SIP message with Call-ID '%s', it's incomplete.\n", callid);
25882       error = 1;
25883    }
25884    if (!error && sscanf(cseq, "%30u%n", &seqno, &len) != 1) {
25885       ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
25886       error = 1;
25887    }
25888    if (error) {
25889       if (!p->initreq.headers) { /* New call */
25890          pvt_set_needdestroy(p, "no headers");
25891       }
25892       return -1;
25893    }
25894    /* Get the command XXX */
25895 
25896    cmd = REQ_OFFSET_TO_STR(req, rlPart1);
25897    e = ast_skip_blanks(REQ_OFFSET_TO_STR(req, rlPart2));
25898 
25899    /* Save useragent of the client */
25900    useragent = get_header(req, "User-Agent");
25901    if (!ast_strlen_zero(useragent))
25902       ast_string_field_set(p, useragent, useragent);
25903 
25904    /* Find out SIP method for incoming request */
25905    if (req->method == SIP_RESPONSE) {  /* Response to our request */
25906       /* ignore means "don't do anything with it" but still have to
25907        * respond appropriately.
25908        * But in this case this is a response already, so we really
25909        * have nothing to do with this message, and even setting the
25910        * ignore flag is pointless.
25911        */
25912       if (ast_strlen_zero(e)) {
25913          return 0;
25914       }
25915       if (sscanf(e, "%30d %n", &respid, &len) != 1) {
25916          ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
25917          return 0;
25918       }
25919       if (respid <= 0) {
25920          ast_log(LOG_WARNING, "Invalid SIP response code: '%d'\n", respid);
25921          return 0;
25922       }
25923       /* RFC 3261 - 8.1.3.3 If more than one Via header field value is present in a reponse
25924        * the UAC SHOULD discard the message. This is not perfect, as it will not catch multiple
25925        * headers joined with a comma. Fixing that would pretty much involve writing a new parser */
25926       if (!ast_strlen_zero(__get_header(req, "via", &via_pos))) {
25927          ast_log(LOG_WARNING, "Misrouted SIP response '%s' with Call-ID '%s', too many vias\n", e, callid);
25928          return 0;
25929       }
25930       if (p->ocseq && (p->ocseq < seqno)) {
25931          ast_debug(1, "Ignoring out of order response %u (expecting %u)\n", seqno, p->ocseq);
25932          return -1;
25933       } else {
25934          char causevar[256], causeval[256];
25935 
25936          if ((respid == 200) || ((respid >= 300) && (respid <= 399))) {
25937             extract_uri(p, req);
25938          }
25939 
25940          handle_response(p, respid, e + len, req, seqno);
25941 
25942          if (global_store_sip_cause && p->owner) {
25943             struct ast_channel *owner = p->owner;
25944 
25945             snprintf(causevar, sizeof(causevar), "MASTER_CHANNEL(HASH(SIP_CAUSE,%s))", owner->name);
25946             snprintf(causeval, sizeof(causeval), "SIP %s", REQ_OFFSET_TO_STR(req, rlPart2));
25947 
25948             ast_channel_ref(owner);
25949             sip_pvt_unlock(p);
25950             ast_channel_unlock(owner);
25951             *nounlock = 1;
25952             pbx_builtin_setvar_helper(owner, causevar, causeval);
25953             ast_channel_unref(owner);
25954             sip_pvt_lock(p);
25955          }
25956       }
25957       return 0;
25958    }
25959 
25960    /* New SIP request coming in
25961       (could be new request in existing SIP dialog as well...)
25962     */         
25963    
25964    p->method = req->method;   /* Find out which SIP method they are using */
25965    ast_debug(4, "**** Received %s (%u) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd);
25966 
25967    if (p->icseq && (p->icseq > seqno) ) {
25968       if (p->pendinginvite && seqno == p->pendinginvite && (req->method == SIP_ACK || req->method == SIP_CANCEL)) {
25969          ast_debug(2, "Got CANCEL or ACK on INVITE with transactions in between.\n");
25970       } else {
25971          ast_debug(1, "Ignoring too old SIP packet packet %u (expecting >= %u)\n", seqno, p->icseq);
25972          if (req->method == SIP_INVITE) {
25973             unsigned int ran = (ast_random() % 10) + 1;
25974             char seconds[4];
25975             snprintf(seconds, sizeof(seconds), "%u", ran);
25976             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 */
25977          } else if (req->method != SIP_ACK) {
25978             transmit_response(p, "500 Server error", req);  /* We must respond according to RFC 3261 sec 12.2 */
25979          }
25980          return -1;
25981       }
25982    } else if (p->icseq &&
25983          p->icseq == seqno &&
25984          req->method != SIP_ACK &&
25985          (p->method != SIP_CANCEL || p->alreadygone)) {
25986       /* ignore means "don't do anything with it" but still have to
25987          respond appropriately.  We do this if we receive a repeat of
25988          the last sequence number  */
25989       req->ignore = 1;
25990       ast_debug(3, "Ignoring SIP message because of retransmit (%s Seqno %u, ours %u)\n", sip_methods[p->method].text, p->icseq, seqno);
25991    }
25992 
25993    /* RFC 3261 section 9. "CANCEL has no effect on a request to which a UAS has
25994     * already given a final response." */
25995    if (!p->pendinginvite && (req->method == SIP_CANCEL)) {
25996       transmit_response(p, "481 Call/Transaction Does Not Exist", req);
25997       return res;
25998    }
25999 
26000    if (seqno >= p->icseq)
26001       /* Next should follow monotonically (but not necessarily
26002          incrementally -- thanks again to the genius authors of SIP --
26003          increasing */
26004       p->icseq = seqno;
26005 
26006    /* Find their tag if we haven't got it */
26007    if (ast_strlen_zero(p->theirtag)) {
26008       char tag[128];
26009 
26010       gettag(req, "From", tag, sizeof(tag));
26011       ast_string_field_set(p, theirtag, tag);
26012    }
26013    snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
26014 
26015    if (sip_cfg.pedanticsipchecking) {
26016       /* If this is a request packet without a from tag, it's not
26017          correct according to RFC 3261  */
26018       /* Check if this a new request in a new dialog with a totag already attached to it,
26019          RFC 3261 - section 12.2 - and we don't want to mess with recovery  */
26020       if (!p->initreq.headers && req->has_to_tag) {
26021          /* If this is a first request and it got a to-tag, it is not for us */
26022          if (!req->ignore && req->method == SIP_INVITE) {
26023             /* Just because we think this is a dialog-starting INVITE with a to-tag
26024              * doesn't mean it actually is. It could be a reinvite for an established, but
26025              * unknown dialog. In such a case, we need to change our tag to the
26026              * incoming INVITE's to-tag so that they will recognize the 481 we send and
26027              * so that we will properly match their incoming ACK.
26028              */
26029             char totag[128];
26030             gettag(req, "To", totag, sizeof(totag));
26031             ast_string_field_set(p, tag, totag);
26032             p->pendinginvite = p->icseq;
26033             transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
26034             /* Will cease to exist after ACK */
26035             return res;
26036          } else if (req->method != SIP_ACK) {
26037             transmit_response(p, "481 Call/Transaction Does Not Exist", req);
26038             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
26039             return res;
26040          }
26041          /* Otherwise, this is an ACK. It will always have a to-tag */
26042       }
26043    }
26044 
26045    if (!e && (p->method == SIP_INVITE || p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_NOTIFY || p->method == SIP_PUBLISH)) {
26046       transmit_response(p, "400 Bad request", req);
26047       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
26048       return -1;
26049    }
26050 
26051    /* Handle various incoming SIP methods in requests */
26052    switch (p->method) {
26053    case SIP_OPTIONS:
26054       res = handle_request_options(p, req, addr, e);
26055       break;
26056    case SIP_INVITE:
26057       res = handle_request_invite(p, req, debug, seqno, addr, recount, e, nounlock);
26058       break;
26059    case SIP_REFER:
26060       res = handle_request_refer(p, req, debug, seqno, nounlock);
26061       break;
26062    case SIP_CANCEL:
26063       res = handle_request_cancel(p, req);
26064       break;
26065    case SIP_BYE:
26066       res = handle_request_bye(p, req);
26067       break;
26068    case SIP_MESSAGE:
26069       res = handle_request_message(p, req);
26070       break;
26071    case SIP_PUBLISH:
26072       res = handle_request_publish(p, req, addr, seqno, e);
26073       break;
26074    case SIP_SUBSCRIBE:
26075       res = handle_request_subscribe(p, req, addr, seqno, e);
26076       break;
26077    case SIP_REGISTER:
26078       res = handle_request_register(p, req, addr, e);
26079       break;
26080    case SIP_INFO:
26081       if (req->debug)
26082          ast_verbose("Receiving INFO!\n");
26083       if (!req->ignore)
26084          handle_request_info(p, req);
26085       else  /* if ignoring, transmit response */
26086          transmit_response(p, "200 OK", req);
26087       break;
26088    case SIP_NOTIFY:
26089       res = handle_request_notify(p, req, addr, seqno, e);
26090       break;
26091    case SIP_UPDATE:
26092       res = handle_request_update(p, req);
26093       break;
26094    case SIP_ACK:
26095       /* Make sure we don't ignore this */
26096       if (seqno == p->pendinginvite) {
26097          p->invitestate = INV_TERMINATED;
26098          p->pendinginvite = 0;
26099          acked = __sip_ack(p, seqno, 1 /* response */, 0);
26100          if (p->owner && find_sdp(req)) {
26101             if (process_sdp(p, req, SDP_T38_NONE)) {
26102                return -1;
26103             }
26104             if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
26105                ast_queue_control(p->owner, AST_CONTROL_SRCCHANGE);
26106             }
26107          }
26108          check_pendings(p);
26109       } else if (p->glareinvite == seqno) {
26110          /* handle ack for the 491 pending sent for glareinvite */
26111          p->glareinvite = 0;
26112          acked = __sip_ack(p, seqno, 1, 0);
26113       }
26114       if (!acked) {
26115          /* Got an ACK that did not match anything. Ignore
26116           * silently and restore previous method */
26117          p->method = oldmethod;
26118       }
26119       if (!p->lastinvite && ast_strlen_zero(p->randdata)) {
26120          pvt_set_needdestroy(p, "unmatched ACK");
26121       }
26122       break;
26123    default:
26124       transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
26125       ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n",
26126          cmd, ast_sockaddr_stringify(&p->sa));
26127       /* If this is some new method, and we don't have a call, destroy it now */
26128       if (!p->initreq.headers) {
26129          pvt_set_needdestroy(p, "unimplemented method");
26130       }
26131       break;
26132    }
26133    return res;
26134 }
26135 
26136 /*! \brief Read data from SIP UDP socket
26137 \note sipsock_read locks the owner channel while we are processing the SIP message
26138 \return 1 on error, 0 on success
26139 \note Successful messages is connected to SIP call and forwarded to handle_incoming()
26140 */
26141 static int sipsock_read(int *id, int fd, short events, void *ignore)
26142 {
26143    struct sip_request req;
26144    struct ast_sockaddr addr;
26145    int res;
26146    static char readbuf[65535];
26147 
26148    memset(&req, 0, sizeof(req));
26149    res = ast_recvfrom(fd, readbuf, sizeof(readbuf) - 1, 0, &addr);
26150    if (res < 0) {
26151 #if !defined(__FreeBSD__)
26152       if (errno == EAGAIN)
26153          ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
26154       else
26155 #endif
26156       if (errno != ECONNREFUSED)
26157          ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
26158       return 1;
26159    }
26160 
26161    readbuf[res] = '\0';
26162 
26163    if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
26164       return 1;
26165    }
26166 
26167    if (ast_str_set(&req.data, 0, "%s", readbuf) == AST_DYNSTR_BUILD_FAILED) {
26168       return -1;
26169    }
26170 
26171    req.socket.fd = sipsock;
26172    set_socket_transport(&req.socket, SIP_TRANSPORT_UDP);
26173    req.socket.tcptls_session  = NULL;
26174    req.socket.port = htons(ast_sockaddr_port(&bindaddr));
26175 
26176    handle_request_do(&req, &addr);
26177    deinit_req(&req);
26178 
26179    return 1;
26180 }
26181 
26182 /*! \brief Handle incoming SIP message - request or response
26183 
26184    This is used for all transports (udp, tcp and tcp/tls)
26185 */
26186 static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr)
26187 {
26188    struct sip_pvt *p;
26189    struct ast_channel *owner_chan_ref = NULL;
26190    int recount = 0;
26191    int nounlock = 0;
26192 
26193    if (sip_debug_test_addr(addr))   /* Set the debug flag early on packet level */
26194       req->debug = 1;
26195    if (sip_cfg.pedanticsipchecking)
26196       lws2sws(req->data);  /* Fix multiline headers */
26197    if (req->debug) {
26198       ast_verbose("\n<--- SIP read from %s:%s --->\n%s\n<------------->\n",
26199          get_transport(req->socket.type), ast_sockaddr_stringify(addr), ast_str_buffer(req->data));
26200    }
26201 
26202    if (parse_request(req) == -1) { /* Bad packet, can't parse */
26203       ast_str_reset(req->data); /* nulling this out is NOT a good idea here. */
26204       return 1;
26205    }
26206    req->method = find_sip_method(REQ_OFFSET_TO_STR(req, rlPart1));
26207 
26208    if (req->debug)
26209       ast_verbose("--- (%d headers %d lines)%s ---\n", req->headers, req->lines, (req->headers + req->lines == 0) ? " Nat keepalive" : "");
26210 
26211    if (req->headers < 2) { /* Must have at least two headers */
26212       ast_str_reset(req->data); /* nulling this out is NOT a good idea here. */
26213       return 1;
26214    }
26215 
26216    /* Process request, with netlock held, and with usual deadlock avoidance */
26217    ast_mutex_lock(&netlock);
26218 
26219    /* Find the active SIP dialog or create a new one */
26220    p = find_call(req, addr, req->method); /* returns p with a reference only. _NOT_ locked*/
26221    if (p == NULL) {
26222       ast_debug(1, "Invalid SIP message - rejected , no callid, len %zu\n", ast_str_strlen(req->data));
26223       ast_mutex_unlock(&netlock);
26224       return 1;
26225    }
26226 
26227    /* Lock both the pvt and the owner if owner is present.  This will
26228     * not fail. */
26229    owner_chan_ref = sip_pvt_lock_full(p);
26230 
26231    copy_socket_data(&p->socket, &req->socket);
26232 
26233    ast_sockaddr_copy(&p->recv, addr);
26234 
26235    /* if we have an owner, then this request has been authenticated */
26236    if (p->owner) {
26237       req->authenticated = 1;
26238    }
26239 
26240    if (p->do_history) /* This is a request or response, note what it was for */
26241       append_history(p, "Rx", "%s / %s / %s", ast_str_buffer(req->data), get_header(req, "CSeq"), REQ_OFFSET_TO_STR(req, rlPart2));
26242 
26243    if (handle_incoming(p, req, addr, &recount, &nounlock) == -1) {
26244       /* Request failed */
26245       ast_debug(1, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
26246    }
26247 
26248    if (recount) {
26249       ast_update_use_count();
26250    }
26251 
26252    if (p->owner && !nounlock) {
26253       ast_channel_unlock(p->owner);
26254    }
26255    if (owner_chan_ref) {
26256       ast_channel_unref(owner_chan_ref);
26257    }
26258    sip_pvt_unlock(p);
26259    ao2_t_ref(p, -1, "throw away dialog ptr from find_call at end of routine"); /* p is gone after the return */
26260    ast_mutex_unlock(&netlock);
26261 
26262    return 1;
26263 }
26264 
26265 /*! \brief Returns the port to use for this socket
26266  *
26267  * \param type The type of transport used
26268  * \param port Port we are checking to see if it's the standard port.
26269  * \note port is expected in host byte order
26270  */
26271 static int sip_standard_port(enum sip_transport type, int port)
26272 {
26273    if (type & SIP_TRANSPORT_TLS)
26274       return port == STANDARD_TLS_PORT;
26275    else
26276       return port == STANDARD_SIP_PORT;
26277 }
26278 
26279 static int threadinfo_locate_cb(void *obj, void *arg, int flags)
26280 {
26281    struct sip_threadinfo *th = obj;
26282    struct ast_sockaddr *s = arg;
26283 
26284    if (!ast_sockaddr_cmp(s, &th->tcptls_session->remote_address)) {
26285       return CMP_MATCH | CMP_STOP;
26286    }
26287 
26288    return 0;
26289 }
26290 
26291 /*!
26292  * \brief Find thread for TCP/TLS session (based on IP/Port
26293  *
26294  * \note This function returns an astobj2 reference
26295  */
26296 static struct ast_tcptls_session_instance *sip_tcp_locate(struct ast_sockaddr *s)
26297 {
26298    struct sip_threadinfo *th;
26299    struct ast_tcptls_session_instance *tcptls_instance = NULL;
26300 
26301    if ((th = ao2_callback(threadt, 0, threadinfo_locate_cb, s))) {
26302       tcptls_instance = (ao2_ref(th->tcptls_session, +1), th->tcptls_session);
26303       ao2_t_ref(th, -1, "decrement ref from callback");
26304    }
26305 
26306    return tcptls_instance;
26307 }
26308 
26309 /*!
26310  * \brief Helper for dns resolution to filter by address family.
26311  *
26312  * \note return 0 if addr is [::] else it returns addr's family.
26313  */
26314 int get_address_family_filter(unsigned int transport)
26315 {
26316    const struct ast_sockaddr *addr = NULL;
26317 
26318    if ((transport == SIP_TRANSPORT_UDP) || !transport) {
26319       addr = &bindaddr;
26320    }
26321    else if (transport == SIP_TRANSPORT_TCP) {
26322       addr = &sip_tcp_desc.local_address;
26323    }
26324    else if (transport == SIP_TRANSPORT_TLS) {
26325       addr = &sip_tls_desc.local_address;
26326    }
26327 
26328    if (ast_sockaddr_is_ipv6(addr) && ast_sockaddr_is_any(addr)) {
26329       return 0;
26330    }
26331 
26332    return addr->ss.ss_family;
26333 }
26334 
26335 /*! \todo Get socket for dialog, prepare if needed, and return file handle  */
26336 static int sip_prepare_socket(struct sip_pvt *p)
26337 {
26338    struct sip_socket *s = &p->socket;
26339    static const char name[] = "SIP socket";
26340    struct sip_threadinfo *th = NULL;
26341    struct ast_tcptls_session_instance *tcptls_session;
26342    struct ast_tcptls_session_args *ca;
26343    struct ast_sockaddr sa_tmp;
26344    pthread_t launched;
26345 
26346    /* check to see if a socket is already active */
26347    if ((s->fd != -1) && (s->type == SIP_TRANSPORT_UDP)) {
26348       return s->fd;
26349    }
26350    if ((s->type & (SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS)) &&
26351          (s->tcptls_session) &&
26352          (s->tcptls_session->fd != -1)) {
26353       return s->tcptls_session->fd;
26354    }
26355 
26356    /*! \todo Check this... This might be wrong, depending on the proxy configuration
26357       If proxy is in "force" mode its correct.
26358     */
26359    if (p->outboundproxy && p->outboundproxy->transport) {
26360       s->type = p->outboundproxy->transport;
26361    }
26362 
26363    if (s->type == SIP_TRANSPORT_UDP) {
26364       s->fd = sipsock;
26365       return s->fd;
26366    }
26367 
26368    /* At this point we are dealing with a TCP/TLS connection
26369     * 1. We need to check to see if a connection thread exists
26370     *    for this address, if so use that.
26371     * 2. If a thread does not exist for this address, but the tcptls_session
26372     *    exists on the socket, the connection was closed.
26373     * 3. If no tcptls_session thread exists for the address, and no tcptls_session
26374     *    already exists on the socket, create a new one and launch a new thread.
26375     */
26376 
26377    /* 1.  check for existing threads */
26378    ast_sockaddr_copy(&sa_tmp, sip_real_dst(p));
26379    if ((tcptls_session = sip_tcp_locate(&sa_tmp))) {
26380       s->fd = tcptls_session->fd;
26381       if (s->tcptls_session) {
26382          ao2_ref(s->tcptls_session, -1);
26383          s->tcptls_session = NULL;
26384       }
26385       s->tcptls_session = tcptls_session;
26386       return s->fd;
26387    /* 2.  Thread not found, if tcptls_session already exists, it once had a thread and is now terminated */
26388    } else if (s->tcptls_session) {
26389       return s->fd; /* XXX whether reconnection is ever necessary here needs to be investigated further */
26390    }
26391 
26392    /* 3.  Create a new TCP/TLS client connection */
26393    /* create new session arguments for the client connection */
26394    if (!(ca = ao2_alloc(sizeof(*ca), sip_tcptls_client_args_destructor)) ||
26395       !(ca->name = ast_strdup(name))) {
26396       goto create_tcptls_session_fail;
26397    }
26398    ca->accept_fd = -1;
26399    ast_sockaddr_copy(&ca->remote_address,sip_real_dst(p));
26400    /* if type is TLS, we need to create a tls cfg for this session arg */
26401    if (s->type == SIP_TRANSPORT_TLS) {
26402       if (!(ca->tls_cfg = ast_calloc(1, sizeof(*ca->tls_cfg)))) {
26403          goto create_tcptls_session_fail;
26404       }
26405       memcpy(ca->tls_cfg, &default_tls_cfg, sizeof(*ca->tls_cfg));
26406 
26407       if (!(ca->tls_cfg->certfile = ast_strdup(default_tls_cfg.certfile)) ||
26408          !(ca->tls_cfg->pvtfile = ast_strdup(default_tls_cfg.pvtfile)) ||
26409          !(ca->tls_cfg->cipher = ast_strdup(default_tls_cfg.cipher)) ||
26410          !(ca->tls_cfg->cafile = ast_strdup(default_tls_cfg.cafile)) ||
26411          !(ca->tls_cfg->capath = ast_strdup(default_tls_cfg.capath))) {
26412 
26413          goto create_tcptls_session_fail;
26414       }
26415 
26416       /* this host is used as the common name in ssl/tls */
26417       if (!ast_strlen_zero(p->tohost)) {
26418          ast_copy_string(ca->hostname, p->tohost, sizeof(ca->hostname));
26419       }
26420    }
26421 
26422    /* Create a client connection for address, this does not start the connection, just sets it up. */
26423    if (!(s->tcptls_session = ast_tcptls_client_create(ca))) {
26424       goto create_tcptls_session_fail;
26425    }
26426 
26427    s->fd = s->tcptls_session->fd;
26428 
26429    /* client connections need to have the sip_threadinfo object created before
26430     * the thread is detached.  This ensures the alert_pipe is up before it will
26431     * be used.  Note that this function links the new threadinfo object into the
26432     * threadt container. */
26433    if (!(th = sip_threadinfo_create(s->tcptls_session, s->type))) {
26434       goto create_tcptls_session_fail;
26435    }
26436 
26437    /* Give the new thread a reference to the tcptls_session */
26438    ao2_ref(s->tcptls_session, +1);
26439 
26440    if (ast_pthread_create_detached_background(&launched, NULL, sip_tcp_worker_fn, s->tcptls_session)) {
26441       ast_debug(1, "Unable to launch '%s'.", ca->name);
26442       ao2_ref(s->tcptls_session, -1); /* take away the thread ref we just gave it */
26443       goto create_tcptls_session_fail;
26444    }
26445 
26446    return s->fd;
26447 
26448 create_tcptls_session_fail:
26449    if (ca) {
26450       ao2_t_ref(ca, -1, "failed to create client, getting rid of client tcptls_session arguments");
26451    }
26452    if (s->tcptls_session) {
26453       ast_tcptls_close_session_file(s->tcptls_session);
26454       s->fd = -1;
26455       ao2_ref(s->tcptls_session, -1);
26456       s->tcptls_session = NULL;
26457    }
26458    if (th) {
26459       ao2_t_unlink(threadt, th, "Removing tcptls thread info object, thread failed to open");
26460    }
26461 
26462    return -1;
26463 }
26464 
26465 /*!
26466  * \brief Get cached MWI info
26467  * \return TRUE if found MWI in cache
26468  */
26469 static int get_cached_mwi(struct sip_peer *peer, int *new, int *old)
26470 {
26471    struct sip_mailbox *mailbox;
26472    int in_cache;
26473 
26474    in_cache = 0;
26475    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
26476       struct ast_event *event;
26477       event = ast_event_get_cached(AST_EVENT_MWI,
26478          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
26479          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
26480          AST_EVENT_IE_END);
26481       if (!event)
26482          continue;
26483       *new += ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
26484       *old += ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
26485       ast_event_destroy(event);
26486       in_cache = 1;
26487    }
26488 
26489    return in_cache;
26490 }
26491 
26492 /*! \brief Send message waiting indication to alert peer that they've got voicemail
26493  *  \note Both peer and associated sip_pvt must be unlocked prior to calling this function
26494 */
26495 static int sip_send_mwi_to_peer(struct sip_peer *peer, int cache_only)
26496 {
26497    /* Called with peer lock, but releases it */
26498    struct sip_pvt *p;
26499    int newmsgs = 0, oldmsgs = 0;
26500    const char *vmexten = NULL;
26501 
26502    ao2_lock(peer);
26503 
26504    if (peer->vmexten) {
26505       vmexten = ast_strdupa(peer->vmexten);
26506    }
26507 
26508    if (ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY) && !peer->mwipvt) {
26509       update_peer_lastmsgssent(peer, -1, 1);
26510       ao2_unlock(peer);
26511       return 0;
26512    }
26513 
26514    /* Do we have an IP address? If not, skip this peer */
26515    if (ast_sockaddr_isnull(&peer->addr) && ast_sockaddr_isnull(&peer->defaddr)) {
26516       update_peer_lastmsgssent(peer, -1, 1);
26517       ao2_unlock(peer);
26518       return 0;
26519    }
26520 
26521    /* Attempt to use cached mwi to get message counts. */
26522    if (!get_cached_mwi(peer, &newmsgs, &oldmsgs) && !cache_only) {
26523       /* Fall back to manually checking the mailbox if not cache_only and get_cached_mwi failed */
26524       struct ast_str *mailbox_str = ast_str_alloca(512);
26525       peer_mailboxes_to_str(&mailbox_str, peer);
26526       ao2_unlock(peer);
26527       /* If there is no mailbox do nothing */
26528       if (!ast_str_strlen(mailbox_str)) {
26529          update_peer_lastmsgssent(peer, -1, 0);
26530          return 0;
26531       }
26532       ast_app_inboxcount(ast_str_buffer(mailbox_str), &newmsgs, &oldmsgs);
26533       ao2_lock(peer);
26534    }
26535 
26536    if (peer->mwipvt) {
26537       /* Base message on subscription */
26538       p = dialog_ref(peer->mwipvt, "sip_send_mwi_to_peer: Setting dialog ptr p from peer->mwipvt");
26539       ao2_unlock(peer);
26540    } else {
26541       ao2_unlock(peer);
26542       /* Build temporary dialog for this message */
26543       if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
26544          update_peer_lastmsgssent(peer, -1, 0);
26545          return -1;
26546       }
26547 
26548       /* If we don't set the socket type to 0, then create_addr_from_peer will fail immediately if the peer
26549        * uses any transport other than UDP. We set the type to 0 here and then let create_addr_from_peer copy
26550        * the peer's socket information to the sip_pvt we just allocated
26551        */
26552       set_socket_transport(&p->socket, 0);
26553       if (create_addr_from_peer(p, peer)) {
26554          /* Maybe they're not registered, etc. */
26555          dialog_unlink_all(p);
26556          dialog_unref(p, "unref dialog p just created via sip_alloc");
26557          update_peer_lastmsgssent(peer, -1, 0);
26558          return 0;
26559       }
26560       /* Recalculate our side, and recalculate Call ID */
26561       ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
26562       build_via(p);
26563 
26564       ao2_lock(peer);
26565       if (!ast_strlen_zero(peer->mwi_from)) {
26566          ast_string_field_set(p, mwi_from, peer->mwi_from);
26567       } else if (!ast_strlen_zero(default_mwi_from)) {
26568          ast_string_field_set(p, mwi_from, default_mwi_from);
26569       }
26570       ao2_unlock(peer);
26571 
26572       /* Change the dialog callid. */
26573       change_callid_pvt(p, NULL);
26574 
26575       /* Destroy this session after 32 secs */
26576       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
26577    }
26578 
26579    /* 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,
26580       we really need to have a lock on it */
26581    sip_pvt_lock(p);
26582 
26583    /* Send MWI */
26584    ast_set_flag(&p->flags[0], SIP_OUTGOING);
26585    /* the following will decrement the refcount on p as it finishes */
26586    transmit_notify_with_mwi(p, newmsgs, oldmsgs, vmexten);
26587    sip_pvt_unlock(p);
26588    dialog_unref(p, "unref dialog ptr p just before it goes out of scope at the end of sip_send_mwi_to_peer.");
26589 
26590    update_peer_lastmsgssent(peer, ((newmsgs > 0x7fff ? 0x7fff0000 : (newmsgs << 16)) | (oldmsgs > 0xffff ? 0xffff : oldmsgs)), 0);
26591 
26592    return 0;
26593 }
26594 
26595 /*! \brief helper function for the monitoring thread -- seems to be called with the assumption that the dialog is locked */
26596 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t)
26597 {
26598    /* If we have no RTP or no active owner, no need to check timers */
26599    if (!dialog->rtp || !dialog->owner)
26600       return;
26601    /* If the call is not in UP state or redirected outside Asterisk, no need to check timers */
26602 
26603    if (dialog->owner->_state != AST_STATE_UP || !ast_sockaddr_isnull(&dialog->redirip))
26604       return;
26605 
26606    /* If the call is involved in a T38 fax session do not check RTP timeout */
26607    if (dialog->t38.state == T38_ENABLED)
26608       return;
26609 
26610    /* If we have no timers set, return now */
26611    if (!ast_rtp_instance_get_keepalive(dialog->rtp) && !ast_rtp_instance_get_timeout(dialog->rtp) && !ast_rtp_instance_get_hold_timeout(dialog->rtp)) {
26612       return;
26613    }
26614 
26615    /* Check AUDIO RTP keepalives */
26616    if (dialog->lastrtptx && ast_rtp_instance_get_keepalive(dialog->rtp) &&
26617           (t > dialog->lastrtptx + ast_rtp_instance_get_keepalive(dialog->rtp))) {
26618       /* Need to send an empty RTP packet */
26619       dialog->lastrtptx = time(NULL);
26620       ast_rtp_instance_sendcng(dialog->rtp, 0);
26621    }
26622 
26623    /*! \todo Check video RTP keepalives
26624 
26625       Do we need to move the lastrtptx to the RTP structure to have one for audio and one
26626       for video? It really does belong to the RTP structure.
26627    */
26628 
26629    /* Check AUDIO RTP timers */
26630    if (dialog->lastrtprx && (ast_rtp_instance_get_timeout(dialog->rtp) || ast_rtp_instance_get_hold_timeout(dialog->rtp)) && (t > dialog->lastrtprx + ast_rtp_instance_get_timeout(dialog->rtp))) {
26631       if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD) || (ast_rtp_instance_get_hold_timeout(dialog->rtp) && (t > dialog->lastrtprx + ast_rtp_instance_get_hold_timeout(dialog->rtp)))) {
26632          /* Needs a hangup */
26633          if (ast_rtp_instance_get_timeout(dialog->rtp)) {
26634             if (!dialog->owner || ast_channel_trylock(dialog->owner)) {
26635                /*
26636                 * Don't block, just try again later.
26637                 * If there was no owner, the call is dead already.
26638                 */
26639                return;
26640             }
26641             ast_log(LOG_NOTICE, "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
26642                dialog->owner->name, (long) (t - dialog->lastrtprx));
26643             /* Issue a softhangup */
26644             ast_softhangup_nolock(dialog->owner, AST_SOFTHANGUP_DEV);
26645             ast_channel_unlock(dialog->owner);
26646             /* forget the timeouts for this call, since a hangup
26647                has already been requested and we don't want to
26648                repeatedly request hangups
26649             */
26650             ast_rtp_instance_set_timeout(dialog->rtp, 0);
26651             ast_rtp_instance_set_hold_timeout(dialog->rtp, 0);
26652             if (dialog->vrtp) {
26653                ast_rtp_instance_set_timeout(dialog->vrtp, 0);
26654                ast_rtp_instance_set_hold_timeout(dialog->vrtp, 0);
26655             }
26656          }
26657       }
26658    }
26659 }
26660 
26661 /*! \brief The SIP monitoring thread
26662 \note This thread monitors all the SIP sessions and peers that needs notification of mwi
26663    (and thus do not have a separate thread) indefinitely
26664 */
26665 static void *do_monitor(void *data)
26666 {
26667    int res;
26668    time_t t;
26669    int reloading;
26670 
26671    /* Add an I/O event to our SIP UDP socket */
26672    if (sipsock > -1)
26673       sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
26674 
26675    /* From here on out, we die whenever asked */
26676    for(;;) {
26677       /* Check for a reload request */
26678       ast_mutex_lock(&sip_reload_lock);
26679       reloading = sip_reloading;
26680       sip_reloading = FALSE;
26681       ast_mutex_unlock(&sip_reload_lock);
26682       if (reloading) {
26683          ast_verb(1, "Reloading SIP\n");
26684          sip_do_reload(sip_reloadreason);
26685 
26686          /* Change the I/O fd of our UDP socket */
26687          if (sipsock > -1) {
26688             if (sipsock_read_id)
26689                sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
26690             else
26691                sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
26692          } else if (sipsock_read_id) {
26693             ast_io_remove(io, sipsock_read_id);
26694             sipsock_read_id = NULL;
26695          }
26696       }
26697 
26698       /* Check for dialogs needing to be killed */
26699       t = time(NULL);
26700       /* don't scan the dialogs list if it hasn't been a reasonable period
26701          of time since the last time we did it (when MWI is being sent, we can
26702          get back to this point every millisecond or less)
26703       */
26704       /*
26705        * We cannot hold the dialogs container lock when we destroy a
26706        * dialog because of potential deadlocks.  Instead we link the
26707        * doomed dialog into dialogs_to_destroy and then iterate over
26708        * that container destroying the dialogs.
26709        */
26710       ao2_t_callback(dialogs, OBJ_NODATA | OBJ_MULTIPLE, dialog_needdestroy, &t,
26711          "callback to monitor dialog status");
26712       if (ao2_container_count(dialogs_to_destroy)) {
26713          /* Now destroy the found dialogs that need to be destroyed. */
26714          ao2_t_callback(dialogs_to_destroy, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE,
26715             dialog_unlink_callback, NULL, "callback to dialog_unlink_all");
26716       }
26717 
26718       /* XXX TODO The scheduler usage in this module does not have sufficient
26719        * synchronization being done between running the scheduler and places
26720        * scheduling tasks.  As it is written, any scheduled item may not run
26721        * any sooner than about  1 second, regardless of whether a sooner time
26722        * was asked for. */
26723 
26724       pthread_testcancel();
26725       /* Wait for sched or io */
26726       res = ast_sched_wait(sched);
26727       if ((res < 0) || (res > 1000))
26728          res = 1000;
26729       res = ast_io_wait(io, res);
26730       if (res > 20)
26731          ast_debug(1, "chan_sip: ast_io_wait ran %d all at once\n", res);
26732       ast_mutex_lock(&monlock);
26733       res = ast_sched_runq(sched);
26734       if (res >= 20)
26735          ast_debug(1, "chan_sip: ast_sched_runq ran %d all at once\n", res);
26736       if (global_store_sip_cause && res >= 100)
26737          ast_log(LOG_WARNING, "scheduler delays detected, setting 'storesipcause' to 'no' in %s will improve performance\n", config);
26738       ast_mutex_unlock(&monlock);
26739    }
26740 
26741    /* Never reached */
26742    return NULL;
26743 }
26744 
26745 /*! \brief Start the channel monitor thread */
26746 static int restart_monitor(void)
26747 {
26748    /* If we're supposed to be stopped -- stay stopped */
26749    if (monitor_thread == AST_PTHREADT_STOP)
26750       return 0;
26751    ast_mutex_lock(&monlock);
26752    if (monitor_thread == pthread_self()) {
26753       ast_mutex_unlock(&monlock);
26754       ast_log(LOG_WARNING, "Cannot kill myself\n");
26755       return -1;
26756    }
26757    if (monitor_thread != AST_PTHREADT_NULL) {
26758       /* Wake up the thread */
26759       pthread_kill(monitor_thread, SIGURG);
26760    } else {
26761       /* Start a new monitor */
26762       if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
26763          ast_mutex_unlock(&monlock);
26764          ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
26765          return -1;
26766       }
26767    }
26768    ast_mutex_unlock(&monlock);
26769    return 0;
26770 }
26771 
26772 
26773 /*! \brief Session-Timers: Restart session timer */
26774 static void restart_session_timer(struct sip_pvt *p)
26775 {
26776    if (p->stimer->st_active == TRUE) {
26777       ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
26778       AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
26779             dialog_unref(p, "Removing session timer ref"));
26780       start_session_timer(p);
26781    }
26782 }
26783 
26784 
26785 /*! \brief Session-Timers: Stop session timer */
26786 static void stop_session_timer(struct sip_pvt *p)
26787 {
26788    if (p->stimer->st_active == TRUE) {
26789       p->stimer->st_active = FALSE;
26790       ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
26791       AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
26792             dialog_unref(p, "removing session timer ref"));
26793    }
26794 }
26795 
26796 
26797 /*! \brief Session-Timers: Start session timer */
26798 static void start_session_timer(struct sip_pvt *p)
26799 {
26800    unsigned int timeout_ms;
26801 
26802    if (p->stimer->st_schedid > -1) {
26803       /* in the event a timer is already going, stop it */
26804       ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
26805       AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
26806          dialog_unref(p, "unref stimer->st_schedid from dialog"));
26807    }
26808 
26809    /*
26810     * RFC 4028 Section 10
26811     * If the side not performing refreshes does not receive a
26812     * session refresh request before the session expiration, it SHOULD send
26813     * a BYE to terminate the session, slightly before the session
26814     * expiration.  The minimum of 32 seconds and one third of the session
26815     * interval is RECOMMENDED.
26816     */
26817 
26818    timeout_ms = (1000 * p->stimer->st_interval);
26819    if (p->stimer->st_ref == SESSION_TIMER_REFRESHER_US) {
26820       timeout_ms /= 2;
26821    } else {
26822       timeout_ms -= MIN(timeout_ms / 3, 32000);
26823    }
26824 
26825    p->stimer->st_schedid = ast_sched_add(sched, timeout_ms, proc_session_timer,
26826          dialog_ref(p, "adding session timer ref"));
26827 
26828    if (p->stimer->st_schedid < 0) {
26829       dialog_unref(p, "removing session timer ref");
26830       ast_log(LOG_ERROR, "ast_sched_add failed - %s\n", p->callid);
26831    } else {
26832       p->stimer->st_active = TRUE;
26833       ast_debug(2, "Session timer started: %d - %s %ums\n", p->stimer->st_schedid, p->callid, timeout_ms);
26834    }
26835 }
26836 
26837 
26838 /*! \brief Session-Timers: Process session refresh timeout event */
26839 static int proc_session_timer(const void *vp)
26840 {
26841    struct sip_pvt *p = (struct sip_pvt *) vp;
26842    int res = 0;
26843 
26844    if (!p->stimer) {
26845       ast_log(LOG_WARNING, "Null stimer in proc_session_timer - %s\n", p->callid);
26846       goto return_unref;
26847    }
26848 
26849    ast_debug(2, "Session timer expired: %d - %s\n", p->stimer->st_schedid, p->callid);
26850 
26851    if (!p->owner) {
26852       goto return_unref;
26853    }
26854 
26855    if ((p->stimer->st_active != TRUE) || (p->owner->_state != AST_STATE_UP)) {
26856       goto return_unref;
26857    }
26858 
26859    if (p->stimer->st_ref == SESSION_TIMER_REFRESHER_US) {
26860       res = 1;
26861       if (T38_ENABLED == p->t38.state) {
26862          transmit_reinvite_with_sdp(p, TRUE, TRUE);
26863       } else {
26864          transmit_reinvite_with_sdp(p, FALSE, TRUE);
26865       }
26866    } else {
26867       if (p->stimer->quit_flag) {
26868          goto return_unref;
26869       }
26870       ast_log(LOG_WARNING, "Session-Timer expired - %s\n", p->callid);
26871       sip_pvt_lock(p);
26872       while (p->owner && ast_channel_trylock(p->owner)) {
26873          sip_pvt_unlock(p);
26874          usleep(1);
26875          if (p->stimer && p->stimer->quit_flag) {
26876             goto return_unref;
26877          }
26878          sip_pvt_lock(p);
26879       }
26880 
26881       ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
26882       ast_channel_unlock(p->owner);
26883       sip_pvt_unlock(p);
26884    }
26885 
26886 return_unref:
26887    if (!res) {
26888       /* An error occurred.  Stop session timer processing */
26889       if (p->stimer) {
26890          ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
26891          /* Don't pass go, don't collect $200.. we are the scheduled
26892           * callback. We can rip ourself out here. */
26893          p->stimer->st_schedid = -1;
26894          /* Calling stop_session_timer is nice for consistent debug
26895           * logs. */
26896          stop_session_timer(p);
26897       }
26898 
26899       /* If we are not asking to be rescheduled, then we need to release our
26900        * reference to the dialog. */
26901       dialog_unref(p, "removing session timer ref");
26902    }
26903 
26904    return res;
26905 }
26906 
26907 
26908 /*! \brief Session-Timers: Function for parsing Min-SE header */
26909 int parse_minse (const char *p_hdrval, int *const p_interval)
26910 {
26911    if (ast_strlen_zero(p_hdrval)) {
26912       ast_log(LOG_WARNING, "Null Min-SE header\n");
26913       return -1;
26914    }
26915 
26916    *p_interval = 0;
26917    p_hdrval = ast_skip_blanks(p_hdrval);
26918    if (!sscanf(p_hdrval, "%30d", p_interval)) {
26919       ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
26920       return -1;
26921    }
26922 
26923    ast_debug(2, "Received Min-SE: %d\n", *p_interval);
26924    return 0;
26925 }
26926 
26927 
26928 /*! \brief Session-Timers: Function for parsing Session-Expires header */
26929 int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher_param *const p_ref)
26930 {
26931    char *p_token;
26932    int  ref_idx;
26933    char *p_se_hdr;
26934 
26935    if (ast_strlen_zero(p_hdrval)) {
26936       ast_log(LOG_WARNING, "Null Session-Expires header\n");
26937       return -1;
26938    }
26939 
26940    *p_ref = SESSION_TIMER_REFRESHER_PARAM_UNKNOWN;
26941    *p_interval = 0;
26942 
26943    p_se_hdr = ast_strdupa(p_hdrval);
26944    p_se_hdr = ast_skip_blanks(p_se_hdr);
26945 
26946    while ((p_token = strsep(&p_se_hdr, ";"))) {
26947       p_token = ast_skip_blanks(p_token);
26948       if (!sscanf(p_token, "%30d", p_interval)) {
26949          ast_log(LOG_WARNING, "Parsing of Session-Expires failed\n");
26950          return -1;
26951       }
26952 
26953       ast_debug(2, "Session-Expires: %d\n", *p_interval);
26954 
26955       if (!p_se_hdr)
26956          continue;
26957 
26958       p_se_hdr = ast_skip_blanks(p_se_hdr);
26959       ref_idx = strlen("refresher=");
26960       if (!strncasecmp(p_se_hdr, "refresher=", ref_idx)) {
26961          p_se_hdr += ref_idx;
26962          p_se_hdr = ast_skip_blanks(p_se_hdr);
26963 
26964          if (!strncasecmp(p_se_hdr, "uac", strlen("uac"))) {
26965             *p_ref = SESSION_TIMER_REFRESHER_PARAM_UAC;
26966             ast_debug(2, "Refresher: UAC\n");
26967          } else if (!strncasecmp(p_se_hdr, "uas", strlen("uas"))) {
26968             *p_ref = SESSION_TIMER_REFRESHER_PARAM_UAS;
26969             ast_debug(2, "Refresher: UAS\n");
26970          } else {
26971             ast_log(LOG_WARNING, "Invalid refresher value %s\n", p_se_hdr);
26972             return -1;
26973          }
26974          break;
26975       }
26976    }
26977    return 0;
26978 }
26979 
26980 
26981 /*! \brief Handle 422 response to INVITE with session-timer requested
26982 
26983    Session-Timers:   An INVITE originated by Asterisk that asks for session-timers support
26984    from the UAS can result into a 422 response. This is how a UAS or an intermediary proxy
26985    server tells Asterisk that the session refresh interval offered by Asterisk is too low
26986    for them.  The proc_422_rsp() function handles a 422 response.  It extracts the Min-SE
26987    header that comes back in 422 and sends a new INVITE accordingly. */
26988 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp)
26989 {
26990    int rtn;
26991    const char *p_hdrval;
26992    int minse;
26993 
26994    p_hdrval = get_header(rsp, "Min-SE");
26995    if (ast_strlen_zero(p_hdrval)) {
26996       ast_log(LOG_WARNING, "422 response without a Min-SE header %s\n", p_hdrval);
26997       return;
26998    }
26999    rtn = parse_minse(p_hdrval, &minse);
27000    if (rtn != 0) {
27001       ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
27002       return;
27003    }
27004    p->stimer->st_cached_min_se = minse;
27005    if (p->stimer->st_interval < minse) {
27006       p->stimer->st_interval = minse;
27007    }
27008    transmit_invite(p, SIP_INVITE, 1, 2, NULL);
27009 }
27010 
27011 
27012 /*! \brief Get Max or Min SE (session timer expiry)
27013  * \param p pointer to the SIP dialog
27014  * \param max if true, get max se, otherwise min se
27015 */
27016 int st_get_se(struct sip_pvt *p, int max)
27017 {
27018    if (max == TRUE) {
27019       if (p->stimer->st_cached_max_se) {
27020          return  p->stimer->st_cached_max_se;
27021       }
27022       if (p->relatedpeer) {
27023          p->stimer->st_cached_max_se = p->relatedpeer->stimer.st_max_se;
27024          return (p->stimer->st_cached_max_se);
27025       }
27026       p->stimer->st_cached_max_se = global_max_se;
27027       return (p->stimer->st_cached_max_se);
27028    } 
27029    /* Find Min SE timer */
27030    if (p->stimer->st_cached_min_se) {
27031       return p->stimer->st_cached_min_se;
27032    } 
27033    if (p->relatedpeer) {
27034       p->stimer->st_cached_min_se = p->relatedpeer->stimer.st_min_se;
27035       return (p->stimer->st_cached_min_se);
27036    }
27037    p->stimer->st_cached_min_se = global_min_se;
27038    return (p->stimer->st_cached_min_se);
27039 }
27040 
27041 
27042 /*! \brief Get the entity (UAC or UAS) that's acting as the session-timer refresher
27043  * \note This is only called when processing an INVITE, so in that case Asterisk is
27044  *       always currently the UAS. If this is ever used to process responses, the
27045  *       function will have to be changed.
27046  * \param p pointer to the SIP dialog
27047 */
27048 enum st_refresher st_get_refresher(struct sip_pvt *p)
27049 {
27050    if (p->stimer->st_cached_ref != SESSION_TIMER_REFRESHER_AUTO) {
27051       return p->stimer->st_cached_ref;
27052    }
27053 
27054    if (p->relatedpeer) {
27055       p->stimer->st_cached_ref = (p->relatedpeer->stimer.st_ref == SESSION_TIMER_REFRESHER_PARAM_UAC) ? SESSION_TIMER_REFRESHER_THEM : SESSION_TIMER_REFRESHER_US;
27056       return p->stimer->st_cached_ref;
27057    }
27058    
27059    p->stimer->st_cached_ref = (global_st_refresher == SESSION_TIMER_REFRESHER_PARAM_UAC) ? SESSION_TIMER_REFRESHER_THEM : SESSION_TIMER_REFRESHER_US;
27060    return p->stimer->st_cached_ref;
27061 }
27062 
27063 
27064 /*!
27065  * \brief Get the session-timer mode 
27066  * \param p pointer to the SIP dialog 
27067  * \param no_cached, set this to true in order to force a peername lookup on
27068  *        the session timer mode.
27069 */
27070 enum st_mode st_get_mode(struct sip_pvt *p, int no_cached)
27071 {
27072    if (!p->stimer) {
27073       sip_st_alloc(p);
27074       if (!p->stimer) {
27075          return SESSION_TIMER_MODE_INVALID;
27076       }
27077    }
27078 
27079    if (!no_cached && p->stimer->st_cached_mode != SESSION_TIMER_MODE_INVALID)
27080       return p->stimer->st_cached_mode;
27081 
27082    if (p->relatedpeer) {
27083       p->stimer->st_cached_mode = p->relatedpeer->stimer.st_mode_oper;
27084       return p->stimer->st_cached_mode;
27085    }
27086 
27087    p->stimer->st_cached_mode = global_st_mode;
27088    return global_st_mode;
27089 }
27090 
27091 
27092 /*! \brief React to lack of answer to Qualify poke */
27093 static int sip_poke_noanswer(const void *data)
27094 {
27095    struct sip_peer *peer = (struct sip_peer *)data;
27096 
27097    peer->pokeexpire = -1;
27098 
27099    if (peer->lastms > -1) {
27100       ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE!  Last qualify: %d\n", peer->name, peer->lastms);
27101       if (sip_cfg.peer_rtupdate) {
27102          ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", "-1", SENTINEL);
27103       }
27104       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
27105       if (sip_cfg.regextenonqualify) {
27106          register_peer_exten(peer, FALSE);
27107       }
27108    }
27109 
27110    if (peer->call) {
27111       dialog_unlink_all(peer->call);
27112       peer->call = dialog_unref(peer->call, "unref dialog peer->call");
27113       /* peer->call = sip_destroy(peer->call);*/
27114    }
27115 
27116    /* Don't send a devstate change if nothing changed. */
27117    if (peer->lastms > -1) {
27118       peer->lastms = -1;
27119       ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, "SIP/%s", peer->name);
27120    }
27121 
27122    /* Try again quickly */
27123    AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
27124          DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer,
27125          unref_peer(_data, "removing poke peer ref"),
27126          unref_peer(peer, "removing poke peer ref"),
27127          ref_peer(peer, "adding poke peer ref"));
27128 
27129    /* Release the ref held by the running scheduler entry */
27130    unref_peer(peer, "release peer poke noanswer ref");
27131 
27132    return 0;
27133 }
27134 
27135 /*! \brief Check availability of peer, also keep NAT open
27136 \note This is done with 60 seconds between each ping,
27137    unless forced by cli or manager. If peer is unreachable,
27138    we check every 10th second by default.
27139 \note Do *not* hold a pvt lock while calling this function.
27140    This function calls sip_alloc, which can cause a deadlock
27141    if another sip_pvt is held.
27142 */
27143 static int sip_poke_peer(struct sip_peer *peer, int force)
27144 {
27145    struct sip_pvt *p;
27146    int xmitres = 0;
27147    
27148    if ((!peer->maxms && !force) || ast_sockaddr_isnull(&peer->addr)) {
27149       /* IF we have no IP, or this isn't to be monitored, return
27150         immediately after clearing things out */
27151       AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
27152             unref_peer(peer, "removing poke peer ref"));
27153       
27154       peer->lastms = 0;
27155       if (peer->call) {
27156          peer->call = dialog_unref(peer->call, "unref dialog peer->call");
27157       }
27158       return 0;
27159    }
27160    if (peer->call) {
27161       if (sipdebug) {
27162          ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
27163       }
27164       dialog_unlink_all(peer->call);
27165       peer->call = dialog_unref(peer->call, "unref dialog peer->call");
27166       /* peer->call = sip_destroy(peer->call); */
27167    }
27168    if (!(p = sip_alloc(NULL, NULL, 0, SIP_OPTIONS, NULL))) {
27169       return -1;
27170    }
27171    peer->call = dialog_ref(p, "copy sip alloc from p to peer->call");
27172 
27173    p->sa = peer->addr;
27174    p->recv = peer->addr;
27175    copy_socket_data(&p->socket, &peer->socket);
27176    ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
27177    ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
27178    ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
27179 
27180    /* Get the outbound proxy information */
27181    ref_proxy(p, obproxy_get(p, peer));
27182 
27183    /* Send OPTIONs to peer's fullcontact */
27184    if (!ast_strlen_zero(peer->fullcontact)) {
27185       ast_string_field_set(p, fullcontact, peer->fullcontact);
27186    }
27187 
27188    if (!ast_strlen_zero(peer->fromuser)) {
27189       ast_string_field_set(p, fromuser, peer->fromuser);
27190    }
27191 
27192    if (!ast_strlen_zero(peer->tohost)) {
27193       ast_string_field_set(p, tohost, peer->tohost);
27194    } else {
27195       ast_string_field_set(p, tohost, ast_sockaddr_stringify_host_remote(&peer->addr));
27196    }
27197 
27198    /* Recalculate our side, and recalculate Call ID */
27199    ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
27200    build_via(p);
27201 
27202    /* Change the dialog callid. */
27203    change_callid_pvt(p, NULL);
27204 
27205    AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
27206          unref_peer(peer, "removing poke peer ref"));
27207    
27208    if (p->relatedpeer)
27209       p->relatedpeer = unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
27210    p->relatedpeer = ref_peer(peer, "setting the relatedpeer field in the dialog");
27211    ast_set_flag(&p->flags[0], SIP_OUTGOING);
27212 #ifdef VOCAL_DATA_HACK
27213    ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
27214    xmitres = transmit_invite(p, SIP_INVITE, 0, 2, NULL); /* sinks the p refcount */
27215 #else
27216    xmitres = transmit_invite(p, SIP_OPTIONS, 0, 2, NULL); /* sinks the p refcount */
27217 #endif
27218    peer->ps = ast_tvnow();
27219    if (xmitres == XMIT_ERROR) {
27220       /* Immediately unreachable, network problems */
27221       sip_poke_noanswer(ref_peer(peer, "add ref for peerexpire (fake, for sip_poke_noanswer to remove)"));
27222    } else if (!force) {
27223       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, peer->maxms * 2, sip_poke_noanswer, peer,
27224             unref_peer(_data, "removing poke peer ref"),
27225             unref_peer(peer, "removing poke peer ref"),
27226             ref_peer(peer, "adding poke peer ref"));
27227    }
27228    dialog_unref(p, "unref dialog at end of sip_poke_peer, obtained from sip_alloc, just before it goes out of scope");
27229    return 0;
27230 }
27231 
27232 /*! \brief Part of PBX channel interface
27233 \note
27234 \par  Return values:---
27235 
27236    If we have qualify on and the device is not reachable, regardless of registration
27237    state we return AST_DEVICE_UNAVAILABLE
27238 
27239    For peers with call limit:
27240       - not registered        AST_DEVICE_UNAVAILABLE
27241       - registered, no call         AST_DEVICE_NOT_INUSE
27242       - registered, active calls    AST_DEVICE_INUSE
27243       - registered, call limit reached AST_DEVICE_BUSY
27244       - registered, onhold       AST_DEVICE_ONHOLD
27245       - registered, ringing         AST_DEVICE_RINGING
27246 
27247    For peers without call limit:
27248       - not registered        AST_DEVICE_UNAVAILABLE
27249       - registered            AST_DEVICE_NOT_INUSE
27250       - fixed IP (!dynamic)         AST_DEVICE_NOT_INUSE
27251    
27252    Peers that does not have a known call and can't be reached by OPTIONS
27253       - unreachable           AST_DEVICE_UNAVAILABLE
27254 
27255    If we return AST_DEVICE_UNKNOWN, the device state engine will try to find
27256    out a state by walking the channel list.
27257 
27258    The queue system (\ref app_queue.c) treats a member as "active"
27259    if devicestate is != AST_DEVICE_UNAVAILBALE && != AST_DEVICE_INVALID
27260 
27261    When placing a call to the queue member, queue system sets a member to busy if
27262    != AST_DEVICE_NOT_INUSE and != AST_DEVICE_UNKNOWN
27263 
27264 */
27265 static int sip_devicestate(void *data)
27266 {
27267    char *host;
27268    char *tmp;
27269    struct sip_peer *p;
27270 
27271    int res = AST_DEVICE_INVALID;
27272 
27273    /* make sure data is not null. Maybe unnecessary, but better be safe */
27274    host = ast_strdupa(data ? data : "");
27275    if ((tmp = strchr(host, '@')))
27276       host = tmp + 1;
27277 
27278    ast_debug(3, "Checking device state for peer %s\n", host);
27279 
27280    /* If find_peer asks for a realtime peer, then this breaks rtautoclear.  This
27281     * is because when a peer tries to autoexpire, the last thing it does is to
27282     * queue up an event telling the system that the devicestate has changed
27283     * (presumably to unavailable).  If we ask for a realtime peer here, this would
27284     * load it BACK into memory, thus defeating the point of trying to clear dead
27285     * hosts out of memory.
27286     */
27287    if ((p = find_peer(host, NULL, FALSE, FINDALLDEVICES, TRUE, 0))) {
27288       if (!(ast_sockaddr_isnull(&p->addr) && ast_sockaddr_isnull(&p->defaddr))) {
27289          /* we have an address for the peer */
27290       
27291          /* Check status in this order
27292             - Hold
27293             - Ringing
27294             - Busy (enforced only by call limit)
27295             - Inuse (we have a call)
27296             - Unreachable (qualify)
27297             If we don't find any of these state, report AST_DEVICE_NOT_INUSE
27298             for registered devices */
27299 
27300          if (p->onHold)
27301             /* First check for hold or ring states */
27302             res = AST_DEVICE_ONHOLD;
27303          else if (p->inRinging) {
27304             if (p->inRinging == p->inUse)
27305                res = AST_DEVICE_RINGING;
27306             else
27307                res = AST_DEVICE_RINGINUSE;
27308          } else if (p->call_limit && (p->inUse == p->call_limit))
27309             /* check call limit */
27310             res = AST_DEVICE_BUSY;
27311          else if (p->call_limit && p->busy_level && p->inUse >= p->busy_level)
27312             /* We're forcing busy before we've reached the call limit */
27313             res = AST_DEVICE_BUSY;
27314          else if (p->call_limit && p->inUse)
27315             /* Not busy, but we do have a call */
27316             res = AST_DEVICE_INUSE;
27317          else if (p->maxms && ((p->lastms > p->maxms) || (p->lastms < 0)))
27318             /* We don't have a call. Are we reachable at all? Requires qualify= */
27319             res = AST_DEVICE_UNAVAILABLE;
27320          else  /* Default reply if we're registered and have no other data */
27321             res = AST_DEVICE_NOT_INUSE;
27322       } else {
27323          /* there is no address, it's unavailable */
27324          res = AST_DEVICE_UNAVAILABLE;
27325       }
27326       unref_peer(p, "unref_peer, from sip_devicestate, release ref from find_peer");
27327    }
27328 
27329    return res;
27330 }
27331 
27332 /*! \brief PBX interface function -build SIP pvt structure
27333  * SIP calls initiated by the PBX arrive here.
27334  *
27335  * \verbatim
27336  * SIP Dial string syntax:
27337  *    SIP/devicename
27338  * or SIP/username@domain (SIP uri)
27339  * or SIP/username[:password[:md5secret[:authname[:transport]]]]@host[:port]
27340  * or SIP/devicename/extension
27341  * or SIP/devicename/extension/IPorHost
27342  * or SIP/username@domain//IPorHost
27343  * and there is an optional [!dnid] argument you can append to alter the
27344  * To: header.
27345  * \endverbatim
27346  */
27347 static struct ast_channel *sip_request_call(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause)
27348 {
27349    struct sip_pvt *p;
27350    struct ast_channel *tmpc = NULL;
27351    char *ext = NULL, *host;
27352    char tmp[256];
27353    char *dest = data;
27354    char *dnid;
27355    char *secret = NULL;
27356    char *md5secret = NULL;
27357    char *authname = NULL;
27358    char *trans = NULL;
27359    char dialstring[256];
27360    char *remote_address;
27361    enum sip_transport transport = 0;
27362    format_t oldformat = format;
27363    AST_DECLARE_APP_ARGS(args,
27364       AST_APP_ARG(peerorhost);
27365       AST_APP_ARG(exten);
27366       AST_APP_ARG(remote_address);
27367    );
27368 
27369    /* mask request with some set of allowed formats.
27370     * XXX this needs to be fixed.
27371     * The original code uses AST_FORMAT_AUDIO_MASK, but it is
27372     * unclear what to use here. We have global_capabilities, which is
27373     * configured from sip.conf, and sip_tech.capabilities, which is
27374     * hardwired to all audio formats.
27375     */
27376    format &= AST_FORMAT_AUDIO_MASK;
27377    if (!format) {
27378       ast_log(LOG_NOTICE, "Asked to get a channel of unsupported format %s while capability is %s\n", ast_getformatname(oldformat), ast_getformatname(sip_cfg.capability));
27379       *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;   /* Can't find codec to connect to host */
27380       return NULL;
27381    }
27382    ast_debug(1, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), oldformat));
27383 
27384    if (ast_strlen_zero(dest)) {
27385       ast_log(LOG_ERROR, "Unable to create channel with empty destination.\n");
27386       *cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
27387       return NULL;
27388    }
27389 
27390    if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE, NULL))) {
27391       ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", dest);
27392       *cause = AST_CAUSE_SWITCH_CONGESTION;
27393       return NULL;
27394    }
27395 
27396    p->outgoing_call = TRUE;
27397 
27398    snprintf(dialstring, sizeof(dialstring), "%s/%s", type, dest);
27399    ast_string_field_set(p, dialstring, dialstring);
27400 
27401    if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
27402       dialog_unlink_all(p);
27403       dialog_unref(p, "unref dialog p from mem fail");
27404       /* sip_destroy(p); */
27405       ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
27406       *cause = AST_CAUSE_SWITCH_CONGESTION;
27407       return NULL;
27408    }
27409 
27410    /* Save the destination, the SIP dial string */
27411    ast_copy_string(tmp, dest, sizeof(tmp));
27412 
27413    /* Find DNID and take it away */
27414    dnid = strchr(tmp, '!');
27415    if (dnid != NULL) {
27416       *dnid++ = '\0';
27417       ast_string_field_set(p, todnid, dnid);
27418    }
27419 
27420    /* Divvy up the items separated by slashes */
27421    AST_NONSTANDARD_APP_ARGS(args, tmp, '/');
27422 
27423    /* Find at sign - @ */
27424    host = strchr(args.peerorhost, '@');
27425    if (host) {
27426       *host++ = '\0';
27427       ext = args.peerorhost;
27428       secret = strchr(ext, ':');
27429    }
27430    if (secret) {
27431       *secret++ = '\0';
27432       md5secret = strchr(secret, ':');
27433    }
27434    if (md5secret) {
27435       *md5secret++ = '\0';
27436       authname = strchr(md5secret, ':');
27437    }
27438    if (authname) {
27439       *authname++ = '\0';
27440       trans = strchr(authname, ':');
27441    }
27442    if (trans) {
27443       *trans++ = '\0';
27444       if (!strcasecmp(trans, "tcp"))
27445          transport = SIP_TRANSPORT_TCP;
27446       else if (!strcasecmp(trans, "tls"))
27447          transport = SIP_TRANSPORT_TLS;
27448       else {
27449          if (strcasecmp(trans, "udp"))
27450             ast_log(LOG_WARNING, "'%s' is not a valid transport option to Dial() for SIP calls, using udp by default.\n", trans);
27451          transport = SIP_TRANSPORT_UDP;
27452       }
27453    } else { /* use default */
27454       transport = SIP_TRANSPORT_UDP;
27455    }
27456 
27457    if (!host) {
27458       ext = args.exten;
27459       host = args.peerorhost;
27460       remote_address = args.remote_address;
27461    } else {
27462       remote_address = args.remote_address;
27463       if (!ast_strlen_zero(args.exten)) {
27464          ast_log(LOG_NOTICE, "Conflicting extension values given. Using '%s' and not '%s'\n", ext, args.exten);
27465       }
27466    }
27467 
27468    if (!ast_strlen_zero(remote_address)) {
27469       p->options->outboundproxy = proxy_from_config(remote_address, 0, NULL);
27470       if (!p->options->outboundproxy) {
27471          ast_log(LOG_WARNING, "Unable to parse outboundproxy %s. We will not use this remote IP address\n", remote_address);
27472       }
27473    }
27474 
27475    set_socket_transport(&p->socket, transport);
27476 
27477    /* We now have
27478       host = peer name, DNS host name or DNS domain (for SRV)
27479       ext = extension (user part of URI)
27480       dnid = destination of the call (applies to the To: header)
27481    */
27482    if (create_addr(p, host, NULL, 1)) {
27483       *cause = AST_CAUSE_UNREGISTERED;
27484       ast_debug(3, "Cant create SIP call - target device not registered\n");
27485       dialog_unlink_all(p);
27486       dialog_unref(p, "unref dialog p UNREGISTERED");
27487       /* sip_destroy(p); */
27488       return NULL;
27489    }
27490    if (ast_strlen_zero(p->peername) && ext)
27491       ast_string_field_set(p, peername, ext);
27492    /* Recalculate our side, and recalculate Call ID */
27493    ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
27494    build_via(p);
27495 
27496    /* Change the dialog callid. */
27497    change_callid_pvt(p, NULL);
27498 
27499    /* We have an extension to call, don't use the full contact here */
27500    /* This to enable dialing registered peers with extension dialling,
27501       like SIP/peername/extension   
27502       SIP/peername will still use the full contact
27503     */
27504    if (ext) {
27505       ast_string_field_set(p, username, ext);
27506       ast_string_field_set(p, fullcontact, NULL);
27507    }
27508    if (secret && !ast_strlen_zero(secret))
27509       ast_string_field_set(p, peersecret, secret);
27510 
27511    if (md5secret && !ast_strlen_zero(md5secret))
27512       ast_string_field_set(p, peermd5secret, md5secret);
27513 
27514    if (authname && !ast_strlen_zero(authname))
27515       ast_string_field_set(p, authname, authname);
27516 #if 0
27517    printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
27518 #endif
27519    p->prefcodec = oldformat;           /* Format for this call */
27520    p->jointcapability = oldformat & p->capability;
27521    sip_pvt_lock(p);
27522    tmpc = sip_new(p, AST_STATE_DOWN, host, requestor ? requestor->linkedid : NULL); /* Place the call */
27523    if (sip_cfg.callevents)
27524       manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
27525          "Channel: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
27526          p->owner ? p->owner->name : "", "SIP", p->callid, p->fullcontact, p->peername);
27527    sip_pvt_unlock(p);
27528    if (!tmpc) {
27529       dialog_unlink_all(p);
27530       /* sip_destroy(p); */
27531    } else {
27532       ast_channel_unlock(tmpc);
27533    }
27534    dialog_unref(p, "toss pvt ptr at end of sip_request_call");
27535    ast_update_use_count();
27536    restart_monitor();
27537    return tmpc;
27538 }
27539 
27540 /*! \brief Parse insecure= setting in sip.conf and set flags according to setting */
27541 static void set_insecure_flags (struct ast_flags *flags, const char *value, int lineno)
27542 {
27543    if (ast_strlen_zero(value))
27544       return;
27545 
27546    if (!ast_false(value)) {
27547       char buf[64];
27548       char *word, *next;
27549 
27550       ast_copy_string(buf, value, sizeof(buf));
27551       next = buf;
27552       while ((word = strsep(&next, ","))) {
27553          if (!strcasecmp(word, "port"))
27554             ast_set_flag(&flags[0], SIP_INSECURE_PORT);
27555          else if (!strcasecmp(word, "invite"))
27556             ast_set_flag(&flags[0], SIP_INSECURE_INVITE);
27557          else
27558             ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", value, lineno);
27559       }
27560    }
27561 }
27562 
27563 /*!
27564   \brief Handle T.38 configuration options common to users and peers
27565   \returns non-zero if any config options were handled, zero otherwise
27566 */
27567 static int handle_t38_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v,
27568                unsigned int *maxdatagram)
27569 {
27570    int res = 1;
27571 
27572    if (!strcasecmp(v->name, "t38pt_udptl")) {
27573       char *buf = ast_strdupa(v->value);
27574       char *word, *next = buf;
27575 
27576       ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT);
27577 
27578       while ((word = strsep(&next, ","))) {
27579          if (ast_true(word) || !strcasecmp(word, "fec")) {
27580             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
27581             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_FEC);
27582          } else if (!strcasecmp(word, "redundancy")) {
27583             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
27584             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY);
27585          } else if (!strcasecmp(word, "none")) {
27586             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
27587             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL);
27588          } else if (!strncasecmp(word, "maxdatagram=", 12)) {
27589             if (sscanf(&word[12], "%30u", maxdatagram) != 1) {
27590                ast_log(LOG_WARNING, "Invalid maxdatagram '%s' at line %d of %s\n", v->value, v->lineno, config);
27591                *maxdatagram = global_t38_maxdatagram;
27592             }
27593          }
27594       }
27595    } else if (!strcasecmp(v->name, "t38pt_usertpsource")) {
27596       ast_set_flag(&mask[1], SIP_PAGE2_UDPTL_DESTINATION);
27597       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_UDPTL_DESTINATION);
27598    } else {
27599       res = 0;
27600    }
27601 
27602    return res;
27603 }
27604 
27605 /*!
27606   \brief Handle flag-type options common to configuration of devices - peers
27607   \param flags array of two struct ast_flags
27608   \param mask array of two struct ast_flags
27609   \param v linked list of config variables to process
27610   \returns non-zero if any config options were handled, zero otherwise
27611 */
27612 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
27613 {
27614    int res = 1;
27615 
27616    if (!strcasecmp(v->name, "trustrpid")) {
27617       ast_set_flag(&mask[0], SIP_TRUSTRPID);
27618       ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
27619    } else if (!strcasecmp(v->name, "sendrpid")) {
27620       ast_set_flag(&mask[0], SIP_SENDRPID);
27621       if (!strcasecmp(v->value, "pai")) {
27622          ast_set_flag(&flags[0], SIP_SENDRPID_PAI);
27623       } else if (!strcasecmp(v->value, "rpid")) {
27624          ast_set_flag(&flags[0], SIP_SENDRPID_RPID);
27625       } else if (ast_true(v->value)) {
27626          ast_set_flag(&flags[0], SIP_SENDRPID_RPID);
27627       }
27628    } else if (!strcasecmp(v->name, "rpid_update")) {
27629       ast_set_flag(&mask[1], SIP_PAGE2_RPID_UPDATE);
27630       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RPID_UPDATE);
27631    } else if (!strcasecmp(v->name, "rpid_immediate")) {
27632       ast_set_flag(&mask[1], SIP_PAGE2_RPID_IMMEDIATE);
27633       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RPID_IMMEDIATE);
27634    } else if (!strcasecmp(v->name, "trust_id_outbound")) {
27635       ast_set_flag(&mask[1], SIP_PAGE2_TRUST_ID_OUTBOUND);
27636       ast_clear_flag(&flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND);
27637       if (!strcasecmp(v->value, "legacy")) {
27638          ast_set_flag(&flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND_LEGACY);
27639       } else if (ast_true(v->value)) {
27640          ast_set_flag(&flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND_YES);
27641       } else if (ast_false(v->value)) {
27642          ast_set_flag(&flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND_NO);
27643       } else {
27644          ast_log(LOG_WARNING, "Unknown trust_id_outbound mode '%s' on line %d, using legacy\n", v->value, v->lineno);
27645          ast_set_flag(&flags[1], SIP_PAGE2_TRUST_ID_OUTBOUND_LEGACY);
27646       }
27647    } else if (!strcasecmp(v->name, "g726nonstandard")) {
27648       ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
27649       ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
27650    } else if (!strcasecmp(v->name, "useclientcode")) {
27651       ast_set_flag(&mask[0], SIP_USECLIENTCODE);
27652       ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
27653    } else if (!strcasecmp(v->name, "dtmfmode")) {
27654       ast_set_flag(&mask[0], SIP_DTMF);
27655       ast_clear_flag(&flags[0], SIP_DTMF);
27656       if (!strcasecmp(v->value, "inband"))
27657          ast_set_flag(&flags[0], SIP_DTMF_INBAND);
27658       else if (!strcasecmp(v->value, "rfc2833"))
27659          ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
27660       else if (!strcasecmp(v->value, "info"))
27661          ast_set_flag(&flags[0], SIP_DTMF_INFO);
27662       else if (!strcasecmp(v->value, "shortinfo"))
27663          ast_set_flag(&flags[0], SIP_DTMF_SHORTINFO);
27664       else if (!strcasecmp(v->value, "auto"))
27665          ast_set_flag(&flags[0], SIP_DTMF_AUTO);
27666       else {
27667          ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
27668          ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
27669       }
27670    } else if (!strcasecmp(v->name, "nat")) {
27671       ast_set_flag(&mask[0], SIP_NAT_FORCE_RPORT);
27672       ast_set_flag(&mask[1], SIP_PAGE2_SYMMETRICRTP);
27673       if (!strcasecmp(v->value, "yes")) {
27674          ast_set_flag(&flags[0], SIP_NAT_FORCE_RPORT);
27675          ast_set_flag(&flags[1], SIP_PAGE2_SYMMETRICRTP);
27676       } else if (!strcasecmp(v->value, "force_rport")) {
27677          ast_set_flag(&flags[0], SIP_NAT_FORCE_RPORT);
27678       } else if (!strcasecmp(v->value, "comedia")) {
27679          ast_set_flag(&flags[1], SIP_PAGE2_SYMMETRICRTP);
27680       }
27681    } else if (!strcasecmp(v->name, "directmedia") || !strcasecmp(v->name, "canreinvite")) {
27682       ast_set_flag(&mask[0], SIP_REINVITE);
27683       ast_clear_flag(&flags[0], SIP_REINVITE);
27684       if (ast_true(v->value)) {
27685          ast_set_flag(&flags[0], SIP_DIRECT_MEDIA | SIP_DIRECT_MEDIA_NAT);
27686       } else if (!ast_false(v->value)) {
27687          char buf[64];
27688          char *word, *next = buf;
27689 
27690          ast_copy_string(buf, v->value, sizeof(buf));
27691          while ((word = strsep(&next, ","))) {
27692             if (!strcasecmp(word, "update")) {
27693                ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_DIRECT_MEDIA);
27694             } else if (!strcasecmp(word, "nonat")) {
27695                ast_set_flag(&flags[0], SIP_DIRECT_MEDIA);
27696                ast_clear_flag(&flags[0], SIP_DIRECT_MEDIA_NAT);
27697             } else if (!strcasecmp(word, "outgoing")) {
27698                ast_set_flag(&flags[0], SIP_DIRECT_MEDIA);
27699                ast_set_flag(&mask[2], SIP_PAGE3_DIRECT_MEDIA_OUTGOING);
27700                ast_set_flag(&flags[2], SIP_PAGE3_DIRECT_MEDIA_OUTGOING);
27701             } else {
27702                ast_log(LOG_WARNING, "Unknown directmedia mode '%s' on line %d\n", v->value, v->lineno);
27703             }
27704          }
27705       }
27706    } else if (!strcasecmp(v->name, "insecure")) {
27707       ast_set_flag(&mask[0], SIP_INSECURE);
27708       ast_clear_flag(&flags[0], SIP_INSECURE);
27709       set_insecure_flags(&flags[0], v->value, v->lineno);   
27710    } else if (!strcasecmp(v->name, "progressinband")) {
27711       ast_set_flag(&mask[0], SIP_PROG_INBAND);
27712       ast_clear_flag(&flags[0], SIP_PROG_INBAND);
27713       if (ast_true(v->value))
27714          ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
27715       else if (strcasecmp(v->value, "never"))
27716          ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
27717    } else if (!strcasecmp(v->name, "promiscredir")) {
27718       ast_set_flag(&mask[0], SIP_PROMISCREDIR);
27719       ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
27720    } else if (!strcasecmp(v->name, "videosupport")) {
27721       if (!strcasecmp(v->value, "always")) {
27722          ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
27723          ast_set_flag(&flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
27724       } else {
27725          ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
27726          ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
27727       }
27728    } else if (!strcasecmp(v->name, "textsupport")) {
27729       ast_set_flag(&mask[1], SIP_PAGE2_TEXTSUPPORT);
27730       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_TEXTSUPPORT);
27731       res = 1;
27732    } else if (!strcasecmp(v->name, "allowoverlap")) {
27733       ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
27734       ast_clear_flag(&flags[1], SIP_PAGE2_ALLOWOVERLAP);
27735       if (ast_true(v->value)) {
27736          ast_set_flag(&flags[1], SIP_PAGE2_ALLOWOVERLAP_YES);
27737       } else if (!strcasecmp(v->value, "dtmf")){
27738          ast_set_flag(&flags[1], SIP_PAGE2_ALLOWOVERLAP_DTMF);
27739       }
27740    } else if (!strcasecmp(v->name, "allowsubscribe")) {
27741       ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
27742       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
27743    } else if (!strcasecmp(v->name, "ignoresdpversion")) {
27744       ast_set_flag(&mask[1], SIP_PAGE2_IGNORESDPVERSION);
27745       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_IGNORESDPVERSION);
27746    } else if (!strcasecmp(v->name, "faxdetect")) {
27747       ast_set_flag(&mask[1], SIP_PAGE2_FAX_DETECT);
27748       if (ast_true(v->value)) {
27749          ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
27750       } else if (ast_false(v->value)) {
27751          ast_clear_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
27752       } else {
27753          char *buf = ast_strdupa(v->value);
27754          char *word, *next = buf;
27755 
27756          while ((word = strsep(&next, ","))) {
27757             if (!strcasecmp(word, "cng")) {
27758                ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_CNG);
27759             } else if (!strcasecmp(word, "t38")) {
27760                ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_T38);
27761             } else {
27762                ast_log(LOG_WARNING, "Unknown faxdetect mode '%s' on line %d.\n", word, v->lineno);
27763             }
27764          }
27765       }
27766    } else if (!strcasecmp(v->name, "rfc2833compensate")) {
27767       ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
27768       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
27769    } else if (!strcasecmp(v->name, "buggymwi")) {
27770       ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
27771       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
27772    } else
27773       res = 0;
27774 
27775    return res;
27776 }
27777 
27778 /*! \brief Add SIP domain to list of domains we are responsible for */
27779 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
27780 {
27781    struct domain *d;
27782 
27783    if (ast_strlen_zero(domain)) {
27784       ast_log(LOG_WARNING, "Zero length domain.\n");
27785       return 1;
27786    }
27787 
27788    if (!(d = ast_calloc(1, sizeof(*d))))
27789       return 0;
27790 
27791    ast_copy_string(d->domain, domain, sizeof(d->domain));
27792 
27793    if (!ast_strlen_zero(context))
27794       ast_copy_string(d->context, context, sizeof(d->context));
27795 
27796    d->mode = mode;
27797 
27798    AST_LIST_LOCK(&domain_list);
27799    AST_LIST_INSERT_TAIL(&domain_list, d, list);
27800    AST_LIST_UNLOCK(&domain_list);
27801 
27802    if (sipdebug)  
27803       ast_debug(1, "Added local SIP domain '%s'\n", domain);
27804 
27805    return 1;
27806 }
27807 
27808 /*! \brief  check_sip_domain: Check if domain part of uri is local to our server */
27809 static int check_sip_domain(const char *domain, char *context, size_t len)
27810 {
27811    struct domain *d;
27812    int result = 0;
27813 
27814    AST_LIST_LOCK(&domain_list);
27815    AST_LIST_TRAVERSE(&domain_list, d, list) {
27816       if (strcasecmp(d->domain, domain)) {
27817          continue;
27818       }
27819 
27820       if (len && !ast_strlen_zero(d->context))
27821          ast_copy_string(context, d->context, len);
27822       
27823       result = 1;
27824       break;
27825    }
27826    AST_LIST_UNLOCK(&domain_list);
27827 
27828    return result;
27829 }
27830 
27831 /*! \brief Clear our domain list (at reload) */
27832 static void clear_sip_domains(void)
27833 {
27834    struct domain *d;
27835 
27836    AST_LIST_LOCK(&domain_list);
27837    while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
27838       ast_free(d);
27839    AST_LIST_UNLOCK(&domain_list);
27840 }
27841 
27842 /*!
27843  * \internal
27844  * \brief Realm authentication container destructor.
27845  *
27846  * \param obj Container object to destroy.
27847  *
27848  * \return Nothing
27849  */
27850 static void destroy_realm_authentication(void *obj)
27851 {
27852    struct sip_auth_container *credentials = obj;
27853    struct sip_auth *auth;
27854 
27855    while ((auth = AST_LIST_REMOVE_HEAD(&credentials->list, node))) {
27856       ast_free(auth);
27857    }
27858 }
27859 
27860 /*!
27861  * \internal
27862  * \brief Add realm authentication to credentials.
27863  *
27864  * \param credentials Realm authentication container to create/add authentication credentials.
27865  * \param configuration Credential configuration value.
27866  * \param lineno Line number in config file.
27867  *
27868  * \return Nothing
27869  */
27870 static void add_realm_authentication(struct sip_auth_container **credentials, const char *configuration, int lineno)
27871 {
27872    char *authcopy;
27873    char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
27874    struct sip_auth *auth;
27875 
27876    if (ast_strlen_zero(configuration)) {
27877       /* Nothing to add */
27878       return;
27879    }
27880 
27881    ast_debug(1, "Auth config ::  %s\n", configuration);
27882 
27883    authcopy = ast_strdupa(configuration);
27884    username = authcopy;
27885 
27886    /* split user[:secret] and relm */
27887    realm = strrchr(username, '@');
27888    if (realm)
27889       *realm++ = '\0';
27890    if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
27891       ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
27892       return;
27893    }
27894 
27895    /* parse username at ':' for secret, or '#" for md5secret */
27896    if ((secret = strchr(username, ':'))) {
27897       *secret++ = '\0';
27898    } else if ((md5secret = strchr(username, '#'))) {
27899       *md5secret++ = '\0';
27900    }
27901 
27902    /* Create the continer if needed. */
27903    if (!*credentials) {
27904       *credentials = ao2_t_alloc(sizeof(**credentials), destroy_realm_authentication,
27905          "Create realm auth container.");
27906       if (!*credentials) {
27907          /* Failed to create the credentials container. */
27908          return;
27909       }
27910    }
27911 
27912    /* Create the authentication credential entry. */
27913    auth = ast_calloc(1, sizeof(*auth));
27914    if (!auth) {
27915       return;
27916    }
27917    ast_copy_string(auth->realm, realm, sizeof(auth->realm));
27918    ast_copy_string(auth->username, username, sizeof(auth->username));
27919    if (secret)
27920       ast_copy_string(auth->secret, secret, sizeof(auth->secret));
27921    if (md5secret)
27922       ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
27923 
27924    /* Add credential to container list. */
27925    AST_LIST_INSERT_TAIL(&(*credentials)->list, auth, node);
27926 
27927    ast_verb(3, "Added authentication for realm %s\n", realm);
27928 }
27929 
27930 /*!
27931  * \internal
27932  * \brief Find authentication for a specific realm.
27933  *
27934  * \param credentials Realm authentication container to search.
27935  * \param realm Authentication realm to find.
27936  *
27937  * \return Found authentication credential or NULL.
27938  */
27939 static struct sip_auth *find_realm_authentication(struct sip_auth_container *credentials, const char *realm)
27940 {
27941    struct sip_auth *auth;
27942 
27943    if (credentials) {
27944       AST_LIST_TRAVERSE(&credentials->list, auth, node) {
27945          if (!strcasecmp(auth->realm, realm)) {
27946             break;
27947          }
27948       }
27949    } else {
27950       auth = NULL;
27951    }
27952 
27953    return auth;
27954 }
27955 
27956 /*! \brief
27957  * implement the setvar config line
27958  */
27959 static struct ast_variable *add_var(const char *buf, struct ast_variable *list)
27960 {
27961    struct ast_variable *tmpvar = NULL;
27962    char *varname = ast_strdupa(buf), *varval = NULL;
27963    
27964    if ((varval = strchr(varname, '='))) {
27965       *varval++ = '\0';
27966       if ((tmpvar = ast_variable_new(varname, varval, ""))) {
27967          tmpvar->next = list;
27968          list = tmpvar;
27969       }
27970    }
27971    return list;
27972 }
27973 
27974 /*! \brief Set peer defaults before configuring specific configurations */
27975 static void set_peer_defaults(struct sip_peer *peer)
27976 {
27977    if (peer->expire == 0) {
27978       /* Don't reset expire or port time during reload
27979          if we have an active registration
27980       */
27981       peer->expire = -1;
27982       peer->pokeexpire = -1;
27983       set_socket_transport(&peer->socket, SIP_TRANSPORT_UDP);
27984    }
27985    peer->type = SIP_TYPE_PEER;
27986    ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
27987    ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
27988    ast_copy_flags(&peer->flags[2], &global_flags[2], SIP_PAGE3_FLAGS_TO_COPY);
27989    ast_string_field_set(peer, context, sip_cfg.default_context);
27990    ast_string_field_set(peer, subscribecontext, sip_cfg.default_subscribecontext);
27991    ast_string_field_set(peer, language, default_language);
27992    ast_string_field_set(peer, mohinterpret, default_mohinterpret);
27993    ast_string_field_set(peer, mohsuggest, default_mohsuggest);
27994    ast_string_field_set(peer, engine, default_engine);
27995    ast_sockaddr_setnull(&peer->addr);
27996    ast_sockaddr_setnull(&peer->defaddr);
27997    peer->capability = sip_cfg.capability;
27998    peer->maxcallbitrate = default_maxcallbitrate;
27999    peer->rtptimeout = global_rtptimeout;
28000    peer->rtpholdtimeout = global_rtpholdtimeout;
28001    peer->rtpkeepalive = global_rtpkeepalive;
28002    peer->allowtransfer = sip_cfg.allowtransfer;
28003    peer->autoframing = global_autoframing;
28004    peer->t38_maxdatagram = global_t38_maxdatagram;
28005    peer->qualifyfreq = global_qualifyfreq;
28006    if (global_callcounter)
28007       peer->call_limit=INT_MAX;
28008    ast_string_field_set(peer, vmexten, default_vmexten);
28009    ast_string_field_set(peer, secret, "");
28010    ast_string_field_set(peer, remotesecret, "");
28011    ast_string_field_set(peer, md5secret, "");
28012    ast_string_field_set(peer, cid_num, "");
28013    ast_string_field_set(peer, cid_name, "");
28014    ast_string_field_set(peer, cid_tag, "");
28015    ast_string_field_set(peer, fromdomain, "");
28016    ast_string_field_set(peer, fromuser, "");
28017    ast_string_field_set(peer, regexten, "");
28018    peer->callgroup = 0;
28019    peer->pickupgroup = 0;
28020    peer->maxms = default_qualify;
28021    peer->prefs = default_prefs;
28022    peer->stimer.st_mode_oper = global_st_mode;  /* Session-Timers */
28023    peer->stimer.st_ref = global_st_refresher;
28024    peer->stimer.st_min_se = global_min_se;
28025    peer->stimer.st_max_se = global_max_se;
28026    peer->timer_t1 = global_t1;
28027    peer->timer_b = global_timer_b;
28028    clear_peer_mailboxes(peer);
28029    peer->disallowed_methods = sip_cfg.disallowed_methods;
28030    peer->transports = default_transports;
28031    peer->default_outbound_transport = default_primary_transport;
28032    if (peer->outboundproxy) {
28033       ao2_ref(peer->outboundproxy, -1);
28034       peer->outboundproxy = NULL;
28035    }
28036 }
28037 
28038 /*! \brief Create temporary peer (used in autocreatepeer mode) */
28039 static struct sip_peer *temp_peer(const char *name)
28040 {
28041    struct sip_peer *peer;
28042 
28043    if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
28044       return NULL;
28045 
28046    if (ast_string_field_init(peer, 512)) {
28047       ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
28048       return NULL;
28049    }
28050    
28051    if (!(peer->cc_params = ast_cc_config_params_init())) {
28052       ao2_t_ref(peer, -1, "failed to allocate cc_params for peer");
28053       return NULL;
28054    }
28055 
28056    ast_atomic_fetchadd_int(&apeerobjs, 1);
28057    set_peer_defaults(peer);
28058 
28059    ast_copy_string(peer->name, name, sizeof(peer->name));
28060 
28061    peer->selfdestruct = TRUE;
28062    peer->host_dynamic = TRUE;
28063    peer->prefs = default_prefs;
28064    reg_source_db(peer);
28065 
28066    return peer;
28067 }
28068 
28069 /*! \todo document this function */
28070 static void add_peer_mailboxes(struct sip_peer *peer, const char *value)
28071 {
28072    char *next, *mbox, *context;
28073 
28074    next = ast_strdupa(value);
28075 
28076    while ((mbox = context = strsep(&next, ","))) {
28077       struct sip_mailbox *mailbox;
28078       int duplicate = 0;
28079       /* remove leading/trailing whitespace from mailbox string */
28080       mbox = ast_strip(mbox);
28081       strsep(&context, "@");
28082 
28083       if (ast_strlen_zero(mbox)) {
28084          continue;
28085       }
28086 
28087       /* Check whether the mailbox is already in the list */
28088       AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
28089          if (!strcmp(mailbox->mailbox, mbox) && !strcmp(S_OR(mailbox->context, ""), S_OR(context, ""))) {
28090             duplicate = 1;
28091             break;
28092          }
28093       }
28094       if (duplicate) {
28095          continue;
28096       }
28097 
28098       if (!(mailbox = ast_calloc(1, sizeof(*mailbox) + strlen(mbox) + strlen(S_OR(context, ""))))) {
28099          continue;
28100       }
28101 
28102       if (!ast_strlen_zero(context)) {
28103          mailbox->context = mailbox->mailbox + strlen(mbox) + 1;
28104          strcpy(mailbox->context, context); /* SAFE */
28105       }
28106       strcpy(mailbox->mailbox, mbox); /* SAFE */
28107 
28108       AST_LIST_INSERT_TAIL(&peer->mailboxes, mailbox, entry);
28109    }
28110 }
28111 
28112 /*! \brief Build peer from configuration (file or realtime static/dynamic) */
28113 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only)
28114 {
28115    struct sip_peer *peer = NULL;
28116    struct ast_ha *oldha = NULL;
28117    struct ast_ha *olddirectmediaha = NULL;
28118    int found = 0;
28119    int firstpass = 1;
28120    uint16_t port = 0;
28121    int format = 0;      /* Ama flags */
28122    int timerb_set = 0, timert1_set = 0;
28123    time_t regseconds = 0;
28124    struct ast_flags peerflags[3] = {{(0)}};
28125    struct ast_flags mask[3] = {{(0)}};
28126    char callback[256] = "";
28127    struct sip_peer tmp_peer;
28128    const char *srvlookup = NULL;
28129    static int deprecation_warning = 1;
28130    int alt_fullcontact = alt ? 1 : 0, headercount = 0;
28131    struct ast_str *fullcontact = ast_str_alloca(512);
28132 
28133    if (!realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
28134       /* Note we do NOT use find_peer here, to avoid realtime recursion */
28135       /* We also use a case-sensitive comparison (unlike find_peer) so
28136          that case changes made to the peer name will be properly handled
28137          during reload
28138       */
28139       ast_copy_string(tmp_peer.name, name, sizeof(tmp_peer.name));
28140       peer = ao2_t_find(peers, &tmp_peer, OBJ_POINTER | OBJ_UNLINK, "find and unlink peer from peers table");
28141    }
28142 
28143    if (peer) {
28144       /* Already in the list, remove it and it will be added back (or FREE'd)  */
28145       found++;
28146       /* we've unlinked the peer from the peers container but not unlinked from the peers_by_ip container yet
28147         this leads to a wrong refcounter and the peer object is never destroyed */
28148       if (!ast_sockaddr_isnull(&peer->addr)) {
28149          ao2_t_unlink(peers_by_ip, peer, "ao2_unlink peer from peers_by_ip table");
28150       }
28151       if (!(peer->the_mark))
28152          firstpass = 0;
28153    } else {
28154       if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
28155          return NULL;
28156 
28157       if (ast_string_field_init(peer, 512)) {
28158          ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
28159          return NULL;
28160       }
28161 
28162       if (!(peer->cc_params = ast_cc_config_params_init())) {
28163          ao2_t_ref(peer, -1, "failed to allocate cc_params for peer");
28164          return NULL;
28165       }
28166 
28167       if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
28168          ast_atomic_fetchadd_int(&rpeerobjs, 1);
28169          ast_debug(3, "-REALTIME- peer built. Name: %s. Peer objects: %d\n", name, rpeerobjs);
28170       } else
28171          ast_atomic_fetchadd_int(&speerobjs, 1);
28172    }
28173 
28174    /* Note that our peer HAS had its reference count increased */
28175    if (firstpass) {
28176       peer->lastmsgssent = -1;
28177       oldha = peer->ha;
28178       peer->ha = NULL;
28179       olddirectmediaha = peer->directmediaha;
28180       peer->directmediaha = NULL;
28181       set_peer_defaults(peer);   /* Set peer defaults */
28182       peer->type = 0;
28183    }
28184 
28185    /* in case the case of the peer name has changed, update the name */
28186    ast_copy_string(peer->name, name, sizeof(peer->name));
28187 
28188    /* If we have channel variables, remove them (reload) */
28189    if (peer->chanvars) {
28190       ast_variables_destroy(peer->chanvars);
28191       peer->chanvars = NULL;
28192       /* XXX should unregister ? */
28193    }
28194 
28195    if (found)
28196       peer->portinuri = 0;
28197 
28198    /* If we have realm authentication information, remove them (reload) */
28199    ao2_lock(peer);
28200    if (peer->auth) {
28201       ao2_t_ref(peer->auth, -1, "Removing old peer authentication");
28202       peer->auth = NULL;
28203    }
28204    ao2_unlock(peer);
28205 
28206    /* clear the transport information.  We will detect if a default value is required after parsing the config */
28207    peer->default_outbound_transport = 0;
28208    peer->transports = 0;
28209 
28210    if (!devstate_only) {
28211       struct sip_mailbox *mailbox;
28212       AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
28213          mailbox->delme = 1;
28214       }
28215    }
28216 
28217    for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
28218       if (!devstate_only) {
28219          if (handle_common_options(&peerflags[0], &mask[0], v)) {
28220             continue;
28221          }
28222          if (handle_t38_options(&peerflags[0], &mask[0], v, &peer->t38_maxdatagram)) {
28223             continue;
28224          }
28225          if (!strcasecmp(v->name, "transport")) {
28226             char *val = ast_strdupa(v->value);
28227             char *trans;
28228 
28229             peer->transports = peer->default_outbound_transport = 0;
28230             while ((trans = strsep(&val, ","))) {
28231                trans = ast_skip_blanks(trans);
28232 
28233                if (!strncasecmp(trans, "udp", 3)) {
28234                   peer->transports |= SIP_TRANSPORT_UDP;
28235                } else if (sip_cfg.tcp_enabled && !strncasecmp(trans, "tcp", 3)) {
28236                   peer->transports |= SIP_TRANSPORT_TCP;
28237                } else if (default_tls_cfg.enabled && !strncasecmp(trans, "tls", 3)) {
28238                   peer->transports |= SIP_TRANSPORT_TLS;
28239                } else if (!strncasecmp(trans, "tcp", 3) || !strncasecmp(trans, "tls", 3)) {
28240                   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);
28241                } else {
28242                   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);
28243                }
28244 
28245                if (!peer->default_outbound_transport) { /*!< The first transport listed should be default outbound */
28246                   peer->default_outbound_transport = peer->transports;
28247                }
28248             }
28249          } else if (realtime && !strcasecmp(v->name, "regseconds")) {
28250             ast_get_time_t(v->value, &regseconds, 0, NULL);
28251          } else if (realtime && !strcasecmp(v->name, "name")) {
28252             ast_copy_string(peer->name, v->value, sizeof(peer->name));
28253          } else if (realtime && !strcasecmp(v->name, "useragent")) {
28254             ast_string_field_set(peer, useragent, v->value);
28255          } else if (!strcasecmp(v->name, "type")) {
28256             if (!strcasecmp(v->value, "peer")) {
28257                peer->type |= SIP_TYPE_PEER;
28258             } else if (!strcasecmp(v->value, "user")) {
28259                peer->type |= SIP_TYPE_USER;
28260             } else if (!strcasecmp(v->value, "friend")) {
28261                peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
28262             }
28263          } else if (!strcasecmp(v->name, "remotesecret")) {
28264             ast_string_field_set(peer, remotesecret, v->value);
28265          } else if (!strcasecmp(v->name, "secret")) {
28266             ast_string_field_set(peer, secret, v->value);
28267          } else if (!strcasecmp(v->name, "md5secret")) {
28268             ast_string_field_set(peer, md5secret, v->value);
28269          } else if (!strcasecmp(v->name, "auth")) {
28270             add_realm_authentication(&peer->auth, v->value, v->lineno);
28271          } else if (!strcasecmp(v->name, "callerid")) {
28272             char cid_name[80] = { '\0' }, cid_num[80] = { '\0' };
28273 
28274             ast_callerid_split(v->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
28275             ast_string_field_set(peer, cid_name, cid_name);
28276             ast_string_field_set(peer, cid_num, cid_num);
28277          } else if (!strcasecmp(v->name, "mwi_from")) {
28278             ast_string_field_set(peer, mwi_from, v->value);
28279          } else if (!strcasecmp(v->name, "fullname")) {
28280             ast_string_field_set(peer, cid_name, v->value);
28281          } else if (!strcasecmp(v->name, "trunkname")) {
28282             /* This is actually for a trunk, so we don't want to override callerid */
28283             ast_string_field_set(peer, cid_name, "");
28284          } else if (!strcasecmp(v->name, "cid_number")) {
28285             ast_string_field_set(peer, cid_num, v->value);
28286          } else if (!strcasecmp(v->name, "cid_tag")) {
28287             ast_string_field_set(peer, cid_tag, v->value);
28288          } else if (!strcasecmp(v->name, "context")) {
28289             ast_string_field_set(peer, context, v->value);
28290             ast_set_flag(&peer->flags[1], SIP_PAGE2_HAVEPEERCONTEXT);
28291          } else if (!strcasecmp(v->name, "subscribecontext")) {
28292             ast_string_field_set(peer, subscribecontext, v->value);
28293          } else if (!strcasecmp(v->name, "fromdomain")) {
28294             char *fromdomainport;
28295             ast_string_field_set(peer, fromdomain, v->value);
28296             if ((fromdomainport = strchr(peer->fromdomain, ':'))) {
28297                *fromdomainport++ = '\0';
28298                if (!(peer->fromdomainport = port_str2int(fromdomainport, 0))) {
28299                   ast_log(LOG_NOTICE, "'%s' is not a valid port number for fromdomain.\n",fromdomainport);
28300                }
28301             } else {
28302                peer->fromdomainport = STANDARD_SIP_PORT;
28303             }
28304          } else if (!strcasecmp(v->name, "usereqphone")) {
28305             ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
28306          } else if (!strcasecmp(v->name, "fromuser")) {
28307             ast_string_field_set(peer, fromuser, v->value);
28308          } else if (!strcasecmp(v->name, "outboundproxy")) {
28309             struct sip_proxy *proxy;
28310             if (ast_strlen_zero(v->value)) {
28311                ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf\n", v->lineno);
28312                continue;
28313             }
28314             proxy = proxy_from_config(v->value, v->lineno, peer->outboundproxy);
28315             if (!proxy) {
28316                ast_log(LOG_WARNING, "failure parsing the outbound proxy on line %d of sip.conf.\n", v->lineno);
28317                continue;
28318             }
28319             peer->outboundproxy = proxy;
28320          } else if (!strcasecmp(v->name, "host")) {
28321             if (!strcasecmp(v->value, "dynamic")) {
28322                /* They'll register with us */
28323                if ((!found && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) || !peer->host_dynamic) {
28324                   /* Initialize stuff if this is a new peer, or if it used to
28325                    * not be dynamic before the reload. */
28326                   ast_sockaddr_setnull(&peer->addr);
28327                }
28328                peer->host_dynamic = TRUE;
28329             } else {
28330                /* Non-dynamic.  Make sure we become that way if we're not */
28331                AST_SCHED_DEL_UNREF(sched, peer->expire,
28332                      unref_peer(peer, "removing register expire ref"));
28333                peer->host_dynamic = FALSE;
28334                srvlookup = v->value;
28335             }
28336          } else if (!strcasecmp(v->name, "defaultip")) {
28337             if (!ast_strlen_zero(v->value) && ast_get_ip(&peer->defaddr, v->value)) {
28338                unref_peer(peer, "unref_peer: from build_peer defaultip");
28339                return NULL;
28340             }
28341          } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
28342             int ha_error = 0;
28343             if (!ast_strlen_zero(v->value)) {
28344                peer->ha = ast_append_ha(v->name, v->value, peer->ha, &ha_error);
28345             }
28346             if (ha_error) {
28347                ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
28348             }
28349          } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
28350             int ha_error = 0;
28351             if (!ast_strlen_zero(v->value)) {
28352                peer->contactha = ast_append_ha(v->name + 7, v->value, peer->contactha, &ha_error);
28353             }
28354             if (ha_error) {
28355                ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
28356             }
28357          } else if (!strcasecmp(v->name, "directmediapermit") || !strcasecmp(v->name, "directmediadeny")) {
28358             int ha_error = 0;
28359             peer->directmediaha = ast_append_ha(v->name + 11, v->value, peer->directmediaha, &ha_error);
28360             if (ha_error) {
28361                ast_log(LOG_ERROR, "Bad directmedia ACL entry in configuration line %d : %s\n", v->lineno, v->value);
28362             }
28363          } else if (!strcasecmp(v->name, "port")) {
28364             peer->portinuri = 1;
28365             if (!(port = port_str2int(v->value, 0))) {
28366                if (realtime) {
28367                   /* If stored as integer, could be 0 for some DBs (notably MySQL) */
28368                   peer->portinuri = 0;
28369                } else {
28370                   ast_log(LOG_WARNING, "Invalid peer port configuration at line %d : %s\n", v->lineno, v->value);
28371                }
28372             }
28373          } else if (!strcasecmp(v->name, "callingpres")) {
28374             peer->callingpres = ast_parse_caller_presentation(v->value);
28375             if (peer->callingpres == -1) {
28376                peer->callingpres = atoi(v->value);
28377             }
28378          } else if (!strcasecmp(v->name, "username") || !strcmp(v->name, "defaultuser")) {   /* "username" is deprecated */
28379             ast_string_field_set(peer, username, v->value);
28380             if (!strcasecmp(v->name, "username")) {
28381                if (deprecation_warning) {
28382                   ast_log(LOG_NOTICE, "The 'username' field for sip peers has been deprecated in favor of the term 'defaultuser'\n");
28383                   deprecation_warning = 0;
28384                }
28385                peer->deprecated_username = 1;
28386             }
28387          } else if (!strcasecmp(v->name, "language")) {
28388             ast_string_field_set(peer, language, v->value);
28389          } else if (!strcasecmp(v->name, "regexten")) {
28390             ast_string_field_set(peer, regexten, v->value);
28391          } else if (!strcasecmp(v->name, "callbackextension")) {
28392             ast_copy_string(callback, v->value, sizeof(callback));
28393          } else if (!strcasecmp(v->name, "amaflags")) {
28394             format = ast_cdr_amaflags2int(v->value);
28395             if (format < 0) {
28396                ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
28397             } else {
28398                peer->amaflags = format;
28399             }
28400          } else if (!strcasecmp(v->name, "maxforwards")) {
28401             if (sscanf(v->value, "%30d", &peer->maxforwards) != 1
28402                || peer->maxforwards < 1 || 255 < peer->maxforwards) {
28403                ast_log(LOG_WARNING, "'%s' is not a valid maxforwards value at line %d.  Using default.\n", v->value, v->lineno);
28404                peer->maxforwards = sip_cfg.default_max_forwards;
28405             }
28406          } else if (!strcasecmp(v->name, "accountcode")) {
28407             ast_string_field_set(peer, accountcode, v->value);
28408          } else if (!strcasecmp(v->name, "mohinterpret")) {
28409             ast_string_field_set(peer, mohinterpret, v->value);
28410          } else if (!strcasecmp(v->name, "mohsuggest")) {
28411             ast_string_field_set(peer, mohsuggest, v->value);
28412          } else if (!strcasecmp(v->name, "parkinglot")) {
28413             ast_string_field_set(peer, parkinglot, v->value);
28414          } else if (!strcasecmp(v->name, "rtp_engine")) {
28415             ast_string_field_set(peer, engine, v->value);
28416          } else if (!strcasecmp(v->name, "mailbox")) {
28417             add_peer_mailboxes(peer, v->value);
28418          } else if (!strcasecmp(v->name, "hasvoicemail")) {
28419             /* People expect that if 'hasvoicemail' is set, that the mailbox will
28420              * be also set, even if not explicitly specified. */
28421             if (ast_true(v->value) && AST_LIST_EMPTY(&peer->mailboxes)) {
28422                add_peer_mailboxes(peer, name);
28423             }
28424          } else if (!strcasecmp(v->name, "subscribemwi")) {
28425             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
28426          } else if (!strcasecmp(v->name, "vmexten")) {
28427             ast_string_field_set(peer, vmexten, v->value);
28428          } else if (!strcasecmp(v->name, "callgroup")) {
28429             peer->callgroup = ast_get_group(v->value);
28430          } else if (!strcasecmp(v->name, "allowtransfer")) {
28431             peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
28432          } else if (!strcasecmp(v->name, "pickupgroup")) {
28433             peer->pickupgroup = ast_get_group(v->value);
28434          } else if (!strcasecmp(v->name, "allow")) {
28435             int error =  ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, TRUE);
28436             if (error) {
28437                ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
28438             }
28439          } else if (!strcasecmp(v->name, "disallow")) {
28440             int error =  ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, FALSE);
28441             if (error) {
28442                ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
28443             }
28444          } else if (!strcasecmp(v->name, "preferred_codec_only")) {
28445             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_PREFERRED_CODEC);
28446          } else if (!strcasecmp(v->name, "autoframing")) {
28447             peer->autoframing = ast_true(v->value);
28448          } else if (!strcasecmp(v->name, "rtptimeout")) {
28449             if ((sscanf(v->value, "%30d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
28450                ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
28451                peer->rtptimeout = global_rtptimeout;
28452             }
28453          } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
28454             if ((sscanf(v->value, "%30d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
28455                ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
28456                peer->rtpholdtimeout = global_rtpholdtimeout;
28457             }
28458          } else if (!strcasecmp(v->name, "rtpkeepalive")) {
28459             if ((sscanf(v->value, "%30d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
28460                ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d.  Using default.\n", v->value, v->lineno);
28461                peer->rtpkeepalive = global_rtpkeepalive;
28462             }
28463          } else if (!strcasecmp(v->name, "timert1")) {
28464             if ((sscanf(v->value, "%30d", &peer->timer_t1) != 1) || (peer->timer_t1 < 200) || (peer->timer_t1 < global_t1min)) {
28465                ast_log(LOG_WARNING, "'%s' is not a valid T1 time at line %d.  Using default.\n", v->value, v->lineno);
28466                peer->timer_t1 = global_t1min;
28467             }
28468             timert1_set = 1;
28469          } else if (!strcasecmp(v->name, "timerb")) {
28470             if ((sscanf(v->value, "%30d", &peer->timer_b) != 1) || (peer->timer_b < 200)) {
28471                ast_log(LOG_WARNING, "'%s' is not a valid Timer B time at line %d.  Using default.\n", v->value, v->lineno);
28472                peer->timer_b = global_timer_b;
28473             }
28474             timerb_set = 1;
28475          } else if (!strcasecmp(v->name, "setvar")) {
28476             peer->chanvars = add_var(v->value, peer->chanvars);
28477          } else if (!strcasecmp(v->name, "header")) {
28478             char tmp[4096];
28479             snprintf(tmp, sizeof(tmp), "__SIPADDHEADERpre%2d=%s", ++headercount, v->value);
28480             peer->chanvars = add_var(tmp, peer->chanvars);
28481          } else if (!strcasecmp(v->name, "qualifyfreq")) {
28482             int i;
28483             if (sscanf(v->value, "%30d", &i) == 1) {
28484                peer->qualifyfreq = i * 1000;
28485             } else {
28486                ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
28487                peer->qualifyfreq = global_qualifyfreq;
28488             }
28489          } else if (!strcasecmp(v->name, "maxcallbitrate")) {
28490             peer->maxcallbitrate = atoi(v->value);
28491             if (peer->maxcallbitrate < 0) {
28492                peer->maxcallbitrate = default_maxcallbitrate;
28493             }
28494          } else if (!strcasecmp(v->name, "session-timers")) {
28495             int i = (int) str2stmode(v->value);
28496             if (i < 0) {
28497                ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
28498                peer->stimer.st_mode_oper = global_st_mode;
28499             } else {
28500                peer->stimer.st_mode_oper = i;
28501             }
28502          } else if (!strcasecmp(v->name, "session-expires")) {
28503             if (sscanf(v->value, "%30d", &peer->stimer.st_max_se) != 1) {
28504                ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
28505                peer->stimer.st_max_se = global_max_se;
28506             }
28507          } else if (!strcasecmp(v->name, "session-minse")) {
28508             if (sscanf(v->value, "%30d", &peer->stimer.st_min_se) != 1) {
28509                ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
28510                peer->stimer.st_min_se = global_min_se;
28511             }
28512             if (peer->stimer.st_min_se < DEFAULT_MIN_SE) {
28513                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);
28514                peer->stimer.st_min_se = global_min_se;
28515             }
28516          } else if (!strcasecmp(v->name, "session-refresher")) {
28517             int i = (int) str2strefresherparam(v->value);
28518             if (i < 0) {
28519                ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
28520                peer->stimer.st_ref = global_st_refresher;
28521             } else {
28522                peer->stimer.st_ref = i;
28523             }
28524          } else if (!strcasecmp(v->name, "disallowed_methods")) {
28525             char *disallow = ast_strdupa(v->value);
28526             mark_parsed_methods(&peer->disallowed_methods, disallow);
28527          } else if (!strcasecmp(v->name, "unsolicited_mailbox")) {
28528             ast_string_field_set(peer, unsolicited_mailbox, v->value);
28529          } else if (!strcasecmp(v->name, "use_q850_reason")) {
28530             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_Q850_REASON);
28531          } else if (!strcasecmp(v->name, "encryption")) {
28532             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_USE_SRTP);
28533          } else if (!strcasecmp(v->name, "snom_aoc_enabled")) {
28534             ast_set2_flag(&peer->flags[2], ast_true(v->value), SIP_PAGE3_SNOM_AOC);
28535          }
28536       }
28537 
28538       /* These apply to devstate lookups */
28539       if (realtime && !strcasecmp(v->name, "lastms")) {
28540          sscanf(v->value, "%30d", &peer->lastms);
28541       } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
28542          ast_sockaddr_parse(&peer->addr, v->value, PARSE_PORT_FORBID);
28543       } else if (realtime && !strcasecmp(v->name, "fullcontact")) {
28544          if (alt_fullcontact && !alt) {
28545             /* Reset, because the alternate also has a fullcontact and we
28546              * do NOT want the field value to be doubled. It might be
28547              * tempting to skip this, but the first table might not have
28548              * fullcontact and since we're here, we know that the alternate
28549              * absolutely does. */
28550             alt_fullcontact = 0;
28551             ast_str_reset(fullcontact);
28552          }
28553          /* Reconstruct field, because realtime separates our value at the ';' */
28554          if (ast_str_strlen(fullcontact) > 0) {
28555             ast_str_append(&fullcontact, 0, ";%s", v->value);
28556          } else {
28557             ast_str_set(&fullcontact, 0, "%s", v->value);
28558          }
28559       } else if (!strcasecmp(v->name, "qualify")) {
28560          if (!strcasecmp(v->value, "no")) {
28561             peer->maxms = 0;
28562          } else if (!strcasecmp(v->value, "yes")) {
28563             peer->maxms = default_qualify ? default_qualify : DEFAULT_MAXMS;
28564          } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
28565             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);
28566             peer->maxms = 0;
28567          }
28568          if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->maxms > 0) {
28569             /* This would otherwise cause a network storm, where the
28570              * qualify response refreshes the peer from the database,
28571              * which in turn causes another qualify to be sent, ad
28572              * infinitum. */
28573             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);
28574             peer->maxms = 0;
28575          }
28576       } else if (!strcasecmp(v->name, "callcounter")) {
28577          peer->call_limit = ast_true(v->value) ? INT_MAX : 0;
28578       } else if (!strcasecmp(v->name, "call-limit")) {
28579          peer->call_limit = atoi(v->value);
28580          if (peer->call_limit < 0) {
28581             peer->call_limit = 0;
28582          }
28583       } else if (!strcasecmp(v->name, "busylevel")) {
28584          peer->busy_level = atoi(v->value);
28585          if (peer->busy_level < 0) {
28586             peer->busy_level = 0;
28587          }
28588       } else if (ast_cc_is_config_param(v->name)) {
28589          ast_cc_set_param(peer->cc_params, v->name, v->value);
28590       }
28591    }
28592 
28593    if (!devstate_only) {
28594       struct sip_mailbox *mailbox;
28595       AST_LIST_TRAVERSE_SAFE_BEGIN(&peer->mailboxes, mailbox, entry) {
28596          if (mailbox->delme) {
28597             AST_LIST_REMOVE_CURRENT(entry);
28598             destroy_mailbox(mailbox);
28599          }
28600       }
28601       AST_LIST_TRAVERSE_SAFE_END;
28602    }
28603 
28604    if (!can_parse_xml && (ast_get_cc_agent_policy(peer->cc_params) == AST_CC_AGENT_NATIVE)) {
28605       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);
28606       ast_set_cc_agent_policy(peer->cc_params, AST_CC_AGENT_NEVER);
28607    }
28608 
28609    /* Note that Timer B is dependent upon T1 and MUST NOT be lower
28610     * than T1 * 64, according to RFC 3261, Section 17.1.1.2 */
28611    if (peer->timer_b < peer->timer_t1 * 64) {
28612       if (timerb_set && timert1_set) {
28613          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);
28614       } else if (timerb_set) {
28615          if ((peer->timer_t1 = peer->timer_b / 64) < global_t1min) {
28616             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);
28617             peer->timer_t1 = global_t1min;
28618             peer->timer_b = peer->timer_t1 * 64;
28619          }
28620          peer->timer_t1 = peer->timer_b / 64;
28621       } else {
28622          peer->timer_b = peer->timer_t1 * 64;
28623       }
28624    }
28625 
28626    if (!peer->default_outbound_transport) {
28627       /* Set default set of transports */
28628       peer->transports = default_transports;
28629       /* Set default primary transport */
28630       peer->default_outbound_transport = default_primary_transport;
28631    }
28632 
28633    /* The default transport type set during build_peer should only replace the socket.type when...
28634     * 1. Registration is not present and the socket.type and default transport types are different.
28635     * 2. The socket.type is not an acceptable transport type after rebuilding peer.
28636     * 3. The socket.type is not set yet. */
28637    if (((peer->socket.type != peer->default_outbound_transport) && (peer->expire == -1)) ||
28638       !(peer->socket.type & peer->transports) || !(peer->socket.type)) {
28639 
28640       set_socket_transport(&peer->socket, peer->default_outbound_transport);
28641    }
28642 
28643    ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
28644    ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
28645    ast_copy_flags(&peer->flags[2], &peerflags[2], mask[2].flags);
28646 
28647    if (ast_str_strlen(fullcontact)) {
28648       ast_string_field_set(peer, fullcontact, ast_str_buffer(fullcontact));
28649       peer->rt_fromcontact = TRUE;
28650       /* We have a hostname in the fullcontact, but if we don't have an
28651        * address listed on the entry (or if it's 'dynamic'), then we need to
28652        * parse the entry to obtain the IP address, so a dynamic host can be
28653        * contacted immediately after reload (as opposed to waiting for it to
28654        * register once again). But if we have an address for this peer and NAT was
28655        * specified, use that address instead. */
28656       /* XXX May need to revisit the final argument; does the realtime DB store whether
28657        * the original contact was over TLS or not? XXX */
28658       if (!ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) || ast_sockaddr_isnull(&peer->addr)) {
28659          __set_address_from_contact(ast_str_buffer(fullcontact), &peer->addr, 0);
28660       }
28661    }
28662 
28663    if (srvlookup && peer->dnsmgr == NULL) {
28664       char transport[MAXHOSTNAMELEN];
28665       char _srvlookup[MAXHOSTNAMELEN];
28666       char *params;
28667 
28668       ast_copy_string(_srvlookup, srvlookup, sizeof(_srvlookup));
28669       if ((params = strchr(_srvlookup, ';'))) {
28670          *params++ = '\0';
28671       }
28672 
28673       snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(peer->socket.type), get_srv_protocol(peer->socket.type));
28674 
28675       peer->addr.ss.ss_family = get_address_family_filter(peer->socket.type); /* Filter address family */
28676       if (ast_dnsmgr_lookup_cb(_srvlookup, &peer->addr, &peer->dnsmgr, sip_cfg.srvlookup && !peer->portinuri ? transport : NULL,
28677                on_dns_update_peer, ref_peer(peer, "Store peer on dnsmgr"))) {
28678          ast_log(LOG_ERROR, "srvlookup failed for host: %s, on peer %s, removing peer\n", _srvlookup, peer->name);
28679          unref_peer(peer, "dnsmgr lookup failed, getting rid of peer dnsmgr ref");
28680          unref_peer(peer, "getting rid of a peer pointer");
28681          return NULL;
28682       }
28683       if (!peer->dnsmgr) {
28684          /* dnsmgr refresh disabeld, release reference */
28685          unref_peer(peer, "dnsmgr disabled, unref peer");
28686       }
28687 
28688       ast_string_field_set(peer, tohost, srvlookup);
28689 
28690       if (global_dynamic_exclude_static && !ast_sockaddr_isnull(&peer->addr)) {
28691          int ha_error = 0;
28692          sip_cfg.contact_ha = ast_append_ha("deny", ast_sockaddr_stringify_addr(&peer->addr), 
28693                      sip_cfg.contact_ha, &ha_error);
28694          if (ha_error) {
28695             ast_log(LOG_ERROR, "Bad or unresolved host/IP entry in configuration for peer %s, cannot add to contact ACL\n", peer->name);
28696          }
28697       }
28698    } else if (peer->dnsmgr && !peer->host_dynamic) {
28699       /* force a refresh here on reload if dnsmgr already exists and host is set. */
28700       ast_dnsmgr_refresh(peer->dnsmgr);
28701    }
28702 
28703    if (port && !realtime && peer->host_dynamic) {
28704       ast_sockaddr_set_port(&peer->defaddr, port);
28705    } else if (port) {
28706       ast_sockaddr_set_port(&peer->addr, port);
28707    }
28708 
28709    if (ast_sockaddr_port(&peer->addr) == 0) {
28710       ast_sockaddr_set_port(&peer->addr,
28711                   (peer->socket.type & SIP_TRANSPORT_TLS) ?
28712                   STANDARD_TLS_PORT : STANDARD_SIP_PORT);
28713    }
28714    if (ast_sockaddr_port(&peer->defaddr) == 0) {
28715       ast_sockaddr_set_port(&peer->defaddr,
28716                   (peer->socket.type & SIP_TRANSPORT_TLS) ?
28717                   STANDARD_TLS_PORT : STANDARD_SIP_PORT);
28718    }
28719    if (!peer->socket.port) {
28720       peer->socket.port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
28721    }
28722 
28723    if (realtime) {
28724       int enablepoke = 1;
28725 
28726       if (!sip_cfg.ignore_regexpire && peer->host_dynamic) {
28727          time_t nowtime = time(NULL);
28728 
28729          if ((nowtime - regseconds) > 0) {
28730             destroy_association(peer);
28731             memset(&peer->addr, 0, sizeof(peer->addr));
28732             peer->lastms = -1;
28733             enablepoke = 0;
28734             ast_debug(1, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
28735          }
28736       }
28737 
28738       /* Startup regular pokes */
28739       if (!devstate_only && enablepoke) {
28740          sip_poke_peer(peer, 0);
28741       }
28742    }
28743 
28744    if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
28745       sip_cfg.allowsubscribe = TRUE;   /* No global ban any more */
28746    }
28747    /* If read-only RT backend, then refresh from local DB cache */
28748    if (peer->host_dynamic && (!peer->is_realtime || !sip_cfg.peer_rtupdate)) {
28749       reg_source_db(peer);
28750    }
28751 
28752    /* If they didn't request that MWI is sent *only* on subscribe, go ahead and
28753     * subscribe to it now. */
28754    if (!devstate_only && !ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
28755       !AST_LIST_EMPTY(&peer->mailboxes)) {
28756       add_peer_mwi_subs(peer);
28757       /* Send MWI from the event cache only.  This is so we can send initial
28758        * MWI if app_voicemail got loaded before chan_sip.  If it is the other
28759        * way, then we will get events when app_voicemail gets loaded. */
28760       sip_send_mwi_to_peer(peer, 1);
28761    }
28762 
28763    peer->the_mark = 0;
28764 
28765    ast_free_ha(oldha);
28766    ast_free_ha(olddirectmediaha);
28767    if (!ast_strlen_zero(callback)) { /* build string from peer info */
28768       char *reg_string;
28769       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, callback) >= 0) {
28770          sip_register(reg_string, 0); /* XXX TODO: count in registry_count */
28771          ast_free(reg_string);
28772       }
28773    }
28774    return peer;
28775 }
28776 
28777 static int peer_markall_func(void *device, void *arg, int flags)
28778 {
28779    struct sip_peer *peer = device;
28780    peer->the_mark = 1;
28781    return 0;
28782 }
28783 
28784 static void display_nat_warning(const char *cat, int reason, struct ast_flags *flags) {
28785    int global_nat, specific_nat;
28786 
28787    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))) {
28788       ast_log(LOG_WARNING, "!!! PLEASE NOTE: Setting 'nat' for a peer/user that differs from the  global setting can make\n");
28789       ast_log(LOG_WARNING, "!!! the name of that peer/user discoverable by an attacker. Replies for non-existent peers/users\n");
28790       ast_log(LOG_WARNING, "!!! will be sent to a different port than replies for an existing peer/user. If at all possible,\n");
28791       ast_log(LOG_WARNING, "!!! use the global 'nat' setting and do not set 'nat' per peer/user.\n");
28792       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));
28793    }
28794 }
28795 
28796 static void cleanup_all_regs(void)
28797 {
28798       /* First, destroy all outstanding registry calls */
28799       /* This is needed, since otherwise active registry entries will not be destroyed */
28800       ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {  /* regl is locked */
28801             ASTOBJ_WRLOCK(iterator); /* now regl is locked, and the object is also locked */
28802             if (iterator->call) {
28803                ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
28804                /* This will also remove references to the registry */
28805                dialog_unlink_all(iterator->call);
28806                iterator->call = dialog_unref(iterator->call, "remove iterator->call from registry traversal");
28807             }
28808             if (iterator->expire > -1) {
28809                AST_SCHED_DEL_UNREF(sched, iterator->expire, registry_unref(iterator, "reg ptr unref from reload config"));
28810             }
28811             if (iterator->timeout > -1) {
28812                AST_SCHED_DEL_UNREF(sched, iterator->timeout, registry_unref(iterator, "reg ptr unref from reload config"));
28813             }
28814             if (iterator->dnsmgr) {
28815                ast_dnsmgr_release(iterator->dnsmgr);
28816                iterator->dnsmgr = NULL;
28817                registry_unref(iterator, "reg ptr unref from dnsmgr");
28818             }
28819             ASTOBJ_UNLOCK(iterator);
28820       } while(0));
28821 }
28822 
28823 /*! \brief Re-read SIP.conf config file
28824 \note This function reloads all config data, except for
28825    active peers (with registrations). They will only
28826    change configuration data at restart, not at reload.
28827    SIP debug and recordhistory state will not change
28828  */
28829 static int reload_config(enum channelreloadreason reason)
28830 {
28831    struct ast_config *cfg, *ucfg;
28832    struct ast_variable *v;
28833    struct sip_peer *peer;
28834    char *cat, *stringp, *context, *oldregcontext;
28835    char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
28836    struct ast_flags mask[3] = {{0}};
28837    struct ast_flags setflags[3] = {{0}};
28838    struct ast_flags config_flags = { reason == CHANNEL_MODULE_LOAD ? 0 : ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) ? 0 : CONFIG_FLAG_FILEUNCHANGED };
28839    int auto_sip_domains = FALSE;
28840    struct ast_sockaddr old_bindaddr = bindaddr;
28841    int registry_count = 0, peer_count = 0, timerb_set = 0, timert1_set = 0;
28842    int subscribe_network_change = 1;
28843    time_t run_start, run_end;
28844    int bindport = 0;
28845 
28846    run_start = time(0);
28847    ast_unload_realtime("sipregs");
28848    ast_unload_realtime("sippeers");
28849    cfg = ast_config_load(config, config_flags);
28850 
28851    /* We *must* have a config file otherwise stop immediately */
28852    if (!cfg) {
28853       ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
28854       return -1;
28855    } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
28856       ucfg = ast_config_load("users.conf", config_flags);
28857       if (ucfg == CONFIG_STATUS_FILEUNCHANGED) {
28858          return 1;
28859       } else if (ucfg == CONFIG_STATUS_FILEINVALID) {
28860          ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
28861          return 1;
28862       }
28863       /* Must reread both files, because one changed */
28864       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
28865       if ((cfg = ast_config_load(config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
28866          ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
28867          ast_config_destroy(ucfg);
28868          return 1;
28869       }
28870       if (!cfg) {
28871          /* should have been able to reload here */
28872          ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
28873          return -1;
28874       }
28875    } else if (cfg == CONFIG_STATUS_FILEINVALID) {
28876       ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
28877       return 1;
28878    } else {
28879       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
28880       if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEINVALID) {
28881          ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
28882          ast_config_destroy(cfg);
28883          return 1;
28884       }
28885    }
28886 
28887    ast_free_ha(sip_cfg.contact_ha);
28888    sip_cfg.contact_ha = NULL;
28889 
28890    default_tls_cfg.enabled = FALSE;    /* Default: Disable TLS */
28891 
28892    if (reason != CHANNEL_MODULE_LOAD) {
28893       ast_debug(4, "--------------- SIP reload started\n");
28894 
28895       clear_sip_domains();
28896       ast_mutex_lock(&authl_lock);
28897       if (authl) {
28898          ao2_t_ref(authl, -1, "Removing old global authentication");
28899          authl = NULL;
28900       }
28901       ast_mutex_unlock(&authl_lock);
28902 
28903 
28904       cleanup_all_regs();
28905       /* Then, actually destroy users and registry */
28906       ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
28907       ast_debug(4, "--------------- Done destroying registry list\n");
28908       ao2_t_callback(peers, OBJ_NODATA, peer_markall_func, NULL, "callback to mark all peers");
28909    }
28910 
28911    /* Reset certificate handling for TLS sessions */
28912    if (reason != CHANNEL_MODULE_LOAD) {
28913       ast_free(default_tls_cfg.certfile);
28914       ast_free(default_tls_cfg.pvtfile);
28915       ast_free(default_tls_cfg.cipher);
28916       ast_free(default_tls_cfg.cafile);
28917       ast_free(default_tls_cfg.capath);
28918    }
28919    default_tls_cfg.certfile = ast_strdup(AST_CERTFILE); /*XXX Not sure if this is useful */
28920    default_tls_cfg.pvtfile = ast_strdup("");
28921    default_tls_cfg.cipher = ast_strdup("");
28922    default_tls_cfg.cafile = ast_strdup("");
28923    default_tls_cfg.capath = ast_strdup("");
28924 
28925    /* Initialize copy of current sip_cfg.regcontext for later use in removing stale contexts */
28926    ast_copy_string(oldcontexts, sip_cfg.regcontext, sizeof(oldcontexts));
28927    oldregcontext = oldcontexts;
28928 
28929    /* Clear all flags before setting default values */
28930    /* Preserve debugging settings for console */
28931    sipdebug &= sip_debug_console;
28932    ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
28933    ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
28934    ast_clear_flag(&global_flags[2], AST_FLAGS_ALL);
28935 
28936    /* Reset IP addresses  */
28937    ast_sockaddr_parse(&bindaddr, "0.0.0.0:0", 0);
28938    memset(&internip, 0, sizeof(internip));
28939 
28940    /* Free memory for local network address mask */
28941    ast_free_ha(localaddr);
28942    memset(&localaddr, 0, sizeof(localaddr));
28943    memset(&externaddr, 0, sizeof(externaddr));
28944    memset(&media_address, 0, sizeof(media_address));
28945    memset(&default_prefs, 0 , sizeof(default_prefs));
28946    memset(&sip_cfg.outboundproxy, 0, sizeof(struct sip_proxy));
28947    sip_cfg.outboundproxy.force = FALSE;      /*!< Don't force proxy usage, use route: headers */
28948    default_transports = SIP_TRANSPORT_UDP;
28949    default_primary_transport = SIP_TRANSPORT_UDP;
28950    ourport_tcp = STANDARD_SIP_PORT;
28951    ourport_tls = STANDARD_TLS_PORT;
28952    externtcpport = STANDARD_SIP_PORT;
28953    externtlsport = STANDARD_TLS_PORT;
28954    sip_cfg.srvlookup = DEFAULT_SRVLOOKUP;
28955    global_tos_sip = DEFAULT_TOS_SIP;
28956    global_tos_audio = DEFAULT_TOS_AUDIO;
28957    global_tos_video = DEFAULT_TOS_VIDEO;
28958    global_tos_text = DEFAULT_TOS_TEXT;
28959    global_cos_sip = DEFAULT_COS_SIP;
28960    global_cos_audio = DEFAULT_COS_AUDIO;
28961    global_cos_video = DEFAULT_COS_VIDEO;
28962    global_cos_text = DEFAULT_COS_TEXT;
28963 
28964    externhost[0] = '\0';         /* External host name (for behind NAT DynDNS support) */
28965    externexpire = 0;       /* Expiration for DNS re-issuing */
28966    externrefresh = 10;
28967 
28968    /* Reset channel settings to default before re-configuring */
28969    sip_cfg.allow_external_domains = DEFAULT_ALLOW_EXT_DOM;           /* Allow external invites */
28970    sip_cfg.regcontext[0] = '\0';
28971    sip_cfg.capability = DEFAULT_CAPABILITY;
28972    sip_cfg.regextenonqualify = DEFAULT_REGEXTENONQUALIFY;
28973    sip_cfg.legacy_useroption_parsing = DEFAULT_LEGACY_USEROPTION_PARSING;
28974    sip_cfg.notifyringing = DEFAULT_NOTIFYRINGING;
28975    sip_cfg.notifycid = DEFAULT_NOTIFYCID;
28976    sip_cfg.notifyhold = FALSE;      /*!< Keep track of hold status for a peer */
28977    sip_cfg.directrtpsetup = FALSE;     /* Experimental feature, disabled by default */
28978    sip_cfg.alwaysauthreject = DEFAULT_ALWAYSAUTHREJECT;
28979    sip_cfg.auth_options_requests = DEFAULT_AUTH_OPTIONS;
28980    sip_cfg.allowsubscribe = FALSE;
28981    sip_cfg.disallowed_methods = SIP_UNKNOWN;
28982    sip_cfg.contact_ha = NULL;    /* Reset the contact ACL */
28983    snprintf(global_useragent, sizeof(global_useragent), "%s %s", DEFAULT_USERAGENT, ast_get_version());
28984    snprintf(global_sdpsession, sizeof(global_sdpsession), "%s %s", DEFAULT_SDPSESSION, ast_get_version());
28985    snprintf(global_sdpowner, sizeof(global_sdpowner), "%s", DEFAULT_SDPOWNER);
28986    global_prematuremediafilter = TRUE;
28987    ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
28988    ast_copy_string(sip_cfg.realm, S_OR(ast_config_AST_SYSTEM_NAME, DEFAULT_REALM), sizeof(sip_cfg.realm));
28989    sip_cfg.domainsasrealm = DEFAULT_DOMAINSASREALM;
28990    ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
28991    ast_copy_string(default_mwi_from, DEFAULT_MWI_FROM, sizeof(default_mwi_from));
28992    sip_cfg.compactheaders = DEFAULT_COMPACTHEADERS;
28993    global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
28994    global_regattempts_max = 0;
28995    global_reg_retry_403 = 0;
28996    sip_cfg.pedanticsipchecking = DEFAULT_PEDANTIC;
28997    sip_cfg.autocreatepeer = DEFAULT_AUTOCREATEPEER;
28998    global_autoframing = 0;
28999    sip_cfg.allowguest = DEFAULT_ALLOWGUEST;
29000    global_callcounter = DEFAULT_CALLCOUNTER;
29001    global_match_auth_username = FALSE;    /*!< Match auth username if available instead of From: Default off. */
29002    global_rtptimeout = 0;
29003    global_rtpholdtimeout = 0;
29004    global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
29005    sip_cfg.allowtransfer = TRANSFER_OPENFORALL; /* Merrily accept all transfers by default */
29006    sip_cfg.rtautoclear = 120;
29007    ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE);   /* Default for all devices: TRUE */
29008    ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP_YES); /* Default for all devices: Yes */
29009    sip_cfg.peer_rtupdate = TRUE;
29010    global_dynamic_exclude_static = 0;  /* Exclude static peers */
29011    sip_cfg.tcp_enabled = FALSE;
29012 
29013    /* Session-Timers */
29014    global_st_mode = SESSION_TIMER_MODE_ACCEPT;
29015    global_st_refresher = SESSION_TIMER_REFRESHER_PARAM_UAS;
29016    global_min_se  = DEFAULT_MIN_SE;
29017    global_max_se  = DEFAULT_MAX_SE;
29018 
29019    /* Peer poking settings */
29020    global_qualify_gap = DEFAULT_QUALIFY_GAP;
29021    global_qualify_peers = DEFAULT_QUALIFY_PEERS;
29022 
29023    /* Initialize some reasonable defaults at SIP reload (used both for channel and as default for devices */
29024    ast_copy_string(sip_cfg.default_context, DEFAULT_CONTEXT, sizeof(sip_cfg.default_context));
29025    sip_cfg.default_subscribecontext[0] = '\0';
29026    sip_cfg.default_max_forwards = DEFAULT_MAX_FORWARDS;
29027    default_language[0] = '\0';
29028    default_fromdomain[0] = '\0';
29029    default_fromdomainport = 0;
29030    default_qualify = DEFAULT_QUALIFY;
29031    default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
29032    ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
29033    ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
29034    ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
29035    ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833);    /*!< Default DTMF setting: RFC2833 */
29036    ast_set_flag(&global_flags[0], SIP_DIRECT_MEDIA);    /*!< Allow re-invites */
29037    ast_set_flag(&global_flags[0], SIP_NAT_FORCE_RPORT); /*!< Default to nat=force_rport */
29038    ast_copy_string(default_engine, DEFAULT_ENGINE, sizeof(default_engine));
29039    ast_copy_string(default_parkinglot, DEFAULT_PARKINGLOT, sizeof(default_parkinglot));
29040 
29041    /* Debugging settings, always default to off */
29042    dumphistory = FALSE;
29043    recordhistory = FALSE;
29044    sipdebug &= ~sip_debug_config;
29045 
29046    /* Misc settings for the channel */
29047    global_relaxdtmf = FALSE;
29048    sip_cfg.callevents = DEFAULT_CALLEVENTS;
29049    global_authfailureevents = FALSE;
29050    global_t1 = DEFAULT_TIMER_T1;
29051    global_timer_b = 64 * DEFAULT_TIMER_T1;
29052    global_t1min = DEFAULT_T1MIN;
29053    global_qualifyfreq = DEFAULT_QUALIFYFREQ;
29054    global_t38_maxdatagram = -1;
29055    global_shrinkcallerid = 1;
29056    authlimit = DEFAULT_AUTHLIMIT;
29057    authtimeout = DEFAULT_AUTHTIMEOUT;
29058    global_store_sip_cause = DEFAULT_STORE_SIP_CAUSE;
29059 
29060    sip_cfg.matchexternaddrlocally = DEFAULT_MATCHEXTERNADDRLOCALLY;
29061 
29062    /* Copy the default jb config over global_jbconf */
29063    memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
29064 
29065    ast_clear_flag(&global_flags[1], SIP_PAGE2_FAX_DETECT);
29066    ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
29067    ast_clear_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT);
29068    ast_clear_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION);
29069 
29070 
29071    /* Read the [general] config section of sip.conf (or from realtime config) */
29072    for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
29073       if (handle_common_options(&setflags[0], &mask[0], v)) {
29074          continue;
29075       }
29076       if (handle_t38_options(&setflags[0], &mask[0], v, &global_t38_maxdatagram)) {
29077          continue;
29078       }
29079       /* handle jb conf */
29080       if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
29081          continue;
29082 
29083       /* handle tls conf, don't allow setting of tlsverifyclient as it isn't supported by chan_sip */
29084       if (!strcasecmp(v->name, "tlsverifyclient")) {
29085          ast_log(LOG_WARNING, "Ignoring unsupported option 'tlsverifyclient'\n");
29086          continue;
29087       } else if (!ast_tls_read_conf(&default_tls_cfg, &sip_tls_desc, v->name, v->value)) {
29088          continue;
29089       }
29090 
29091       if (!strcasecmp(v->name, "context")) {
29092          ast_copy_string(sip_cfg.default_context, v->value, sizeof(sip_cfg.default_context));
29093       } else if (!strcasecmp(v->name, "subscribecontext")) {
29094          ast_copy_string(sip_cfg.default_subscribecontext, v->value, sizeof(sip_cfg.default_subscribecontext));
29095       } else if (!strcasecmp(v->name, "callcounter")) {
29096          global_callcounter = ast_true(v->value) ? 1 : 0;
29097       } else if (!strcasecmp(v->name, "allowguest")) {
29098          sip_cfg.allowguest = ast_true(v->value) ? 1 : 0;
29099       } else if (!strcasecmp(v->name, "realm")) {
29100          ast_copy_string(sip_cfg.realm, v->value, sizeof(sip_cfg.realm));
29101       } else if (!strcasecmp(v->name, "domainsasrealm")) {
29102          sip_cfg.domainsasrealm = ast_true(v->value);
29103       } else if (!strcasecmp(v->name, "useragent")) {
29104          ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
29105          ast_debug(1, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
29106       } else if (!strcasecmp(v->name, "sdpsession")) {
29107          ast_copy_string(global_sdpsession, v->value, sizeof(global_sdpsession));
29108       } else if (!strcasecmp(v->name, "sdpowner")) {
29109          /* Field cannot contain spaces */
29110          if (!strstr(v->value, " ")) {
29111             ast_copy_string(global_sdpowner, v->value, sizeof(global_sdpowner));
29112          } else {
29113             ast_log(LOG_WARNING, "'%s' must not contain spaces at line %d.  Using default.\n", v->value, v->lineno);
29114          }
29115       } else if (!strcasecmp(v->name, "allowtransfer")) {
29116          sip_cfg.allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
29117       } else if (!strcasecmp(v->name, "rtcachefriends")) {
29118          ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);
29119       } else if (!strcasecmp(v->name, "rtsavesysname")) {
29120          sip_cfg.rtsave_sysname = ast_true(v->value);
29121       } else if (!strcasecmp(v->name, "rtupdate")) {
29122          sip_cfg.peer_rtupdate = ast_true(v->value);
29123       } else if (!strcasecmp(v->name, "ignoreregexpire")) {
29124          sip_cfg.ignore_regexpire = ast_true(v->value);
29125       } else if (!strcasecmp(v->name, "timert1")) {
29126          /* Defaults to 500ms, but RFC 3261 states that it is recommended
29127           * for the value to be set higher, though a lower value is only
29128           * allowed on private networks unconnected to the Internet. */
29129          global_t1 = atoi(v->value);
29130       } else if (!strcasecmp(v->name, "timerb")) {
29131          int tmp = atoi(v->value);
29132          if (tmp < 500) {
29133             global_timer_b = global_t1 * 64;
29134             ast_log(LOG_WARNING, "Invalid value for timerb ('%s').  Setting to default ('%d').\n", v->value, global_timer_b);
29135          }
29136          timerb_set = 1;
29137       } else if (!strcasecmp(v->name, "t1min")) {
29138          global_t1min = atoi(v->value);
29139       } else if (!strcasecmp(v->name, "transport")) {
29140          char *val = ast_strdupa(v->value);
29141          char *trans;
29142 
29143          default_transports = default_primary_transport = 0;
29144          while ((trans = strsep(&val, ","))) {
29145             trans = ast_skip_blanks(trans);
29146 
29147             if (!strncasecmp(trans, "udp", 3)) {
29148                default_transports |= SIP_TRANSPORT_UDP;
29149             } else if (!strncasecmp(trans, "tcp", 3)) {
29150                default_transports |= SIP_TRANSPORT_TCP;
29151             } else if (!strncasecmp(trans, "tls", 3)) {
29152                default_transports |= SIP_TRANSPORT_TLS;
29153             } else {
29154                ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
29155             }
29156             if (default_primary_transport == 0) {
29157                default_primary_transport = default_transports;
29158             }
29159          }
29160       } else if (!strcasecmp(v->name, "tcpenable")) {
29161          if (!ast_false(v->value)) {
29162             ast_debug(2, "Enabling TCP socket for listening\n");
29163             sip_cfg.tcp_enabled = TRUE;
29164          }
29165       } else if (!strcasecmp(v->name, "tcpbindaddr")) {
29166          if (ast_parse_arg(v->value, PARSE_ADDR,
29167                  &sip_tcp_desc.local_address)) {
29168             ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
29169                v->name, v->value, v->lineno, config);
29170          }
29171          ast_debug(2, "Setting TCP socket address to %s\n",
29172               ast_sockaddr_stringify(&sip_tcp_desc.local_address));
29173       } else if (!strcasecmp(v->name, "dynamic_exclude_static") || !strcasecmp(v->name, "dynamic_excludes_static")) {
29174          global_dynamic_exclude_static = ast_true(v->value);
29175       } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
29176          int ha_error = 0;
29177          sip_cfg.contact_ha = ast_append_ha(v->name + 7, v->value, sip_cfg.contact_ha, &ha_error);
29178          if (ha_error) {
29179             ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
29180          }
29181       } else if (!strcasecmp(v->name, "rtautoclear")) {
29182          int i = atoi(v->value);
29183          if (i > 0) {
29184             sip_cfg.rtautoclear = i;
29185          } else {
29186             i = 0;
29187          }
29188          ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
29189       } else if (!strcasecmp(v->name, "usereqphone")) {
29190          ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);
29191       } else if (!strcasecmp(v->name, "prematuremedia")) {
29192          global_prematuremediafilter = ast_true(v->value);
29193       } else if (!strcasecmp(v->name, "relaxdtmf")) {
29194          global_relaxdtmf = ast_true(v->value);
29195       } else if (!strcasecmp(v->name, "vmexten")) {
29196          ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
29197       } else if (!strcasecmp(v->name, "rtptimeout")) {
29198          if ((sscanf(v->value, "%30d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
29199             ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
29200             global_rtptimeout = 0;
29201          }
29202       } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
29203          if ((sscanf(v->value, "%30d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
29204             ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
29205             global_rtpholdtimeout = 0;
29206          }
29207       } else if (!strcasecmp(v->name, "rtpkeepalive")) {
29208          if ((sscanf(v->value, "%30d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
29209             ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d.  Using default.\n", v->value, v->lineno);
29210             global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
29211          }
29212       } else if (!strcasecmp(v->name, "compactheaders")) {
29213          sip_cfg.compactheaders = ast_true(v->value);
29214       } else if (!strcasecmp(v->name, "notifymimetype")) {
29215          ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
29216       } else if (!strcasecmp(v->name, "directrtpsetup")) {
29217          sip_cfg.directrtpsetup = ast_true(v->value);
29218       } else if (!strcasecmp(v->name, "notifyringing")) {
29219          sip_cfg.notifyringing = ast_true(v->value);
29220       } else if (!strcasecmp(v->name, "notifyhold")) {
29221          sip_cfg.notifyhold = ast_true(v->value);
29222       } else if (!strcasecmp(v->name, "notifycid")) {
29223          if (!strcasecmp(v->value, "ignore-context")) {
29224             sip_cfg.notifycid = IGNORE_CONTEXT;
29225          } else {
29226             sip_cfg.notifycid = ast_true(v->value) ? ENABLED : DISABLED;
29227          }
29228       } else if (!strcasecmp(v->name, "alwaysauthreject")) {
29229          sip_cfg.alwaysauthreject = ast_true(v->value);
29230       } else if (!strcasecmp(v->name, "auth_options_requests")) {
29231          if (ast_true(v->value)) {
29232             sip_cfg.auth_options_requests = 1;
29233          }
29234       } else if (!strcasecmp(v->name, "mohinterpret")) {
29235          ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
29236       } else if (!strcasecmp(v->name, "mohsuggest")) {
29237          ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
29238       } else if (!strcasecmp(v->name, "language")) {
29239          ast_copy_string(default_language, v->value, sizeof(default_language));
29240       } else if (!strcasecmp(v->name, "regcontext")) {
29241          ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
29242          stringp = newcontexts;
29243          /* Let's remove any contexts that are no longer defined in regcontext */
29244          cleanup_stale_contexts(stringp, oldregcontext);
29245          /* Create contexts if they don't exist already */
29246          while ((context = strsep(&stringp, "&"))) {
29247             ast_copy_string(used_context, context, sizeof(used_context));
29248             ast_context_find_or_create(NULL, NULL, context, "SIP");
29249          }
29250          ast_copy_string(sip_cfg.regcontext, v->value, sizeof(sip_cfg.regcontext));
29251       } else if (!strcasecmp(v->name, "regextenonqualify")) {
29252          sip_cfg.regextenonqualify = ast_true(v->value);
29253       } else if (!strcasecmp(v->name, "legacy_useroption_parsing")) {
29254          sip_cfg.legacy_useroption_parsing = ast_true(v->value);
29255       } else if (!strcasecmp(v->name, "callerid")) {
29256          ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
29257       } else if (!strcasecmp(v->name, "mwi_from")) {
29258          ast_copy_string(default_mwi_from, v->value, sizeof(default_mwi_from));
29259       } else if (!strcasecmp(v->name, "fromdomain")) {
29260          char *fromdomainport;
29261          ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
29262          if ((fromdomainport = strchr(default_fromdomain, ':'))) {
29263             *fromdomainport++ = '\0';
29264             if (!(default_fromdomainport = port_str2int(fromdomainport, 0))) {
29265                ast_log(LOG_NOTICE, "'%s' is not a valid port number for fromdomain.\n",fromdomainport);
29266             }
29267          } else {
29268             default_fromdomainport = STANDARD_SIP_PORT;
29269          }
29270       } else if (!strcasecmp(v->name, "outboundproxy")) {
29271          struct sip_proxy *proxy;
29272          if (ast_strlen_zero(v->value)) {
29273             ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf\n", v->lineno);
29274             continue;
29275          }
29276          proxy = proxy_from_config(v->value, v->lineno, &sip_cfg.outboundproxy);
29277          if (!proxy) {
29278             ast_log(LOG_WARNING, "failure parsing the outbound proxy on line %d of sip.conf.\n", v->lineno);
29279             continue;
29280          }
29281       } else if (!strcasecmp(v->name, "autocreatepeer")) {
29282          sip_cfg.autocreatepeer = ast_true(v->value);
29283       } else if (!strcasecmp(v->name, "match_auth_username")) {
29284          global_match_auth_username = ast_true(v->value);
29285       } else if (!strcasecmp(v->name, "srvlookup")) {
29286          sip_cfg.srvlookup = ast_true(v->value);
29287       } else if (!strcasecmp(v->name, "pedantic")) {
29288          sip_cfg.pedanticsipchecking = ast_true(v->value);
29289       } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
29290          max_expiry = atoi(v->value);
29291          if (max_expiry < 1) {
29292             max_expiry = DEFAULT_MAX_EXPIRY;
29293          }
29294       } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
29295          min_expiry = atoi(v->value);
29296          if (min_expiry < 1) {
29297             min_expiry = DEFAULT_MIN_EXPIRY;
29298          }
29299       } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
29300          default_expiry = atoi(v->value);
29301          if (default_expiry < 1) {
29302             default_expiry = DEFAULT_DEFAULT_EXPIRY;
29303          }
29304       } else if (!strcasecmp(v->name, "mwiexpiry") || !strcasecmp(v->name, "mwiexpirey")) {
29305          mwi_expiry = atoi(v->value);
29306          if (mwi_expiry < 1) {
29307             mwi_expiry = DEFAULT_MWI_EXPIRY;
29308          }
29309       } else if (!strcasecmp(v->name, "tcpauthtimeout")) {
29310          if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
29311                  &authtimeout, DEFAULT_AUTHTIMEOUT, 1, INT_MAX)) {
29312             ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
29313                v->name, v->value, v->lineno, config);
29314          }
29315       } else if (!strcasecmp(v->name, "tcpauthlimit")) {
29316          if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
29317                  &authlimit, DEFAULT_AUTHLIMIT, 1, INT_MAX)) {
29318             ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
29319                v->name, v->value, v->lineno, config);
29320          }
29321       } else if (!strcasecmp(v->name, "sipdebug")) {
29322          if (ast_true(v->value))
29323             sipdebug |= sip_debug_config;
29324       } else if (!strcasecmp(v->name, "dumphistory")) {
29325          dumphistory = ast_true(v->value);
29326       } else if (!strcasecmp(v->name, "recordhistory")) {
29327          recordhistory = ast_true(v->value);
29328       } else if (!strcasecmp(v->name, "registertimeout")) {
29329          global_reg_timeout = atoi(v->value);
29330          if (global_reg_timeout < 1) {
29331             global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
29332          }
29333       } else if (!strcasecmp(v->name, "registerattempts")) {
29334          global_regattempts_max = atoi(v->value);
29335       } else if (!strcasecmp(v->name, "register_retry_403")) {
29336          global_reg_retry_403 = ast_true(v->value);
29337       } else if (!strcasecmp(v->name, "bindaddr") || !strcasecmp(v->name, "udpbindaddr")) {
29338          if (ast_parse_arg(v->value, PARSE_ADDR, &bindaddr)) {
29339             ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
29340          }
29341       } else if (!strcasecmp(v->name, "localnet")) {
29342          struct ast_ha *na;
29343          int ha_error = 0;
29344 
29345          if (!(na = ast_append_ha("d", v->value, localaddr, &ha_error))) {
29346             ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
29347          } else {
29348             localaddr = na;
29349          }
29350          if (ha_error) {
29351             ast_log(LOG_ERROR, "Bad localnet configuration value line %d : %s\n", v->lineno, v->value);
29352          }
29353       } else if (!strcasecmp(v->name, "media_address")) {
29354          if (ast_parse_arg(v->value, PARSE_ADDR, &media_address))
29355             ast_log(LOG_WARNING, "Invalid address for media_address keyword: %s\n", v->value);
29356       } else if (!strcasecmp(v->name, "externaddr") || !strcasecmp(v->name, "externip")) {
29357          if (ast_parse_arg(v->value, PARSE_ADDR, &externaddr)) {
29358             ast_log(LOG_WARNING,
29359                "Invalid address for externaddr keyword: %s\n",
29360                v->value);
29361          }
29362          externexpire = 0;
29363       } else if (!strcasecmp(v->name, "externhost")) {
29364          ast_copy_string(externhost, v->value, sizeof(externhost));
29365          if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
29366             ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
29367          }
29368          externexpire = time(NULL);
29369       } else if (!strcasecmp(v->name, "externrefresh")) {
29370          if (sscanf(v->value, "%30d", &externrefresh) != 1) {
29371             ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
29372             externrefresh = 10;
29373          }
29374       } else if (!strcasecmp(v->name, "externtcpport")) {
29375          if (!(externtcpport = port_str2int(v->value, 0))) {
29376             ast_log(LOG_WARNING, "Invalid externtcpport value, must be a positive integer between 1 and 65535 at line %d\n", v->lineno);
29377             externtcpport = 0;
29378          }
29379       } else if (!strcasecmp(v->name, "externtlsport")) {
29380          if (!(externtlsport = port_str2int(v->value, STANDARD_TLS_PORT))) {
29381             ast_log(LOG_WARNING, "Invalid externtlsport value, must be a positive integer between 1 and 65535 at line %d\n", v->lineno);
29382          }
29383       } else if (!strcasecmp(v->name, "allow")) {
29384          int error =  ast_parse_allow_disallow(&default_prefs, &sip_cfg.capability, v->value, TRUE);
29385          if (error) {
29386             ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
29387          }
29388       } else if (!strcasecmp(v->name, "disallow")) {
29389          int error =  ast_parse_allow_disallow(&default_prefs, &sip_cfg.capability, v->value, FALSE);
29390          if (error) {
29391             ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
29392          }
29393       } else if (!strcasecmp(v->name, "preferred_codec_only")) {
29394          ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_PREFERRED_CODEC);
29395       } else if (!strcasecmp(v->name, "autoframing")) {
29396          global_autoframing = ast_true(v->value);
29397       } else if (!strcasecmp(v->name, "allowexternaldomains")) {
29398          sip_cfg.allow_external_domains = ast_true(v->value);
29399       } else if (!strcasecmp(v->name, "autodomain")) {
29400          auto_sip_domains = ast_true(v->value);
29401       } else if (!strcasecmp(v->name, "domain")) {
29402          char *domain = ast_strdupa(v->value);
29403          char *cntx = strchr(domain, ',');
29404 
29405          if (cntx) {
29406             *cntx++ = '\0';
29407          }
29408 
29409          if (ast_strlen_zero(cntx)) {
29410             ast_debug(1, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
29411          }
29412          if (ast_strlen_zero(domain)) {
29413             ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
29414          } else {
29415             add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, cntx ? ast_strip(cntx) : "");
29416          }
29417       } else if (!strcasecmp(v->name, "register")) {
29418          if (sip_register(v->value, v->lineno) == 0) {
29419             registry_count++;
29420          }
29421       } else if (!strcasecmp(v->name, "mwi")) {
29422          sip_subscribe_mwi(v->value, v->lineno);
29423       } else if (!strcasecmp(v->name, "tos_sip")) {
29424          if (ast_str2tos(v->value, &global_tos_sip)) {
29425             ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, refer to QoS documentation\n", v->lineno);
29426          }
29427       } else if (!strcasecmp(v->name, "tos_audio")) {
29428          if (ast_str2tos(v->value, &global_tos_audio)) {
29429             ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, refer to QoS documentation\n", v->lineno);
29430          }
29431       } else if (!strcasecmp(v->name, "tos_video")) {
29432          if (ast_str2tos(v->value, &global_tos_video)) {
29433             ast_log(LOG_WARNING, "Invalid tos_video value at line %d, refer to QoS documentation\n", v->lineno);
29434          }
29435       } else if (!strcasecmp(v->name, "tos_text")) {
29436          if (ast_str2tos(v->value, &global_tos_text)) {
29437             ast_log(LOG_WARNING, "Invalid tos_text value at line %d, refer to QoS documentation\n", v->lineno);
29438          }
29439       } else if (!strcasecmp(v->name, "cos_sip")) {
29440          if (ast_str2cos(v->value, &global_cos_sip)) {
29441             ast_log(LOG_WARNING, "Invalid cos_sip value at line %d, refer to QoS documentation\n", v->lineno);
29442          }
29443       } else if (!strcasecmp(v->name, "cos_audio")) {
29444          if (ast_str2cos(v->value, &global_cos_audio)) {
29445             ast_log(LOG_WARNING, "Invalid cos_audio value at line %d, refer to QoS documentation\n", v->lineno);
29446          }
29447       } else if (!strcasecmp(v->name, "cos_video")) {
29448          if (ast_str2cos(v->value, &global_cos_video)) {
29449             ast_log(LOG_WARNING, "Invalid cos_video value at line %d, refer to QoS documentation\n", v->lineno);
29450          }
29451       } else if (!strcasecmp(v->name, "cos_text")) {
29452          if (ast_str2cos(v->value, &global_cos_text)) {
29453             ast_log(LOG_WARNING, "Invalid cos_text value at line %d, refer to QoS documentation\n", v->lineno);
29454          }
29455       } else if (!strcasecmp(v->name, "bindport")) {
29456          if (sscanf(v->value, "%5d", &bindport) != 1) {
29457             ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
29458          }
29459       } else if (!strcasecmp(v->name, "qualify")) {
29460          if (!strcasecmp(v->value, "no")) {
29461             default_qualify = 0;
29462          } else if (!strcasecmp(v->value, "yes")) {
29463             default_qualify = DEFAULT_MAXMS;
29464          } else if (sscanf(v->value, "%30d", &default_qualify) != 1) {
29465             ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
29466             default_qualify = 0;
29467          }
29468       } else if (!strcasecmp(v->name, "qualifyfreq")) {
29469          int i;
29470          if (sscanf(v->value, "%30d", &i) == 1) {
29471             global_qualifyfreq = i * 1000;
29472          } else {
29473             ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
29474             global_qualifyfreq = DEFAULT_QUALIFYFREQ;
29475          }
29476       } else if (!strcasecmp(v->name, "callevents")) {
29477          sip_cfg.callevents = ast_true(v->value);
29478       } else if (!strcasecmp(v->name, "authfailureevents")) {
29479          global_authfailureevents = ast_true(v->value);
29480       } else if (!strcasecmp(v->name, "maxcallbitrate")) {
29481          default_maxcallbitrate = atoi(v->value);
29482          if (default_maxcallbitrate < 0)
29483             default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
29484       } else if (!strcasecmp(v->name, "matchexternaddrlocally") || !strcasecmp(v->name, "matchexterniplocally")) {
29485          sip_cfg.matchexternaddrlocally = ast_true(v->value);
29486       } else if (!strcasecmp(v->name, "session-timers")) {
29487          int i = (int) str2stmode(v->value);
29488          if (i < 0) {
29489             ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
29490             global_st_mode = SESSION_TIMER_MODE_ACCEPT;
29491          } else {
29492             global_st_mode = i;
29493          }
29494       } else if (!strcasecmp(v->name, "session-expires")) {
29495          if (sscanf(v->value, "%30d", &global_max_se) != 1) {
29496             ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
29497             global_max_se = DEFAULT_MAX_SE;
29498          }
29499       } else if (!strcasecmp(v->name, "session-minse")) {
29500          if (sscanf(v->value, "%30d", &global_min_se) != 1) {
29501             ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
29502             global_min_se = DEFAULT_MIN_SE;
29503          }
29504          if (global_min_se < DEFAULT_MIN_SE) {
29505             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);
29506             global_min_se = DEFAULT_MIN_SE;
29507          }
29508       } else if (!strcasecmp(v->name, "session-refresher")) {
29509          int i = (int) str2strefresherparam(v->value);
29510          if (i < 0) {
29511             ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
29512             global_st_refresher = SESSION_TIMER_REFRESHER_PARAM_UAS;
29513          } else {
29514             global_st_refresher = i;
29515          }
29516       } else if (!strcasecmp(v->name, "storesipcause")) {
29517          global_store_sip_cause = ast_true(v->value);
29518       } else if (!strcasecmp(v->name, "qualifygap")) {
29519          if (sscanf(v->value, "%30d", &global_qualify_gap) != 1) {
29520             ast_log(LOG_WARNING, "Invalid qualifygap '%s' at line %d of %s\n", v->value, v->lineno, config);
29521             global_qualify_gap = DEFAULT_QUALIFY_GAP;
29522          }
29523       } else if (!strcasecmp(v->name, "qualifypeers")) {
29524          if (sscanf(v->value, "%30d", &global_qualify_peers) != 1) {
29525             ast_log(LOG_WARNING, "Invalid pokepeers '%s' at line %d of %s\n", v->value, v->lineno, config);
29526             global_qualify_peers = DEFAULT_QUALIFY_PEERS;
29527          }
29528       } else if (!strcasecmp(v->name, "disallowed_methods")) {
29529          char *disallow = ast_strdupa(v->value);
29530          mark_parsed_methods(&sip_cfg.disallowed_methods, disallow);
29531       } else if (!strcasecmp(v->name, "shrinkcallerid")) {
29532          if (ast_true(v->value)) {
29533             global_shrinkcallerid = 1;
29534          } else if (ast_false(v->value)) {
29535             global_shrinkcallerid = 0;
29536          } else {
29537             ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
29538          }
29539       } else if (!strcasecmp(v->name, "use_q850_reason")) {
29540          ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_Q850_REASON);
29541       } else if (!strcasecmp(v->name, "maxforwards")) {
29542          if (sscanf(v->value, "%30d", &sip_cfg.default_max_forwards) != 1
29543             || sip_cfg.default_max_forwards < 1 || 255 < sip_cfg.default_max_forwards) {
29544             ast_log(LOG_WARNING, "'%s' is not a valid maxforwards value at line %d.  Using default.\n", v->value, v->lineno);
29545             sip_cfg.default_max_forwards = DEFAULT_MAX_FORWARDS;
29546          }
29547       } else if (!strcasecmp(v->name, "subscribe_network_change_event")) {
29548          if (ast_true(v->value)) {
29549             subscribe_network_change = 1;
29550          } else if (ast_false(v->value)) {
29551             subscribe_network_change = 0;
29552          } else {
29553             ast_log(LOG_WARNING, "subscribe_network_change_event value %s is not valid at line %d.\n", v->value, v->lineno);
29554          }
29555       } else if (!strcasecmp(v->name, "snom_aoc_enabled")) {
29556          ast_set2_flag(&global_flags[2], ast_true(v->value), SIP_PAGE3_SNOM_AOC);
29557       } else if (!strcasecmp(v->name, "parkinglot")) {
29558          ast_copy_string(default_parkinglot, v->value, sizeof(default_parkinglot));
29559       }
29560    }
29561 
29562    /* Override global defaults if setting found in general section */
29563    ast_copy_flags(&global_flags[0], &setflags[0], mask[0].flags);
29564    ast_copy_flags(&global_flags[1], &setflags[1], mask[1].flags);
29565    ast_copy_flags(&global_flags[2], &setflags[2], mask[2].flags);
29566 
29567    if (subscribe_network_change) {
29568       network_change_event_subscribe();
29569    } else {
29570       network_change_event_unsubscribe();
29571    }
29572 
29573    if (global_t1 < global_t1min) {
29574       ast_log(LOG_WARNING, "'t1min' (%d) cannot be greater than 't1timer' (%d).  Resetting 't1timer' to the value of 't1min'\n", global_t1min, global_t1);
29575       global_t1 = global_t1min;
29576    }
29577 
29578    if (global_timer_b < global_t1 * 64) {
29579       if (timerb_set && timert1_set) {
29580          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);
29581       } else if (timerb_set) {
29582          if ((global_t1 = global_timer_b / 64) < global_t1min) {
29583             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);
29584             global_t1 = global_t1min;
29585             global_timer_b = global_t1 * 64;
29586          }
29587       } else {
29588          global_timer_b = global_t1 * 64;
29589       }
29590    }
29591    if (!sip_cfg.allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
29592       ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
29593       sip_cfg.allow_external_domains = 1;
29594    }
29595    /* If not or badly configured, set default transports */
29596    if (!sip_cfg.tcp_enabled && (default_transports & SIP_TRANSPORT_TCP)) {
29597       ast_log(LOG_WARNING, "Cannot use 'tcp' transport with tcpenable=no. Removing from available transports.\n");
29598       default_primary_transport &= ~SIP_TRANSPORT_TCP;
29599       default_transports &= ~SIP_TRANSPORT_TCP;
29600    }
29601    if (!default_tls_cfg.enabled && (default_transports & SIP_TRANSPORT_TLS)) {
29602       ast_log(LOG_WARNING, "Cannot use 'tls' transport with tlsenable=no. Removing from available transports.\n");
29603       default_primary_transport &= ~SIP_TRANSPORT_TLS;
29604       default_transports &= ~SIP_TRANSPORT_TLS;
29605    }
29606    if (!default_transports) {
29607       ast_log(LOG_WARNING, "No valid transports available, falling back to 'udp'.\n");
29608       default_transports = default_primary_transport = SIP_TRANSPORT_UDP;
29609    } else if (!default_primary_transport) {
29610       ast_log(LOG_WARNING, "No valid default transport. Selecting 'udp' as default.\n");
29611       default_primary_transport = SIP_TRANSPORT_UDP;
29612    }
29613 
29614    /* Build list of authentication to various SIP realms, i.e. service providers */
29615    for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
29616       /* Format for authentication is auth = username:password@realm */
29617       if (!strcasecmp(v->name, "auth")) {
29618          add_realm_authentication(&authl, v->value, v->lineno);
29619       }
29620    }
29621 
29622    if (bindport) {
29623       if (ast_sockaddr_port(&bindaddr)) {
29624          ast_log(LOG_WARNING, "bindport is also specified in bindaddr. "
29625             "Using %d.\n", bindport);
29626       }
29627       ast_sockaddr_set_port(&bindaddr, bindport);
29628    }
29629 
29630    if (!ast_sockaddr_port(&bindaddr)) {
29631       ast_sockaddr_set_port(&bindaddr, STANDARD_SIP_PORT);
29632    }
29633 
29634    /* Set UDP address and open socket */
29635    ast_sockaddr_copy(&internip, &bindaddr);
29636    if (ast_find_ourip(&internip, &bindaddr, 0)) {
29637       ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
29638       ast_config_destroy(cfg);
29639       return 0;
29640    }
29641 
29642    ast_mutex_lock(&netlock);
29643    if ((sipsock > -1) && (ast_sockaddr_cmp(&old_bindaddr, &bindaddr))) {
29644       close(sipsock);
29645       sipsock = -1;
29646    }
29647    if (sipsock < 0) {
29648       sipsock = socket(ast_sockaddr_is_ipv6(&bindaddr) ?
29649              AF_INET6 : AF_INET, SOCK_DGRAM, 0);
29650       if (sipsock < 0) {
29651          ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
29652          ast_config_destroy(cfg);
29653          ast_mutex_unlock(&netlock);
29654          return -1;
29655       } else {
29656          /* Allow SIP clients on the same host to access us: */
29657          const int reuseFlag = 1;
29658 
29659          setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
29660                (const char*)&reuseFlag,
29661                sizeof reuseFlag);
29662 
29663          ast_enable_packet_fragmentation(sipsock);
29664 
29665          if (ast_bind(sipsock, &bindaddr) < 0) {
29666             ast_log(LOG_WARNING, "Failed to bind to %s: %s\n",
29667                ast_sockaddr_stringify(&bindaddr), strerror(errno));
29668             close(sipsock);
29669             sipsock = -1;
29670          } else {
29671             ast_verb(2, "SIP Listening on %s\n", ast_sockaddr_stringify(&bindaddr));
29672             ast_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
29673          }
29674       }
29675    } else {
29676       ast_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
29677    }
29678    ast_mutex_unlock(&netlock);
29679 
29680    /* Start TCP server */
29681    if (sip_cfg.tcp_enabled) {
29682       if (ast_sockaddr_isnull(&sip_tcp_desc.local_address)) {
29683          ast_sockaddr_copy(&sip_tcp_desc.local_address, &bindaddr);
29684       }
29685       if (!ast_sockaddr_port(&sip_tcp_desc.local_address)) {
29686          ast_sockaddr_set_port(&sip_tcp_desc.local_address, STANDARD_SIP_PORT);
29687       }
29688    } else {
29689       ast_sockaddr_setnull(&sip_tcp_desc.local_address);
29690    }
29691    ast_tcptls_server_start(&sip_tcp_desc);
29692    if (sip_cfg.tcp_enabled && sip_tcp_desc.accept_fd == -1) {
29693       /* TCP server start failed. Tell the admin */
29694       ast_log(LOG_ERROR, "SIP TCP Server start failed. Not listening on TCP socket.\n");
29695    } else {
29696       ast_debug(2, "SIP TCP server started\n");
29697    }
29698 
29699    /* Start TLS server if needed */
29700    memcpy(sip_tls_desc.tls_cfg, &default_tls_cfg, sizeof(default_tls_cfg));
29701 
29702    if (ast_ssl_setup(sip_tls_desc.tls_cfg)) {
29703       if (ast_sockaddr_isnull(&sip_tls_desc.local_address)) {
29704          ast_sockaddr_copy(&sip_tls_desc.local_address, &bindaddr);
29705          ast_sockaddr_set_port(&sip_tls_desc.local_address,
29706                      STANDARD_TLS_PORT);
29707       }
29708       if (!ast_sockaddr_port(&sip_tls_desc.local_address)) {
29709          ast_sockaddr_set_port(&sip_tls_desc.local_address,
29710                      STANDARD_TLS_PORT);
29711       }
29712       ast_tcptls_server_start(&sip_tls_desc);
29713       if (default_tls_cfg.enabled && sip_tls_desc.accept_fd == -1) {
29714          ast_log(LOG_ERROR, "TLS Server start failed. Not listening on TLS socket.\n");
29715          sip_tls_desc.tls_cfg = NULL;
29716       }
29717    } else if (sip_tls_desc.tls_cfg->enabled) {
29718       sip_tls_desc.tls_cfg = NULL;
29719       ast_log(LOG_WARNING, "SIP TLS server did not load because of errors.\n");
29720    }
29721 
29722    if (ucfg) {
29723       struct ast_variable *gen;
29724       int genhassip, genregistersip;
29725       const char *hassip, *registersip;
29726       
29727       genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
29728       genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
29729       gen = ast_variable_browse(ucfg, "general");
29730       cat = ast_category_browse(ucfg, NULL);
29731       while (cat) {
29732          if (strcasecmp(cat, "general")) {
29733             hassip = ast_variable_retrieve(ucfg, cat, "hassip");
29734             registersip = ast_variable_retrieve(ucfg, cat, "registersip");
29735             if (ast_true(hassip) || (!hassip && genhassip)) {
29736                peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0, 0);
29737                if (peer) {
29738                   /* user.conf entries are always of type friend */
29739                   peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
29740                   ao2_t_link(peers, peer, "link peer into peer table");
29741                   if ((peer->type & SIP_TYPE_PEER) && !ast_sockaddr_isnull(&peer->addr)) {
29742                      ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
29743                   }
29744                   
29745                   unref_peer(peer, "unref_peer: from reload_config");
29746                   peer_count++;
29747                }
29748             }
29749             if (ast_true(registersip) || (!registersip && genregistersip)) {
29750                char tmp[256];
29751                const char *host = ast_variable_retrieve(ucfg, cat, "host");
29752                const char *username = ast_variable_retrieve(ucfg, cat, "username");
29753                const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
29754                const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
29755                const char *authuser = ast_variable_retrieve(ucfg, cat, "authuser");
29756                if (!host) {
29757                   host = ast_variable_retrieve(ucfg, "general", "host");
29758                }
29759                if (!username) {
29760                   username = ast_variable_retrieve(ucfg, "general", "username");
29761                }
29762                if (!secret) {
29763                   secret = ast_variable_retrieve(ucfg, "general", "secret");
29764                }
29765                if (!contact) {
29766                   contact = "s";
29767                }
29768                if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
29769                   if (!ast_strlen_zero(secret)) {
29770                      if (!ast_strlen_zero(authuser)) {
29771                         snprintf(tmp, sizeof(tmp), "%s?%s:%s:%s@%s/%s", cat, username, secret, authuser, host, contact);
29772                      } else {
29773                         snprintf(tmp, sizeof(tmp), "%s?%s:%s@%s/%s", cat, username, secret, host, contact);
29774                      }
29775                   } else if (!ast_strlen_zero(authuser)) {
29776                      snprintf(tmp, sizeof(tmp), "%s?%s::%s@%s/%s", cat, username, authuser, host, contact);
29777                   } else {
29778                      snprintf(tmp, sizeof(tmp), "%s?%s@%s/%s", cat, username, host, contact);
29779                   }
29780                   if (sip_register(tmp, 0) == 0) {
29781                      registry_count++;
29782                   }
29783                }
29784             }
29785          }
29786          cat = ast_category_browse(ucfg, cat);
29787       }
29788       ast_config_destroy(ucfg);
29789    }
29790 
29791    /* Load peers, users and friends */
29792    cat = NULL;
29793    while ( (cat = ast_category_browse(cfg, cat)) ) {
29794       const char *utype;
29795       if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
29796          continue;
29797       utype = ast_variable_retrieve(cfg, cat, "type");
29798       if (!utype) {
29799          ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
29800          continue;
29801       } else {
29802          if (!strcasecmp(utype, "user")) {
29803             ;
29804          } else if (!strcasecmp(utype, "friend")) {
29805             ;
29806          } else if (!strcasecmp(utype, "peer")) {
29807             ;
29808          } else {
29809             ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
29810             continue;
29811          }
29812          peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0, 0);
29813          if (peer) {
29814             display_nat_warning(cat, reason, &peer->flags[0]);
29815             ao2_t_link(peers, peer, "link peer into peers table");
29816             if ((peer->type & SIP_TYPE_PEER) && !ast_sockaddr_isnull(&peer->addr)) {
29817                ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
29818             }
29819             unref_peer(peer, "unref the result of the build_peer call. Now, the links from the tables are the only ones left.");
29820             peer_count++;
29821          }
29822       }
29823    }
29824 
29825    /* Add default domains - host name, IP address and IP:port
29826     * Only do this if user added any sip domain with "localdomains"
29827     * In order to *not* break backwards compatibility
29828     *    Some phones address us at IP only, some with additional port number
29829     */
29830    if (auto_sip_domains) {
29831       char temp[MAXHOSTNAMELEN];
29832 
29833       /* First our default IP address */
29834       if (!ast_sockaddr_isnull(&bindaddr) && !ast_sockaddr_is_any(&bindaddr)) {
29835          add_sip_domain(ast_sockaddr_stringify_addr(&bindaddr),
29836                    SIP_DOMAIN_AUTO, NULL);
29837       } else if (!ast_sockaddr_isnull(&internip) && !ast_sockaddr_is_any(&internip)) {
29838       /* Our internal IP address, if configured */
29839          add_sip_domain(ast_sockaddr_stringify_addr(&internip),
29840                    SIP_DOMAIN_AUTO, NULL);
29841       } else {
29842          ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
29843       }
29844 
29845       /* If TCP is running on a different IP than UDP, then add it too */
29846       if (!ast_sockaddr_isnull(&sip_tcp_desc.local_address) &&
29847           !ast_sockaddr_cmp(&bindaddr, &sip_tcp_desc.local_address)) {
29848          add_sip_domain(ast_sockaddr_stringify_addr(&sip_tcp_desc.local_address),
29849                    SIP_DOMAIN_AUTO, NULL);
29850       }
29851 
29852       /* If TLS is running on a different IP than UDP and TCP, then add that too */
29853       if (!ast_sockaddr_isnull(&sip_tls_desc.local_address) &&
29854           !ast_sockaddr_cmp(&bindaddr, &sip_tls_desc.local_address) &&
29855           !ast_sockaddr_cmp(&sip_tcp_desc.local_address,
29856                   &sip_tls_desc.local_address)) {
29857          add_sip_domain(ast_sockaddr_stringify_addr(&sip_tcp_desc.local_address),
29858                    SIP_DOMAIN_AUTO, NULL);
29859       }
29860 
29861       /* Our extern IP address, if configured */
29862       if (!ast_sockaddr_isnull(&externaddr)) {
29863          add_sip_domain(ast_sockaddr_stringify_addr(&externaddr),
29864                    SIP_DOMAIN_AUTO, NULL);
29865       }
29866 
29867       /* Extern host name (NAT traversal support) */
29868       if (!ast_strlen_zero(externhost)) {
29869          add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
29870       }
29871       
29872       /* Our host name */
29873       if (!gethostname(temp, sizeof(temp))) {
29874          add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
29875       }
29876    }
29877 
29878    /* Release configuration from memory */
29879    ast_config_destroy(cfg);
29880 
29881    /* Load the list of manual NOTIFY types to support */
29882    if (notify_types)
29883       ast_config_destroy(notify_types);
29884    if ((notify_types = ast_config_load(notify_config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
29885       ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed.\n", notify_config);
29886       notify_types = NULL;
29887    }
29888 
29889    /* Done, tell the manager */
29890    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);
29891    run_end = time(0);
29892    ast_debug(4, "SIP reload_config done...Runtime= %d sec\n", (int)(run_end-run_start));
29893 
29894    return 0;
29895 }
29896 
29897 static int apply_directmedia_ha(struct sip_pvt *p1, struct sip_pvt *p2, const char *op)
29898 {
29899    struct ast_sockaddr us = { { 0, }, }, them = { { 0, }, };
29900    int res = AST_SENSE_ALLOW;
29901 
29902    ast_rtp_instance_get_remote_address(p1->rtp, &them);
29903    ast_rtp_instance_get_local_address(p1->rtp, &us);
29904 
29905    /* If p2 is a guest call, there will be no peer. If there is no peer, there
29906     * is no directmediaha, so go ahead and allow it */
29907    if (!p2->relatedpeer) {
29908       return res;
29909    }
29910 
29911    if ((res = ast_apply_ha(p2->relatedpeer->directmediaha, &them)) == AST_SENSE_DENY) {
29912       const char *us_addr = ast_strdupa(ast_sockaddr_stringify(&us));
29913       const char *them_addr = ast_strdupa(ast_sockaddr_stringify(&them));
29914 
29915       ast_debug(3, "Reinvite %s to %s denied by directmedia ACL on %s\n",
29916          op, them_addr, us_addr);
29917    }
29918 
29919    return res;
29920 }
29921 
29922 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan)
29923 {
29924    struct sip_pvt *p;
29925    struct ast_channel *opp_chan;
29926    struct sip_pvt *opp;
29927    struct ast_udptl *udptl = NULL;
29928 
29929    p = chan->tech_pvt;
29930    if (!p) {
29931       return NULL;
29932    }
29933 
29934    if (!(opp_chan = ast_bridged_channel(chan))) {
29935       return NULL;
29936    } else if (((opp_chan->tech != &sip_tech) && (opp_chan->tech != &sip_tech_info)) ||
29937          (!(opp = opp_chan->tech_pvt))) {
29938       return NULL;
29939    }
29940 
29941    sip_pvt_lock(p);
29942    while (sip_pvt_trylock(opp)) {
29943       sip_pvt_unlock(p);
29944       usleep(1);
29945       sip_pvt_lock(p);
29946    }
29947 
29948    if (p->udptl && ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
29949       if (apply_directmedia_ha(p, opp, "UDPTL T.38 data")) {
29950          udptl = p->udptl;
29951       }
29952    }
29953 
29954    sip_pvt_unlock(opp);
29955    sip_pvt_unlock(p);
29956    return udptl;
29957 }
29958 
29959 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl)
29960 {
29961    struct sip_pvt *p;
29962 
29963    /* Lock the channel and the private safely. */
29964    ast_channel_lock(chan);
29965    p = chan->tech_pvt;
29966    if (!p) {
29967       ast_channel_unlock(chan);
29968       return -1;
29969    }
29970    sip_pvt_lock(p);
29971    if (p->owner != chan) {
29972       /* I suppose it could be argued that if this happens it is a bug. */
29973       ast_debug(1, "The private is not owned by channel %s anymore.\n", chan->name);
29974       sip_pvt_unlock(p);
29975       ast_channel_unlock(chan);
29976       return 0;
29977    }
29978 
29979    if (udptl) {
29980       ast_udptl_get_peer(udptl, &p->udptlredirip);
29981    } else {
29982       memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
29983    }
29984    if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
29985       if (!p->pendinginvite) {
29986          ast_debug(3, "Sending reinvite on SIP '%s' - It's UDPTL soon redirected to IP %s\n",
29987                p->callid, ast_sockaddr_stringify(udptl ? &p->udptlredirip : &p->ourip));
29988          transmit_reinvite_with_sdp(p, TRUE, FALSE);
29989       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
29990          ast_debug(3, "Deferring reinvite on SIP '%s' - It's UDPTL will be redirected to IP %s\n",
29991                p->callid, ast_sockaddr_stringify(udptl ? &p->udptlredirip : &p->ourip));
29992          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
29993       }
29994    }
29995    /* Reset lastrtprx timer */
29996    p->lastrtprx = p->lastrtptx = time(NULL);
29997    sip_pvt_unlock(p);
29998    ast_channel_unlock(chan);
29999    return 0;
30000 }
30001 
30002 static enum ast_rtp_glue_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
30003 {
30004    struct sip_pvt *p = NULL;
30005    struct ast_channel *opp_chan;
30006    struct sip_pvt *opp = NULL;
30007    enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_LOCAL;
30008 
30009    if (!(p = chan->tech_pvt)) {
30010       return AST_RTP_GLUE_RESULT_FORBID;
30011    }
30012 
30013    if ((opp_chan = ast_bridged_channel(chan)) && (((opp_chan->tech != &sip_tech) && (opp_chan->tech != &sip_tech_info)) ||
30014                          (!(opp = opp_chan->tech_pvt)))) {
30015       return AST_RTP_GLUE_RESULT_FORBID;
30016    }
30017 
30018    sip_pvt_lock(p);
30019    while (opp && sip_pvt_trylock(opp)) {
30020       sip_pvt_unlock(p);
30021       usleep(1);
30022       sip_pvt_lock(p);
30023    }
30024 
30025    if (!(p->rtp)) {
30026       if (opp) {
30027          sip_pvt_unlock(opp);
30028       }
30029       sip_pvt_unlock(p);
30030       return AST_RTP_GLUE_RESULT_FORBID;
30031    }
30032 
30033    ao2_ref(p->rtp, +1);
30034    *instance = p->rtp;
30035 
30036    if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
30037       res = AST_RTP_GLUE_RESULT_REMOTE;
30038       if (opp && !apply_directmedia_ha(p, opp, "audio")) {
30039          res = AST_RTP_GLUE_RESULT_FORBID;
30040       }
30041    } else if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT)) {
30042       res = AST_RTP_GLUE_RESULT_REMOTE;
30043    } else if (ast_test_flag(&global_jbconf, AST_JB_FORCED)) {
30044       res = AST_RTP_GLUE_RESULT_FORBID;
30045    }
30046 
30047    if (opp) {
30048       sip_pvt_unlock(opp);
30049    }
30050 
30051    if (p->srtp) {
30052       res = AST_RTP_GLUE_RESULT_FORBID;
30053    }
30054 
30055    sip_pvt_unlock(p);
30056 
30057    return res;
30058 }
30059 
30060 static enum ast_rtp_glue_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
30061 {
30062    struct sip_pvt *p = NULL;
30063    struct ast_channel *opp_chan;
30064    struct sip_pvt *opp = NULL;
30065    enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_FORBID;
30066 
30067    if (!(p = chan->tech_pvt)) {
30068       return AST_RTP_GLUE_RESULT_FORBID;
30069    }
30070 
30071    if ((opp_chan = ast_bridged_channel(chan)) && (((opp_chan->tech != &sip_tech) && (opp_chan->tech != &sip_tech_info)) ||
30072                          (!(opp = opp_chan->tech_pvt)))) {
30073       return AST_RTP_GLUE_RESULT_FORBID;
30074    }
30075 
30076    sip_pvt_lock(p);
30077    while (opp && sip_pvt_trylock(opp)) {
30078       sip_pvt_unlock(p);
30079       usleep(1);
30080       sip_pvt_lock(p);
30081    }
30082 
30083    if (!(p->vrtp)) {
30084       if (opp) {
30085          sip_pvt_unlock(opp);
30086       }
30087       sip_pvt_unlock(p);
30088       return AST_RTP_GLUE_RESULT_FORBID;
30089    }
30090 
30091    ao2_ref(p->vrtp, +1);
30092    *instance = p->vrtp;
30093 
30094    if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
30095       res = AST_RTP_GLUE_RESULT_REMOTE;
30096       if (opp && !apply_directmedia_ha(p, opp, "video")) {
30097          res = AST_RTP_GLUE_RESULT_FORBID;
30098       }
30099    }
30100 
30101    if (opp) {
30102       sip_pvt_unlock(opp);
30103    }
30104    sip_pvt_unlock(p);
30105 
30106    return res;
30107 }
30108 
30109 static enum ast_rtp_glue_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
30110 {
30111    struct sip_pvt *p = NULL;
30112    struct ast_channel *opp_chan;
30113    struct sip_pvt *opp = NULL;
30114    enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_FORBID;
30115 
30116    if (!(p = chan->tech_pvt)) {
30117       return AST_RTP_GLUE_RESULT_FORBID;
30118    }
30119 
30120    if ((opp_chan = ast_bridged_channel(chan)) && (((opp_chan->tech != &sip_tech) && (opp_chan->tech != &sip_tech_info)) ||
30121                          (!(opp = opp_chan->tech_pvt)))) {
30122       return AST_RTP_GLUE_RESULT_FORBID;
30123    }
30124 
30125    sip_pvt_lock(p);
30126    while (opp && sip_pvt_trylock(opp)) {
30127       sip_pvt_unlock(p);
30128       usleep(1);
30129       sip_pvt_lock(p);
30130    }
30131 
30132    if (!(p->trtp)) {
30133       if (opp) {
30134          sip_pvt_unlock(opp);
30135       }
30136       sip_pvt_unlock(p);
30137       return AST_RTP_GLUE_RESULT_FORBID;
30138    }
30139 
30140    ao2_ref(p->trtp, +1);
30141    *instance = p->trtp;
30142 
30143    if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
30144       res = AST_RTP_GLUE_RESULT_REMOTE;
30145       if (opp && !apply_directmedia_ha(p, opp, "text")) {
30146          res = AST_RTP_GLUE_RESULT_FORBID;
30147       }
30148    }
30149 
30150    if (opp) {
30151       sip_pvt_unlock(opp);
30152    }
30153    sip_pvt_unlock(p);
30154 
30155    return res;
30156 }
30157 
30158 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, format_t codecs, int nat_active)
30159 {
30160    struct sip_pvt *p;
30161    int changed = 0;
30162 
30163    /* Lock the channel and the private safely. */
30164    ast_channel_lock(chan);
30165    p = chan->tech_pvt;
30166    if (!p) {
30167       ast_channel_unlock(chan);
30168       return -1;
30169    }
30170    sip_pvt_lock(p);
30171    if (p->owner != chan) {
30172       /* I suppose it could be argued that if this happens it is a bug. */
30173       ast_debug(1, "The private is not owned by channel %s anymore.\n", chan->name);
30174       sip_pvt_unlock(p);
30175       ast_channel_unlock(chan);
30176       return 0;
30177    }
30178 
30179    /* Disable early RTP bridge  */
30180    if ((instance || vinstance || tinstance) &&
30181       !ast_bridged_channel(chan) &&
30182       !sip_cfg.directrtpsetup) {
30183       sip_pvt_unlock(p);
30184       ast_channel_unlock(chan);
30185       return 0;
30186    }
30187 
30188    if (p->alreadygone) {
30189       /* If we're destroyed, don't bother */
30190       sip_pvt_unlock(p);
30191       ast_channel_unlock(chan);
30192       return 0;
30193    }
30194 
30195    /* if this peer cannot handle reinvites of the media stream to devices
30196       that are known to be behind a NAT, then stop the process now
30197    */
30198    if (nat_active && !ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT)) {
30199       sip_pvt_unlock(p);
30200       ast_channel_unlock(chan);
30201       return 0;
30202    }
30203 
30204    if (instance) {
30205       changed |= ast_rtp_instance_get_and_cmp_remote_address(instance, &p->redirip);
30206 
30207       if (p->rtp) {
30208          /* Prevent audio RTCP reads */
30209          ast_channel_set_fd(chan, 1, -1);
30210          /* Silence RTCP while audio RTP is inactive */
30211          ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 0);
30212       }
30213    } else if (!ast_sockaddr_isnull(&p->redirip)) {
30214       memset(&p->redirip, 0, sizeof(p->redirip));
30215       changed = 1;
30216 
30217       if (p->rtp) {
30218          /* Enable RTCP since it will be inactive if we're coming back
30219           * from a reinvite */
30220          ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 1);
30221          /* Enable audio RTCP reads */
30222          ast_channel_set_fd(chan, 1, ast_rtp_instance_fd(p->rtp, 1));
30223       }
30224    }
30225 
30226    if (vinstance) {
30227       changed |= ast_rtp_instance_get_and_cmp_remote_address(vinstance, &p->vredirip);
30228 
30229       if (p->vrtp) {
30230          /* Prevent video RTCP reads */
30231          ast_channel_set_fd(chan, 3, -1);
30232          /* Silence RTCP while video RTP is inactive */
30233          ast_rtp_instance_set_prop(p->vrtp, AST_RTP_PROPERTY_RTCP, 0);
30234       }
30235    } else if (!ast_sockaddr_isnull(&p->vredirip)) {
30236       memset(&p->vredirip, 0, sizeof(p->vredirip));
30237       changed = 1;
30238 
30239       if (p->vrtp) {
30240          /* Enable RTCP since it will be inactive if we're coming back
30241           * from a reinvite */
30242          ast_rtp_instance_set_prop(p->vrtp, AST_RTP_PROPERTY_RTCP, 1);
30243          /* Enable video RTCP reads */
30244          ast_channel_set_fd(chan, 3, ast_rtp_instance_fd(p->vrtp, 1));
30245       }
30246    }
30247 
30248    if (tinstance) {
30249       changed |= ast_rtp_instance_get_and_cmp_remote_address(tinstance, &p->tredirip);
30250    } else if (!ast_sockaddr_isnull(&p->tredirip)) {
30251       memset(&p->tredirip, 0, sizeof(p->tredirip));
30252       changed = 1;
30253    }
30254    if (codecs && (p->redircodecs != codecs)) {
30255       p->redircodecs = codecs;
30256       changed = 1;
30257    }
30258 
30259    if (ast_test_flag(&p->flags[2], SIP_PAGE3_DIRECT_MEDIA_OUTGOING) && !p->outgoing_call) {
30260       /* We only wish to withhold sending the initial direct media reinvite on the incoming dialog.
30261        * Further direct media reinvites beyond the initial should be sent. In order to allow further
30262        * direct media reinvites to be sent, we clear this flag.
30263        */
30264       ast_clear_flag(&p->flags[2], SIP_PAGE3_DIRECT_MEDIA_OUTGOING);
30265       sip_pvt_unlock(p);
30266       ast_channel_unlock(chan);
30267       return 0;
30268    }
30269 
30270    if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER) && !ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
30271       if (chan->_state != AST_STATE_UP) {     /* We are in early state */
30272          if (p->do_history)
30273             append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
30274          ast_debug(1, "Early remote bridge setting SIP '%s' - Sending media to %s\n", p->callid, ast_sockaddr_stringify(instance ? &p->redirip : &p->ourip));
30275       } else if (!p->pendinginvite) {   /* We are up, and have no outstanding invite */
30276          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));
30277          transmit_reinvite_with_sdp(p, FALSE, FALSE);
30278       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
30279          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));
30280          /* We have a pending Invite. Send re-invite when we're done with the invite */
30281          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
30282       }
30283    }
30284    /* Reset lastrtprx timer */
30285    p->lastrtprx = p->lastrtptx = time(NULL);
30286    sip_pvt_unlock(p);
30287    ast_channel_unlock(chan);
30288    return 0;
30289 }
30290 
30291 static format_t sip_get_codec(struct ast_channel *chan)
30292 {
30293    struct sip_pvt *p = chan->tech_pvt;
30294    return p->peercapability ? p->peercapability : p->capability;
30295 }
30296 
30297 static struct ast_rtp_glue sip_rtp_glue = {
30298    .type = "SIP",
30299    .get_rtp_info = sip_get_rtp_peer,
30300    .get_vrtp_info = sip_get_vrtp_peer,
30301    .get_trtp_info = sip_get_trtp_peer,
30302    .update_peer = sip_set_rtp_peer,
30303    .get_codec = sip_get_codec,
30304 };
30305 
30306 static char *app_dtmfmode = "SIPDtmfMode";
30307 static char *app_sipaddheader = "SIPAddHeader";
30308 static char *app_sipremoveheader = "SIPRemoveHeader";
30309 
30310 /*! \brief Set the DTMFmode for an outbound SIP call (application) */
30311 static int sip_dtmfmode(struct ast_channel *chan, const char *data)
30312 {
30313    struct sip_pvt *p;
30314    const char *mode = data;
30315 
30316    if (!data) {
30317       ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
30318       return 0;
30319    }
30320    ast_channel_lock(chan);
30321    if (!IS_SIP_TECH(chan->tech)) {
30322       ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
30323       ast_channel_unlock(chan);
30324       return 0;
30325    }
30326    p = chan->tech_pvt;
30327    if (!p) {
30328       ast_channel_unlock(chan);
30329       return 0;
30330    }
30331    sip_pvt_lock(p);
30332    if (!strcasecmp(mode, "info")) {
30333       ast_clear_flag(&p->flags[0], SIP_DTMF);
30334       ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
30335       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
30336    } else if (!strcasecmp(mode, "shortinfo")) {
30337       ast_clear_flag(&p->flags[0], SIP_DTMF);
30338       ast_set_flag(&p->flags[0], SIP_DTMF_SHORTINFO);
30339       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
30340    } else if (!strcasecmp(mode, "rfc2833")) {
30341       ast_clear_flag(&p->flags[0], SIP_DTMF);
30342       ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
30343       p->jointnoncodeccapability |= AST_RTP_DTMF;
30344    } else if (!strcasecmp(mode, "inband")) {
30345       ast_clear_flag(&p->flags[0], SIP_DTMF);
30346       ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
30347       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
30348    } else {
30349       ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n", mode);
30350    }
30351    if (p->rtp)
30352       ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
30353    if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
30354        (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
30355       enable_dsp_detect(p);
30356    } else {
30357       disable_dsp_detect(p);
30358    }
30359    sip_pvt_unlock(p);
30360    ast_channel_unlock(chan);
30361    return 0;
30362 }
30363 
30364 /*! \brief Add a SIP header to an outbound INVITE */
30365 static int sip_addheader(struct ast_channel *chan, const char *data)
30366 {
30367    int no = 0;
30368    int ok = FALSE;
30369    char varbuf[30];
30370    const char *inbuf = data;
30371    char *subbuf;
30372    
30373    if (ast_strlen_zero(inbuf)) {
30374       ast_log(LOG_WARNING, "This application requires the argument: Header\n");
30375       return 0;
30376    }
30377    ast_channel_lock(chan);
30378 
30379    /* Check for headers */
30380    while (!ok && no <= 50) {
30381       no++;
30382       snprintf(varbuf, sizeof(varbuf), "__SIPADDHEADER%.2d", no);
30383 
30384       /* Compare without the leading underscores */
30385       if ((pbx_builtin_getvar_helper(chan, (const char *) varbuf + 2) == (const char *) NULL)) {
30386          ok = TRUE;
30387       }
30388    }
30389    if (ok) {
30390       size_t len = strlen(inbuf);
30391       subbuf = ast_alloca(len + 1);
30392       ast_get_encoded_str(inbuf, subbuf, len + 1);
30393       pbx_builtin_setvar_helper(chan, varbuf, subbuf);
30394       if (sipdebug) {
30395          ast_debug(1, "SIP Header added \"%s\" as %s\n", inbuf, varbuf);
30396       }
30397    } else {
30398       ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
30399    }
30400    ast_channel_unlock(chan);
30401    return 0;
30402 }
30403 
30404 /*! \brief Remove SIP headers added previously with SipAddHeader application */
30405 static int sip_removeheader(struct ast_channel *chan, const char *data)
30406 {
30407    struct ast_var_t *newvariable;
30408    struct varshead *headp;
30409    int removeall = 0;
30410    char *inbuf = (char *) data;
30411 
30412    if (ast_strlen_zero(inbuf)) {
30413       removeall = 1;
30414    }
30415    ast_channel_lock(chan);
30416 
30417    headp=&chan->varshead;
30418    AST_LIST_TRAVERSE_SAFE_BEGIN (headp, newvariable, entries) {
30419       if (strncasecmp(ast_var_name(newvariable), "SIPADDHEADER", strlen("SIPADDHEADER")) == 0) {
30420          if (removeall || (!strncasecmp(ast_var_value(newvariable),inbuf,strlen(inbuf)))) {
30421             if (sipdebug)
30422                ast_debug(1,"removing SIP Header \"%s\" as %s\n",
30423                   ast_var_value(newvariable),
30424                   ast_var_name(newvariable));
30425             AST_LIST_REMOVE_CURRENT(entries);
30426             ast_var_delete(newvariable);
30427          }
30428       }
30429    }
30430    AST_LIST_TRAVERSE_SAFE_END;
30431 
30432    ast_channel_unlock(chan);
30433    return 0;
30434 }
30435 
30436 /*! \brief Transfer call before connect with a 302 redirect
30437 \note Called by the transfer() dialplan application through the sip_transfer()
30438    pbx interface function if the call is in ringing state
30439 \todo Fix this function so that we wait for reply to the REFER and
30440    react to errors, denials or other issues the other end might have.
30441  */
30442 static int sip_sipredirect(struct sip_pvt *p, const char *dest)
30443 {
30444    char *cdest;
30445    char *extension, *domain;
30446 
30447    cdest = ast_strdupa(dest);
30448 
30449    extension = strsep(&cdest, "@");
30450    domain = cdest;
30451    if (ast_strlen_zero(extension)) {
30452       ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
30453       return 0;
30454    }
30455 
30456    /* we'll issue the redirect message here */
30457    if (!domain) {
30458       char *local_to_header;
30459       char to_header[256];
30460 
30461       ast_copy_string(to_header, get_header(&p->initreq, "To"), sizeof(to_header));
30462       if (ast_strlen_zero(to_header)) {
30463          ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
30464          return 0;
30465       }
30466       if (((local_to_header = strcasestr(to_header, "sip:")) || (local_to_header = strcasestr(to_header, "sips:")))
30467          && (local_to_header = strchr(local_to_header, '@'))) {
30468          char ldomain[256];
30469 
30470          memset(ldomain, 0, sizeof(ldomain));
30471          local_to_header++;
30472          /* This is okey because lhost and lport are as big as tmp */
30473          sscanf(local_to_header, "%256[^<>; ]", ldomain);
30474          if (ast_strlen_zero(ldomain)) {
30475             ast_log(LOG_ERROR, "Can't find the host address\n");
30476             return 0;
30477          }
30478          domain = ast_strdupa(ldomain);
30479       }
30480    }
30481 
30482    ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s>", extension, domain);
30483    transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);
30484 
30485    sip_scheddestroy(p, SIP_TRANS_TIMEOUT);   /* Make sure we stop send this reply. */
30486    sip_alreadygone(p);
30487 
30488    if (p->owner) {
30489       enum ast_control_transfer message = AST_TRANSFER_SUCCESS;
30490       ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
30491    }
30492    /* hangup here */
30493    return 0;
30494 }
30495 
30496 static int sip_is_xml_parsable(void)
30497 {
30498 #ifdef HAVE_LIBXML2
30499    return TRUE;
30500 #else
30501    return FALSE;
30502 #endif
30503 }
30504 
30505 /*! \brief Send a poke to all known peers */
30506 static void sip_poke_all_peers(void)
30507 {
30508    int ms = 0, num = 0;
30509    struct ao2_iterator i;
30510    struct sip_peer *peer;
30511 
30512    if (!speerobjs) { /* No peers, just give up */
30513       return;
30514    }
30515 
30516    i = ao2_iterator_init(peers, 0);
30517    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
30518       ao2_lock(peer);
30519       /* Don't schedule poking on a peer without qualify */
30520       if (peer->maxms) {
30521          if (num == global_qualify_peers) {
30522             ms += global_qualify_gap;
30523             num = 0;
30524          } else {
30525             num++;
30526          }
30527          AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ms, sip_poke_peer_s, peer,
30528                unref_peer(_data, "removing poke peer ref"),
30529                unref_peer(peer, "removing poke peer ref"),
30530                ref_peer(peer, "adding poke peer ref"));
30531       }
30532       ao2_unlock(peer);
30533       unref_peer(peer, "toss iterator peer ptr");
30534    }
30535    ao2_iterator_destroy(&i);
30536 }
30537 
30538 /*! \brief Send all known registrations */
30539 static void sip_send_all_registers(void)
30540 {
30541    int ms;
30542    int regspacing;
30543    if (!regobjs)
30544       return;
30545    regspacing = default_expiry * 1000/regobjs;
30546    if (regspacing > 100) {
30547       regspacing = 100;
30548    }
30549    ms = regspacing;
30550    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
30551       ASTOBJ_WRLOCK(iterator);
30552       ms += regspacing;
30553       AST_SCHED_REPLACE_UNREF(iterator->expire, sched, ms, sip_reregister, iterator,
30554                         registry_unref(_data, "REPLACE sched del decs the refcount"),
30555                         registry_unref(iterator, "REPLACE sched add failure decs the refcount"),
30556                         registry_addref(iterator, "REPLACE sched add incs the refcount"));
30557       ASTOBJ_UNLOCK(iterator);
30558    } while (0)
30559    );
30560 }
30561 
30562 /*! \brief Send all MWI subscriptions */
30563 static void sip_send_all_mwi_subscriptions(void)
30564 {
30565    ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
30566       struct sip_subscription_mwi *saved;
30567       ASTOBJ_WRLOCK(iterator);
30568       AST_SCHED_DEL(sched, iterator->resub);
30569       saved = ASTOBJ_REF(iterator);
30570       if ((iterator->resub = ast_sched_add(sched, 1, sip_subscribe_mwi_do, saved)) < 0) {
30571          ASTOBJ_UNREF(saved, sip_subscribe_mwi_destroy);
30572       }
30573       ASTOBJ_UNLOCK(iterator);
30574    } while (0));
30575 }
30576 
30577 /* SRTP */
30578 static int setup_srtp(struct sip_srtp **srtp)
30579 {
30580    if (!ast_rtp_engine_srtp_is_registered()) {
30581       ast_log(LOG_ERROR, "No SRTP module loaded, can't setup SRTP session.\n");
30582       return -1;
30583    }
30584 
30585    if (!(*srtp = sip_srtp_alloc())) { /* Allocate SRTP data structure */
30586       return -1;
30587    }
30588 
30589    return 0;
30590 }
30591 
30592 static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct sip_srtp **srtp, const char *a)
30593 {
30594    /* If no RTP instance exists for this media stream don't bother processing the crypto line */
30595    if (!rtp) {
30596       ast_debug(3, "Received offer with crypto line for media stream that is not enabled\n");
30597       return FALSE;
30598    }
30599 
30600    if (strncasecmp(a, "crypto:", 7)) {
30601       return FALSE;
30602    }
30603    if (!*srtp) {
30604       if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
30605          ast_log(LOG_WARNING, "Ignoring unexpected crypto attribute in SDP answer\n");
30606          return FALSE;
30607       }
30608 
30609       if (setup_srtp(srtp) < 0) {
30610          return FALSE;
30611       }
30612    }
30613 
30614    if (!(*srtp)->crypto && !((*srtp)->crypto = sdp_crypto_setup())) {
30615       return FALSE;
30616    }
30617 
30618    if (sdp_crypto_process((*srtp)->crypto, a, rtp) < 0) {
30619       return FALSE;
30620    }
30621 
30622    ast_set_flag(*srtp, SRTP_CRYPTO_OFFER_OK);
30623 
30624    return TRUE;
30625 }
30626 
30627 /*! \brief Reload module */
30628 static int sip_do_reload(enum channelreloadreason reason)
30629 {
30630    time_t start_poke, end_poke;
30631    
30632    reload_config(reason);
30633    ast_sched_dump(sched);
30634 
30635    start_poke = time(0);
30636    /* Prune peers who still are supposed to be deleted */
30637    unlink_marked_peers_from_tables();
30638 
30639    ast_debug(4, "--------------- Done destroying pruned peers\n");
30640 
30641    /* Send qualify (OPTIONS) to all peers */
30642    sip_poke_all_peers();
30643 
30644    /* Register with all services */
30645    sip_send_all_registers();
30646 
30647    sip_send_all_mwi_subscriptions();
30648 
30649    end_poke = time(0);
30650    
30651    ast_debug(4, "do_reload finished. peer poke/prune reg contact time = %d sec.\n", (int)(end_poke-start_poke));
30652 
30653    ast_debug(4, "--------------- SIP reload done\n");
30654 
30655    return 0;
30656 }
30657 
30658 /*! \brief Force reload of module from cli */
30659 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
30660 {
30661    static struct sip_peer *tmp_peer, *new_peer;
30662    
30663    switch (cmd) {
30664    case CLI_INIT:
30665       e->command = "sip reload";
30666       e->usage =
30667          "Usage: sip reload\n"
30668          "       Reloads SIP configuration from sip.conf\n";
30669       return NULL;
30670    case CLI_GENERATE:
30671       return NULL;
30672    }
30673 
30674    ast_mutex_lock(&sip_reload_lock);
30675    if (sip_reloading) {
30676       ast_verbose("Previous SIP reload not yet done\n");
30677    } else {
30678       sip_reloading = TRUE;
30679       sip_reloadreason = (a && a->fd) ? CHANNEL_CLI_RELOAD : CHANNEL_MODULE_RELOAD;
30680    }
30681    ast_mutex_unlock(&sip_reload_lock);
30682    restart_monitor();
30683 
30684    tmp_peer = bogus_peer;
30685    /* Create new bogus peer possibly with new global settings. */
30686    if ((new_peer = temp_peer("(bogus_peer)"))) {
30687       ast_string_field_set(new_peer, md5secret, BOGUS_PEER_MD5SECRET);
30688       ast_clear_flag(&new_peer->flags[0], SIP_INSECURE);
30689       bogus_peer = new_peer;
30690       ao2_t_ref(tmp_peer, -1, "unref the old bogus_peer during reload");
30691    } else {
30692       ast_log(LOG_ERROR, "Could not update the fake authentication peer.\n");
30693       /* You probably have bigger (memory?) issues to worry about though.. */
30694    }
30695 
30696    return CLI_SUCCESS;
30697 }
30698 
30699 /*! \brief  Part of Asterisk module interface */
30700 static int reload(void)
30701 {
30702    if (sip_reload(0, 0, NULL))
30703       return 0;
30704    return 1;
30705 }
30706 
30707 /*! \brief  Return the first entry from ast_sockaddr_resolve filtered by address family
30708  *
30709  * \warn Using this function probably means you have a faulty design.
30710  */
30711 static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
30712                   const char* name, int flag, int family)
30713 {
30714    struct ast_sockaddr *addrs;
30715    int addrs_cnt;
30716 
30717    addrs_cnt = ast_sockaddr_resolve(&addrs, name, flag, family);
30718    if (addrs_cnt <= 0) {
30719       return 1;
30720    }
30721    if (addrs_cnt > 1) {
30722       ast_debug(1, "Multiple addresses, using the first one only\n");
30723    }
30724 
30725    ast_sockaddr_copy(addr, &addrs[0]);
30726 
30727    ast_free(addrs);
30728    return 0;
30729 }
30730 
30731 /*! \brief  Return the first entry from ast_sockaddr_resolve filtered by family of binddaddr
30732  *
30733  * \warn Using this function probably means you have a faulty design.
30734  */
30735 static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
30736                   const char* name, int flag)
30737 {
30738    return ast_sockaddr_resolve_first_af(addr, name, flag, get_address_family_filter(SIP_TRANSPORT_UDP));
30739 }
30740 
30741 /*! \brief  Return the first entry from ast_sockaddr_resolve filtered by family of binddaddr
30742  *
30743  * \warn Using this function probably means you have a faulty design.
30744  */
30745 static int ast_sockaddr_resolve_first_transport(struct ast_sockaddr *addr,
30746                   const char* name, int flag, unsigned int transport)
30747 {
30748         return ast_sockaddr_resolve_first_af(addr, name, flag, get_address_family_filter(transport));
30749 }
30750 
30751 /*! \brief
30752  * \note The only member of the peer used here is the name field
30753  */
30754 static int peer_hash_cb(const void *obj, const int flags)
30755 {
30756    const struct sip_peer *peer = obj;
30757 
30758    return ast_str_case_hash(peer->name);
30759 }
30760 
30761 /*!
30762  * \note The only member of the peer used here is the name field
30763  */
30764 static int peer_cmp_cb(void *obj, void *arg, int flags)
30765 {
30766    struct sip_peer *peer = obj, *peer2 = arg;
30767 
30768    return !strcasecmp(peer->name, peer2->name) ? CMP_MATCH | CMP_STOP : 0;
30769 }
30770 
30771 /*!
30772  * Hash function based on the the peer's ip address.  For IPv6, we use the end
30773  * of the address.
30774  * \todo Find a better hashing function
30775  */
30776 static int peer_iphash_cb(const void *obj, const int flags)
30777 {
30778    const struct sip_peer *peer = obj;
30779    int ret = 0;
30780 
30781    if (ast_sockaddr_isnull(&peer->addr)) {
30782       ast_log(LOG_ERROR, "Empty address\n");
30783    }
30784 
30785    ret = ast_sockaddr_hash(&peer->addr);
30786 
30787    if (ret < 0) {
30788       ret = -ret;
30789    }
30790 
30791    return ret;
30792 }
30793 
30794 /*!
30795  * Match Peers by IP and Port number.
30796  *
30797  * This function has two modes.
30798  *  - If the peer arg does not have INSECURE_PORT set, then we will only return
30799  *    a match for a peer that matches both the IP and port.
30800  *  - If the peer arg does have the INSECURE_PORT flag set, then we will only
30801  *    return a match for a peer that matches the IP and has insecure=port
30802  *    in its configuration.
30803  *
30804  * This callback will be used twice when doing peer matching.  There is a first
30805  * pass for full IP+port matching, and a second pass in case there is a match
30806  * that meets the insecure=port criteria.
30807  *
30808  * \note Connections coming in over TCP or TLS should never be matched by port.
30809  *
30810  * \note the peer's addr struct provides to fields combined to make a key: the sin_addr.s_addr and sin_port fields.
30811  */
30812 static int peer_ipcmp_cb(void *obj, void *arg, int flags)
30813 {
30814    struct sip_peer *peer = obj, *peer2 = arg;
30815 
30816    if (ast_sockaddr_cmp_addr(&peer->addr, &peer2->addr)) {
30817       /* IP doesn't match */
30818       return 0;
30819    }
30820 
30821    /* We matched the IP, check to see if we need to match by port as well. */
30822    if ((peer->transports & peer2->transports) & (SIP_TRANSPORT_TLS | SIP_TRANSPORT_TCP)) {
30823       /* peer matching on port is not possible with TCP/TLS */
30824       return CMP_MATCH | CMP_STOP;
30825    } else if (ast_test_flag(&peer2->flags[0], SIP_INSECURE_PORT)) {
30826       /* We are allowing match without port for peers configured that
30827        * way in this pass through the peers. */
30828       return ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT) ?
30829             (CMP_MATCH | CMP_STOP) : 0;
30830    }
30831 
30832    /* Now only return a match if the port matches, as well. */
30833    return ast_sockaddr_port(&peer->addr) == ast_sockaddr_port(&peer2->addr) ?
30834          (CMP_MATCH | CMP_STOP) : 0;
30835 }
30836 
30837 
30838 static int threadt_hash_cb(const void *obj, const int flags)
30839 {
30840    const struct sip_threadinfo *th = obj;
30841 
30842    return ast_sockaddr_hash(&th->tcptls_session->remote_address);
30843 }
30844 
30845 static int threadt_cmp_cb(void *obj, void *arg, int flags)
30846 {
30847    struct sip_threadinfo *th = obj, *th2 = arg;
30848 
30849    return (th->tcptls_session == th2->tcptls_session) ? CMP_MATCH | CMP_STOP : 0;
30850 }
30851 
30852 /*!
30853  * \note The only member of the dialog used here callid string
30854  */
30855 static int dialog_hash_cb(const void *obj, const int flags)
30856 {
30857    const struct sip_pvt *pvt = obj;
30858 
30859    return ast_str_case_hash(pvt->callid);
30860 }
30861 
30862 /*!
30863  * \note Same as dialog_cmp_cb, except without the CMP_STOP on match
30864  */
30865 static int dialog_find_multiple(void *obj, void *arg, int flags)
30866 {
30867    struct sip_pvt *pvt = obj, *pvt2 = arg;
30868 
30869    return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH : 0;
30870 }
30871 
30872 /*!
30873  * \note The only member of the dialog used here callid string
30874  */
30875 static int dialog_cmp_cb(void *obj, void *arg, int flags)
30876 {
30877    struct sip_pvt *pvt = obj, *pvt2 = arg;
30878 
30879    return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH | CMP_STOP : 0;
30880 }
30881 
30882 /*! \brief SIP Cli commands definition */
30883 static struct ast_cli_entry cli_sip[] = {
30884    AST_CLI_DEFINE(sip_show_channels, "List active SIP channels or subscriptions"),
30885    AST_CLI_DEFINE(sip_show_channelstats, "List statistics for active SIP channels"),
30886    AST_CLI_DEFINE(sip_show_domains, "List our local SIP domains"),
30887    AST_CLI_DEFINE(sip_show_inuse, "List all inuse/limits"),
30888    AST_CLI_DEFINE(sip_show_objects, "List all SIP object allocations"),
30889    AST_CLI_DEFINE(sip_show_peers, "List defined SIP peers"),
30890    AST_CLI_DEFINE(sip_show_registry, "List SIP registration status"),
30891    AST_CLI_DEFINE(sip_unregister, "Unregister (force expiration) a SIP peer from the registry"),
30892    AST_CLI_DEFINE(sip_show_settings, "Show SIP global settings"),
30893    AST_CLI_DEFINE(sip_show_mwi, "Show MWI subscriptions"),
30894    AST_CLI_DEFINE(sip_cli_notify, "Send a notify packet to a SIP peer"),
30895    AST_CLI_DEFINE(sip_show_channel, "Show detailed SIP channel info"),
30896    AST_CLI_DEFINE(sip_show_history, "Show SIP dialog history"),
30897    AST_CLI_DEFINE(sip_show_peer, "Show details on specific SIP peer"),
30898    AST_CLI_DEFINE(sip_show_users, "List defined SIP users"),
30899    AST_CLI_DEFINE(sip_show_user, "Show details on specific SIP user"),
30900    AST_CLI_DEFINE(sip_qualify_peer, "Send an OPTIONS packet to a peer"),
30901    AST_CLI_DEFINE(sip_show_sched, "Present a report on the status of the scheduler queue"),
30902    AST_CLI_DEFINE(sip_prune_realtime, "Prune cached Realtime users/peers"),
30903    AST_CLI_DEFINE(sip_do_debug, "Enable/Disable SIP debugging"),
30904    AST_CLI_DEFINE(sip_set_history, "Enable/Disable SIP history"),
30905    AST_CLI_DEFINE(sip_reload, "Reload SIP configuration"),
30906    AST_CLI_DEFINE(sip_show_tcp, "List TCP Connections")
30907 };
30908 
30909 /*! \brief SIP test registration */
30910 static void sip_register_tests(void)
30911 {
30912    sip_config_parser_register_tests();
30913    sip_request_parser_register_tests();
30914    sip_dialplan_function_register_tests();
30915 }
30916 
30917 /*! \brief SIP test registration */
30918 static void sip_unregister_tests(void)
30919 {
30920    sip_config_parser_unregister_tests();
30921    sip_request_parser_unregister_tests();
30922    sip_dialplan_function_unregister_tests();
30923 }
30924 
30925 #ifdef TEST_FRAMEWORK
30926 AST_TEST_DEFINE(test_sip_mwi_subscribe_parse)
30927 {
30928    int found = 0;
30929    enum ast_test_result_state res = AST_TEST_PASS;
30930    const char *mwi1 = "1234@mysipprovider.com/1234";
30931    const char *mwi2 = "1234:password@mysipprovider.com/1234";
30932    const char *mwi3 = "1234:password@mysipprovider.com:5061/1234";
30933    const char *mwi4 = "1234:password:authuser@mysipprovider.com/1234";
30934    const char *mwi5 = "1234:password:authuser@mysipprovider.com:5061/1234";
30935    const char *mwi6 = "1234:password";
30936 
30937    switch (cmd) {
30938    case TEST_INIT:
30939       info->name = "sip_mwi_subscribe_parse_test";
30940       info->category = "/channels/chan_sip/";
30941       info->summary = "SIP MWI subscribe line parse unit test";
30942       info->description =
30943          "Tests the parsing of mwi subscription lines (e.g., mwi => from sip.conf)";
30944       return AST_TEST_NOT_RUN;
30945    case TEST_EXECUTE:
30946       break;
30947    }
30948 
30949    if (sip_subscribe_mwi(mwi1, 1)) {
30950       res = AST_TEST_FAIL;
30951    } else {
30952       found = 0;
30953       res = AST_TEST_FAIL;
30954       ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
30955          ASTOBJ_WRLOCK(iterator);
30956          if (
30957             !strcmp(iterator->hostname, "mysipprovider.com") &&
30958             !strcmp(iterator->username, "1234") &&
30959             !strcmp(iterator->secret, "") &&
30960             !strcmp(iterator->authuser, "") &&
30961             !strcmp(iterator->mailbox, "1234") &&
30962             iterator->portno == 0) {
30963             found = 1;
30964             res = AST_TEST_PASS;
30965          }
30966          ASTOBJ_UNLOCK(iterator);
30967       } while(0));
30968       if (!found) {
30969          ast_test_status_update(test, "sip_subscribe_mwi test 1 failed\n");
30970       }
30971    }
30972 
30973    if (sip_subscribe_mwi(mwi2, 1)) {
30974       res = AST_TEST_FAIL;
30975    } else {
30976       found = 0;
30977       res = AST_TEST_FAIL;
30978       ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
30979          ASTOBJ_WRLOCK(iterator);
30980          if (
30981             !strcmp(iterator->hostname, "mysipprovider.com") &&
30982             !strcmp(iterator->username, "1234") &&
30983             !strcmp(iterator->secret, "password") &&
30984             !strcmp(iterator->authuser, "") &&
30985             !strcmp(iterator->mailbox, "1234") &&
30986             iterator->portno == 0) {
30987             found = 1;
30988             res = AST_TEST_PASS;
30989          }
30990          ASTOBJ_UNLOCK(iterator);
30991       } while(0));
30992       if (!found) {
30993          ast_test_status_update(test, "sip_subscribe_mwi test 2 failed\n");
30994       }
30995    }
30996 
30997    if (sip_subscribe_mwi(mwi3, 1)) {
30998       res = AST_TEST_FAIL;
30999    } else {
31000       found = 0;
31001       res = AST_TEST_FAIL;
31002       ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
31003          ASTOBJ_WRLOCK(iterator);
31004          if (
31005             !strcmp(iterator->hostname, "mysipprovider.com") &&
31006             !strcmp(iterator->username, "1234") &&
31007             !strcmp(iterator->secret, "password") &&
31008             !strcmp(iterator->authuser, "") &&
31009             !strcmp(iterator->mailbox, "1234") &&
31010             iterator->portno == 5061) {
31011             found = 1;
31012             res = AST_TEST_PASS;
31013          }
31014          ASTOBJ_UNLOCK(iterator);
31015       } while(0));
31016       if (!found) {
31017          ast_test_status_update(test, "sip_subscribe_mwi test 3 failed\n");
31018       }
31019    }
31020 
31021    if (sip_subscribe_mwi(mwi4, 1)) {
31022       res = AST_TEST_FAIL;
31023    } else {
31024       found = 0;
31025       res = AST_TEST_FAIL;
31026       ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
31027          ASTOBJ_WRLOCK(iterator);
31028          if (
31029             !strcmp(iterator->hostname, "mysipprovider.com") &&
31030             !strcmp(iterator->username, "1234") &&
31031             !strcmp(iterator->secret, "password") &&
31032             !strcmp(iterator->authuser, "authuser") &&
31033             !strcmp(iterator->mailbox, "1234") &&
31034             iterator->portno == 0) {
31035             found = 1;
31036             res = AST_TEST_PASS;
31037          }
31038          ASTOBJ_UNLOCK(iterator);
31039       } while(0));
31040       if (!found) {
31041          ast_test_status_update(test, "sip_subscribe_mwi test 4 failed\n");
31042       }
31043    }
31044 
31045    if (sip_subscribe_mwi(mwi5, 1)) {
31046       res = AST_TEST_FAIL;
31047    } else {
31048       found = 0;
31049       res = AST_TEST_FAIL;
31050       ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
31051          ASTOBJ_WRLOCK(iterator);
31052          if (
31053             !strcmp(iterator->hostname, "mysipprovider.com") &&
31054             !strcmp(iterator->username, "1234") &&
31055             !strcmp(iterator->secret, "password") &&
31056             !strcmp(iterator->authuser, "authuser") &&
31057             !strcmp(iterator->mailbox, "1234") &&
31058             iterator->portno == 5061) {
31059             found = 1;
31060             res = AST_TEST_PASS;
31061          }
31062          ASTOBJ_UNLOCK(iterator);
31063       } while(0));
31064       if (!found) {
31065          ast_test_status_update(test, "sip_subscribe_mwi test 5 failed\n");
31066       }
31067    }
31068    
31069    if (sip_subscribe_mwi(mwi6, 1)) {
31070       res = AST_TEST_PASS;
31071    } else {
31072       res = AST_TEST_FAIL;
31073    }
31074    return res;
31075 }
31076 
31077 AST_TEST_DEFINE(test_sip_peers_get)
31078 {
31079    struct sip_peer *peer;
31080    struct ast_data *node;
31081    struct ast_data_query query = {
31082       .path = "/asterisk/channel/sip/peers",
31083       .search = "peers/peer/name=test_peer_data_provider"
31084    };
31085 
31086    switch (cmd) {
31087       case TEST_INIT:
31088          info->name = "sip_peers_get_data_test";
31089          info->category = "/main/data/sip/peers/";
31090          info->summary = "SIP peers data providers unit test";
31091          info->description =
31092             "Tests whether the SIP peers data provider implementation works as expected.";
31093          return AST_TEST_NOT_RUN;
31094       case TEST_EXECUTE:
31095          break;
31096    }
31097 
31098    /* Create the peer that we will retrieve. */
31099    peer = build_peer("test_peer_data_provider", NULL, NULL, 0, 0);
31100    if (!peer) {
31101       return AST_TEST_FAIL;
31102    }
31103    peer->type = SIP_TYPE_USER;
31104    peer->call_limit = 10;
31105    ao2_link(peers, peer);
31106 
31107    /* retrieve the chan_sip/peers tree and check the created peer. */
31108    node = ast_data_get(&query);
31109    if (!node) {
31110       ao2_unlink(peers, peer);
31111       ao2_ref(peer, -1);
31112       return AST_TEST_FAIL;
31113    }
31114 
31115    /* compare item. */
31116    if (strcmp(ast_data_retrieve_string(node, "peer/name"), "test_peer_data_provider")) {
31117       ao2_unlink(peers, peer);
31118       ao2_ref(peer, -1);
31119       ast_data_free(node);
31120       return AST_TEST_FAIL;
31121    }
31122 
31123    if (strcmp(ast_data_retrieve_string(node, "peer/type"), "user")) {
31124       ao2_unlink(peers, peer);
31125       ao2_ref(peer, -1);
31126       ast_data_free(node);
31127       return AST_TEST_FAIL;
31128    }
31129 
31130    if (ast_data_retrieve_int(node, "peer/call_limit") != 10) {
31131       ao2_unlink(peers, peer);
31132       ao2_ref(peer, -1);
31133       ast_data_free(node);
31134       return AST_TEST_FAIL;
31135    }
31136 
31137    /* release resources */
31138    ast_data_free(node);
31139 
31140    ao2_unlink(peers, peer);
31141    ao2_ref(peer, -1);
31142 
31143    return AST_TEST_PASS;
31144 }
31145 
31146 /*!
31147  * \brief Imitation TCP reception loop
31148  *
31149  * This imitates the logic used by SIP's TCP code. Its purpose
31150  * is to either
31151  * 1) Combine fragments into a single message
31152  * 2) Break up combined messages into single messages
31153  *
31154  * \param fragments The message fragments. This simulates the data received on a TCP socket.
31155  * \param num_fragments This indicates the number of fragments to receive
31156  * \param overflow This is a place to stash extra data if more than one message is received
31157  *        in a single fragment
31158  * \param[out] messages The parsed messages are placed in this array
31159  * \param[out] num_messages The number of messages that were parsed
31160  * \param test Used for printing messages
31161  * \retval 0 Success
31162  * \retval -1 Failure
31163  */
31164 static int mock_tcp_loop(char *fragments[], size_t num_fragments,
31165       struct ast_str **overflow, char **messages, int *num_messages, struct ast_test* test)
31166 {
31167    struct ast_str *req_data;
31168    int i = 0;
31169    int res = 0;
31170 
31171    req_data = ast_str_create(128);
31172    ast_str_reset(*overflow);
31173 
31174    while (i < num_fragments || ast_str_strlen(*overflow) > 0) {
31175       enum message_integrity message_integrity = MESSAGE_FRAGMENT;
31176       ast_str_reset(req_data);
31177       while (message_integrity == MESSAGE_FRAGMENT) {
31178          if (ast_str_strlen(*overflow) > 0) {
31179             ast_str_append(&req_data, 0, "%s", ast_str_buffer(*overflow));
31180             ast_str_reset(*overflow);
31181          } else {
31182             ast_str_append(&req_data, 0, "%s", fragments[i++]);
31183          }
31184          message_integrity = check_message_integrity(&req_data, overflow);
31185       }
31186       if (strcmp(ast_str_buffer(req_data), messages[*num_messages])) {
31187          ast_test_status_update(test, "Mismatch in SIP messages.\n");
31188          ast_test_status_update(test, "Expected message:\n%s", messages[*num_messages]);
31189          ast_test_status_update(test, "Parsed message:\n%s", ast_str_buffer(req_data));
31190          res = -1;
31191          goto end;
31192       } else {
31193          ast_test_status_update(test, "Successfully read message:\n%s", ast_str_buffer(req_data));
31194       }
31195       (*num_messages)++;
31196    }
31197 
31198 end:
31199    ast_free(req_data);
31200    return res;
31201 };
31202 
31203 AST_TEST_DEFINE(test_tcp_message_fragmentation)
31204 {
31205    /* Normal single message in one fragment */
31206    char *normal[] = {
31207       "INVITE sip:bob@example.org SIP/2.0\r\n"
31208       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31209       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31210       "To: <sip:bob@example.org:5060>\r\n"
31211       "Call-ID: 12345\r\n"
31212       "CSeq: 1 INVITE\r\n"
31213       "Contact: sip:127.0.0.1:5061\r\n"
31214       "Max-Forwards: 70\r\n"
31215       "Content-Type: application/sdp\r\n"
31216       "Content-Length: 130\r\n"
31217       "\r\n"
31218       "v=0\r\n"
31219       "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
31220       "s=-\r\n"
31221       "c=IN IP4 127.0.0.1\r\n"
31222       "t=0 0\r\n"
31223       "m=audio 10000 RTP/AVP 0\r\n"
31224       "a=rtpmap:0 PCMU/8000\r\n"
31225    };
31226 
31227    /* Single message in two fragments.
31228     * Fragments combine to make "normal"
31229     */
31230    char *fragmented[] = {
31231       "INVITE sip:bob@example.org SIP/2.0\r\n"
31232       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31233       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31234       "To: <sip:bob@example.org:5060>\r\n"
31235       "Call-ID: 12345\r\n"
31236       "CSeq: 1 INVITE\r\n"
31237       "Contact: sip:127.0.0.1:5061\r\n"
31238       "Max-Forwards: ",
31239 
31240       "70\r\n"
31241       "Content-Type: application/sdp\r\n"
31242       "Content-Length: 130\r\n"
31243       "\r\n"
31244       "v=0\r\n"
31245       "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
31246       "s=-\r\n"
31247       "c=IN IP4 127.0.0.1\r\n"
31248       "t=0 0\r\n"
31249       "m=audio 10000 RTP/AVP 0\r\n"
31250       "a=rtpmap:0 PCMU/8000\r\n"
31251    };
31252    /* Single message in two fragments, divided precisely at the body
31253     * Fragments combine to make "normal"
31254     */
31255    char *fragmented_body[] = {
31256       "INVITE sip:bob@example.org SIP/2.0\r\n"
31257       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31258       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31259       "To: <sip:bob@example.org:5060>\r\n"
31260       "Call-ID: 12345\r\n"
31261       "CSeq: 1 INVITE\r\n"
31262       "Contact: sip:127.0.0.1:5061\r\n"
31263       "Max-Forwards: 70\r\n"
31264       "Content-Type: application/sdp\r\n"
31265       "Content-Length: 130\r\n"
31266       "\r\n",
31267 
31268       "v=0\r\n"
31269       "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
31270       "s=-\r\n"
31271       "c=IN IP4 127.0.0.1\r\n"
31272       "t=0 0\r\n"
31273       "m=audio 10000 RTP/AVP 0\r\n"
31274       "a=rtpmap:0 PCMU/8000\r\n"
31275    };
31276 
31277    /* Single message in three fragments
31278     * Fragments combine to make "normal"
31279     */
31280    char *multi_fragment[] = {
31281       "INVITE sip:bob@example.org SIP/2.0\r\n"
31282       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31283       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31284       "To: <sip:bob@example.org:5060>\r\n"
31285       "Call-ID: 12345\r\n"
31286       "CSeq: 1 INVITE\r\n",
31287 
31288       "Contact: sip:127.0.0.1:5061\r\n"
31289       "Max-Forwards: 70\r\n"
31290       "Content-Type: application/sdp\r\n"
31291       "Content-Length: 130\r\n"
31292       "\r\n"
31293       "v=0\r\n"
31294       "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
31295       "s=-\r\n"
31296       "c=IN IP4",
31297 
31298       " 127.0.0.1\r\n"
31299       "t=0 0\r\n"
31300       "m=audio 10000 RTP/AVP 0\r\n"
31301       "a=rtpmap:0 PCMU/8000\r\n"
31302    };
31303 
31304    /* Two messages in a single fragment
31305     * Fragments split into "multi_message_divided"
31306     */
31307    char *multi_message[] = {
31308       "SIP/2.0 100 Trying\r\n"
31309       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31310       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31311       "To: <sip:bob@example.org:5060>\r\n"
31312       "Call-ID: 12345\r\n"
31313       "CSeq: 1 INVITE\r\n"
31314       "Contact: <sip:bob@example.org:5060>\r\n"
31315       "Content-Length: 0\r\n"
31316       "\r\n"
31317       "SIP/2.0 180 Ringing\r\n"
31318       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31319       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31320       "To: <sip:bob@example.org:5060>\r\n"
31321       "Call-ID: 12345\r\n"
31322       "CSeq: 1 INVITE\r\n"
31323       "Contact: <sip:bob@example.org:5060>\r\n"
31324       "Content-Length: 0\r\n"
31325       "\r\n"
31326    };
31327    char *multi_message_divided[] = {
31328       "SIP/2.0 100 Trying\r\n"
31329       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31330       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31331       "To: <sip:bob@example.org:5060>\r\n"
31332       "Call-ID: 12345\r\n"
31333       "CSeq: 1 INVITE\r\n"
31334       "Contact: <sip:bob@example.org:5060>\r\n"
31335       "Content-Length: 0\r\n"
31336       "\r\n",
31337 
31338       "SIP/2.0 180 Ringing\r\n"
31339       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31340       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31341       "To: <sip:bob@example.org:5060>\r\n"
31342       "Call-ID: 12345\r\n"
31343       "CSeq: 1 INVITE\r\n"
31344       "Contact: <sip:bob@example.org:5060>\r\n"
31345       "Content-Length: 0\r\n"
31346       "\r\n"
31347    };
31348    /* Two messages with bodies combined into one fragment
31349     * Fragments split into "multi_message_body_divided"
31350     */
31351    char *multi_message_body[] = {
31352       "INVITE sip:bob@example.org SIP/2.0\r\n"
31353       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31354       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31355       "To: <sip:bob@example.org:5060>\r\n"
31356       "Call-ID: 12345\r\n"
31357       "CSeq: 1 INVITE\r\n"
31358       "Contact: sip:127.0.0.1:5061\r\n"
31359       "Max-Forwards: 70\r\n"
31360       "Content-Type: application/sdp\r\n"
31361       "Content-Length: 130\r\n"
31362       "\r\n"
31363       "v=0\r\n"
31364       "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
31365       "s=-\r\n"
31366       "c=IN IP4 127.0.0.1\r\n"
31367       "t=0 0\r\n"
31368       "m=audio 10000 RTP/AVP 0\r\n"
31369       "a=rtpmap:0 PCMU/8000\r\n"
31370       "INVITE sip:bob@example.org SIP/2.0\r\n"
31371       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31372       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31373       "To: <sip:bob@example.org:5060>\r\n"
31374       "Call-ID: 12345\r\n"
31375       "CSeq: 2 INVITE\r\n"
31376       "Contact: sip:127.0.0.1:5061\r\n"
31377       "Max-Forwards: 70\r\n"
31378       "Content-Type: application/sdp\r\n"
31379       "Content-Length: 130\r\n"
31380       "\r\n"
31381       "v=0\r\n"
31382       "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
31383       "s=-\r\n"
31384       "c=IN IP4 127.0.0.1\r\n"
31385       "t=0 0\r\n"
31386       "m=audio 10000 RTP/AVP 0\r\n"
31387       "a=rtpmap:0 PCMU/8000\r\n"
31388    };
31389    char *multi_message_body_divided[] = {
31390       "INVITE sip:bob@example.org SIP/2.0\r\n"
31391       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31392       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31393       "To: <sip:bob@example.org:5060>\r\n"
31394       "Call-ID: 12345\r\n"
31395       "CSeq: 1 INVITE\r\n"
31396       "Contact: sip:127.0.0.1:5061\r\n"
31397       "Max-Forwards: 70\r\n"
31398       "Content-Type: application/sdp\r\n"
31399       "Content-Length: 130\r\n"
31400       "\r\n"
31401       "v=0\r\n"
31402       "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
31403       "s=-\r\n"
31404       "c=IN IP4 127.0.0.1\r\n"
31405       "t=0 0\r\n"
31406       "m=audio 10000 RTP/AVP 0\r\n"
31407       "a=rtpmap:0 PCMU/8000\r\n",
31408 
31409       "INVITE sip:bob@example.org SIP/2.0\r\n"
31410       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31411       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31412       "To: <sip:bob@example.org:5060>\r\n"
31413       "Call-ID: 12345\r\n"
31414       "CSeq: 2 INVITE\r\n"
31415       "Contact: sip:127.0.0.1:5061\r\n"
31416       "Max-Forwards: 70\r\n"
31417       "Content-Type: application/sdp\r\n"
31418       "Content-Length: 130\r\n"
31419       "\r\n"
31420       "v=0\r\n"
31421       "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
31422       "s=-\r\n"
31423       "c=IN IP4 127.0.0.1\r\n"
31424       "t=0 0\r\n"
31425       "m=audio 10000 RTP/AVP 0\r\n"
31426       "a=rtpmap:0 PCMU/8000\r\n"
31427    };
31428 
31429    /* Two messages that appear in two fragments. Fragment
31430     * boundaries do not align with message boundaries.
31431     * Fragments combine to make "multi_message_divided"
31432     */
31433    char *multi_message_in_fragments[] = {
31434       "SIP/2.0 100 Trying\r\n"
31435       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31436       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31437       "To: <sip:bob@example.org:5060>\r\n"
31438       "Call-ID: 12345\r\n"
31439       "CSeq: 1 INVI",
31440 
31441       "TE\r\n"
31442       "Contact: <sip:bob@example.org:5060>\r\n"
31443       "Content-Length: 0\r\n"
31444       "\r\n"
31445       "SIP/2.0 180 Ringing\r\n"
31446       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31447       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31448       "To: <sip:bob@example.org:5060>\r\n"
31449       "Call-ID: 12345\r\n"
31450       "CSeq: 1 INVITE\r\n"
31451       "Contact: <sip:bob@example.org:5060>\r\n"
31452       "Content-Length: 0\r\n"
31453       "\r\n"
31454    };
31455 
31456    /* Message with compact content-length header
31457     * Same as "normal" but with compact content-length header
31458     */
31459    char *compact[] = {
31460       "INVITE sip:bob@example.org SIP/2.0\r\n"
31461       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31462       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31463       "To: <sip:bob@example.org:5060>\r\n"
31464       "Call-ID: 12345\r\n"
31465       "CSeq: 1 INVITE\r\n"
31466       "Contact: sip:127.0.0.1:5061\r\n"
31467       "Max-Forwards: 70\r\n"
31468       "Content-Type: application/sdp\r\n"
31469       "l:130\r\n" /* intentionally no space */
31470       "\r\n"
31471       "v=0\r\n"
31472       "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
31473       "s=-\r\n"
31474       "c=IN IP4 127.0.0.1\r\n"
31475       "t=0 0\r\n"
31476       "m=audio 10000 RTP/AVP 0\r\n"
31477       "a=rtpmap:0 PCMU/8000\r\n"
31478    };
31479 
31480    /* Message with faux content-length headers
31481     * Same as "normal" but with extra fake content-length headers
31482     */
31483    char *faux[] = {
31484       "INVITE sip:bob@example.org SIP/2.0\r\n"
31485       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31486       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31487       "To: <sip:bob@example.org:5060>\r\n"
31488       "Call-ID: 12345\r\n"
31489       "CSeq: 1 INVITE\r\n"
31490       "Contact: sip:127.0.0.1:5061\r\n"
31491       "Max-Forwards: 70\r\n"
31492       "Content-Type: application/sdp\r\n"
31493       "DisContent-Length: 0\r\n"
31494       "MalContent-Length: 60\r\n"
31495       "Content-Length:130\r\n" /* intentionally no space */
31496       "\r\n"
31497       "v=0\r\n"
31498       "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
31499       "s=-\r\n"
31500       "c=IN IP4 127.0.0.1\r\n"
31501       "t=0 0\r\n"
31502       "m=audio 10000 RTP/AVP 0\r\n"
31503       "a=rtpmap:0 PCMU/8000\r\n"
31504    };
31505 
31506    /* Message with folded Content-Length header
31507     * Message is "normal" with Content-Length spread across three lines
31508     *
31509     * This is the test that requires pedantic=yes in order to pass
31510     */
31511    char *folded[] = {
31512       "INVITE sip:bob@example.org SIP/2.0\r\n"
31513       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31514       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31515       "To: <sip:bob@example.org:5060>\r\n"
31516       "Call-ID: 12345\r\n"
31517       "CSeq: 1 INVITE\r\n"
31518       "Contact: sip:127.0.0.1:5061\r\n"
31519       "Max-Forwards: 70\r\n"
31520       "Content-Type: application/sdp\r\n"
31521       "Content-Length: \t\r\n"
31522       "\t \r\n"
31523       " 130\t \r\n"
31524       "\r\n"
31525       "v=0\r\n"
31526       "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
31527       "s=-\r\n"
31528       "c=IN IP4 127.0.0.1\r\n"
31529       "t=0 0\r\n"
31530       "m=audio 10000 RTP/AVP 0\r\n"
31531       "a=rtpmap:0 PCMU/8000\r\n"
31532    };
31533 
31534    /* Message with compact Content-length header in message and
31535     * full Content-Length header in the body. Ensure that the header
31536     * in the message is read and that the one in the body is ignored
31537     */
31538    char *cl_in_body[] = {
31539       "INVITE sip:bob@example.org SIP/2.0\r\n"
31540       "Via: SIP/2.0/TCP 127.0.0.1:5060;branch=[branch]\r\n"
31541       "From: sipp <sip:127.0.0.1:5061>;tag=12345\r\n"
31542       "To: <sip:bob@example.org:5060>\r\n"
31543       "Call-ID: 12345\r\n"
31544       "CSeq: 1 INVITE\r\n"
31545       "Contact: sip:127.0.0.1:5061\r\n"
31546       "Max-Forwards: 70\r\n"
31547       "Content-Type: application/sdp\r\n"
31548       "l: 149\r\n"
31549       "\r\n"
31550       "v=0\r\n"
31551       "Content-Length: 0\r\n"
31552       "o=user1 53655765 2353687637 IN IP4 127.0.0.1\r\n"
31553       "s=-\r\n"
31554       "c=IN IP4 127.0.0.1\r\n"
31555       "t=0 0\r\n"
31556       "m=audio 10000 RTP/AVP 0\r\n"
31557       "a=rtpmap:0 PCMU/8000\r\n"
31558    };
31559 
31560    struct ast_str *overflow;
31561    struct {
31562       char **fragments;
31563       char **expected;
31564       int num_expected;
31565       const char *description;
31566    } tests[] = {
31567       { normal, normal, 1, "normal" },
31568       { fragmented, normal, 1, "fragmented" },
31569       { fragmented_body, normal, 1, "fragmented_body" },
31570       { multi_fragment, normal, 1, "multi_fragment" },
31571       { multi_message, multi_message_divided, 2, "multi_message" },
31572       { multi_message_body, multi_message_body_divided, 2, "multi_message_body" },
31573       { multi_message_in_fragments, multi_message_divided, 2, "multi_message_in_fragments" },
31574       { compact, compact, 1, "compact" },
31575       { faux, faux, 1, "faux" },
31576       { folded, folded, 1, "folded" },
31577       { cl_in_body, cl_in_body, 1, "cl_in_body" },
31578    };
31579    int i;
31580    enum ast_test_result_state res = AST_TEST_PASS;
31581 
31582    switch (cmd) {
31583       case TEST_INIT:
31584          info->name = "sip_tcp_message_fragmentation";
31585          info->category = "/main/sip/transport/";
31586          info->summary = "SIP TCP message fragmentation test";
31587          info->description =
31588             "Tests reception of different TCP messages that have been fragmented or"
31589             "run together. This test mimicks the code that TCP reception uses.";
31590          return AST_TEST_NOT_RUN;
31591       case TEST_EXECUTE:
31592          break;
31593    }
31594    if (!sip_cfg.pedanticsipchecking) {
31595       ast_log(LOG_WARNING, "Not running test. Pedantic SIP checking is not enabled, so it is guaranteed to fail\n");
31596       return AST_TEST_NOT_RUN;
31597    }
31598 
31599    overflow = ast_str_create(128);
31600    if (!overflow) {
31601       return AST_TEST_FAIL;
31602    }
31603    for (i = 0; i < ARRAY_LEN(tests); ++i) {
31604       int num_messages = 0;
31605       if (mock_tcp_loop(tests[i].fragments, ARRAY_LEN(tests[i].fragments),
31606                &overflow, tests[i].expected, &num_messages, test)) {
31607          ast_test_status_update(test, "Failed to parse message '%s'\n", tests[i].description);
31608          res = AST_TEST_FAIL;
31609          break;
31610       }
31611       if (num_messages != tests[i].num_expected) {
31612          ast_test_status_update(test, "Did not receive the expected number of messages. "
31613                "Expected %d but received %d\n", tests[i].num_expected, num_messages);
31614          res = AST_TEST_FAIL;
31615          break;
31616       }
31617    }
31618    ast_free(overflow);
31619    return res;
31620 }
31621 
31622 AST_TEST_DEFINE(get_in_brackets_const_test)
31623 {
31624    const char *input;
31625    const char *start = NULL;
31626    int len = 0;
31627    int res;
31628 
31629 #define CHECK_RESULTS(in, expected_res, expected_start, expected_len)   do {  \
31630       input = (in);                 \
31631       res = get_in_brackets_const(input, &start, &len);  \
31632       if ((expected_res) != res) {           \
31633          ast_test_status_update(test, "Unexpected result: %d != %d\n", expected_res, res); \
31634          return AST_TEST_FAIL;            \
31635       }                    \
31636       if ((expected_start) != start) {       \
31637          const char *e = expected_start ? expected_start : "(null)"; \
31638          const char *a = start ? start : "(null)"; \
31639          ast_test_status_update(test, "Unexpected start: %s != %s\n", e, a); \
31640          return AST_TEST_FAIL;            \
31641       }                    \
31642       if ((expected_len) != len) {           \
31643          ast_test_status_update(test, "Unexpected len: %d != %d\n", expected_len, len); \
31644          return AST_TEST_FAIL;            \
31645       }                    \
31646    } while(0)
31647 
31648    switch (cmd) {
31649    case TEST_INIT:
31650       info->name = __func__;
31651       info->category = "/channels/chan_sip/";
31652       info->summary = "get_in_brackets_const test";
31653       info->description =
31654          "Tests the get_in_brackets_const function";
31655       return AST_TEST_NOT_RUN;
31656    case TEST_EXECUTE:
31657       break;
31658    }
31659 
31660    CHECK_RESULTS("", 1, NULL, -1);
31661    CHECK_RESULTS("normal <test>", 0, input + 8, 4);
31662    CHECK_RESULTS("\"normal\" <test>", 0, input + 10, 4);
31663    CHECK_RESULTS("not normal <test", -1, NULL, -1);
31664    CHECK_RESULTS("\"yes < really\" <test>", 0, input + 16, 4);
31665    CHECK_RESULTS("\"even > this\" <test>", 0, input + 15, 4);
31666    CHECK_RESULTS("<sip:id1@10.10.10.10;lr>", 0, input + 1, 22);
31667    CHECK_RESULTS("<sip:id1@10.10.10.10;lr>, <sip:id1@10.10.10.20;lr>", 0, input + 1, 22);
31668    CHECK_RESULTS("<sip:id1,id2@10.10.10.10;lr>", 0, input + 1, 26);
31669    CHECK_RESULTS("<sip:id1@10., <sip:id2@10.10.10.10;lr>", 0, input + 1, 36);
31670    CHECK_RESULTS("\"quoted text\" <sip:dlg1@10.10.10.10;lr>", 0, input + 15, 23);
31671 
31672    return AST_TEST_PASS;
31673 }
31674 
31675 #endif
31676 
31677 #define DATA_EXPORT_SIP_PEER(MEMBER)            \
31678    MEMBER(sip_peer, name, AST_DATA_STRING)         \
31679    MEMBER(sip_peer, secret, AST_DATA_PASSWORD)     \
31680    MEMBER(sip_peer, md5secret, AST_DATA_PASSWORD)     \
31681    MEMBER(sip_peer, remotesecret, AST_DATA_PASSWORD)  \
31682    MEMBER(sip_peer, context, AST_DATA_STRING)      \
31683    MEMBER(sip_peer, subscribecontext, AST_DATA_STRING)   \
31684    MEMBER(sip_peer, username, AST_DATA_STRING)     \
31685    MEMBER(sip_peer, accountcode, AST_DATA_STRING)     \
31686    MEMBER(sip_peer, tohost, AST_DATA_STRING)    \
31687    MEMBER(sip_peer, regexten, AST_DATA_STRING)     \
31688    MEMBER(sip_peer, fromuser, AST_DATA_STRING)     \
31689    MEMBER(sip_peer, fromdomain, AST_DATA_STRING)      \
31690    MEMBER(sip_peer, fullcontact, AST_DATA_STRING)     \
31691    MEMBER(sip_peer, cid_num, AST_DATA_STRING)      \
31692    MEMBER(sip_peer, cid_name, AST_DATA_STRING)     \
31693    MEMBER(sip_peer, vmexten, AST_DATA_STRING)      \
31694    MEMBER(sip_peer, language, AST_DATA_STRING)     \
31695    MEMBER(sip_peer, mohinterpret, AST_DATA_STRING)    \
31696    MEMBER(sip_peer, mohsuggest, AST_DATA_STRING)      \
31697    MEMBER(sip_peer, parkinglot, AST_DATA_STRING)      \
31698    MEMBER(sip_peer, useragent, AST_DATA_STRING)    \
31699    MEMBER(sip_peer, mwi_from, AST_DATA_STRING)     \
31700    MEMBER(sip_peer, engine, AST_DATA_STRING)    \
31701    MEMBER(sip_peer, unsolicited_mailbox, AST_DATA_STRING)   \
31702    MEMBER(sip_peer, is_realtime, AST_DATA_BOOLEAN)    \
31703    MEMBER(sip_peer, host_dynamic, AST_DATA_BOOLEAN)   \
31704    MEMBER(sip_peer, autoframing, AST_DATA_BOOLEAN)    \
31705    MEMBER(sip_peer, inUse, AST_DATA_INTEGER)    \
31706    MEMBER(sip_peer, inRinging, AST_DATA_INTEGER)      \
31707    MEMBER(sip_peer, onHold, AST_DATA_INTEGER)      \
31708    MEMBER(sip_peer, call_limit, AST_DATA_INTEGER)     \
31709    MEMBER(sip_peer, t38_maxdatagram, AST_DATA_INTEGER)   \
31710    MEMBER(sip_peer, maxcallbitrate, AST_DATA_INTEGER) \
31711    MEMBER(sip_peer, rtptimeout, AST_DATA_SECONDS)     \
31712    MEMBER(sip_peer, rtpholdtimeout, AST_DATA_SECONDS) \
31713    MEMBER(sip_peer, rtpkeepalive, AST_DATA_SECONDS)   \
31714    MEMBER(sip_peer, lastms, AST_DATA_MILLISECONDS)    \
31715    MEMBER(sip_peer, maxms, AST_DATA_MILLISECONDS)     \
31716    MEMBER(sip_peer, qualifyfreq, AST_DATA_MILLISECONDS)  \
31717    MEMBER(sip_peer, timer_t1, AST_DATA_MILLISECONDS)  \
31718    MEMBER(sip_peer, timer_b, AST_DATA_MILLISECONDS)
31719 
31720 AST_DATA_STRUCTURE(sip_peer, DATA_EXPORT_SIP_PEER);
31721 
31722 static int peers_data_provider_get(const struct ast_data_search *search,
31723    struct ast_data *data_root)
31724 {
31725    struct sip_peer *peer;
31726    struct ao2_iterator i;
31727    struct ast_data *data_peer, *data_peer_mailboxes = NULL, *data_peer_mailbox, *enum_node;
31728    struct ast_data *data_sip_options;
31729    int total_mailboxes, x;
31730    struct sip_mailbox *mailbox;
31731 
31732    i = ao2_iterator_init(peers, 0);
31733    while ((peer = ao2_iterator_next(&i))) {
31734       ao2_lock(peer);
31735 
31736       data_peer = ast_data_add_node(data_root, "peer");
31737       if (!data_peer) {
31738          ao2_unlock(peer);
31739          ao2_ref(peer, -1);
31740          continue;
31741       }
31742 
31743       ast_data_add_structure(sip_peer, data_peer, peer);
31744 
31745       /* transfer mode */
31746       enum_node = ast_data_add_node(data_peer, "allowtransfer");
31747       if (!enum_node) {
31748          ao2_unlock(peer);
31749          ao2_ref(peer, -1);
31750          continue;
31751       }
31752       ast_data_add_str(enum_node, "text", transfermode2str(peer->allowtransfer));
31753       ast_data_add_int(enum_node, "value", peer->allowtransfer);
31754 
31755       /* transports */
31756       ast_data_add_str(data_peer, "transports", get_transport_list(peer->transports));
31757 
31758       /* peer type */
31759       if ((peer->type & SIP_TYPE_USER) && (peer->type & SIP_TYPE_PEER)) {
31760          ast_data_add_str(data_peer, "type", "friend");
31761       } else if (peer->type & SIP_TYPE_PEER) {
31762          ast_data_add_str(data_peer, "type", "peer");
31763       } else if (peer->type & SIP_TYPE_USER) {
31764          ast_data_add_str(data_peer, "type", "user");
31765       }
31766 
31767       /* mailboxes */
31768       total_mailboxes = 0;
31769       AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
31770          if (!total_mailboxes) {
31771             data_peer_mailboxes = ast_data_add_node(data_peer, "mailboxes");
31772             if (!data_peer_mailboxes) {
31773                break;
31774             }
31775             total_mailboxes++;
31776          }
31777 
31778          data_peer_mailbox = ast_data_add_node(data_peer_mailboxes, "mailbox");
31779          if (!data_peer_mailbox) {
31780             continue;
31781          }
31782          ast_data_add_str(data_peer_mailbox, "mailbox", mailbox->mailbox);
31783          ast_data_add_str(data_peer_mailbox, "context", mailbox->context);
31784       }
31785 
31786       /* amaflags */
31787       enum_node = ast_data_add_node(data_peer, "amaflags");
31788       if (!enum_node) {
31789          ao2_unlock(peer);
31790          ao2_ref(peer, -1);
31791          continue;
31792       }
31793       ast_data_add_int(enum_node, "value", peer->amaflags);
31794       ast_data_add_str(enum_node, "text", ast_cdr_flags2str(peer->amaflags));
31795 
31796       /* sip options */
31797       data_sip_options = ast_data_add_node(data_peer, "sipoptions");
31798       if (!data_sip_options) {
31799          ao2_unlock(peer);
31800          ao2_ref(peer, -1);
31801          continue;
31802       }
31803       for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
31804          ast_data_add_bool(data_sip_options, sip_options[x].text, peer->sipoptions & sip_options[x].id);
31805       }
31806 
31807       /* callingpres */
31808       enum_node = ast_data_add_node(data_peer, "callingpres");
31809       if (!enum_node) {
31810          ao2_unlock(peer);
31811          ao2_ref(peer, -1);
31812          continue;
31813       }
31814       ast_data_add_int(enum_node, "value", peer->callingpres);
31815       ast_data_add_str(enum_node, "text", ast_describe_caller_presentation(peer->callingpres));
31816 
31817       /* codecs */
31818       ast_data_add_codecs(data_peer, "codecs", peer->capability);
31819 
31820       if (!ast_data_search_match(search, data_peer)) {
31821          ast_data_remove_node(data_root, data_peer);
31822       }
31823 
31824       ao2_unlock(peer);
31825       ao2_ref(peer, -1);
31826    }
31827    ao2_iterator_destroy(&i);
31828 
31829    return 0;
31830 }
31831 
31832 static const struct ast_data_handler peers_data_provider = {
31833    .version = AST_DATA_HANDLER_VERSION,
31834    .get = peers_data_provider_get
31835 };
31836 
31837 static const struct ast_data_entry sip_data_providers[] = {
31838    AST_DATA_ENTRY("asterisk/channel/sip/peers", &peers_data_provider),
31839 };
31840 
31841 /*! \brief PBX load module - initialization */
31842 static int load_module(void)
31843 {
31844    ast_verbose("SIP channel loading...\n");
31845 
31846    /* the fact that ao2_containers can't resize automatically is a major worry! */
31847    /* if the number of objects gets above MAX_XXX_BUCKETS, things will slow down */
31848    peers = ao2_t_container_alloc(HASH_PEER_SIZE, peer_hash_cb, peer_cmp_cb, "allocate peers");
31849    peers_by_ip = ao2_t_container_alloc(HASH_PEER_SIZE, peer_iphash_cb, peer_ipcmp_cb, "allocate peers_by_ip");
31850    dialogs = ao2_t_container_alloc(HASH_DIALOG_SIZE, dialog_hash_cb, dialog_cmp_cb, "allocate dialogs");
31851    dialogs_to_destroy = ao2_t_container_alloc(1, NULL, NULL, "allocate dialogs_to_destroy");
31852    threadt = ao2_t_container_alloc(HASH_DIALOG_SIZE, threadt_hash_cb, threadt_cmp_cb, "allocate threadt table");
31853    if (!peers || !peers_by_ip || !dialogs || !dialogs_to_destroy || !threadt) {
31854       ast_log(LOG_ERROR, "Unable to create primary SIP container(s)\n");
31855       return AST_MODULE_LOAD_FAILURE;
31856    }
31857 
31858    ASTOBJ_CONTAINER_INIT(&regl); /* Registry object list -- not searched for anything */
31859    ASTOBJ_CONTAINER_INIT(&submwil); /* MWI subscription object list */
31860 
31861    if (!(sched = sched_context_create())) {
31862       ast_log(LOG_ERROR, "Unable to create scheduler context\n");
31863       return AST_MODULE_LOAD_FAILURE;
31864    }
31865 
31866    if (!(io = io_context_create())) {
31867       ast_log(LOG_ERROR, "Unable to create I/O context\n");
31868       sched_context_destroy(sched);
31869       return AST_MODULE_LOAD_FAILURE;
31870    }
31871 
31872    sip_reloadreason = CHANNEL_MODULE_LOAD;
31873 
31874    can_parse_xml = sip_is_xml_parsable();
31875    if (reload_config(sip_reloadreason)) { /* Load the configuration from sip.conf */
31876       return AST_MODULE_LOAD_DECLINE;
31877    }
31878 
31879    /* Initialize bogus peer. Can be done first after reload_config() */
31880    if (!(bogus_peer = temp_peer("(bogus_peer)"))) {
31881       ast_log(LOG_ERROR, "Unable to create bogus_peer for authentication\n");
31882       io_context_destroy(io);
31883       sched_context_destroy(sched);
31884       return AST_MODULE_LOAD_FAILURE;
31885    }
31886    /* Make sure the auth will always fail. */
31887    ast_string_field_set(bogus_peer, md5secret, BOGUS_PEER_MD5SECRET);
31888    ast_clear_flag(&bogus_peer->flags[0], SIP_INSECURE);
31889 
31890    /* Prepare the version that does not require DTMF BEGIN frames.
31891     * We need to use tricks such as memcpy and casts because the variable
31892     * has const fields.
31893     */
31894    memcpy(&sip_tech_info, &sip_tech, sizeof(sip_tech));
31895    memset((void *) &sip_tech_info.send_digit_begin, 0, sizeof(sip_tech_info.send_digit_begin));
31896 
31897    /* Make sure we can register our sip channel type */
31898    if (ast_channel_register(&sip_tech)) {
31899       ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
31900       ao2_t_ref(bogus_peer, -1, "unref the bogus_peer");
31901       io_context_destroy(io);
31902       sched_context_destroy(sched);
31903       return AST_MODULE_LOAD_FAILURE;
31904    }
31905 
31906 #ifdef TEST_FRAMEWORK
31907    AST_TEST_REGISTER(test_sip_peers_get);
31908    AST_TEST_REGISTER(test_sip_mwi_subscribe_parse);
31909    AST_TEST_REGISTER(test_tcp_message_fragmentation);
31910    AST_TEST_REGISTER(get_in_brackets_const_test);
31911 #endif
31912 
31913    /* Register AstData providers */
31914    ast_data_register_multiple(sip_data_providers, ARRAY_LEN(sip_data_providers));
31915 
31916    /* Register all CLI functions for SIP */
31917    ast_cli_register_multiple(cli_sip, ARRAY_LEN(cli_sip));
31918 
31919    /* Tell the UDPTL subdriver that we're here */
31920    ast_udptl_proto_register(&sip_udptl);
31921 
31922    /* Tell the RTP engine about our RTP glue */
31923    ast_rtp_glue_register(&sip_rtp_glue);
31924 
31925    /* Register dialplan applications */
31926    ast_register_application_xml(app_dtmfmode, sip_dtmfmode);
31927    ast_register_application_xml(app_sipaddheader, sip_addheader);
31928    ast_register_application_xml(app_sipremoveheader, sip_removeheader);
31929 
31930    /* Register dialplan functions */
31931    ast_custom_function_register(&sip_header_function);
31932    ast_custom_function_register(&sippeer_function);
31933    ast_custom_function_register(&sipchaninfo_function);
31934    ast_custom_function_register(&checksipdomain_function);
31935 
31936    /* Register manager commands */
31937    ast_manager_register_xml("SIPpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peers);
31938    ast_manager_register_xml("SIPshowpeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peer);
31939    ast_manager_register_xml("SIPqualifypeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_qualify_peer);
31940    ast_manager_register_xml("SIPshowregistry", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_show_registry);
31941    ast_manager_register_xml("SIPnotify", EVENT_FLAG_SYSTEM, manager_sipnotify);
31942    sip_poke_all_peers();   
31943    sip_send_all_registers();
31944    sip_send_all_mwi_subscriptions();
31945    initialize_escs();
31946 
31947    if (sip_epa_register(&cc_epa_static_data)) {
31948       return AST_MODULE_LOAD_DECLINE;
31949    }
31950 
31951    if (sip_reqresp_parser_init() == -1) {
31952       ast_log(LOG_ERROR, "Unable to initialize the SIP request and response parser\n");
31953       return AST_MODULE_LOAD_DECLINE;
31954    }
31955 
31956    if (can_parse_xml) {
31957       /* SIP CC agents require the ability to parse XML PIDF bodies
31958        * in incoming PUBLISH requests
31959        */
31960       if (ast_cc_agent_register(&sip_cc_agent_callbacks)) {
31961          return AST_MODULE_LOAD_DECLINE;
31962       }
31963    }
31964    if (ast_cc_monitor_register(&sip_cc_monitor_callbacks)) {
31965       return AST_MODULE_LOAD_DECLINE;
31966    }
31967    if (!(sip_monitor_instances = ao2_container_alloc(37, sip_monitor_instance_hash_fn, sip_monitor_instance_cmp_fn))) {
31968       return AST_MODULE_LOAD_DECLINE;
31969    }
31970 
31971    /* And start the monitor for the first time */
31972    restart_monitor();
31973 
31974    ast_realtime_require_field(ast_check_realtime("sipregs") ? "sipregs" : "sippeers",
31975       "name", RQ_CHAR, 10,
31976       "ipaddr", RQ_CHAR, INET6_ADDRSTRLEN - 1,
31977       "port", RQ_UINTEGER2, 5,
31978       "regseconds", RQ_INTEGER4, 11,
31979       "defaultuser", RQ_CHAR, 10,
31980       "fullcontact", RQ_CHAR, 35,
31981       "regserver", RQ_CHAR, 20,
31982       "useragent", RQ_CHAR, 20,
31983       "lastms", RQ_INTEGER4, 11,
31984       SENTINEL);
31985 
31986 
31987    sip_register_tests();
31988    network_change_event_subscribe();
31989 
31990    return AST_MODULE_LOAD_SUCCESS;
31991 }
31992 
31993 /*! \brief PBX unload module API */
31994 static int unload_module(void)
31995 {
31996    struct sip_pvt *p;
31997    struct sip_threadinfo *th;
31998    struct ast_context *con;
31999    struct ao2_iterator i;
32000    int wait_count;
32001 
32002    network_change_event_unsubscribe();
32003 
32004    ast_sched_dump(sched);
32005    
32006    /* First, take us out of the channel type list */
32007    ast_channel_unregister(&sip_tech);
32008 
32009    /* Unregister dial plan functions */
32010    ast_custom_function_unregister(&sipchaninfo_function);
32011    ast_custom_function_unregister(&sippeer_function);
32012    ast_custom_function_unregister(&sip_header_function);
32013    ast_custom_function_unregister(&checksipdomain_function);
32014 
32015    /* Unregister dial plan applications */
32016    ast_unregister_application(app_dtmfmode);
32017    ast_unregister_application(app_sipaddheader);
32018    ast_unregister_application(app_sipremoveheader);
32019 
32020 #ifdef TEST_FRAMEWORK
32021    AST_TEST_UNREGISTER(test_sip_peers_get);
32022    AST_TEST_UNREGISTER(test_sip_mwi_subscribe_parse);
32023    AST_TEST_UNREGISTER(test_tcp_message_fragmentation);
32024    AST_TEST_UNREGISTER(get_in_brackets_const_test);
32025 #endif
32026    /* Unregister all the AstData providers */
32027    ast_data_unregister(NULL);
32028 
32029    /* Unregister CLI commands */
32030    ast_cli_unregister_multiple(cli_sip, ARRAY_LEN(cli_sip));
32031 
32032    /* Disconnect from UDPTL */
32033    ast_udptl_proto_unregister(&sip_udptl);
32034 
32035    /* Disconnect from RTP engine */
32036    ast_rtp_glue_unregister(&sip_rtp_glue);
32037 
32038    /* Unregister AMI actions */
32039    ast_manager_unregister("SIPpeers");
32040    ast_manager_unregister("SIPshowpeer");
32041    ast_manager_unregister("SIPqualifypeer");
32042    ast_manager_unregister("SIPshowregistry");
32043    ast_manager_unregister("SIPnotify");
32044    
32045    /* Kill TCP/TLS server threads */
32046    if (sip_tcp_desc.master) {
32047       ast_tcptls_server_stop(&sip_tcp_desc);
32048    }
32049    if (sip_tls_desc.master) {
32050       ast_tcptls_server_stop(&sip_tls_desc);
32051    }
32052    ast_ssl_teardown(sip_tls_desc.tls_cfg);
32053 
32054    /* Kill all existing TCP/TLS threads */
32055    i = ao2_iterator_init(threadt, 0);
32056    while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
32057       pthread_t thread = th->threadid;
32058       th->stop = 1;
32059       pthread_kill(thread, SIGURG);
32060       ao2_t_ref(th, -1, "decrement ref from iterator");
32061    }
32062    ao2_iterator_destroy(&i);
32063 
32064    /* Hangup all dialogs if they have an owner */
32065    i = ao2_iterator_init(dialogs, 0);
32066    while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
32067       if (p->owner)
32068          ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
32069       ao2_t_ref(p, -1, "toss dialog ptr from iterator_next");
32070    }
32071    ao2_iterator_destroy(&i);
32072 
32073    unlink_all_peers_from_tables();
32074 
32075    ast_mutex_lock(&monlock);
32076    if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
32077       pthread_t th = monitor_thread;
32078       monitor_thread = AST_PTHREADT_STOP;
32079       pthread_cancel(th);
32080       pthread_kill(th, SIGURG);
32081       ast_mutex_unlock(&monlock);
32082       pthread_join(th, NULL);
32083    } else {
32084       monitor_thread = AST_PTHREADT_STOP;
32085       ast_mutex_unlock(&monlock);
32086    }
32087 
32088    /* Destroy all the dialogs and free their memory */
32089    i = ao2_iterator_init(dialogs, 0);
32090    while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
32091       dialog_unlink_all(p);
32092       ao2_t_ref(p, -1, "throw away iterator result");
32093    }
32094    ao2_iterator_destroy(&i);
32095 
32096    /* Free memory for local network address mask */
32097    ast_free_ha(localaddr);
32098 
32099    ast_mutex_lock(&authl_lock);
32100    if (authl) {
32101       ao2_t_ref(authl, -1, "Removing global authentication");
32102       authl = NULL;
32103    }
32104    ast_mutex_unlock(&authl_lock);
32105 
32106    sip_epa_unregister_all();
32107    destroy_escs();
32108 
32109    ast_free(default_tls_cfg.certfile);
32110    ast_free(default_tls_cfg.pvtfile);
32111    ast_free(default_tls_cfg.cipher);
32112    ast_free(default_tls_cfg.cafile);
32113    ast_free(default_tls_cfg.capath);
32114 
32115    cleanup_all_regs();
32116    ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
32117    ASTOBJ_CONTAINER_DESTROY(&regl);
32118 
32119    ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
32120       ASTOBJ_WRLOCK(iterator);
32121       if (iterator->dnsmgr) {
32122          ast_dnsmgr_release(iterator->dnsmgr);
32123          iterator->dnsmgr = NULL;
32124          ASTOBJ_UNREF(iterator, sip_subscribe_mwi_destroy);
32125       }
32126       ASTOBJ_UNLOCK(iterator);
32127    } while(0));
32128    ASTOBJ_CONTAINER_DESTROYALL(&submwil, sip_subscribe_mwi_destroy);
32129    ASTOBJ_CONTAINER_DESTROY(&submwil);
32130 
32131    /*
32132     * Wait awhile for the TCP/TLS thread container to become empty.
32133     *
32134     * XXX This is a hack, but the worker threads cannot be created
32135     * joinable.  They can die on their own and remove themselves
32136     * from the container thus resulting in a huge memory leak.
32137     */
32138    wait_count = 1000;
32139    while (ao2_container_count(threadt) && --wait_count) {
32140       sched_yield();
32141    }
32142    if (!wait_count) {
32143       ast_debug(2, "TCP/TLS thread container did not become empty :(\n");
32144    }
32145 
32146    ao2_t_ref(bogus_peer, -1, "unref the bogus_peer");
32147 
32148    ao2_t_ref(peers, -1, "unref the peers table");
32149    ao2_t_ref(peers_by_ip, -1, "unref the peers_by_ip table");
32150    ao2_t_ref(dialogs, -1, "unref the dialogs table");
32151    ao2_t_ref(dialogs_to_destroy, -1, "unref dialogs_to_destroy");
32152    ao2_t_ref(threadt, -1, "unref the thread table");
32153    ao2_t_ref(sip_monitor_instances, -1, "unref the sip_monitor_instances table");
32154 
32155    clear_sip_domains();
32156    ast_free_ha(sip_cfg.contact_ha);
32157    if (sipsock_read_id) {
32158       ast_io_remove(io, sipsock_read_id);
32159       sipsock_read_id = NULL;
32160    }
32161    close(sipsock);
32162    io_context_destroy(io);
32163    sched_context_destroy(sched);
32164    con = ast_context_find(used_context);
32165    if (con) {
32166       ast_context_destroy(con, "SIP");
32167    }
32168    ast_unload_realtime("sipregs");
32169    ast_unload_realtime("sippeers");
32170    ast_cc_monitor_unregister(&sip_cc_monitor_callbacks);
32171    ast_cc_agent_unregister(&sip_cc_agent_callbacks);
32172 
32173    sip_reqresp_parser_exit();
32174    sip_unregister_tests();
32175 
32176    if (notify_types) {
32177       ast_config_destroy(notify_types);
32178       notify_types = NULL;
32179    }
32180 
32181    return 0;
32182 }
32183 
32184 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Session Initiation Protocol (SIP)",
32185       .load = load_module,
32186       .unload = unload_module,
32187       .reload = reload,
32188       .load_pri = AST_MODPRI_CHANNEL_DRIVER,
32189       .nonoptreq = "res_crypto,chan_local",
32190           );

Generated on 7 Sep 2017 for Asterisk - The Open Source Telephony Project by  doxygen 1.6.1