Wed Nov 28 2012 04:18:07

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: 374456 $")
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 /*
00222    Uncomment the define below,  if you are having refcount related memory leaks.
00223    With this uncommented, this module will generate a file, /tmp/refs, which contains
00224    a history of the ao2_ref() calls. To be useful, all calls to ao2_* functions should
00225    be modified to ao2_t_* calls, and include a tag describing what is happening with
00226    enough detail, to make pairing up a reference count increment with its corresponding decrement.
00227    The refcounter program in utils/ can be invaluable in highlighting objects that are not
00228    balanced, along with the complete history for that object.
00229    In normal operation, the macros defined will throw away the tags, so they do not
00230    affect the speed of the program at all. They can be considered to be documentation.
00231 */
00232 /* #define  REF_DEBUG 1 */
00233 #include "asterisk/lock.h"
00234 #include "asterisk/config.h"
00235 #include "asterisk/module.h"
00236 #include "asterisk/pbx.h"
00237 #include "asterisk/sched.h"
00238 #include "asterisk/io.h"
00239 #include "asterisk/rtp_engine.h"
00240 #include "asterisk/udptl.h"
00241 #include "asterisk/acl.h"
00242 #include "asterisk/manager.h"
00243 #include "asterisk/callerid.h"
00244 #include "asterisk/cli.h"
00245 #include "asterisk/musiconhold.h"
00246 #include "asterisk/dsp.h"
00247 #include "asterisk/features.h"
00248 #include "asterisk/srv.h"
00249 #include "asterisk/astdb.h"
00250 #include "asterisk/causes.h"
00251 #include "asterisk/utils.h"
00252 #include "asterisk/file.h"
00253 #include "asterisk/astobj2.h"
00254 #include "asterisk/dnsmgr.h"
00255 #include "asterisk/devicestate.h"
00256 #include "asterisk/monitor.h"
00257 #include "asterisk/netsock2.h"
00258 #include "asterisk/localtime.h"
00259 #include "asterisk/abstract_jb.h"
00260 #include "asterisk/threadstorage.h"
00261 #include "asterisk/translate.h"
00262 #include "asterisk/ast_version.h"
00263 #include "asterisk/event.h"
00264 #include "asterisk/cel.h"
00265 #include "asterisk/data.h"
00266 #include "asterisk/aoc.h"
00267 #include "sip/include/sip.h"
00268 #include "sip/include/globals.h"
00269 #include "sip/include/config_parser.h"
00270 #include "sip/include/reqresp_parser.h"
00271 #include "sip/include/sip_utils.h"
00272 #include "sip/include/srtp.h"
00273 #include "sip/include/sdp_crypto.h"
00274 #include "asterisk/ccss.h"
00275 #include "asterisk/xml.h"
00276 #include "sip/include/dialog.h"
00277 #include "sip/include/dialplan_functions.h"
00278 
00279 
00280 /*** DOCUMENTATION
00281    <application name="SIPDtmfMode" language="en_US">
00282       <synopsis>
00283          Change the dtmfmode for a SIP call.
00284       </synopsis>
00285       <syntax>
00286          <parameter name="mode" required="true">
00287             <enumlist>
00288                <enum name="inband" />
00289                <enum name="info" />
00290                <enum name="rfc2833" />
00291             </enumlist>
00292          </parameter>
00293       </syntax>
00294       <description>
00295          <para>Changes the dtmfmode for a SIP call.</para>
00296       </description>
00297    </application>
00298    <application name="SIPAddHeader" language="en_US">
00299       <synopsis>
00300          Add a SIP header to the outbound call.
00301       </synopsis>
00302       <syntax argsep=":">
00303          <parameter name="Header" required="true" />
00304          <parameter name="Content" required="true" />
00305       </syntax>
00306       <description>
00307          <para>Adds a header to a SIP call placed with DIAL.</para>
00308          <para>Remember to use the X-header if you are adding non-standard SIP
00309          headers, like <literal>X-Asterisk-Accountcode:</literal>. Use this with care.
00310          Adding the wrong headers may jeopardize the SIP dialog.</para>
00311          <para>Always returns <literal>0</literal>.</para>
00312       </description>
00313    </application>
00314    <application name="SIPRemoveHeader" language="en_US">
00315       <synopsis>
00316          Remove SIP headers previously added with SIPAddHeader
00317       </synopsis>
00318       <syntax>
00319          <parameter name="Header" required="false" />
00320       </syntax>
00321       <description>
00322          <para>SIPRemoveHeader() allows you to remove headers which were previously
00323          added with SIPAddHeader(). If no parameter is supplied, all previously added
00324          headers will be removed. If a parameter is supplied, only the matching headers
00325          will be removed.</para>
00326          <para>For example you have added these 2 headers:</para>
00327          <para>SIPAddHeader(P-Asserted-Identity: sip:foo@bar);</para>
00328          <para>SIPAddHeader(P-Preferred-Identity: sip:bar@foo);</para>
00329          <para></para>
00330          <para>// remove all headers</para>
00331          <para>SIPRemoveHeader();</para>
00332          <para>// remove all P- headers</para>
00333          <para>SIPRemoveHeader(P-);</para>
00334          <para>// remove only the PAI header (note the : at the end)</para>
00335          <para>SIPRemoveHeader(P-Asserted-Identity:);</para>
00336          <para></para>
00337          <para>Always returns <literal>0</literal>.</para>
00338       </description>
00339    </application>
00340    <function name="SIP_HEADER" language="en_US">
00341       <synopsis>
00342          Gets the specified SIP header from an incoming INVITE message.
00343       </synopsis>
00344       <syntax>
00345          <parameter name="name" required="true" />
00346          <parameter name="number">
00347             <para>If not specified, defaults to <literal>1</literal>.</para>
00348          </parameter>
00349       </syntax>
00350       <description>
00351          <para>Since there are several headers (such as Via) which can occur multiple
00352          times, SIP_HEADER takes an optional second argument to specify which header with
00353          that name to retrieve. Headers start at offset <literal>1</literal>.</para>
00354       </description>
00355    </function>
00356    <function name="SIPPEER" language="en_US">
00357       <synopsis>
00358          Gets SIP peer information.
00359       </synopsis>
00360       <syntax>
00361          <parameter name="peername" required="true" />
00362          <parameter name="item">
00363             <enumlist>
00364                <enum name="ip">
00365                   <para>(default) The ip address.</para>
00366                </enum>
00367                <enum name="port">
00368                   <para>The port number.</para>
00369                </enum>
00370                <enum name="mailbox">
00371                   <para>The configured mailbox.</para>
00372                </enum>
00373                <enum name="context">
00374                   <para>The configured context.</para>
00375                </enum>
00376                <enum name="expire">
00377                   <para>The epoch time of the next expire.</para>
00378                </enum>
00379                <enum name="dynamic">
00380                   <para>Is it dynamic? (yes/no).</para>
00381                </enum>
00382                <enum name="callerid_name">
00383                   <para>The configured Caller ID name.</para>
00384                </enum>
00385                <enum name="callerid_num">
00386                   <para>The configured Caller ID number.</para>
00387                </enum>
00388                <enum name="callgroup">
00389                   <para>The configured Callgroup.</para>
00390                </enum>
00391                <enum name="pickupgroup">
00392                   <para>The configured Pickupgroup.</para>
00393                </enum>
00394                <enum name="codecs">
00395                   <para>The configured codecs.</para>
00396                </enum>
00397                <enum name="status">
00398                   <para>Status (if qualify=yes).</para>
00399                </enum>
00400                <enum name="regexten">
00401                   <para>Registration extension.</para>
00402                </enum>
00403                <enum name="limit">
00404                   <para>Call limit (call-limit).</para>
00405                </enum>
00406                <enum name="busylevel">
00407                   <para>Configured call level for signalling busy.</para>
00408                </enum>
00409                <enum name="curcalls">
00410                   <para>Current amount of calls. Only available if call-limit is set.</para>
00411                </enum>
00412                <enum name="language">
00413                   <para>Default language for peer.</para>
00414                </enum>
00415                <enum name="accountcode">
00416                   <para>Account code for this peer.</para>
00417                </enum>
00418                <enum name="useragent">
00419                   <para>Current user agent id for peer.</para>
00420                </enum>
00421                <enum name="maxforwards">
00422                   <para>The value used for SIP loop prevention in outbound requests</para>
00423                </enum>
00424                <enum name="chanvar[name]">
00425                   <para>A channel variable configured with setvar for this peer.</para>
00426                </enum>
00427                <enum name="codec[x]">
00428                   <para>Preferred codec index number <replaceable>x</replaceable> (beginning with zero).</para>
00429                </enum>
00430             </enumlist>
00431          </parameter>
00432       </syntax>
00433       <description></description>
00434    </function>
00435    <function name="SIPCHANINFO" language="en_US">
00436       <synopsis>
00437          Gets the specified SIP parameter from the current channel.
00438       </synopsis>
00439       <syntax>
00440          <parameter name="item" required="true">
00441             <enumlist>
00442                <enum name="peerip">
00443                   <para>The IP address of the peer.</para>
00444                </enum>
00445                <enum name="recvip">
00446                   <para>The source IP address of the peer.</para>
00447                </enum>
00448                <enum name="from">
00449                   <para>The URI from the <literal>From:</literal> header.</para>
00450                </enum>
00451                <enum name="uri">
00452                   <para>The URI from the <literal>Contact:</literal> header.</para>
00453                </enum>
00454                <enum name="useragent">
00455                   <para>The useragent.</para>
00456                </enum>
00457                <enum name="peername">
00458                   <para>The name of the peer.</para>
00459                </enum>
00460                <enum name="t38passthrough">
00461                   <para><literal>1</literal> if T38 is offered or enabled in this channel,
00462                   otherwise <literal>0</literal>.</para>
00463                </enum>
00464             </enumlist>
00465          </parameter>
00466       </syntax>
00467       <description></description>
00468    </function>
00469    <function name="CHECKSIPDOMAIN" language="en_US">
00470       <synopsis>
00471          Checks if domain is a local domain.
00472       </synopsis>
00473       <syntax>
00474          <parameter name="domain" required="true" />
00475       </syntax>
00476       <description>
00477          <para>This function checks if the <replaceable>domain</replaceable> in the argument is configured
00478          as a local SIP domain that this Asterisk server is configured to handle.
00479          Returns the domain name if it is locally handled, otherwise an empty string.
00480          Check the <literal>domain=</literal> configuration in <filename>sip.conf</filename>.</para>
00481       </description>
00482    </function>
00483    <manager name="SIPpeers" language="en_US">
00484       <synopsis>
00485          List SIP peers (text format).
00486       </synopsis>
00487       <syntax>
00488          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00489       </syntax>
00490       <description>
00491          <para>Lists SIP peers in text format with details on current status.
00492          Peerlist will follow as separate events, followed by a final event called
00493          PeerlistComplete.</para>
00494       </description>
00495    </manager>
00496    <manager name="SIPshowpeer" language="en_US">
00497       <synopsis>
00498          show SIP peer (text format).
00499       </synopsis>
00500       <syntax>
00501          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00502          <parameter name="Peer" required="true">
00503             <para>The peer name you want to check.</para>
00504          </parameter>
00505       </syntax>
00506       <description>
00507          <para>Show one SIP peer with details on current status.</para>
00508       </description>
00509    </manager>
00510    <manager name="SIPqualifypeer" language="en_US">
00511       <synopsis>
00512          Qualify SIP peers.
00513       </synopsis>
00514       <syntax>
00515          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00516          <parameter name="Peer" required="true">
00517             <para>The peer name you want to qualify.</para>
00518          </parameter>
00519       </syntax>
00520       <description>
00521          <para>Qualify a SIP peer.</para>
00522       </description>
00523    </manager>
00524    <manager name="SIPshowregistry" language="en_US">
00525       <synopsis>
00526          Show SIP registrations (text format).
00527       </synopsis>
00528       <syntax>
00529          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00530       </syntax>
00531       <description>
00532          <para>Lists all registration requests and status. Registrations will follow as separate
00533          events. followed by a final event called RegistrationsComplete.</para>
00534       </description>
00535    </manager>
00536    <manager name="SIPnotify" language="en_US">
00537       <synopsis>
00538          Send a SIP notify.
00539       </synopsis>
00540       <syntax>
00541          <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
00542          <parameter name="Channel" required="true">
00543             <para>Peer to receive the notify.</para>
00544          </parameter>
00545          <parameter name="Variable" required="true">
00546             <para>At least one variable pair must be specified.
00547             <replaceable>name</replaceable>=<replaceable>value</replaceable></para>
00548          </parameter>
00549       </syntax>
00550       <description>
00551          <para>Sends a SIP Notify event.</para>
00552          <para>All parameters for this event must be specified in the body of this request
00553          via multiple Variable: name=value sequences.</para>
00554       </description>
00555    </manager>
00556  ***/
00557 
00558 static int min_expiry = DEFAULT_MIN_EXPIRY;        /*!< Minimum accepted registration time */
00559 static int max_expiry = DEFAULT_MAX_EXPIRY;        /*!< Maximum accepted registration time */
00560 static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
00561 static int mwi_expiry = DEFAULT_MWI_EXPIRY;
00562 
00563 static int unauth_sessions = 0;
00564 static int authlimit = DEFAULT_AUTHLIMIT;
00565 static int authtimeout = DEFAULT_AUTHTIMEOUT;
00566 
00567 /*! \brief Global jitterbuffer configuration - by default, jb is disabled
00568  *  \note Values shown here match the defaults shown in sip.conf.sample */
00569 static struct ast_jb_conf default_jbconf =
00570 {
00571    .flags = 0,
00572    .max_size = 200,
00573    .resync_threshold = 1000,
00574    .impl = "fixed",
00575    .target_extra = 40,
00576 };
00577 static struct ast_jb_conf global_jbconf;                /*!< Global jitterbuffer configuration */
00578 
00579 static const char config[] = "sip.conf";                /*!< Main configuration file */
00580 static const char notify_config[] = "sip_notify.conf";  /*!< Configuration file for sending Notify with CLI commands to reconfigure or reboot phones */
00581 
00582 /*! \brief Readable descriptions of device states.
00583  *  \note Should be aligned to above table as index */
00584 static const struct invstate2stringtable {
00585    const enum invitestates state;
00586    const char *desc;
00587 } invitestate2string[] = {
00588    {INV_NONE,              "None"  },
00589    {INV_CALLING,           "Calling (Trying)"},
00590    {INV_PROCEEDING,        "Proceeding "},
00591    {INV_EARLY_MEDIA,       "Early media"},
00592    {INV_COMPLETED,         "Completed (done)"},
00593    {INV_CONFIRMED,         "Confirmed (up)"},
00594    {INV_TERMINATED,        "Done"},
00595    {INV_CANCELLED,         "Cancelled"}
00596 };
00597 
00598 /*! \brief Subscription types that we support. We support
00599  * - dialoginfo updates (really device status, not dialog info as was the original intent of the standard)
00600  * - SIMPLE presence used for device status
00601  * - Voicemail notification subscriptions
00602  */
00603 static const struct cfsubscription_types {
00604    enum subscriptiontype type;
00605    const char * const event;
00606    const char * const mediatype;
00607    const char * const text;
00608 } subscription_types[] = {
00609    { NONE,        "-",        "unknown",               "unknown" },
00610    /* RFC 4235: SIP Dialog event package */
00611    { DIALOG_INFO_XML, "dialog",   "application/dialog-info+xml", "dialog-info+xml" },
00612    { CPIM_PIDF_XML,   "presence", "application/cpim-pidf+xml",   "cpim-pidf+xml" },  /* RFC 3863 */
00613    { PIDF_XML,        "presence", "application/pidf+xml",        "pidf+xml" },       /* RFC 3863 */
00614    { XPIDF_XML,       "presence", "application/xpidf+xml",       "xpidf+xml" },       /* Pre-RFC 3863 with MS additions */
00615    { MWI_NOTIFICATION,  "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
00616 };
00617 
00618 /*! \brief The core structure to setup dialogs. We parse incoming messages by using
00619  *  structure and then route the messages according to the type.
00620  *
00621  *  \note Note that sip_methods[i].id == i must hold or the code breaks
00622  */
00623 static const struct  cfsip_methods {
00624    enum sipmethod id;
00625    int need_rtp;     /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
00626    char * const text;
00627    enum can_create_dialog can_create;
00628 } sip_methods[] = {
00629    { SIP_UNKNOWN,   RTP,    "-UNKNOWN-",CAN_CREATE_DIALOG },
00630    { SIP_RESPONSE,  NO_RTP, "SIP/2.0",  CAN_NOT_CREATE_DIALOG },
00631    { SIP_REGISTER,  NO_RTP, "REGISTER", CAN_CREATE_DIALOG },
00632    { SIP_OPTIONS,   NO_RTP, "OPTIONS",  CAN_CREATE_DIALOG },
00633    { SIP_NOTIFY,    NO_RTP, "NOTIFY",   CAN_CREATE_DIALOG },
00634    { SIP_INVITE,    RTP,    "INVITE",   CAN_CREATE_DIALOG },
00635    { SIP_ACK,       NO_RTP, "ACK",      CAN_NOT_CREATE_DIALOG },
00636    { SIP_PRACK,     NO_RTP, "PRACK",    CAN_NOT_CREATE_DIALOG },
00637    { SIP_BYE,       NO_RTP, "BYE",      CAN_NOT_CREATE_DIALOG },
00638    { SIP_REFER,     NO_RTP, "REFER",    CAN_CREATE_DIALOG },
00639    { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE",CAN_CREATE_DIALOG },
00640    { SIP_MESSAGE,   NO_RTP, "MESSAGE",  CAN_CREATE_DIALOG },
00641    { SIP_UPDATE,    NO_RTP, "UPDATE",   CAN_NOT_CREATE_DIALOG },
00642    { SIP_INFO,      NO_RTP, "INFO",     CAN_NOT_CREATE_DIALOG },
00643    { SIP_CANCEL,    NO_RTP, "CANCEL",   CAN_NOT_CREATE_DIALOG },
00644    { SIP_PUBLISH,   NO_RTP, "PUBLISH",  CAN_CREATE_DIALOG },
00645    { SIP_PING,      NO_RTP, "PING",     CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
00646 };
00647 
00648 /*! \brief Diversion header reasons
00649  *
00650  * The core defines a bunch of constants used to define
00651  * redirecting reasons. This provides a translation table
00652  * between those and the strings which may be present in
00653  * a SIP Diversion header
00654  */
00655 static const struct sip_reasons {
00656    enum AST_REDIRECTING_REASON code;
00657    char * const text;
00658 } sip_reason_table[] = {
00659    { AST_REDIRECTING_REASON_UNKNOWN, "unknown" },
00660    { AST_REDIRECTING_REASON_USER_BUSY, "user-busy" },
00661    { AST_REDIRECTING_REASON_NO_ANSWER, "no-answer" },
00662    { AST_REDIRECTING_REASON_UNAVAILABLE, "unavailable" },
00663    { AST_REDIRECTING_REASON_UNCONDITIONAL, "unconditional" },
00664    { AST_REDIRECTING_REASON_TIME_OF_DAY, "time-of-day" },
00665    { AST_REDIRECTING_REASON_DO_NOT_DISTURB, "do-not-disturb" },
00666    { AST_REDIRECTING_REASON_DEFLECTION, "deflection" },
00667    { AST_REDIRECTING_REASON_FOLLOW_ME, "follow-me" },
00668    { AST_REDIRECTING_REASON_OUT_OF_ORDER, "out-of-service" },
00669    { AST_REDIRECTING_REASON_AWAY, "away" },
00670    { AST_REDIRECTING_REASON_CALL_FWD_DTE, "unknown"}
00671 };
00672 
00673 
00674 /*! \name DefaultSettings
00675    Default setttings are used as a channel setting and as a default when
00676    configuring devices
00677 */
00678 /*@{*/
00679 static char default_language[MAX_LANGUAGE];      /*!< Default language setting for new channels */
00680 static char default_callerid[AST_MAX_EXTENSION]; /*!< Default caller ID for sip messages */
00681 static char default_mwi_from[80];                /*!< Default caller ID for MWI updates */
00682 static char default_fromdomain[AST_MAX_EXTENSION]; /*!< Default domain on outound messages */
00683 static int default_fromdomainport;                 /*!< Default domain port on outbound messages */
00684 static char default_notifymime[AST_MAX_EXTENSION]; /*!< Default MIME media type for MWI notify messages */
00685 static char default_vmexten[AST_MAX_EXTENSION];    /*!< Default From Username on MWI updates */
00686 static int default_qualify;                        /*!< Default Qualify= setting */
00687 static char default_mohinterpret[MAX_MUSICCLASS];  /*!< Global setting for moh class to use when put on hold */
00688 static char default_mohsuggest[MAX_MUSICCLASS];    /*!< Global setting for moh class to suggest when putting
00689                                                     *   a bridged channel on hold */
00690 static char default_parkinglot[AST_MAX_CONTEXT];   /*!< Parkinglot */
00691 static char default_engine[256];                   /*!< Default RTP engine */
00692 static int default_maxcallbitrate;                 /*!< Maximum bitrate for call */
00693 static struct ast_codec_pref default_prefs;        /*!< Default codec prefs */
00694 static unsigned int default_transports;            /*!< Default Transports (enum sip_transport) that are acceptable */
00695 static unsigned int default_primary_transport;     /*!< Default primary Transport (enum sip_transport) for outbound connections to devices */
00696 /*@}*/
00697 
00698 static struct sip_settings sip_cfg;    /*!< SIP configuration data.
00699                \note in the future we could have multiple of these (per domain, per device group etc) */
00700 
00701 /*!< use this macro when ast_uri_decode is dependent on pedantic checking to be on. */
00702 #define SIP_PEDANTIC_DECODE(str) \
00703    if (sip_cfg.pedanticsipchecking && !ast_strlen_zero(str)) { \
00704       ast_uri_decode(str); \
00705    }  \
00706 
00707 static unsigned int chan_idx;       /*!< used in naming sip channel */
00708 static int global_match_auth_username;    /*!< Match auth username if available instead of From: Default off. */
00709 
00710 static int global_relaxdtmf;        /*!< Relax DTMF */
00711 static int global_prematuremediafilter;   /*!< Enable/disable premature frames in a call (causing 183 early media) */
00712 static int global_rtptimeout;       /*!< Time out call if no RTP */
00713 static int global_rtpholdtimeout;   /*!< Time out call if no RTP during hold */
00714 static int global_rtpkeepalive;     /*!< Send RTP keepalives */
00715 static int global_reg_timeout;      /*!< Global time between attempts for outbound registrations */
00716 static int global_regattempts_max;  /*!< Registration attempts before giving up */
00717 static int global_shrinkcallerid;   /*!< enable or disable shrinking of caller id  */
00718 static int global_callcounter;      /*!< Enable call counters for all devices. This is currently enabled by setting the peer
00719                                      *   call-limit to INT_MAX. When we remove the call-limit from the code, we can make it
00720                                      *   with just a boolean flag in the device structure */
00721 static unsigned int global_tos_sip;      /*!< IP type of service for SIP packets */
00722 static unsigned int global_tos_audio;    /*!< IP type of service for audio RTP packets */
00723 static unsigned int global_tos_video;    /*!< IP type of service for video RTP packets */
00724 static unsigned int global_tos_text;     /*!< IP type of service for text RTP packets */
00725 static unsigned int global_cos_sip;      /*!< 802.1p class of service for SIP packets */
00726 static unsigned int global_cos_audio;    /*!< 802.1p class of service for audio RTP packets */
00727 static unsigned int global_cos_video;    /*!< 802.1p class of service for video RTP packets */
00728 static unsigned int global_cos_text;     /*!< 802.1p class of service for text RTP packets */
00729 static unsigned int recordhistory;       /*!< Record SIP history. Off by default */
00730 static unsigned int dumphistory;         /*!< Dump history to verbose before destroying SIP dialog */
00731 static char global_useragent[AST_MAX_EXTENSION];    /*!< Useragent for the SIP channel */
00732 static char global_sdpsession[AST_MAX_EXTENSION];   /*!< SDP session name for the SIP channel */
00733 static char global_sdpowner[AST_MAX_EXTENSION];     /*!< SDP owner name for the SIP channel */
00734 static int global_authfailureevents;     /*!< Whether we send authentication failure manager events or not. Default no. */
00735 static int global_t1;           /*!< T1 time */
00736 static int global_t1min;        /*!< T1 roundtrip time minimum */
00737 static int global_timer_b;      /*!< Timer B - RFC 3261 Section 17.1.1.2 */
00738 static unsigned int global_autoframing; /*!< Turn autoframing on or off. */
00739 static int global_qualifyfreq;          /*!< Qualify frequency */
00740 static int global_qualify_gap;          /*!< Time between our group of peer pokes */
00741 static int global_qualify_peers;        /*!< Number of peers to poke at a given time */
00742 
00743 static enum st_mode global_st_mode;           /*!< Mode of operation for Session-Timers           */
00744 static enum st_refresher_param global_st_refresher; /*!< Session-Timer refresher                        */
00745 static int global_min_se;                     /*!< Lowest threshold for session refresh interval  */
00746 static int global_max_se;                     /*!< Highest threshold for session refresh interval */
00747 
00748 static int global_store_sip_cause;    /*!< Whether the MASTER_CHANNEL(HASH(SIP_CAUSE,[chan_name])) var should be set */
00749 
00750 static int global_dynamic_exclude_static = 0; /*!< Exclude static peers from contact registrations */
00751 /*@}*/
00752 
00753 /*!
00754  * We use libxml2 in order to parse XML that may appear in the body of a SIP message. Currently,
00755  * the only usage is for parsing PIDF bodies of incoming PUBLISH requests in the call-completion
00756  * event package. This variable is set at module load time and may be checked at runtime to determine
00757  * if XML parsing support was found.
00758  */
00759 static int can_parse_xml;
00760 
00761 /*! \name Object counters @{
00762  *  \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
00763  *  should be used to modify these values. */
00764 static int speerobjs = 0;     /*!< Static peers */
00765 static int rpeerobjs = 0;     /*!< Realtime peers */
00766 static int apeerobjs = 0;     /*!< Autocreated peer objects */
00767 static int regobjs = 0;       /*!< Registry objects */
00768 /* }@ */
00769 
00770 static struct ast_flags global_flags[3] = {{0}};  /*!< global SIP_ flags */
00771 static int global_t38_maxdatagram;                /*!< global T.38 FaxMaxDatagram override */
00772 
00773 static struct ast_event_sub *network_change_event_subscription; /*!< subscription id for network change events */
00774 static int network_change_event_sched_id = -1;
00775 
00776 static char used_context[AST_MAX_CONTEXT];        /*!< name of automatically created context for unloading */
00777 
00778 AST_MUTEX_DEFINE_STATIC(netlock);
00779 
00780 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
00781    when it's doing something critical. */
00782 AST_MUTEX_DEFINE_STATIC(monlock);
00783 
00784 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
00785 
00786 /*! \brief This is the thread for the monitor which checks for input on the channels
00787    which are not currently in use.  */
00788 static pthread_t monitor_thread = AST_PTHREADT_NULL;
00789 
00790 static int sip_reloading = FALSE;                       /*!< Flag for avoiding multiple reloads at the same time */
00791 static enum channelreloadreason sip_reloadreason;       /*!< Reason for last reload/load of configuration */
00792 
00793 struct sched_context *sched;     /*!< The scheduling context */
00794 static struct io_context *io;           /*!< The IO context */
00795 static int *sipsock_read_id;            /*!< ID of IO entry for sipsock FD */
00796 struct sip_pkt;
00797 static AST_LIST_HEAD_STATIC(domain_list, domain);    /*!< The SIP domain list */
00798 
00799 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
00800 
00801 static enum sip_debug_e sipdebug;
00802 
00803 /*! \brief extra debugging for 'text' related events.
00804  *  At the moment this is set together with sip_debug_console.
00805  *  \note It should either go away or be implemented properly.
00806  */
00807 static int sipdebug_text;
00808 
00809 static const struct _map_x_s referstatusstrings[] = {
00810    { REFER_IDLE,      "<none>" },
00811    { REFER_SENT,      "Request sent" },
00812    { REFER_RECEIVED,  "Request received" },
00813    { REFER_CONFIRMED, "Confirmed" },
00814    { REFER_ACCEPTED,  "Accepted" },
00815    { REFER_RINGING,   "Target ringing" },
00816    { REFER_200OK,     "Done" },
00817    { REFER_FAILED,    "Failed" },
00818    { REFER_NOAUTH,    "Failed - auth failure" },
00819    { -1,               NULL} /* terminator */
00820 };
00821 
00822 /* --- Hash tables of various objects --------*/
00823 #ifdef LOW_MEMORY
00824 static const int HASH_PEER_SIZE = 17;
00825 static const int HASH_DIALOG_SIZE = 17;
00826 #else
00827 static const int HASH_PEER_SIZE = 563; /*!< Size of peer hash table, prime number preferred! */
00828 static const int HASH_DIALOG_SIZE = 563;
00829 #endif
00830 
00831 static const struct {
00832    enum ast_cc_service_type service;
00833    const char *service_string;
00834 } sip_cc_service_map [] = {
00835    [AST_CC_NONE] = { AST_CC_NONE, "" },
00836    [AST_CC_CCBS] = { AST_CC_CCBS, "BS" },
00837    [AST_CC_CCNR] = { AST_CC_CCNR, "NR" },
00838    [AST_CC_CCNL] = { AST_CC_CCNL, "NL" },
00839 };
00840 
00841 static enum ast_cc_service_type service_string_to_service_type(const char * const service_string)
00842 {
00843    enum ast_cc_service_type service;
00844    for (service = AST_CC_CCBS; service <= AST_CC_CCNL; ++service) {
00845       if (!strcasecmp(service_string, sip_cc_service_map[service].service_string)) {
00846          return service;
00847       }
00848    }
00849    return AST_CC_NONE;
00850 }
00851 
00852 static const struct {
00853    enum sip_cc_notify_state state;
00854    const char *state_string;
00855 } sip_cc_notify_state_map [] = {
00856    [CC_QUEUED] = {CC_QUEUED, "cc-state: queued"},
00857    [CC_READY] = {CC_READY, "cc-state: ready"},
00858 };
00859 
00860 AST_LIST_HEAD_STATIC(epa_static_data_list, epa_backend);
00861 
00862 static int sip_epa_register(const struct epa_static_data *static_data)
00863 {
00864    struct epa_backend *backend = ast_calloc(1, sizeof(*backend));
00865 
00866    if (!backend) {
00867       return -1;
00868    }
00869 
00870    backend->static_data = static_data;
00871 
00872    AST_LIST_LOCK(&epa_static_data_list);
00873    AST_LIST_INSERT_TAIL(&epa_static_data_list, backend, next);
00874    AST_LIST_UNLOCK(&epa_static_data_list);
00875    return 0;
00876 }
00877 
00878 static void sip_epa_unregister_all(void)
00879 {
00880    struct epa_backend *backend;
00881 
00882    AST_LIST_LOCK(&epa_static_data_list);
00883    while ((backend = AST_LIST_REMOVE_HEAD(&epa_static_data_list, next))) {
00884       ast_free(backend);
00885    }
00886    AST_LIST_UNLOCK(&epa_static_data_list);
00887 }
00888 
00889 static void cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry);
00890 
00891 static void cc_epa_destructor(void *data)
00892 {
00893    struct sip_epa_entry *epa_entry = data;
00894    struct cc_epa_entry *cc_entry = epa_entry->instance_data;
00895    ast_free(cc_entry);
00896 }
00897 
00898 static const struct epa_static_data cc_epa_static_data  = {
00899    .event = CALL_COMPLETION,
00900    .name = "call-completion",
00901    .handle_error = cc_handle_publish_error,
00902    .destructor = cc_epa_destructor,
00903 };
00904 
00905 static const struct epa_static_data *find_static_data(const char * const event_package)
00906 {
00907    const struct epa_backend *backend = NULL;
00908 
00909    AST_LIST_LOCK(&epa_static_data_list);
00910    AST_LIST_TRAVERSE(&epa_static_data_list, backend, next) {
00911       if (!strcmp(backend->static_data->name, event_package)) {
00912          break;
00913       }
00914    }
00915    AST_LIST_UNLOCK(&epa_static_data_list);
00916    return backend ? backend->static_data : NULL;
00917 }
00918 
00919 static struct sip_epa_entry *create_epa_entry (const char * const event_package, const char * const destination)
00920 {
00921    struct sip_epa_entry *epa_entry;
00922    const struct epa_static_data *static_data;
00923 
00924    if (!(static_data = find_static_data(event_package))) {
00925       return NULL;
00926    }
00927 
00928    if (!(epa_entry = ao2_t_alloc(sizeof(*epa_entry), static_data->destructor, "Allocate new EPA entry"))) {
00929       return NULL;
00930    }
00931 
00932    epa_entry->static_data = static_data;
00933    ast_copy_string(epa_entry->destination, destination, sizeof(epa_entry->destination));
00934    return epa_entry;
00935 }
00936 
00937 /*!
00938  * Used to create new entity IDs by ESCs.
00939  */
00940 static int esc_etag_counter;
00941 static const int DEFAULT_PUBLISH_EXPIRES = 3600;
00942 
00943 #ifdef HAVE_LIBXML2
00944 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);
00945 
00946 static const struct sip_esc_publish_callbacks cc_esc_publish_callbacks = {
00947    .initial_handler = cc_esc_publish_handler,
00948    .modify_handler = cc_esc_publish_handler,
00949 };
00950 #endif
00951 
00952 /*!
00953  * \brief The Event State Compositors
00954  *
00955  * An Event State Compositor is an entity which
00956  * accepts PUBLISH requests and acts appropriately
00957  * based on these requests.
00958  *
00959  * The actual event_state_compositor structure is simply
00960  * an ao2_container of sip_esc_entrys. When an incoming
00961  * PUBLISH is received, we can match the appropriate sip_esc_entry
00962  * using the entity ID of the incoming PUBLISH.
00963  */
00964 static struct event_state_compositor {
00965    enum subscriptiontype event;
00966    const char * name;
00967    const struct sip_esc_publish_callbacks *callbacks;
00968    struct ao2_container *compositor;
00969 } event_state_compositors [] = {
00970 #ifdef HAVE_LIBXML2
00971    {CALL_COMPLETION, "call-completion", &cc_esc_publish_callbacks},
00972 #endif
00973 };
00974 
00975 static const int ESC_MAX_BUCKETS = 37;
00976 
00977 static void esc_entry_destructor(void *obj)
00978 {
00979    struct sip_esc_entry *esc_entry = obj;
00980    if (esc_entry->sched_id > -1) {
00981       AST_SCHED_DEL(sched, esc_entry->sched_id);
00982    }
00983 }
00984 
00985 static int esc_hash_fn(const void *obj, const int flags)
00986 {
00987    const struct sip_esc_entry *entry = obj;
00988    return ast_str_hash(entry->entity_tag);
00989 }
00990 
00991 static int esc_cmp_fn(void *obj, void *arg, int flags)
00992 {
00993    struct sip_esc_entry *entry1 = obj;
00994    struct sip_esc_entry *entry2 = arg;
00995 
00996    return (!strcmp(entry1->entity_tag, entry2->entity_tag)) ? (CMP_MATCH | CMP_STOP) : 0;
00997 }
00998 
00999 static struct event_state_compositor *get_esc(const char * const event_package) {
01000    int i;
01001    for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
01002       if (!strcasecmp(event_package, event_state_compositors[i].name)) {
01003          return &event_state_compositors[i];
01004       }
01005    }
01006    return NULL;
01007 }
01008 
01009 static struct sip_esc_entry *get_esc_entry(const char * entity_tag, struct event_state_compositor *esc) {
01010    struct sip_esc_entry *entry;
01011    struct sip_esc_entry finder;
01012 
01013    ast_copy_string(finder.entity_tag, entity_tag, sizeof(finder.entity_tag));
01014 
01015    entry = ao2_find(esc->compositor, &finder, OBJ_POINTER);
01016 
01017    return entry;
01018 }
01019 
01020 static int publish_expire(const void *data)
01021 {
01022    struct sip_esc_entry *esc_entry = (struct sip_esc_entry *) data;
01023    struct event_state_compositor *esc = get_esc(esc_entry->event);
01024 
01025    ast_assert(esc != NULL);
01026 
01027    ao2_unlink(esc->compositor, esc_entry);
01028    ao2_ref(esc_entry, -1);
01029    return 0;
01030 }
01031 
01032 static void create_new_sip_etag(struct sip_esc_entry *esc_entry, int is_linked)
01033 {
01034    int new_etag = ast_atomic_fetchadd_int(&esc_etag_counter, +1);
01035    struct event_state_compositor *esc = get_esc(esc_entry->event);
01036 
01037    ast_assert(esc != NULL);
01038    if (is_linked) {
01039       ao2_unlink(esc->compositor, esc_entry);
01040    }
01041    snprintf(esc_entry->entity_tag, sizeof(esc_entry->entity_tag), "%d", new_etag);
01042    ao2_link(esc->compositor, esc_entry);
01043 }
01044 
01045 static struct sip_esc_entry *create_esc_entry(struct event_state_compositor *esc, struct sip_request *req, const int expires)
01046 {
01047    struct sip_esc_entry *esc_entry;
01048    int expires_ms;
01049 
01050    if (!(esc_entry = ao2_alloc(sizeof(*esc_entry), esc_entry_destructor))) {
01051       return NULL;
01052    }
01053 
01054    esc_entry->event = esc->name;
01055 
01056    expires_ms = expires * 1000;
01057    /* Bump refcount for scheduler */
01058    ao2_ref(esc_entry, +1);
01059    esc_entry->sched_id = ast_sched_add(sched, expires_ms, publish_expire, esc_entry);
01060 
01061    /* Note: This links the esc_entry into the ESC properly */
01062    create_new_sip_etag(esc_entry, 0);
01063 
01064    return esc_entry;
01065 }
01066 
01067 static int initialize_escs(void)
01068 {
01069    int i, res = 0;
01070    for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
01071       if (!((event_state_compositors[i].compositor) =
01072                ao2_container_alloc(ESC_MAX_BUCKETS, esc_hash_fn, esc_cmp_fn))) {
01073          res = -1;
01074       }
01075    }
01076    return res;
01077 }
01078 
01079 static void destroy_escs(void)
01080 {
01081    int i;
01082    for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
01083       ao2_ref(event_state_compositors[i].compositor, -1);
01084    }
01085 }
01086 
01087 /*!
01088  * \details
01089  * This container holds the dialogs that will be destroyed immediately.
01090  */
01091 struct ao2_container *dialogs_to_destroy;
01092 
01093 /*! \brief
01094  * Here we implement the container for dialogs (sip_pvt), defining
01095  * generic wrapper functions to ease the transition from the current
01096  * implementation (a single linked list) to a different container.
01097  * In addition to a reference to the container, we need functions to lock/unlock
01098  * the container and individual items, and functions to add/remove
01099  * references to the individual items.
01100  */
01101 static struct ao2_container *dialogs;
01102 #define sip_pvt_lock(x) ao2_lock(x)
01103 #define sip_pvt_trylock(x) ao2_trylock(x)
01104 #define sip_pvt_unlock(x) ao2_unlock(x)
01105 
01106 /*! \brief  The table of TCP threads */
01107 static struct ao2_container *threadt;
01108 
01109 /*! \brief  The peer list: Users, Peers and Friends */
01110 static struct ao2_container *peers;
01111 static struct ao2_container *peers_by_ip;
01112 
01113 /*! \brief  The register list: Other SIP proxies we register with and receive calls from */
01114 static struct ast_register_list {
01115    ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
01116    int recheck;
01117 } regl;
01118 
01119 /*! \brief  The MWI subscription list */
01120 static struct ast_subscription_mwi_list {
01121    ASTOBJ_CONTAINER_COMPONENTS(struct sip_subscription_mwi);
01122 } submwil;
01123 static int temp_pvt_init(void *);
01124 static void temp_pvt_cleanup(void *);
01125 
01126 /*! \brief A per-thread temporary pvt structure */
01127 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
01128 
01129 /*! \brief Authentication container for realm authentication */
01130 static struct sip_auth_container *authl = NULL;
01131 /*! \brief Global authentication container protection while adjusting the references. */
01132 AST_MUTEX_DEFINE_STATIC(authl_lock);
01133 
01134 /* --- Sockets and networking --------------*/
01135 
01136 /*! \brief Main socket for UDP SIP communication.
01137  *
01138  * sipsock is shared between the SIP manager thread (which handles reload
01139  * requests), the udp io handler (sipsock_read()) and the user routines that
01140  * issue udp writes (using __sip_xmit()).
01141  * The socket is -1 only when opening fails (this is a permanent condition),
01142  * or when we are handling a reload() that changes its address (this is
01143  * a transient situation during which we might have a harmless race, see
01144  * below). Because the conditions for the race to be possible are extremely
01145  * rare, we don't want to pay the cost of locking on every I/O.
01146  * Rather, we remember that when the race may occur, communication is
01147  * bound to fail anyways, so we just live with this event and let
01148  * the protocol handle this above us.
01149  */
01150 static int sipsock  = -1;
01151 
01152 struct ast_sockaddr bindaddr; /*!< UDP: The address we bind to */
01153 
01154 /*! \brief our (internal) default address/port to put in SIP/SDP messages
01155  *  internip is initialized picking a suitable address from one of the
01156  * interfaces, and the same port number we bind to. It is used as the
01157  * default address/port in SIP messages, and as the default address
01158  * (but not port) in SDP messages.
01159  */
01160 static struct ast_sockaddr internip;
01161 
01162 /*! \brief our external IP address/port for SIP sessions.
01163  * externaddr.sin_addr is only set when we know we might be behind
01164  * a NAT, and this is done using a variety of (mutually exclusive)
01165  * ways from the config file:
01166  *
01167  * + with "externaddr = host[:port]" we specify the address/port explicitly.
01168  *   The address is looked up only once when (re)loading the config file;
01169  *
01170  * + with "externhost = host[:port]" we do a similar thing, but the
01171  *   hostname is stored in externhost, and the hostname->IP mapping
01172  *   is refreshed every 'externrefresh' seconds;
01173  *
01174  * Other variables (externhost, externexpire, externrefresh) are used
01175  * to support the above functions.
01176  */
01177 static struct ast_sockaddr externaddr;      /*!< External IP address if we are behind NAT */
01178 static struct ast_sockaddr media_address; /*!< External RTP IP address if we are behind NAT */
01179 
01180 static char externhost[MAXHOSTNAMELEN];   /*!< External host name */
01181 static time_t externexpire;             /*!< Expiration counter for re-resolving external host name in dynamic DNS */
01182 static int externrefresh = 10;          /*!< Refresh timer for DNS-based external address (dyndns) */
01183 static uint16_t externtcpport;          /*!< external tcp port */ 
01184 static uint16_t externtlsport;          /*!< external tls port */
01185 
01186 /*! \brief  List of local networks
01187  * We store "localnet" addresses from the config file into an access list,
01188  * marked as 'DENY', so the call to ast_apply_ha() will return
01189  * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
01190  * (i.e. presumably public) addresses.
01191  */
01192 static struct ast_ha *localaddr;    /*!< List of local networks, on the same side of NAT as this Asterisk */
01193 
01194 static int ourport_tcp;             /*!< The port used for TCP connections */
01195 static int ourport_tls;             /*!< The port used for TCP/TLS connections */
01196 static struct ast_sockaddr debugaddr;
01197 
01198 static struct ast_config *notify_types = NULL;    /*!< The list of manual NOTIFY types we know how to send */
01199 
01200 /*! some list management macros. */
01201 
01202 #define UNLINK(element, head, prev) do {  \
01203    if (prev)            \
01204       (prev)->next = (element)->next;  \
01205    else              \
01206       (head) = (element)->next;  \
01207    } while (0)
01208 
01209 /*---------------------------- Forward declarations of functions in chan_sip.c */
01210 /* Note: This is added to help splitting up chan_sip.c into several files
01211    in coming releases. */
01212 
01213 /*--- PBX interface functions */
01214 static struct ast_channel *sip_request_call(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause);
01215 static int sip_devicestate(void *data);
01216 static int sip_sendtext(struct ast_channel *ast, const char *text);
01217 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
01218 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
01219 static int sip_hangup(struct ast_channel *ast);
01220 static int sip_answer(struct ast_channel *ast);
01221 static struct ast_frame *sip_read(struct ast_channel *ast);
01222 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
01223 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
01224 static int sip_transfer(struct ast_channel *ast, const char *dest);
01225 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
01226 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
01227 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
01228 static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen);
01229 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
01230 static const char *sip_get_callid(struct ast_channel *chan);
01231 
01232 static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr);
01233 static int sip_standard_port(enum sip_transport type, int port);
01234 static int sip_prepare_socket(struct sip_pvt *p);
01235 static int get_address_family_filter(unsigned int transport);
01236 
01237 /*--- Transmitting responses and requests */
01238 static int sipsock_read(int *id, int fd, short events, void *ignore);
01239 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data);
01240 static int __sip_reliable_xmit(struct sip_pvt *p, uint32_t seqno, int resp, struct ast_str *data, int fatal, int sipmethod);
01241 static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp);
01242 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
01243 static int retrans_pkt(const void *data);
01244 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);
01245 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01246 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01247 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01248 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);
01249 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
01250 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);
01251 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
01252 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
01253 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable);
01254 static int transmit_request(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch);
01255 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch);
01256 static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri);
01257 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri);
01258 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
01259 static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded);
01260 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
01261 static int transmit_info_with_vidupdate(struct sip_pvt *p);
01262 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
01263 static int transmit_refer(struct sip_pvt *p, const char *dest);
01264 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
01265 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
01266 static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state);
01267 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
01268 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno);
01269 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno);
01270 static void copy_request(struct sip_request *dst, const struct sip_request *src);
01271 static void receive_message(struct sip_pvt *p, struct sip_request *req);
01272 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward);
01273 static int sip_send_mwi_to_peer(struct sip_peer *peer, int cache_only);
01274 
01275 /* Misc dialog routines */
01276 static int __sip_autodestruct(const void *data);
01277 static void *registry_unref(struct sip_registry *reg, char *tag);
01278 static int update_call_counter(struct sip_pvt *fup, int event);
01279 static int auto_congest(const void *arg);
01280 static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method);
01281 static void free_old_route(struct sip_route *route);
01282 static void list_route(struct sip_route *route);
01283 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards, int resp);
01284 static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
01285                      struct sip_request *req, const char *uri);
01286 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
01287 static void check_pendings(struct sip_pvt *p);
01288 static void *sip_park_thread(void *stuff);
01289 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);
01290 
01291 static void *sip_pickup_thread(void *stuff);
01292 static int sip_pickup(struct ast_channel *chan);
01293 
01294 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
01295 static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method);
01296 
01297 /*--- Codec handling / SDP */
01298 static void try_suggested_sip_codec(struct sip_pvt *p);
01299 static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
01300 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
01301 static int find_sdp(struct sip_request *req);
01302 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
01303 static int process_sdp_o(const char *o, struct sip_pvt *p);
01304 static int process_sdp_c(const char *c, struct ast_sockaddr *addr);
01305 static int process_sdp_a_sendonly(const char *a, int *sendonly);
01306 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec);
01307 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec);
01308 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);
01309 static int process_sdp_a_image(const char *a, struct sip_pvt *p);
01310 static void add_codec_to_sdp(const struct sip_pvt *p, format_t codec,
01311               struct ast_str **m_buf, struct ast_str **a_buf,
01312               int debug, int *min_packet_size);
01313 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
01314             struct ast_str **m_buf, struct ast_str **a_buf,
01315             int debug);
01316 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
01317 static void do_setnat(struct sip_pvt *p);
01318 static void stop_media_flows(struct sip_pvt *p);
01319 
01320 /*--- Authentication stuff */
01321 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
01322 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
01323 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
01324                 const char *secret, const char *md5secret, int sipmethod,
01325                 const char *uri, enum xmittype reliable, int ignore);
01326 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
01327                      int sipmethod, const char *uri, enum xmittype reliable,
01328                      struct ast_sockaddr *addr, struct sip_peer **authpeer);
01329 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr);
01330 
01331 /*--- Domain handling */
01332 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
01333 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
01334 static void clear_sip_domains(void);
01335 
01336 /*--- SIP realm authentication */
01337 static void add_realm_authentication(struct sip_auth_container **credentials, const char *configuration, int lineno);
01338 static struct sip_auth *find_realm_authentication(struct sip_auth_container *credentials, const char *realm);
01339 
01340 /*--- Misc functions */
01341 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t);
01342 static int reload_config(enum channelreloadreason reason);
01343 static void add_diversion_header(struct sip_request *req, struct sip_pvt *pvt);
01344 static int expire_register(const void *data);
01345 static void *do_monitor(void *data);
01346 static int restart_monitor(void);
01347 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
01348 static struct ast_variable *copy_vars(struct ast_variable *src);
01349 static int dialog_find_multiple(void *obj, void *arg, int flags);
01350 static struct ast_channel *sip_pvt_lock_full(struct sip_pvt *pvt);
01351 /* static int sip_addrcmp(char *name, struct sockaddr_in *sin);   Support for peer matching */
01352 static int sip_refer_allocate(struct sip_pvt *p);
01353 static int sip_notify_allocate(struct sip_pvt *p);
01354 static void ast_quiet_chan(struct ast_channel *chan);
01355 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
01356 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
01357 
01358 /*--- Device monitoring and Device/extension state/event handling */
01359 static int cb_extensionstate(char *context, char* exten, int state, void *data);
01360 static int sip_devicestate(void *data);
01361 static int sip_poke_noanswer(const void *data);
01362 static int sip_poke_peer(struct sip_peer *peer, int force);
01363 static void sip_poke_all_peers(void);
01364 static void sip_peer_hold(struct sip_pvt *p, int hold);
01365 static void mwi_event_cb(const struct ast_event *, void *);
01366 static void network_change_event_cb(const struct ast_event *, void *);
01367 
01368 /*--- Applications, functions, CLI and manager command helpers */
01369 static const char *sip_nat_mode(const struct sip_pvt *p);
01370 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01371 static char *transfermode2str(enum transfermodes mode) attribute_const;
01372 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
01373 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01374 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01375 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01376 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01377 static void  print_group(int fd, ast_group_t group, int crlf);
01378 static const char *dtmfmode2str(int mode) attribute_const;
01379 static int str2dtmfmode(const char *str) attribute_unused;
01380 static const char *insecure2str(int mode) attribute_const;
01381 static const char *allowoverlap2str(int mode) attribute_const;
01382 static void cleanup_stale_contexts(char *new, char *old);
01383 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
01384 static const char *domain_mode_to_text(const enum domain_mode mode);
01385 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01386 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01387 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01388 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
01389 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01390 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01391 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01392 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01393 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01394 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
01395 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
01396 static char *complete_sip_peer(const char *word, int state, int flags2);
01397 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
01398 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
01399 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
01400 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
01401 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
01402 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01403 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01404 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01405 static char *sip_do_debug_ip(int fd, const char *arg);
01406 static char *sip_do_debug_peer(int fd, const char *arg);
01407 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01408 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01409 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01410 static int sip_dtmfmode(struct ast_channel *chan, const char *data);
01411 static int sip_addheader(struct ast_channel *chan, const char *data);
01412 static int sip_do_reload(enum channelreloadreason reason);
01413 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01414 static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
01415                   const char *name, int flag, int family);
01416 static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
01417                   const char *name, int flag);
01418 static int ast_sockaddr_resolve_first_transport(struct ast_sockaddr *addr,
01419                   const char *name, int flag, unsigned int transport);
01420 
01421 /*--- Debugging
01422    Functions for enabling debug per IP or fully, or enabling history logging for
01423    a SIP dialog
01424 */
01425 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to debuglog at end of dialog, before destroying data */
01426 static inline int sip_debug_test_addr(const struct ast_sockaddr *addr);
01427 static inline int sip_debug_test_pvt(struct sip_pvt *p);
01428 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
01429 static void sip_dump_history(struct sip_pvt *dialog);
01430 
01431 /*--- Device object handling */
01432 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
01433 static int update_call_counter(struct sip_pvt *fup, int event);
01434 static void sip_destroy_peer(struct sip_peer *peer);
01435 static void sip_destroy_peer_fn(void *peer);
01436 static void set_peer_defaults(struct sip_peer *peer);
01437 static struct sip_peer *temp_peer(const char *name);
01438 static void register_peer_exten(struct sip_peer *peer, int onoff);
01439 static struct sip_peer *find_peer(const char *peer, struct ast_sockaddr *addr, int realtime, int forcenamematch, int devstate_only, int transport);
01440 static int sip_poke_peer_s(const void *data);
01441 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
01442 static void reg_source_db(struct sip_peer *peer);
01443 static void destroy_association(struct sip_peer *peer);
01444 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
01445 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
01446 static void set_socket_transport(struct sip_socket *socket, int transport);
01447 
01448 /* Realtime device support */
01449 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);
01450 static void update_peer(struct sip_peer *p, int expire);
01451 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
01452 static const char *get_name_from_variable(const struct ast_variable *var);
01453 static struct sip_peer *realtime_peer(const char *peername, struct ast_sockaddr *sin, int devstate_only, int which_objects);
01454 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
01455 
01456 /*--- Internal UA client handling (outbound registrations) */
01457 static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p);
01458 static void sip_registry_destroy(struct sip_registry *reg);
01459 static int sip_register(const char *value, int lineno);
01460 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
01461 static int sip_reregister(const void *data);
01462 static int __sip_do_register(struct sip_registry *r);
01463 static int sip_reg_timeout(const void *data);
01464 static void sip_send_all_registers(void);
01465 static int sip_reinvite_retry(const void *data);
01466 
01467 /*--- Parsing SIP requests and responses */
01468 static void append_date(struct sip_request *req);  /* Append date to SIP packet */
01469 static int determine_firstline_parts(struct sip_request *req);
01470 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
01471 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
01472 static int find_sip_method(const char *msg);
01473 static unsigned int parse_allowed_methods(struct sip_request *req);
01474 static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req);
01475 static int parse_request(struct sip_request *req);
01476 static const char *get_header(const struct sip_request *req, const char *name);
01477 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
01478 static int method_match(enum sipmethod id, const char *name);
01479 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
01480 static const char *find_alias(const char *name, const char *_default);
01481 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
01482 static void lws2sws(struct ast_str *msgbuf);
01483 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
01484 static char *remove_uri_parameters(char *uri);
01485 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
01486 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
01487 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
01488 static int set_address_from_contact(struct sip_pvt *pvt);
01489 static void check_via(struct sip_pvt *p, struct sip_request *req);
01490 static int get_rpid(struct sip_pvt *p, struct sip_request *oreq);
01491 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason);
01492 static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id);
01493 static int get_msg_text(char *buf, int len, struct sip_request *req);
01494 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
01495 static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen);
01496 static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen);
01497 static int get_domain(const char *str, char *domain, int len);
01498 static void get_realm(struct sip_pvt *p, const struct sip_request *req);
01499 
01500 /*-- TCP connection handling ---*/
01501 static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session);
01502 static void *sip_tcp_worker_fn(void *);
01503 
01504 /*--- Constructing requests and responses */
01505 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
01506 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
01507 static void deinit_req(struct sip_request *req);
01508 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, uint32_t seqno, int newbranch);
01509 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri);
01510 static int init_resp(struct sip_request *resp, const char *msg);
01511 static inline int resp_needs_contact(const char *msg, enum sipmethod method);
01512 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
01513 static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p);
01514 static void build_via(struct sip_pvt *p);
01515 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
01516 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog);
01517 static char *generate_random_string(char *buf, size_t size);
01518 static void build_callid_pvt(struct sip_pvt *pvt);
01519 static void change_callid_pvt(struct sip_pvt *pvt, const char *callid);
01520 static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain);
01521 static void make_our_tag(struct sip_pvt *pvt);
01522 static int add_header(struct sip_request *req, const char *var, const char *value);
01523 static int add_header_max_forwards(struct sip_pvt *dialog, struct sip_request *req);
01524 static int add_content(struct sip_request *req, const char *line);
01525 static int finalize_content(struct sip_request *req);
01526 static int add_text(struct sip_request *req, const char *text);
01527 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
01528 static int add_rpid(struct sip_request *req, struct sip_pvt *p);
01529 static int add_vidupdate(struct sip_request *req);
01530 static void add_route(struct sip_request *req, struct sip_route *route);
01531 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
01532 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
01533 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
01534 static void set_destination(struct sip_pvt *p, char *uri);
01535 static void append_date(struct sip_request *req);
01536 static void build_contact(struct sip_pvt *p);
01537 
01538 /*------Request handling functions */
01539 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock);
01540 static int handle_request_update(struct sip_pvt *p, struct sip_request *req);
01541 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);
01542 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, int *nounlock);
01543 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
01544 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *sin, const char *e);
01545 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
01546 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
01547 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
01548 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
01549 static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e);
01550 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, struct ast_sockaddr *addr, int *nounlock);
01551 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e);
01552 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, uint32_t seqno, int *nounlock);
01553 
01554 /*------Response handling functions */
01555 static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01556 static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01557 static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01558 static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01559 static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01560 static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01561 static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno);
01562 
01563 /*------ SRTP Support -------- */
01564 static int setup_srtp(struct sip_srtp **srtp);
01565 static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct sip_srtp **srtp, const char *a);
01566 
01567 /*------ T38 Support --------- */
01568 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
01569 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
01570 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
01571 static void change_t38_state(struct sip_pvt *p, int state);
01572 
01573 /*------ Session-Timers functions --------- */
01574 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
01575 static int  proc_session_timer(const void *vp);
01576 static void stop_session_timer(struct sip_pvt *p);
01577 static void start_session_timer(struct sip_pvt *p);
01578 static void restart_session_timer(struct sip_pvt *p);
01579 static const char *strefresherparam2str(enum st_refresher r);
01580 static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher_param *const p_ref);
01581 static int parse_minse(const char *p_hdrval, int *const p_interval);
01582 static int st_get_se(struct sip_pvt *, int max);
01583 static enum st_refresher st_get_refresher(struct sip_pvt *);
01584 static enum st_mode st_get_mode(struct sip_pvt *, int no_cached);
01585 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
01586 
01587 /*------- RTP Glue functions -------- */
01588 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);
01589 
01590 /*!--- SIP MWI Subscription support */
01591 static int sip_subscribe_mwi(const char *value, int lineno);
01592 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi);
01593 static void sip_send_all_mwi_subscriptions(void);
01594 static int sip_subscribe_mwi_do(const void *data);
01595 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
01596 
01597 /*! \brief Definition of this channel for PBX channel registration */
01598 const struct ast_channel_tech sip_tech = {
01599    .type = "SIP",
01600    .description = "Session Initiation Protocol (SIP)",
01601    .capabilities = AST_FORMAT_AUDIO_MASK, /* all audio formats */
01602    .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
01603    .requester = sip_request_call,         /* called with chan unlocked */
01604    .devicestate = sip_devicestate,        /* called with chan unlocked (not chan-specific) */
01605    .call = sip_call,       /* called with chan locked */
01606    .send_html = sip_sendhtml,
01607    .hangup = sip_hangup,         /* called with chan locked */
01608    .answer = sip_answer,         /* called with chan locked */
01609    .read = sip_read,       /* called with chan locked */
01610    .write = sip_write,        /* called with chan locked */
01611    .write_video = sip_write,     /* called with chan locked */
01612    .write_text = sip_write,
01613    .indicate = sip_indicate,     /* called with chan locked */
01614    .transfer = sip_transfer,     /* called with chan locked */
01615    .fixup = sip_fixup,        /* called with chan locked */
01616    .send_digit_begin = sip_senddigit_begin,  /* called with chan unlocked */
01617    .send_digit_end = sip_senddigit_end,
01618    .bridge = ast_rtp_instance_bridge,        /* XXX chan unlocked ? */
01619    .early_bridge = ast_rtp_instance_early_bridge,
01620    .send_text = sip_sendtext,    /* called with chan locked */
01621    .func_channel_read = sip_acf_channel_read,
01622    .setoption = sip_setoption,
01623    .queryoption = sip_queryoption,
01624    .get_pvt_uniqueid = sip_get_callid,
01625 };
01626 
01627 /*! \brief This version of the sip channel tech has no send_digit_begin
01628  * callback so that the core knows that the channel does not want
01629  * DTMF BEGIN frames.
01630  * The struct is initialized just before registering the channel driver,
01631  * and is for use with channels using SIP INFO DTMF.
01632  */
01633 struct ast_channel_tech sip_tech_info;
01634 
01635 static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan);
01636 static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent);
01637 static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent);
01638 static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason);
01639 static int sip_cc_agent_status_request(struct ast_cc_agent *agent);
01640 static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent);
01641 static int sip_cc_agent_recall(struct ast_cc_agent *agent);
01642 static void sip_cc_agent_destructor(struct ast_cc_agent *agent);
01643 
01644 static struct ast_cc_agent_callbacks sip_cc_agent_callbacks = {
01645    .type = "SIP",
01646    .init = sip_cc_agent_init,
01647    .start_offer_timer = sip_cc_agent_start_offer_timer,
01648    .stop_offer_timer = sip_cc_agent_stop_offer_timer,
01649    .respond = sip_cc_agent_respond,
01650    .status_request = sip_cc_agent_status_request,
01651    .start_monitoring = sip_cc_agent_start_monitoring,
01652    .callee_available = sip_cc_agent_recall,
01653    .destructor = sip_cc_agent_destructor,
01654 };
01655 
01656 static int find_by_notify_uri_helper(void *obj, void *arg, int flags)
01657 {
01658    struct ast_cc_agent *agent = obj;
01659    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01660    const char *uri = arg;
01661 
01662    return !sip_uri_cmp(agent_pvt->notify_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
01663 }
01664 
01665 static struct ast_cc_agent *find_sip_cc_agent_by_notify_uri(const char * const uri)
01666 {
01667    struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_notify_uri_helper, (char *)uri, "SIP");
01668    return agent;
01669 }
01670 
01671 static int find_by_subscribe_uri_helper(void *obj, void *arg, int flags)
01672 {
01673    struct ast_cc_agent *agent = obj;
01674    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01675    const char *uri = arg;
01676 
01677    return !sip_uri_cmp(agent_pvt->subscribe_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
01678 }
01679 
01680 static struct ast_cc_agent *find_sip_cc_agent_by_subscribe_uri(const char * const uri)
01681 {
01682    struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_subscribe_uri_helper, (char *)uri, "SIP");
01683    return agent;
01684 }
01685 
01686 static int find_by_callid_helper(void *obj, void *arg, int flags)
01687 {
01688    struct ast_cc_agent *agent = obj;
01689    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01690    struct sip_pvt *call_pvt = arg;
01691 
01692    return !strcmp(agent_pvt->original_callid, call_pvt->callid) ? CMP_MATCH | CMP_STOP : 0;
01693 }
01694 
01695 static struct ast_cc_agent *find_sip_cc_agent_by_original_callid(struct sip_pvt *pvt)
01696 {
01697    struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_callid_helper, pvt, "SIP");
01698    return agent;
01699 }
01700 
01701 static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan)
01702 {
01703    struct sip_cc_agent_pvt *agent_pvt = ast_calloc(1, sizeof(*agent_pvt));
01704    struct sip_pvt *call_pvt = chan->tech_pvt;
01705 
01706    if (!agent_pvt) {
01707       return -1;
01708    }
01709 
01710    ast_assert(!strcmp(chan->tech->type, "SIP"));
01711 
01712    ast_copy_string(agent_pvt->original_callid, call_pvt->callid, sizeof(agent_pvt->original_callid));
01713    ast_copy_string(agent_pvt->original_exten, call_pvt->exten, sizeof(agent_pvt->original_exten));
01714    agent_pvt->offer_timer_id = -1;
01715    agent->private_data = agent_pvt;
01716    sip_pvt_lock(call_pvt);
01717    ast_set_flag(&call_pvt->flags[0], SIP_OFFER_CC);
01718    sip_pvt_unlock(call_pvt);
01719    return 0;
01720 }
01721 
01722 static int sip_offer_timer_expire(const void *data)
01723 {
01724    struct ast_cc_agent *agent = (struct ast_cc_agent *) data;
01725    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01726 
01727    agent_pvt->offer_timer_id = -1;
01728 
01729    return ast_cc_failed(agent->core_id, "SIP agent %s's offer timer expired", agent->device_name);
01730 }
01731 
01732 static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent)
01733 {
01734    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01735    int when;
01736 
01737    when = ast_get_cc_offer_timer(agent->cc_params) * 1000;
01738    agent_pvt->offer_timer_id = ast_sched_add(sched, when, sip_offer_timer_expire, agent);
01739    return 0;
01740 }
01741 
01742 static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent)
01743 {
01744    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01745 
01746    AST_SCHED_DEL(sched, agent_pvt->offer_timer_id);
01747    return 0;
01748 }
01749 
01750 static void sip_cc_agent_respond(struct ast_cc_agent *agent, enum ast_cc_agent_response_reason reason)
01751 {
01752    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01753 
01754    sip_pvt_lock(agent_pvt->subscribe_pvt);
01755    ast_set_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
01756    if (reason == AST_CC_AGENT_RESPONSE_SUCCESS || !ast_strlen_zero(agent_pvt->notify_uri)) {
01757       /* The second half of this if statement may be a bit hard to grasp,
01758        * so here's an explanation. When a subscription comes into
01759        * chan_sip, as long as it is not malformed, it will be passed
01760        * to the CC core. If the core senses an out-of-order state transition,
01761        * then the core will call this callback with the "reason" set to a
01762        * failure condition.
01763        * However, an out-of-order state transition will occur during a resubscription
01764        * for CC. In such a case, we can see that we have already generated a notify_uri
01765        * and so we can detect that this isn't a *real* failure. Rather, it is just
01766        * something the core doesn't recognize as a legitimate SIP state transition.
01767        * Thus we respond with happiness and flowers.
01768        */
01769       transmit_response(agent_pvt->subscribe_pvt, "200 OK", &agent_pvt->subscribe_pvt->initreq);
01770       transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_QUEUED);
01771    } else {
01772       transmit_response(agent_pvt->subscribe_pvt, "500 Internal Error", &agent_pvt->subscribe_pvt->initreq);
01773    }
01774    sip_pvt_unlock(agent_pvt->subscribe_pvt);
01775    agent_pvt->is_available = TRUE;
01776 }
01777 
01778 static int sip_cc_agent_status_request(struct ast_cc_agent *agent)
01779 {
01780    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01781    enum ast_device_state state = agent_pvt->is_available ? AST_DEVICE_NOT_INUSE : AST_DEVICE_INUSE;
01782    return ast_cc_agent_status_response(agent->core_id, state);
01783 }
01784 
01785 static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent)
01786 {
01787    /* To start monitoring just means to wait for an incoming PUBLISH
01788     * to tell us that the caller has become available again. No special
01789     * action is needed
01790     */
01791    return 0;
01792 }
01793 
01794 static int sip_cc_agent_recall(struct ast_cc_agent *agent)
01795 {
01796    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01797    /* If we have received a PUBLISH beforehand stating that the caller in question
01798     * is not available, we can save ourself a bit of effort here and just report
01799     * the caller as busy
01800     */
01801    if (!agent_pvt->is_available) {
01802       return ast_cc_agent_caller_busy(agent->core_id, "Caller %s is busy, reporting to the core",
01803             agent->device_name);
01804    }
01805    /* Otherwise, we transmit a NOTIFY to the caller and await either
01806     * a PUBLISH or an INVITE
01807     */
01808    sip_pvt_lock(agent_pvt->subscribe_pvt);
01809    transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_READY);
01810    sip_pvt_unlock(agent_pvt->subscribe_pvt);
01811    return 0;
01812 }
01813 
01814 static void sip_cc_agent_destructor(struct ast_cc_agent *agent)
01815 {
01816    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
01817 
01818    if (!agent_pvt) {
01819       /* The agent constructor probably failed. */
01820       return;
01821    }
01822 
01823    sip_cc_agent_stop_offer_timer(agent);
01824    if (agent_pvt->subscribe_pvt) {
01825       sip_pvt_lock(agent_pvt->subscribe_pvt);
01826       if (!ast_test_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
01827          /* If we haven't sent a 200 OK for the SUBSCRIBE dialog yet, then we need to send a response letting
01828           * the subscriber know something went wrong
01829           */
01830          transmit_response(agent_pvt->subscribe_pvt, "500 Internal Server Error", &agent_pvt->subscribe_pvt->initreq);
01831       }
01832       sip_pvt_unlock(agent_pvt->subscribe_pvt);
01833       agent_pvt->subscribe_pvt = dialog_unref(agent_pvt->subscribe_pvt, "SIP CC agent destructor: Remove ref to subscription");
01834    }
01835    ast_free(agent_pvt);
01836 }
01837 
01838 struct ao2_container *sip_monitor_instances;
01839 
01840 static int sip_monitor_instance_hash_fn(const void *obj, const int flags)
01841 {
01842    const struct sip_monitor_instance *monitor_instance = obj;
01843    return monitor_instance->core_id;
01844 }
01845 
01846 static int sip_monitor_instance_cmp_fn(void *obj, void *arg, int flags)
01847 {
01848    struct sip_monitor_instance *monitor_instance1 = obj;
01849    struct sip_monitor_instance *monitor_instance2 = arg;
01850 
01851    return monitor_instance1->core_id == monitor_instance2->core_id ? CMP_MATCH | CMP_STOP : 0;
01852 }
01853 
01854 static void sip_monitor_instance_destructor(void *data)
01855 {
01856    struct sip_monitor_instance *monitor_instance = data;
01857    if (monitor_instance->subscription_pvt) {
01858       sip_pvt_lock(monitor_instance->subscription_pvt);
01859       monitor_instance->subscription_pvt->expiry = 0;
01860       transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 0, monitor_instance->subscribe_uri);
01861       sip_pvt_unlock(monitor_instance->subscription_pvt);
01862       dialog_unref(monitor_instance->subscription_pvt, "Unref monitor instance ref of subscription pvt");
01863    }
01864    if (monitor_instance->suspension_entry) {
01865       monitor_instance->suspension_entry->body[0] = '\0';
01866       transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_REMOVE ,monitor_instance->notify_uri);
01867       ao2_t_ref(monitor_instance->suspension_entry, -1, "Decrementing suspension entry refcount in sip_monitor_instance_destructor");
01868    }
01869    ast_string_field_free_memory(monitor_instance);
01870 }
01871 
01872 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)
01873 {
01874    struct sip_monitor_instance *monitor_instance = ao2_alloc(sizeof(*monitor_instance), sip_monitor_instance_destructor);
01875 
01876    if (!monitor_instance) {
01877       return NULL;
01878    }
01879 
01880    if (ast_string_field_init(monitor_instance, 256)) {
01881       ao2_ref(monitor_instance, -1);
01882       return NULL;
01883    }
01884 
01885    ast_string_field_set(monitor_instance, subscribe_uri, subscribe_uri);
01886    ast_string_field_set(monitor_instance, peername, peername);
01887    ast_string_field_set(monitor_instance, device_name, device_name);
01888    monitor_instance->core_id = core_id;
01889    ao2_link(sip_monitor_instances, monitor_instance);
01890    return monitor_instance;
01891 }
01892 
01893 static int find_sip_monitor_instance_by_subscription_pvt(void *obj, void *arg, int flags)
01894 {
01895    struct sip_monitor_instance *monitor_instance = obj;
01896    return monitor_instance->subscription_pvt == arg ? CMP_MATCH | CMP_STOP : 0;
01897 }
01898 
01899 static int find_sip_monitor_instance_by_suspension_entry(void *obj, void *arg, int flags)
01900 {
01901    struct sip_monitor_instance *monitor_instance = obj;
01902    return monitor_instance->suspension_entry == arg ? CMP_MATCH | CMP_STOP : 0;
01903 }
01904 
01905 static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id);
01906 static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor);
01907 static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor);
01908 static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id);
01909 static void sip_cc_monitor_destructor(void *private_data);
01910 
01911 static struct ast_cc_monitor_callbacks sip_cc_monitor_callbacks = {
01912    .type = "SIP",
01913    .request_cc = sip_cc_monitor_request_cc,
01914    .suspend = sip_cc_monitor_suspend,
01915    .unsuspend = sip_cc_monitor_unsuspend,
01916    .cancel_available_timer = sip_cc_monitor_cancel_available_timer,
01917    .destructor = sip_cc_monitor_destructor,
01918 };
01919 
01920 static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id)
01921 {
01922    struct sip_monitor_instance *monitor_instance = monitor->private_data;
01923    enum ast_cc_service_type service = monitor->service_offered;
01924    int when;
01925 
01926    if (!monitor_instance) {
01927       return -1;
01928    }
01929 
01930    if (!(monitor_instance->subscription_pvt = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
01931       return -1;
01932    }
01933 
01934    when = service == AST_CC_CCBS ? ast_get_ccbs_available_timer(monitor->interface->config_params) :
01935       ast_get_ccnr_available_timer(monitor->interface->config_params);
01936 
01937    sip_pvt_lock(monitor_instance->subscription_pvt);
01938    ast_set_flag(&monitor_instance->subscription_pvt->flags[0], SIP_OUTGOING);
01939    create_addr(monitor_instance->subscription_pvt, monitor_instance->peername, 0, 1);
01940    ast_sip_ouraddrfor(&monitor_instance->subscription_pvt->sa, &monitor_instance->subscription_pvt->ourip, monitor_instance->subscription_pvt);
01941    monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
01942    monitor_instance->subscription_pvt->expiry = when;
01943 
01944    transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 2, monitor_instance->subscribe_uri);
01945    sip_pvt_unlock(monitor_instance->subscription_pvt);
01946 
01947    ao2_t_ref(monitor, +1, "Adding a ref to the monitor for the scheduler");
01948    *available_timer_id = ast_sched_add(sched, when * 1000, ast_cc_available_timer_expire, monitor);
01949    return 0;
01950 }
01951 
01952 static int construct_pidf_body(enum sip_cc_publish_state state, char *pidf_body, size_t size, const char *presentity)
01953 {
01954    struct ast_str *body = ast_str_alloca(size);
01955    char tuple_id[32];
01956 
01957    generate_random_string(tuple_id, sizeof(tuple_id));
01958 
01959    /* We'll make this a bare-bones pidf body. In state_notify_build_xml, the PIDF
01960     * body gets a lot more extra junk that isn't necessary, so we'll leave it out here.
01961     */
01962    ast_str_append(&body, 0, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
01963    /* XXX The entity attribute is currently set to the peer name associated with the
01964     * dialog. This is because we currently only call this function for call-completion
01965     * PUBLISH bodies. In such cases, the entity is completely disregarded. For other
01966     * event packages, it may be crucial to have a proper URI as the presentity so this
01967     * should be revisited as support is expanded.
01968     */
01969    ast_str_append(&body, 0, "<presence xmlns=\"urn:ietf:params:xml:ns:pidf\" entity=\"%s\">\n", presentity);
01970    ast_str_append(&body, 0, "<tuple id=\"%s\">\n", tuple_id);
01971    ast_str_append(&body, 0, "<status><basic>%s</basic></status>\n", state == CC_OPEN ? "open" : "closed");
01972    ast_str_append(&body, 0, "</tuple>\n");
01973    ast_str_append(&body, 0, "</presence>\n");
01974    ast_copy_string(pidf_body, ast_str_buffer(body), size);
01975    return 0;
01976 }
01977 
01978 static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor)
01979 {
01980    struct sip_monitor_instance *monitor_instance = monitor->private_data;
01981    enum sip_publish_type publish_type;
01982    struct cc_epa_entry *cc_entry;
01983 
01984    if (!monitor_instance) {
01985       return -1;
01986    }
01987 
01988    if (!monitor_instance->suspension_entry) {
01989       /* We haven't yet allocated the suspension entry, so let's give it a shot */
01990       if (!(monitor_instance->suspension_entry = create_epa_entry("call-completion", monitor_instance->peername))) {
01991          ast_log(LOG_WARNING, "Unable to allocate sip EPA entry for call-completion\n");
01992          ao2_ref(monitor_instance, -1);
01993          return -1;
01994       }
01995       if (!(cc_entry = ast_calloc(1, sizeof(*cc_entry)))) {
01996          ast_log(LOG_WARNING, "Unable to allocate space for instance data of EPA entry for call-completion\n");
01997          ao2_ref(monitor_instance, -1);
01998          return -1;
01999       }
02000       cc_entry->core_id = monitor->core_id;
02001       monitor_instance->suspension_entry->instance_data = cc_entry;
02002       publish_type = SIP_PUBLISH_INITIAL;
02003    } else {
02004       publish_type = SIP_PUBLISH_MODIFY;
02005       cc_entry = monitor_instance->suspension_entry->instance_data;
02006    }
02007 
02008    cc_entry->current_state = CC_CLOSED;
02009 
02010    if (ast_strlen_zero(monitor_instance->notify_uri)) {
02011       /* If we have no set notify_uri, then what this means is that we have
02012        * not received a NOTIFY from this destination stating that he is
02013        * currently available.
02014        *
02015        * This situation can arise when the core calls the suspend callbacks
02016        * of multiple destinations. If one of the other destinations aside
02017        * from this one notified Asterisk that he is available, then there
02018        * is no reason to take any suspension action on this device. Rather,
02019        * we should return now and if we receive a NOTIFY while monitoring
02020        * is still "suspended" then we can immediately respond with the
02021        * proper PUBLISH to let this endpoint know what is going on.
02022        */
02023       return 0;
02024    }
02025    construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
02026    return transmit_publish(monitor_instance->suspension_entry, publish_type, monitor_instance->notify_uri);
02027 }
02028 
02029 static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor)
02030 {
02031    struct sip_monitor_instance *monitor_instance = monitor->private_data;
02032    struct cc_epa_entry *cc_entry;
02033 
02034    if (!monitor_instance) {
02035       return -1;
02036    }
02037 
02038    ast_assert(monitor_instance->suspension_entry != NULL);
02039 
02040    cc_entry = monitor_instance->suspension_entry->instance_data;
02041    cc_entry->current_state = CC_OPEN;
02042    if (ast_strlen_zero(monitor_instance->notify_uri)) {
02043       /* This means we are being asked to unsuspend a call leg we never
02044        * sent a PUBLISH on. As such, there is no reason to send another
02045        * PUBLISH at this point either. We can just return instead.
02046        */
02047       return 0;
02048    }
02049    construct_pidf_body(CC_OPEN, monitor_instance->suspension_entry->body, sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
02050    return transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_MODIFY, monitor_instance->notify_uri);
02051 }
02052 
02053 static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id)
02054 {
02055    if (*sched_id != -1) {
02056       AST_SCHED_DEL(sched, *sched_id);
02057       ao2_t_ref(monitor, -1, "Removing scheduler's reference to the monitor");
02058    }
02059    return 0;
02060 }
02061 
02062 static void sip_cc_monitor_destructor(void *private_data)
02063 {
02064    struct sip_monitor_instance *monitor_instance = private_data;
02065    ao2_unlink(sip_monitor_instances, monitor_instance);
02066    ast_module_unref(ast_module_info->self);
02067 }
02068 
02069 static int sip_get_cc_information(struct sip_request *req, char *subscribe_uri, size_t size, enum ast_cc_service_type *service)
02070 {
02071    char *call_info = ast_strdupa(get_header(req, "Call-Info"));
02072    char *uri;
02073    char *purpose;
02074    char *service_str;
02075    static const char cc_purpose[] = "purpose=call-completion";
02076    static const int cc_purpose_len = sizeof(cc_purpose) - 1;
02077 
02078    if (ast_strlen_zero(call_info)) {
02079       /* No Call-Info present. Definitely no CC offer */
02080       return -1;
02081    }
02082 
02083    uri = strsep(&call_info, ";");
02084 
02085    while ((purpose = strsep(&call_info, ";"))) {
02086       if (!strncmp(purpose, cc_purpose, cc_purpose_len)) {
02087          break;
02088       }
02089    }
02090    if (!purpose) {
02091       /* We didn't find the appropriate purpose= parameter. Oh well */
02092       return -1;
02093    }
02094 
02095    /* Okay, call-completion has been offered. Let's figure out what type of service this is */
02096    while ((service_str = strsep(&call_info, ";"))) {
02097       if (!strncmp(service_str, "m=", 2)) {
02098          break;
02099       }
02100    }
02101    if (!service_str) {
02102       /* So they didn't offer a particular service, We'll just go with CCBS since it really
02103        * doesn't matter anyway
02104        */
02105       service_str = "BS";
02106    } else {
02107       /* We already determined that there is an "m=" so no need to check
02108        * the result of this strsep
02109        */
02110       strsep(&service_str, "=");
02111    }
02112 
02113    if ((*service = service_string_to_service_type(service_str)) == AST_CC_NONE) {
02114       /* Invalid service offered */
02115       return -1;
02116    }
02117 
02118    ast_copy_string(subscribe_uri, get_in_brackets(uri), size);
02119 
02120    return 0;
02121 }
02122 
02123 /*
02124  * \brief Determine what, if any, CC has been offered and queue a CC frame if possible
02125  *
02126  * After taking care of some formalities to be sure that this call is eligible for CC,
02127  * we first try to see if we can make use of native CC. We grab the information from
02128  * the passed-in sip_request (which is always a response to an INVITE). If we can
02129  * use native CC monitoring for the call, then so be it.
02130  *
02131  * If native cc monitoring is not possible or not supported, then we will instead attempt
02132  * to use generic monitoring. Falling back to generic from a failed attempt at using native
02133  * monitoring will only work if the monitor policy of the endpoint is "always"
02134  *
02135  * \param pvt The current dialog. Contains CC parameters for the endpoint
02136  * \param req The response to the INVITE we want to inspect
02137  * \param service The service to use if generic monitoring is to be used. For native
02138  * monitoring, we get the service from the SIP response itself
02139  */
02140 static void sip_handle_cc(struct sip_pvt *pvt, struct sip_request *req, enum ast_cc_service_type service)
02141 {
02142    enum ast_cc_monitor_policies monitor_policy = ast_get_cc_monitor_policy(pvt->cc_params);
02143    int core_id;
02144    char interface_name[AST_CHANNEL_NAME];
02145 
02146    if (monitor_policy == AST_CC_MONITOR_NEVER) {
02147       /* Don't bother, just return */
02148       return;
02149    }
02150 
02151    if ((core_id = ast_cc_get_current_core_id(pvt->owner)) == -1) {
02152       /* For some reason, CC is invalid, so don't try it! */
02153       return;
02154    }
02155 
02156    ast_channel_get_device_name(pvt->owner, interface_name, sizeof(interface_name));
02157 
02158    if (monitor_policy == AST_CC_MONITOR_ALWAYS || monitor_policy == AST_CC_MONITOR_NATIVE) {
02159       char subscribe_uri[SIPBUFSIZE];
02160       char device_name[AST_CHANNEL_NAME];
02161       enum ast_cc_service_type offered_service;
02162       struct sip_monitor_instance *monitor_instance;
02163       if (sip_get_cc_information(req, subscribe_uri, sizeof(subscribe_uri), &offered_service)) {
02164          /* If CC isn't being offered to us, or for some reason the CC offer is
02165           * not formatted correctly, then it may still be possible to use generic
02166           * call completion since the monitor policy may be "always"
02167           */
02168          goto generic;
02169       }
02170       ast_channel_get_device_name(pvt->owner, device_name, sizeof(device_name));
02171       if (!(monitor_instance = sip_monitor_instance_init(core_id, subscribe_uri, pvt->peername, device_name))) {
02172          /* Same deal. We can try using generic still */
02173          goto generic;
02174       }
02175       /* We bump the refcount of chan_sip because once we queue this frame, the CC core
02176        * will have a reference to callbacks in this module. We decrement the module
02177        * refcount once the monitor destructor is called
02178        */
02179       ast_module_ref(ast_module_info->self);
02180       ast_queue_cc_frame(pvt->owner, "SIP", pvt->dialstring, offered_service, monitor_instance);
02181       ao2_ref(monitor_instance, -1);
02182       return;
02183    }
02184 
02185 generic:
02186    if (monitor_policy == AST_CC_MONITOR_GENERIC || monitor_policy == AST_CC_MONITOR_ALWAYS) {
02187       ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE, interface_name, service, NULL);
02188    }
02189 }
02190 
02191 /*! \brief Working TLS connection configuration */
02192 static struct ast_tls_config sip_tls_cfg;
02193 
02194 /*! \brief Default TLS connection configuration */
02195 static struct ast_tls_config default_tls_cfg;
02196 
02197 /*! \brief The TCP server definition */
02198 static struct ast_tcptls_session_args sip_tcp_desc = {
02199    .accept_fd = -1,
02200    .master = AST_PTHREADT_NULL,
02201    .tls_cfg = NULL,
02202    .poll_timeout = -1,
02203    .name = "SIP TCP server",
02204    .accept_fn = ast_tcptls_server_root,
02205    .worker_fn = sip_tcp_worker_fn,
02206 };
02207 
02208 /*! \brief The TCP/TLS server definition */
02209 static struct ast_tcptls_session_args sip_tls_desc = {
02210    .accept_fd = -1,
02211    .master = AST_PTHREADT_NULL,
02212    .tls_cfg = &sip_tls_cfg,
02213    .poll_timeout = -1,
02214    .name = "SIP TLS server",
02215    .accept_fn = ast_tcptls_server_root,
02216    .worker_fn = sip_tcp_worker_fn,
02217 };
02218 
02219 /*! \brief Append to SIP dialog history
02220    \return Always returns 0 */
02221 #define append_history(p, event, fmt , args... )   append_history_full(p, "%-15s " fmt, event, ## args)
02222 
02223 struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
02224 {
02225    if (p)
02226 #ifdef REF_DEBUG
02227       __ao2_ref_debug(p, 1, tag, file, line, func);
02228 #else
02229       ao2_ref(p, 1);
02230 #endif
02231    else
02232       ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
02233    return p;
02234 }
02235 
02236 struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
02237 {
02238    if (p)
02239 #ifdef REF_DEBUG
02240       __ao2_ref_debug(p, -1, tag, file, line, func);
02241 #else
02242       ao2_ref(p, -1);
02243 #endif
02244    return NULL;
02245 }
02246 
02247 /*! \brief map from an integer value to a string.
02248  * If no match is found, return errorstring
02249  */
02250 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
02251 {
02252    const struct _map_x_s *cur;
02253 
02254    for (cur = table; cur->s; cur++)
02255       if (cur->x == x)
02256          return cur->s;
02257    return errorstring;
02258 }
02259 
02260 /*! \brief map from a string to an integer value, case insensitive.
02261  * If no match is found, return errorvalue.
02262  */
02263 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
02264 {
02265    const struct _map_x_s *cur;
02266 
02267    for (cur = table; cur->s; cur++)
02268       if (!strcasecmp(cur->s, s))
02269          return cur->x;
02270    return errorvalue;
02271 }
02272 
02273 static enum AST_REDIRECTING_REASON sip_reason_str_to_code(const char *text)
02274 {
02275    enum AST_REDIRECTING_REASON ast = AST_REDIRECTING_REASON_UNKNOWN;
02276    int i;
02277 
02278    for (i = 0; i < ARRAY_LEN(sip_reason_table); ++i) {
02279       if (!strcasecmp(text, sip_reason_table[i].text)) {
02280          ast = sip_reason_table[i].code;
02281          break;
02282       }
02283    }
02284 
02285    return ast;
02286 }
02287 
02288 static const char *sip_reason_code_to_str(enum AST_REDIRECTING_REASON code)
02289 {
02290    if (code >= 0 && code < ARRAY_LEN(sip_reason_table)) {
02291       return sip_reason_table[code].text;
02292    }
02293 
02294    return "unknown";
02295 }
02296 
02297 /*!
02298  * \brief generic function for determining if a correct transport is being
02299  * used to contact a peer
02300  *
02301  * this is done as a macro so that the "tmpl" var can be passed either a
02302  * sip_request or a sip_peer
02303  */
02304 #define check_request_transport(peer, tmpl) ({ \
02305    int ret = 0; \
02306    if (peer->socket.type == tmpl->socket.type) \
02307       ; \
02308    else if (!(peer->transports & tmpl->socket.type)) {\
02309       ast_log(LOG_ERROR, \
02310          "'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
02311          get_transport(tmpl->socket.type), peer->name, get_transport_list(peer->transports) \
02312          ); \
02313       ret = 1; \
02314    } else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
02315       ast_log(LOG_WARNING, \
02316          "peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
02317          peer->name, get_transport(tmpl->socket.type) \
02318       ); \
02319    } else { \
02320       ast_debug(1, \
02321          "peer '%s' has contacted us over %s even though we prefer %s.\n", \
02322          peer->name, get_transport(tmpl->socket.type), get_transport(peer->socket.type) \
02323       ); \
02324    }\
02325    (ret); \
02326 })
02327 
02328 /*! \brief
02329  * duplicate a list of channel variables, \return the copy.
02330  */
02331 static struct ast_variable *copy_vars(struct ast_variable *src)
02332 {
02333    struct ast_variable *res = NULL, *tmp, *v = NULL;
02334 
02335    for (v = src ; v ; v = v->next) {
02336       if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
02337          tmp->next = res;
02338          res = tmp;
02339       }
02340    }
02341    return res;
02342 }
02343 
02344 static void tcptls_packet_destructor(void *obj)
02345 {
02346    struct tcptls_packet *packet = obj;
02347 
02348    ast_free(packet->data);
02349 }
02350 
02351 static void sip_tcptls_client_args_destructor(void *obj)
02352 {
02353    struct ast_tcptls_session_args *args = obj;
02354    if (args->tls_cfg) {
02355       ast_free(args->tls_cfg->certfile);
02356       ast_free(args->tls_cfg->pvtfile);
02357       ast_free(args->tls_cfg->cipher);
02358       ast_free(args->tls_cfg->cafile);
02359       ast_free(args->tls_cfg->capath);
02360 
02361       ast_ssl_teardown(args->tls_cfg);
02362    }
02363    ast_free(args->tls_cfg);
02364    ast_free((char *) args->name);
02365 }
02366 
02367 static void sip_threadinfo_destructor(void *obj)
02368 {
02369    struct sip_threadinfo *th = obj;
02370    struct tcptls_packet *packet;
02371    if (th->alert_pipe[1] > -1) {
02372       close(th->alert_pipe[0]);
02373    }
02374    if (th->alert_pipe[1] > -1) {
02375       close(th->alert_pipe[1]);
02376    }
02377    th->alert_pipe[0] = th->alert_pipe[1] = -1;
02378 
02379    while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
02380       ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
02381    }
02382 
02383    if (th->tcptls_session) {
02384       ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
02385    }
02386 }
02387 
02388 /*! \brief creates a sip_threadinfo object and links it into the threadt table. */
02389 static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
02390 {
02391    struct sip_threadinfo *th;
02392 
02393    if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
02394       return NULL;
02395    }
02396 
02397    th->alert_pipe[0] = th->alert_pipe[1] = -1;
02398 
02399    if (pipe(th->alert_pipe) == -1) {
02400       ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
02401       ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
02402       return NULL;
02403    }
02404    ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
02405    th->tcptls_session = tcptls_session;
02406    th->type = transport ? transport : (tcptls_session->ssl ? SIP_TRANSPORT_TLS: SIP_TRANSPORT_TCP);
02407    ao2_t_link(threadt, th, "Adding new tcptls helper thread");
02408    ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
02409    return th;
02410 }
02411 
02412 /*! \brief used to indicate to a tcptls thread that data is ready to be written */
02413 static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
02414 {
02415    int res = len;
02416    struct sip_threadinfo *th = NULL;
02417    struct tcptls_packet *packet = NULL;
02418    struct sip_threadinfo tmp = {
02419       .tcptls_session = tcptls_session,
02420    };
02421    enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
02422 
02423    if (!tcptls_session) {
02424       return XMIT_ERROR;
02425    }
02426 
02427    ast_mutex_lock(&tcptls_session->lock);
02428 
02429    if ((tcptls_session->fd == -1) ||
02430       !(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
02431       !(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
02432       !(packet->data = ast_str_create(len))) {
02433       goto tcptls_write_setup_error;
02434    }
02435 
02436    /* goto tcptls_write_error should _NOT_ be used beyond this point */
02437    ast_str_set(&packet->data, 0, "%s", (char *) buf);
02438    packet->len = len;
02439 
02440    /* alert tcptls thread handler that there is a packet to be sent.
02441     * must lock the thread info object to guarantee control of the
02442     * packet queue */
02443    ao2_lock(th);
02444    if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
02445       ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
02446       ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
02447       packet = NULL;
02448       res = XMIT_ERROR;
02449    } else { /* it is safe to queue the frame after issuing the alert when we hold the threadinfo lock */
02450       AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
02451    }
02452    ao2_unlock(th);
02453 
02454    ast_mutex_unlock(&tcptls_session->lock);
02455    ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
02456    return res;
02457 
02458 tcptls_write_setup_error:
02459    if (th) {
02460       ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
02461    }
02462    if (packet) {
02463       ao2_t_ref(packet, -1, "could not allocate packet's data");
02464    }
02465    ast_mutex_unlock(&tcptls_session->lock);
02466 
02467    return XMIT_ERROR;
02468 }
02469 
02470 /*! \brief SIP TCP connection handler */
02471 static void *sip_tcp_worker_fn(void *data)
02472 {
02473    struct ast_tcptls_session_instance *tcptls_session = data;
02474 
02475    return _sip_tcp_helper_thread(tcptls_session);
02476 }
02477 
02478 /*! \brief Check if the authtimeout has expired.
02479  * \param start the time when the session started
02480  *
02481  * \retval 0 the timeout has expired
02482  * \retval -1 error
02483  * \return the number of milliseconds until the timeout will expire
02484  */
02485 static int sip_check_authtimeout(time_t start)
02486 {
02487    int timeout;
02488    time_t now;
02489    if(time(&now) == -1) {
02490       ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
02491       return -1;
02492    }
02493 
02494    timeout = (authtimeout - (now - start)) * 1000;
02495    if (timeout < 0) {
02496       /* we have timed out */
02497       return 0;
02498    }
02499 
02500    return timeout;
02501 }
02502 
02503 /*! \brief SIP TCP thread management function
02504    This function reads from the socket, parses the packet into a request
02505 */
02506 static void *_sip_tcp_helper_thread(struct ast_tcptls_session_instance *tcptls_session)
02507 {
02508    int res, cl, timeout = -1, authenticated = 0, flags, after_poll = 0, need_poll = 1;
02509    time_t start;
02510    struct sip_request req = { 0, } , reqcpy = { 0, };
02511    struct sip_threadinfo *me = NULL;
02512    char buf[1024] = "";
02513    struct pollfd fds[2] = { { 0 }, { 0 }, };
02514    struct ast_tcptls_session_args *ca = NULL;
02515 
02516    /* If this is a server session, then the connection has already been
02517     * setup. Check if the authlimit has been reached and if not create the
02518     * threadinfo object so we can access this thread for writing.
02519     *
02520     * if this is a client connection more work must be done.
02521     * 1. We own the parent session args for a client connection.  This pointer needs
02522     *    to be held on to so we can decrement it's ref count on thread destruction.
02523     * 2. The threadinfo object was created before this thread was launched, however
02524     *    it must be found within the threadt table.
02525     * 3. Last, the tcptls_session must be started.
02526     */
02527    if (!tcptls_session->client) {
02528       if (ast_atomic_fetchadd_int(&unauth_sessions, +1) >= authlimit) {
02529          /* unauth_sessions is decremented in the cleanup code */
02530          goto cleanup;
02531       }
02532 
02533       if ((flags = fcntl(tcptls_session->fd, F_GETFL)) == -1) {
02534          ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
02535          goto cleanup;
02536       }
02537 
02538       flags |= O_NONBLOCK;
02539       if (fcntl(tcptls_session->fd, F_SETFL, flags) == -1) {
02540          ast_log(LOG_ERROR, "error setting socket to non blocking mode, fcntl() failed: %s\n", strerror(errno));
02541          goto cleanup;
02542       }
02543 
02544       if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? SIP_TRANSPORT_TLS : SIP_TRANSPORT_TCP))) {
02545          goto cleanup;
02546       }
02547       ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
02548    } else {
02549       struct sip_threadinfo tmp = {
02550          .tcptls_session = tcptls_session,
02551       };
02552 
02553       if ((!(ca = tcptls_session->parent)) ||
02554          (!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
02555          (!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
02556          goto cleanup;
02557       }
02558    }
02559 
02560    flags = 1;
02561    if (setsockopt(tcptls_session->fd, SOL_SOCKET, SO_KEEPALIVE, &flags, sizeof(flags))) {
02562       ast_log(LOG_ERROR, "error enabling TCP keep-alives on sip socket: %s\n", strerror(errno));
02563       goto cleanup;
02564    }
02565 
02566    me->threadid = pthread_self();
02567    ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
02568 
02569    /* set up pollfd to watch for reads on both the socket and the alert_pipe */
02570    fds[0].fd = tcptls_session->fd;
02571    fds[1].fd = me->alert_pipe[0];
02572    fds[0].events = fds[1].events = POLLIN | POLLPRI;
02573 
02574    if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
02575       goto cleanup;
02576    }
02577    if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET))) {
02578       goto cleanup;
02579    }
02580 
02581    if(time(&start) == -1) {
02582       ast_log(LOG_ERROR, "error executing time(): %s\n", strerror(errno));
02583       goto cleanup;
02584    }
02585 
02586    for (;;) {
02587       struct ast_str *str_save;
02588 
02589       if (!tcptls_session->client && req.authenticated && !authenticated) {
02590          authenticated = 1;
02591          ast_atomic_fetchadd_int(&unauth_sessions, -1);
02592       }
02593 
02594       /* calculate the timeout for unauthenticated server sessions */
02595       if (!tcptls_session->client && !authenticated ) {
02596          if ((timeout = sip_check_authtimeout(start)) < 0) {
02597             goto cleanup;
02598          }
02599 
02600          if (timeout == 0) {
02601             ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
02602             goto cleanup;
02603          }
02604       } else {
02605          timeout = -1;
02606       }
02607 
02608       res = ast_poll(fds, 2, timeout); /* polls for both socket and alert_pipe */
02609       if (res < 0) {
02610          ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
02611          goto cleanup;
02612       } else if (res == 0) {
02613          /* timeout */
02614          ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
02615          goto cleanup;
02616       }
02617 
02618       /* handle the socket event, check for both reads from the socket fd,
02619        * and writes from alert_pipe fd */
02620       if (fds[0].revents) { /* there is data on the socket to be read */
02621          after_poll = 1;
02622 
02623          fds[0].revents = 0;
02624 
02625          /* clear request structure */
02626          str_save = req.data;
02627          memset(&req, 0, sizeof(req));
02628          req.data = str_save;
02629          ast_str_reset(req.data);
02630 
02631          str_save = reqcpy.data;
02632          memset(&reqcpy, 0, sizeof(reqcpy));
02633          reqcpy.data = str_save;
02634          ast_str_reset(reqcpy.data);
02635 
02636          memset(buf, 0, sizeof(buf));
02637 
02638          if (tcptls_session->ssl) {
02639             set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
02640             req.socket.port = htons(ourport_tls);
02641          } else {
02642             set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
02643             req.socket.port = htons(ourport_tcp);
02644          }
02645          req.socket.fd = tcptls_session->fd;
02646 
02647          /* Read in headers one line at a time */
02648          while (ast_str_strlen(req.data) < 4 || strncmp(REQ_OFFSET_TO_STR(&req, data->used - 4), "\r\n\r\n", 4)) {
02649             if (!tcptls_session->client && !authenticated ) {
02650                if ((timeout = sip_check_authtimeout(start)) < 0) {
02651                   goto cleanup;
02652                }
02653 
02654                if (timeout == 0) {
02655                   ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
02656                   goto cleanup;
02657                }
02658             } else {
02659                timeout = -1;
02660             }
02661 
02662             /* special polling behavior is required for TLS
02663              * sockets because of the buffering done in the
02664              * TLS layer */
02665             if (!tcptls_session->ssl || need_poll) {
02666                need_poll = 0;
02667                after_poll = 1;
02668                res = ast_wait_for_input(tcptls_session->fd, timeout);
02669                if (res < 0) {
02670                   ast_debug(2, "SIP TCP server :: ast_wait_for_input returned %d\n", res);
02671                   goto cleanup;
02672                } else if (res == 0) {
02673                   /* timeout */
02674                   ast_debug(2, "SIP TCP server timed out\n");
02675                   goto cleanup;
02676                }
02677             }
02678 
02679             ast_mutex_lock(&tcptls_session->lock);
02680             if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
02681                ast_mutex_unlock(&tcptls_session->lock);
02682                if (after_poll) {
02683                   goto cleanup;
02684                } else {
02685                   need_poll = 1;
02686                   continue;
02687                }
02688             }
02689             ast_mutex_unlock(&tcptls_session->lock);
02690             after_poll = 0;
02691             if (me->stop) {
02692                 goto cleanup;
02693             }
02694             ast_str_append(&req.data, 0, "%s", buf);
02695          }
02696          copy_request(&reqcpy, &req);
02697          parse_request(&reqcpy);
02698          /* In order to know how much to read, we need the content-length header */
02699          if (sscanf(get_header(&reqcpy, "Content-Length"), "%30d", &cl)) {
02700             while (cl > 0) {
02701                size_t bytes_read;
02702                if (!tcptls_session->client && !authenticated ) {
02703                   if ((timeout = sip_check_authtimeout(start)) < 0) {
02704                      goto cleanup;
02705                   }
02706 
02707                   if (timeout == 0) {
02708                      ast_debug(2, "SIP %s server timed out\n", tcptls_session->ssl ? "SSL": "TCP");
02709                      goto cleanup;
02710                   }
02711                } else {
02712                   timeout = -1;
02713                }
02714 
02715                if (!tcptls_session->ssl || need_poll) {
02716                   need_poll = 0;
02717                   after_poll = 1;
02718                   res = ast_wait_for_input(tcptls_session->fd, timeout);
02719                   if (res < 0) {
02720                      ast_debug(2, "SIP TCP server :: ast_wait_for_input returned %d\n", res);
02721                      goto cleanup;
02722                   } else if (res == 0) {
02723                      /* timeout */
02724                      ast_debug(2, "SIP TCP server timed out\n");
02725                      goto cleanup;
02726                   }
02727                }
02728 
02729                ast_mutex_lock(&tcptls_session->lock);
02730                if (!(bytes_read = fread(buf, 1, MIN(sizeof(buf) - 1, cl), tcptls_session->f))) {
02731                   ast_mutex_unlock(&tcptls_session->lock);
02732                   if (after_poll) {
02733                      goto cleanup;
02734                   } else {
02735                      need_poll = 1;
02736                      continue;
02737                   }
02738                }
02739                buf[bytes_read] = '\0';
02740                ast_mutex_unlock(&tcptls_session->lock);
02741                after_poll = 0;
02742                if (me->stop) {
02743                   goto cleanup;
02744                }
02745                cl -= strlen(buf);
02746                ast_str_append(&req.data, 0, "%s", buf);
02747             }
02748          }
02749          /*! \todo XXX If there's no Content-Length or if the content-length and what
02750                we receive is not the same - we should generate an error */
02751 
02752          req.socket.tcptls_session = tcptls_session;
02753          handle_request_do(&req, &tcptls_session->remote_address);
02754       }
02755 
02756       if (fds[1].revents) { /* alert_pipe indicates there is data in the send queue to be sent */
02757          enum sip_tcptls_alert alert;
02758          struct tcptls_packet *packet;
02759 
02760          fds[1].revents = 0;
02761 
02762          if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
02763             ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
02764             continue;
02765          }
02766 
02767          switch (alert) {
02768          case TCPTLS_ALERT_STOP:
02769             goto cleanup;
02770          case TCPTLS_ALERT_DATA:
02771             ao2_lock(me);
02772             if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
02773                ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty\n");
02774             }
02775             ao2_unlock(me);
02776 
02777             if (packet) {
02778                if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
02779                   ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
02780                }
02781                ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
02782             }
02783             break;
02784          default:
02785             ast_log(LOG_ERROR, "Unknown tcptls thread alert '%d'\n", alert);
02786          }
02787       }
02788    }
02789 
02790    ast_debug(2, "Shutting down thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
02791 
02792 cleanup:
02793    if (tcptls_session && !tcptls_session->client && !authenticated) {
02794       ast_atomic_fetchadd_int(&unauth_sessions, -1);
02795    }
02796 
02797    if (me) {
02798       ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
02799       ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
02800    }
02801    deinit_req(&reqcpy);
02802    deinit_req(&req);
02803 
02804    /* if client, we own the parent session arguments and must decrement ref */
02805    if (ca) {
02806       ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
02807    }
02808 
02809    if (tcptls_session) {
02810       ast_mutex_lock(&tcptls_session->lock);
02811       ast_tcptls_close_session_file(tcptls_session);
02812       tcptls_session->parent = NULL;
02813       ast_mutex_unlock(&tcptls_session->lock);
02814 
02815       ao2_ref(tcptls_session, -1);
02816       tcptls_session = NULL;
02817    }
02818    return NULL;
02819 }
02820 
02821 #ifdef REF_DEBUG
02822 #define ref_peer(arg1,arg2) _ref_peer((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
02823 #define unref_peer(arg1,arg2) _unref_peer((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
02824 static struct sip_peer *_ref_peer(struct sip_peer *peer, char *tag, char *file, int line, const char *func)
02825 {
02826    if (peer)
02827       __ao2_ref_debug(peer, 1, tag, file, line, func);
02828    else
02829       ast_log(LOG_ERROR, "Attempt to Ref a null peer pointer\n");
02830    return peer;
02831 }
02832 
02833 static struct sip_peer *_unref_peer(struct sip_peer *peer, char *tag, char *file, int line, const char *func)
02834 {
02835    if (peer)
02836       __ao2_ref_debug(peer, -1, tag, file, line, func);
02837    return NULL;
02838 }
02839 #else
02840 /*!
02841  * helper functions to unreference various types of objects.
02842  * By handling them this way, we don't have to declare the
02843  * destructor on each call, which removes the chance of errors.
02844  */
02845 static void *unref_peer(struct sip_peer *peer, char *tag)
02846 {
02847    ao2_t_ref(peer, -1, tag);
02848    return NULL;
02849 }
02850 
02851 static struct sip_peer *ref_peer(struct sip_peer *peer, char *tag)
02852 {
02853    ao2_t_ref(peer, 1, tag);
02854    return peer;
02855 }
02856 #endif /* REF_DEBUG */
02857 
02858 static void peer_sched_cleanup(struct sip_peer *peer)
02859 {
02860    if (peer->pokeexpire != -1) {
02861       AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
02862             unref_peer(peer, "removing poke peer ref"));
02863    }
02864    if (peer->expire != -1) {
02865       AST_SCHED_DEL_UNREF(sched, peer->expire,
02866             unref_peer(peer, "remove register expire ref"));
02867    }
02868 }
02869 
02870 typedef enum {
02871    SIP_PEERS_MARKED,
02872    SIP_PEERS_ALL,
02873 } peer_unlink_flag_t;
02874 
02875 /* this func is used with ao2_callback to unlink/delete all marked or linked
02876    peers, depending on arg */
02877 static int match_and_cleanup_peer_sched(void *peerobj, void *arg, int flags)
02878 {
02879    struct sip_peer *peer = peerobj;
02880    peer_unlink_flag_t which = *(peer_unlink_flag_t *)arg;
02881 
02882    if (which == SIP_PEERS_ALL || peer->the_mark) {
02883       peer_sched_cleanup(peer);
02884       if (peer->dnsmgr) {
02885          ast_dnsmgr_release(peer->dnsmgr);
02886          peer->dnsmgr = NULL;
02887          unref_peer(peer, "Release peer from dnsmgr");
02888       }
02889       return CMP_MATCH;
02890    }
02891    return 0;
02892 }
02893 
02894 static void unlink_peers_from_tables(peer_unlink_flag_t flag)
02895 {
02896    ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
02897       match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
02898    ao2_t_callback(peers_by_ip, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE,
02899       match_and_cleanup_peer_sched, &flag, "initiating callback to remove marked peers");
02900 }
02901 
02902 /* \brief Unlink all marked peers from ao2 containers */
02903 static void unlink_marked_peers_from_tables(void)
02904 {
02905    unlink_peers_from_tables(SIP_PEERS_MARKED);
02906 }
02907 
02908 static void unlink_all_peers_from_tables(void)
02909 {
02910    unlink_peers_from_tables(SIP_PEERS_ALL);
02911 }
02912 
02913 /* \brief Unlink single peer from all ao2 containers */
02914 static void unlink_peer_from_tables(struct sip_peer *peer)
02915 {
02916    ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
02917    if (!ast_sockaddr_isnull(&peer->addr)) {
02918       ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
02919    }
02920 }
02921 
02922 /*! \brief maintain proper refcounts for a sip_pvt's outboundproxy
02923  *
02924  * This function sets pvt's outboundproxy pointer to the one referenced
02925  * by the proxy parameter. Because proxy may be a refcounted object, and
02926  * because pvt's old outboundproxy may also be a refcounted object, we need
02927  * to maintain the proper refcounts.
02928  *
02929  * \param pvt The sip_pvt for which we wish to set the outboundproxy
02930  * \param proxy The sip_proxy which we will point pvt towards.
02931  * \return Returns void
02932  */
02933 static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
02934 {
02935    struct sip_proxy *old_obproxy = pvt->outboundproxy;
02936    /* The sip_cfg.outboundproxy is statically allocated, and so
02937     * we don't ever need to adjust refcounts for it
02938     */
02939    if (proxy && proxy != &sip_cfg.outboundproxy) {
02940       ao2_ref(proxy, +1);
02941    }
02942    pvt->outboundproxy = proxy;
02943    if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
02944       ao2_ref(old_obproxy, -1);
02945    }
02946 }
02947 
02948 /*!
02949  * \brief Unlink a dialog from the dialogs container, as well as any other places
02950  * that it may be currently stored.
02951  *
02952  * \note A reference to the dialog must be held before calling this function, and this
02953  * function does not release that reference.
02954  */
02955 void dialog_unlink_all(struct sip_pvt *dialog)
02956 {
02957    struct sip_pkt *cp;
02958    struct ast_channel *owner;
02959 
02960    dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
02961 
02962    ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
02963 
02964    /* Unlink us from the owner (channel) if we have one */
02965    owner = sip_pvt_lock_full(dialog);
02966    if (owner) {
02967       ast_debug(1, "Detaching from channel %s\n", owner->name);
02968       owner->tech_pvt = dialog_unref(owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
02969       ast_channel_unlock(owner);
02970       ast_channel_unref(owner);
02971       dialog->owner = NULL;
02972    }
02973    sip_pvt_unlock(dialog);
02974 
02975    if (dialog->registry) {
02976       if (dialog->registry->call == dialog) {
02977          dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
02978       }
02979       dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
02980    }
02981    if (dialog->stateid != -1) {
02982       ast_extension_state_del(dialog->stateid, cb_extensionstate);
02983       dialog->stateid = -1;
02984    }
02985    /* Remove link from peer to subscription of MWI */
02986    if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog) {
02987       dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
02988    }
02989    if (dialog->relatedpeer && dialog->relatedpeer->call == dialog) {
02990       dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
02991    }
02992 
02993    /* remove all current packets in this dialog */
02994    while((cp = dialog->packets)) {
02995       dialog->packets = dialog->packets->next;
02996       AST_SCHED_DEL(sched, cp->retransid);
02997       dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
02998       if (cp->data) {
02999          ast_free(cp->data);
03000       }
03001       ast_free(cp);
03002    }
03003 
03004    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"));
03005 
03006    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"));
03007    
03008    if (dialog->autokillid > -1) {
03009       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"));
03010    }
03011 
03012    if (dialog->request_queue_sched_id > -1) {
03013       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"));
03014    }
03015 
03016    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"));
03017 
03018    if (dialog->t38id > -1) {
03019       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"));
03020    }
03021 
03022    if (dialog->stimer) {
03023       stop_session_timer(dialog);
03024    }
03025 
03026    dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
03027 }
03028 
03029 void *registry_unref(struct sip_registry *reg, char *tag)
03030 {
03031    ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
03032    ASTOBJ_UNREF(reg, sip_registry_destroy);
03033    return NULL;
03034 }
03035 
03036 /*! \brief Add object reference to SIP registry */
03037 static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
03038 {
03039    ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
03040    return ASTOBJ_REF(reg); /* Add pointer to registry in packet */
03041 }
03042 
03043 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
03044 static struct ast_udptl_protocol sip_udptl = {
03045    .type = "SIP",
03046    .get_udptl_info = sip_get_udptl_peer,
03047    .set_udptl_peer = sip_set_udptl_peer,
03048 };
03049 
03050 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03051    __attribute__((format(printf, 2, 3)));
03052 
03053 
03054 /*! \brief Convert transfer status to string */
03055 static const char *referstatus2str(enum referstatus rstatus)
03056 {
03057    return map_x_s(referstatusstrings, rstatus, "");
03058 }
03059 
03060 static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
03061 {
03062    if (pvt->final_destruction_scheduled) {
03063       return; /* This is already scheduled for final destruction, let the scheduler take care of it. */
03064    }
03065    append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
03066    pvt->needdestroy = 1;
03067 }
03068 
03069 /*! \brief Initialize the initital request packet in the pvt structure.
03070    This packet is used for creating replies and future requests in
03071    a dialog */
03072 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
03073 {
03074    if (p->initreq.headers) {
03075       ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
03076    } else {
03077       ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
03078    }
03079    /* Use this as the basis */
03080    copy_request(&p->initreq, req);
03081    parse_request(&p->initreq);
03082    if (req->debug) {
03083       ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
03084    }
03085 }
03086 
03087 /*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
03088 static void sip_alreadygone(struct sip_pvt *dialog)
03089 {
03090    ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
03091    dialog->alreadygone = 1;
03092 }
03093 
03094 /*! Resolve DNS srv name or host name in a sip_proxy structure */
03095 static int proxy_update(struct sip_proxy *proxy)
03096 {
03097    /* if it's actually an IP address and not a name,
03098            there's no need for a managed lookup */
03099    if (!ast_sockaddr_parse(&proxy->ip, proxy->name, 0)) {
03100       /* Ok, not an IP address, then let's check if it's a domain or host */
03101       /* XXX Todo - if we have proxy port, don't do SRV */
03102       proxy->ip.ss.ss_family = get_address_family_filter(SIP_TRANSPORT_UDP); /* Filter address family */
03103       if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
03104             ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
03105             return FALSE;
03106       }
03107 
03108    }
03109 
03110    ast_sockaddr_set_port(&proxy->ip, proxy->port);
03111 
03112    proxy->last_dnsupdate = time(NULL);
03113    return TRUE;
03114 }
03115 
03116 /*! \brief Parse proxy string and return an ao2_alloc'd proxy. If dest is
03117  *         non-NULL, no allocation is performed and dest is used instead.
03118  *         On error NULL is returned. */
03119 static struct sip_proxy *proxy_from_config(const char *proxy, int sipconf_lineno, struct sip_proxy *dest)
03120 {
03121    char *mutable_proxy, *sep, *name;
03122    int allocated = 0;
03123 
03124    if (!dest) {
03125       dest = ao2_alloc(sizeof(struct sip_proxy), NULL);
03126       if (!dest) {
03127          ast_log(LOG_WARNING, "Unable to allocate config storage for proxy\n");
03128          return NULL;
03129       }
03130       allocated = 1;
03131    }
03132 
03133    /* Format is: [transport://]name[:port][,force] */
03134    mutable_proxy = ast_skip_blanks(ast_strdupa(proxy));
03135    sep = strchr(mutable_proxy, ',');
03136    if (sep) {
03137       *sep++ = '\0';
03138       dest->force = !strncasecmp(ast_skip_blanks(sep), "force", 5);
03139    } else {
03140       dest->force = FALSE;
03141    }
03142 
03143    sip_parse_host(mutable_proxy, sipconf_lineno, &name, &dest->port, &dest->transport);
03144 
03145    /* Check that there is a name at all */
03146    if (ast_strlen_zero(name)) {
03147       if (allocated) {
03148          ao2_ref(dest, -1);
03149       } else {
03150          dest->name[0] = '\0';
03151       }
03152       return NULL;
03153    }
03154    ast_copy_string(dest->name, name, sizeof(dest->name));
03155 
03156    /* Resolve host immediately */
03157    proxy_update(dest);
03158 
03159    return dest;
03160 }
03161 
03162 /*! \brief converts ascii port to int representation. If no
03163  *  pt buffer is provided or the pt has errors when being converted
03164  *  to an int value, the port provided as the standard is used.
03165  */
03166 unsigned int port_str2int(const char *pt, unsigned int standard)
03167 {
03168    int port = standard;
03169    if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
03170       port = standard;
03171    }
03172 
03173    return port;
03174 }
03175 
03176 /*! \brief Get default outbound proxy or global proxy */
03177 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
03178 {
03179    if (dialog && dialog->options && dialog->options->outboundproxy) {
03180       if (sipdebug) {
03181          ast_debug(1, "OBPROXY: Applying dialplan set OBproxy to this call\n");
03182       }
03183       append_history(dialog, "OBproxy", "Using dialplan obproxy %s", dialog->options->outboundproxy->name);
03184       return dialog->options->outboundproxy;
03185    }
03186    if (peer && peer->outboundproxy) {
03187       if (sipdebug) {
03188          ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
03189       }
03190       append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
03191       return peer->outboundproxy;
03192    }
03193    if (sip_cfg.outboundproxy.name[0]) {
03194       if (sipdebug) {
03195          ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
03196       }
03197       append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
03198       return &sip_cfg.outboundproxy;
03199    }
03200    if (sipdebug) {
03201       ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
03202    }
03203    return NULL;
03204 }
03205 
03206 /*! \brief returns true if 'name' (with optional trailing whitespace)
03207  * matches the sip method 'id'.
03208  * Strictly speaking, SIP methods are case SENSITIVE, but we do
03209  * a case-insensitive comparison to be more tolerant.
03210  * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
03211  */
03212 static int method_match(enum sipmethod id, const char *name)
03213 {
03214    int len = strlen(sip_methods[id].text);
03215    int l_name = name ? strlen(name) : 0;
03216    /* true if the string is long enough, and ends with whitespace, and matches */
03217    return (l_name >= len && name && name[len] < 33 &&
03218       !strncasecmp(sip_methods[id].text, name, len));
03219 }
03220 
03221 /*! \brief  find_sip_method: Find SIP method from header */
03222 static int find_sip_method(const char *msg)
03223 {
03224    int i, res = 0;
03225    
03226    if (ast_strlen_zero(msg)) {
03227       return 0;
03228    }
03229    for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
03230       if (method_match(i, msg)) {
03231          res = sip_methods[i].id;
03232       }
03233    }
03234    return res;
03235 }
03236 
03237 /*! \brief See if we pass debug IP filter */
03238 static inline int sip_debug_test_addr(const struct ast_sockaddr *addr)
03239 {
03240    /* Can't debug if sipdebug is not enabled */
03241    if (!sipdebug) {
03242       return 0;
03243    }
03244 
03245    /* A null debug_addr means we'll debug any address */
03246    if (ast_sockaddr_isnull(&debugaddr)) {
03247       return 1;
03248    }
03249 
03250    /* If no port was specified for a debug address, just compare the
03251     * addresses, otherwise compare the address and port
03252     */
03253    if (ast_sockaddr_port(&debugaddr)) {
03254       return !ast_sockaddr_cmp(&debugaddr, addr);
03255    } else {
03256       return !ast_sockaddr_cmp_addr(&debugaddr, addr);
03257    }
03258 }
03259 
03260 /*! \brief The real destination address for a write */
03261 static const struct ast_sockaddr *sip_real_dst(const struct sip_pvt *p)
03262 {
03263    if (p->outboundproxy) {
03264       return &p->outboundproxy->ip;
03265    }
03266 
03267    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;
03268 }
03269 
03270 /*! \brief Display SIP nat mode */
03271 static const char *sip_nat_mode(const struct sip_pvt *p)
03272 {
03273    return ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) ? "NAT" : "no NAT";
03274 }
03275 
03276 /*! \brief Test PVT for debugging output */
03277 static inline int sip_debug_test_pvt(struct sip_pvt *p)
03278 {
03279    if (!sipdebug) {
03280       return 0;
03281    }
03282    return sip_debug_test_addr(sip_real_dst(p));
03283 }
03284 
03285 /*! \brief Return int representing a bit field of transport types found in const char *transport */
03286 static int get_transport_str2enum(const char *transport)
03287 {
03288    int res = 0;
03289 
03290    if (ast_strlen_zero(transport)) {
03291       return res;
03292    }
03293 
03294    if (!strcasecmp(transport, "udp")) {
03295       res |= SIP_TRANSPORT_UDP;
03296    }
03297    if (!strcasecmp(transport, "tcp")) {
03298       res |= SIP_TRANSPORT_TCP;
03299    }
03300    if (!strcasecmp(transport, "tls")) {
03301       res |= SIP_TRANSPORT_TLS;
03302    }
03303 
03304    return res;
03305 }
03306 
03307 /*! \brief Return configuration of transports for a device */
03308 static inline const char *get_transport_list(unsigned int transports) {
03309    switch (transports) {
03310       case SIP_TRANSPORT_UDP:
03311          return "UDP";
03312       case SIP_TRANSPORT_TCP:
03313          return "TCP";
03314       case SIP_TRANSPORT_TLS:
03315          return "TLS";
03316       case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TCP:
03317          return "TCP,UDP";
03318       case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TLS:
03319          return "TLS,UDP";
03320       case SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS:
03321          return "TLS,TCP";
03322       default:
03323          return transports ?
03324             "TLS,TCP,UDP" : "UNKNOWN"; 
03325    }
03326 }
03327 
03328 /*! \brief Return transport as string */
03329 static inline const char *get_transport(enum sip_transport t)
03330 {
03331    switch (t) {
03332    case SIP_TRANSPORT_UDP:
03333       return "UDP";
03334    case SIP_TRANSPORT_TCP:
03335       return "TCP";
03336    case SIP_TRANSPORT_TLS:
03337       return "TLS";
03338    }
03339 
03340    return "UNKNOWN";
03341 }
03342 
03343 /*! \brief Return protocol string for srv dns query */
03344 static inline const char *get_srv_protocol(enum sip_transport t)
03345 {
03346    switch (t) {
03347    case SIP_TRANSPORT_UDP:
03348       return "udp";
03349    case SIP_TRANSPORT_TLS:
03350    case SIP_TRANSPORT_TCP:
03351       return "tcp";
03352    }
03353 
03354    return "udp";
03355 }
03356 
03357 /*! \brief Return service string for srv dns query */
03358 static inline const char *get_srv_service(enum sip_transport t)
03359 {
03360    switch (t) {
03361    case SIP_TRANSPORT_TCP:
03362    case SIP_TRANSPORT_UDP:
03363       return "sip";
03364    case SIP_TRANSPORT_TLS:
03365       return "sips";
03366    }
03367    return "sip";
03368 }
03369 
03370 /*! \brief Return transport of dialog.
03371    \note this is based on a false assumption. We don't always use the
03372    outbound proxy for all requests in a dialog. It depends on the
03373    "force" parameter. The FIRST request is always sent to the ob proxy.
03374    \todo Fix this function to work correctly
03375 */
03376 static inline const char *get_transport_pvt(struct sip_pvt *p)
03377 {
03378    if (p->outboundproxy && p->outboundproxy->transport) {
03379       set_socket_transport(&p->socket, p->outboundproxy->transport);
03380    }
03381 
03382    return get_transport(p->socket.type);
03383 }
03384 
03385 /*!
03386  * \internal
03387  * \brief Transmit SIP message
03388  *
03389  * \details
03390  * Sends a SIP request or response on a given socket (in the pvt)
03391  * \note
03392  * Called by retrans_pkt, send_request, send_response and __sip_reliable_xmit
03393  *
03394  * \return length of transmitted message, XMIT_ERROR on known network failures -1 on other failures.
03395  */
03396 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data)
03397 {
03398    int res = 0;
03399    const struct ast_sockaddr *dst = sip_real_dst(p);
03400 
03401    ast_debug(2, "Trying to put '%.11s' onto %s socket destined for %s\n", data->str, get_transport_pvt(p), ast_sockaddr_stringify(dst));
03402 
03403    if (sip_prepare_socket(p) < 0) {
03404       return XMIT_ERROR;
03405    }
03406 
03407    if (p->socket.type == SIP_TRANSPORT_UDP) {
03408       res = ast_sendto(p->socket.fd, data->str, ast_str_strlen(data), 0, dst);
03409    } else if (p->socket.tcptls_session) {
03410       res = sip_tcptls_write(p->socket.tcptls_session, data->str, ast_str_strlen(data));
03411    } else {
03412       ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
03413       return XMIT_ERROR;
03414    }
03415 
03416    if (res == -1) {
03417       switch (errno) {
03418       case EBADF:       /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
03419       case EHOSTUNREACH:   /* Host can't be reached */
03420       case ENETDOWN:       /* Interface down */
03421       case ENETUNREACH: /* Network failure */
03422       case ECONNREFUSED:      /* ICMP port unreachable */
03423          res = XMIT_ERROR; /* Don't bother with trying to transmit again */
03424       }
03425    }
03426    if (res != ast_str_strlen(data)) {
03427       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));
03428    }
03429 
03430    return res;
03431 }
03432 
03433 /*! \brief Build a Via header for a request */
03434 static void build_via(struct sip_pvt *p)
03435 {
03436    /* Work around buggy UNIDEN UIP200 firmware */
03437    const char *rport = (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) || ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)) ? ";rport" : "";
03438 
03439    /* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
03440    snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s;branch=z9hG4bK%08x%s",
03441        get_transport_pvt(p),
03442        ast_sockaddr_stringify_remote(&p->ourip),
03443        (int) p->branch, rport);
03444 }
03445 
03446 /*! \brief NAT fix - decide which IP address to use for Asterisk server?
03447  *
03448  * Using the localaddr structure built up with localnet statements in sip.conf
03449  * apply it to their address to see if we need to substitute our
03450  * externaddr or can get away with our internal bindaddr
03451  * 'us' is always overwritten.
03452  */
03453 static void ast_sip_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us, struct sip_pvt *p)
03454 {
03455    struct ast_sockaddr theirs;
03456 
03457    /* Set want_remap to non-zero if we want to remap 'us' to an externally
03458     * reachable IP address and port. This is done if:
03459     * 1. we have a localaddr list (containing 'internal' addresses marked
03460     *    as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
03461     *    and AST_SENSE_ALLOW on 'external' ones);
03462     * 2. externaddr is set, so we know what to use as the
03463     *    externally visible address;
03464     * 3. the remote address, 'them', is external;
03465     * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
03466     *    when passed to ast_apply_ha() so it does need to be remapped.
03467     *    This fourth condition is checked later.
03468     */
03469    int want_remap = 0;
03470 
03471    ast_sockaddr_copy(us, &internip); /* starting guess for the internal address */
03472    /* now ask the system what would it use to talk to 'them' */
03473    ast_ouraddrfor(them, us);
03474    ast_sockaddr_copy(&theirs, them);
03475 
03476    if (ast_sockaddr_is_ipv6(&theirs)) {
03477       if (localaddr && !ast_sockaddr_isnull(&externaddr) && !ast_sockaddr_is_any(&bindaddr)) {
03478          ast_log(LOG_WARNING, "Address remapping activated in sip.conf "
03479             "but we're using IPv6, which doesn't need it. Please "
03480             "remove \"localnet\" and/or \"externaddr\" settings.\n");
03481       }
03482    } else {
03483       want_remap = localaddr &&
03484          !ast_sockaddr_isnull(&externaddr) &&
03485          ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
03486    }
03487 
03488    if (want_remap &&
03489        (!sip_cfg.matchexternaddrlocally || !ast_apply_ha(localaddr, us)) ) {
03490       /* if we used externhost, see if it is time to refresh the info */
03491       if (externexpire && time(NULL) >= externexpire) {
03492          if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
03493             ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
03494          }
03495          externexpire = time(NULL) + externrefresh;
03496       }
03497       if (!ast_sockaddr_isnull(&externaddr)) {
03498          ast_sockaddr_copy(us, &externaddr);
03499          switch (p->socket.type) {
03500          case SIP_TRANSPORT_TCP:
03501             if (!externtcpport && ast_sockaddr_port(&externaddr)) {
03502                /* for consistency, default to the externaddr port */
03503                externtcpport = ast_sockaddr_port(&externaddr);
03504             }
03505             ast_sockaddr_set_port(us, externtcpport);
03506             break;
03507          case SIP_TRANSPORT_TLS:
03508             ast_sockaddr_set_port(us, externtlsport);
03509             break;
03510          case SIP_TRANSPORT_UDP:
03511             if (!ast_sockaddr_port(&externaddr)) {
03512                ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
03513             }
03514             break;
03515          default:
03516             break;
03517          }
03518       }
03519       ast_debug(1, "Target address %s is not local, substituting externaddr\n",
03520            ast_sockaddr_stringify(them));
03521    } else {
03522       /* no remapping, but we bind to a specific address, so use it. */
03523       switch (p->socket.type) {
03524       case SIP_TRANSPORT_TCP:
03525          if (!ast_sockaddr_is_any(&sip_tcp_desc.local_address)) {
03526             ast_sockaddr_copy(us,
03527                     &sip_tcp_desc.local_address);
03528          } else {
03529             ast_sockaddr_set_port(us,
03530                         ast_sockaddr_port(&sip_tcp_desc.local_address));
03531          }
03532          break;
03533       case SIP_TRANSPORT_TLS:
03534          if (!ast_sockaddr_is_any(&sip_tls_desc.local_address)) {
03535             ast_sockaddr_copy(us,
03536                     &sip_tls_desc.local_address);
03537          } else {
03538             ast_sockaddr_set_port(us,
03539                         ast_sockaddr_port(&sip_tls_desc.local_address));
03540          }
03541          break;
03542       case SIP_TRANSPORT_UDP:
03543          /* fall through on purpose */
03544       default:
03545          if (!ast_sockaddr_is_any(&bindaddr)) {
03546             ast_sockaddr_copy(us, &bindaddr);
03547          }
03548          if (!ast_sockaddr_port(us)) {
03549             ast_sockaddr_set_port(us, ast_sockaddr_port(&bindaddr));
03550          }
03551       }
03552    }
03553    ast_debug(3, "Setting SIP_TRANSPORT_%s with address %s\n", get_transport(p->socket.type), ast_sockaddr_stringify(us));
03554 }
03555 
03556 /*! \brief Append to SIP dialog history with arg list  */
03557 static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
03558 {
03559    char buf[80], *c = buf; /* max history length */
03560    struct sip_history *hist;
03561    int l;
03562 
03563    vsnprintf(buf, sizeof(buf), fmt, ap);
03564    strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
03565    l = strlen(buf) + 1;
03566    if (!(hist = ast_calloc(1, sizeof(*hist) + l))) {
03567       return;
03568    }
03569    if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
03570       ast_free(hist);
03571       return;
03572    }
03573    memcpy(hist->event, buf, l);
03574    if (p->history_entries == MAX_HISTORY_ENTRIES) {
03575       struct sip_history *oldest;
03576       oldest = AST_LIST_REMOVE_HEAD(p->history, list);
03577       p->history_entries--;
03578       ast_free(oldest);
03579    }
03580    AST_LIST_INSERT_TAIL(p->history, hist, list);
03581    p->history_entries++;
03582 }
03583 
03584 /*! \brief Append to SIP dialog history with arg list  */
03585 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03586 {
03587    va_list ap;
03588 
03589    if (!p) {
03590       return;
03591    }
03592 
03593    if (!p->do_history && !recordhistory && !dumphistory) {
03594       return;
03595    }
03596 
03597    va_start(ap, fmt);
03598    append_history_va(p, fmt, ap);
03599    va_end(ap);
03600 
03601    return;
03602 }
03603 
03604 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
03605 static int retrans_pkt(const void *data)
03606 {
03607    struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
03608    int reschedule = DEFAULT_RETRANS;
03609    int xmitres = 0;
03610    /* how many ms until retrans timeout is reached */
03611    int64_t diff = pkt->retrans_stop_time - ast_tvdiff_ms(ast_tvnow(), pkt->time_sent);
03612 
03613    /* Do not retransmit if time out is reached. This will be negative if the time between
03614     * the first transmission and now is larger than our timeout period. This is a fail safe
03615     * check in case the scheduler gets behind or the clock is changed. */
03616    if ((diff <= 0) || (diff > pkt->retrans_stop_time)) {
03617       pkt->retrans_stop = 1;
03618    }
03619 
03620    /* Lock channel PVT */
03621    sip_pvt_lock(pkt->owner);
03622 
03623    if (!pkt->retrans_stop) {
03624       pkt->retrans++;
03625       if (!pkt->timer_t1) {   /* Re-schedule using timer_a and timer_t1 */
03626          if (sipdebug) {
03627             ast_debug(4, "SIP TIMER: Not rescheduling id #%d:%s (Method %d) (No timer T1)\n",
03628                pkt->retransid,
03629                sip_methods[pkt->method].text,
03630                pkt->method);
03631          }
03632       } else {
03633          int siptimer_a;
03634 
03635          if (sipdebug) {
03636             ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n",
03637                pkt->retransid,
03638                pkt->retrans,
03639                sip_methods[pkt->method].text,
03640                pkt->method);
03641          }
03642          if (!pkt->timer_a) {
03643             pkt->timer_a = 2 ;
03644          } else {
03645             pkt->timer_a = 2 * pkt->timer_a;
03646          }
03647 
03648          /* For non-invites, a maximum of 4 secs */
03649          siptimer_a = pkt->timer_t1 * pkt->timer_a;   /* Double each time */
03650          if (pkt->method != SIP_INVITE && siptimer_a > 4000) {
03651             siptimer_a = 4000;
03652          }
03653 
03654          /* Reschedule re-transmit */
03655          reschedule = siptimer_a;
03656          ast_debug(4, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n",
03657             pkt->retrans + 1,
03658             siptimer_a,
03659             pkt->timer_t1,
03660             pkt->retransid);
03661       }
03662 
03663       if (sip_debug_test_pvt(pkt->owner)) {
03664          const struct ast_sockaddr *dst = sip_real_dst(pkt->owner);
03665          ast_verbose("Retransmitting #%d (%s) to %s:\n%s\n---\n",
03666             pkt->retrans, sip_nat_mode(pkt->owner),
03667             ast_sockaddr_stringify(dst),
03668             pkt->data->str);
03669       }
03670 
03671       append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
03672       xmitres = __sip_xmit(pkt->owner, pkt->data);
03673 
03674       /* If there was no error during the network transmission, schedule the next retransmission,
03675        * but if the next retransmission is going to be beyond our timeout period, mark the packet's
03676        * stop_retrans value and set the next retransmit to be the exact time of timeout.  This will
03677        * allow any responses to the packet to be processed before the packet is destroyed on the next
03678        * call to this function by the scheduler. */
03679       if (xmitres != XMIT_ERROR) {
03680          if (reschedule >= diff) {
03681             pkt->retrans_stop = 1;
03682             reschedule = diff;
03683          }
03684          sip_pvt_unlock(pkt->owner);
03685          return  reschedule;
03686       }
03687    }
03688 
03689    /* At this point, either the packet's retransmission timed out, or there was a
03690     * transmission error, either way destroy the scheduler item and this packet. */
03691 
03692    pkt->retransid = -1; /* Kill this scheduler item */
03693 
03694    if (pkt->method != SIP_OPTIONS && xmitres == 0) {
03695       if (pkt->is_fatal || sipdebug) { /* Tell us if it's critical or if we're debugging */
03696          ast_log(LOG_WARNING, "Retransmission timeout reached on transmission %s for seqno %u (%s %s) -- See https://wiki.asterisk.org/wiki/display/AST/SIP+Retransmissions\n"
03697             "Packet timed out after %dms with no response\n",
03698             pkt->owner->callid,
03699             pkt->seqno,
03700             pkt->is_fatal ? "Critical" : "Non-critical",
03701             pkt->is_resp ? "Response" : "Request",
03702             (int) ast_tvdiff_ms(ast_tvnow(), pkt->time_sent));
03703       }
03704    } else if (pkt->method == SIP_OPTIONS && sipdebug) {
03705       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);
03706    }
03707 
03708    if (xmitres == XMIT_ERROR) {
03709       ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
03710       append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03711    } else {
03712       append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03713    }
03714 
03715    if (pkt->is_fatal) {
03716       while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
03717          sip_pvt_unlock(pkt->owner);   /* SIP_PVT, not channel */
03718          usleep(1);
03719          sip_pvt_lock(pkt->owner);
03720       }
03721       if (pkt->owner->owner && !pkt->owner->owner->hangupcause) {
03722          pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
03723       }
03724       if (pkt->owner->owner) {
03725          ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet (see https://wiki.asterisk.org/wiki/display/AST/SIP+Retransmissions).\n", pkt->owner->callid);
03726 
03727          if (pkt->is_resp &&
03728             (pkt->response_code >= 200) &&
03729             (pkt->response_code < 300) &&
03730             pkt->owner->pendinginvite &&
03731             ast_test_flag(&pkt->owner->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
03732             /* This is a timeout of the 2XX response to a pending INVITE.  In this case terminate the INVITE
03733              * transaction just as if we received the ACK, but immediately hangup with a BYE (sip_hangup
03734              * will send the BYE as long as the dialog is not set as "alreadygone")
03735              * RFC 3261 section 13.3.1.4.
03736              * "If the server retransmits the 2xx response for 64*T1 seconds without receiving
03737              * an ACK, the dialog is confirmed, but the session SHOULD be terminated.  This is
03738              * accomplished with a BYE, as described in Section 15." */
03739             pkt->owner->invitestate = INV_TERMINATED;
03740             pkt->owner->pendinginvite = 0;
03741          } else {
03742             /* there is nothing left to do, mark the dialog as gone */
03743             sip_alreadygone(pkt->owner);
03744          }
03745          ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_NO_USER_RESPONSE);
03746          ast_channel_unlock(pkt->owner->owner);
03747       } else {
03748          /* If no channel owner, destroy now */
03749 
03750          /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
03751          if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
03752             pvt_set_needdestroy(pkt->owner, "no response to critical packet");
03753             sip_alreadygone(pkt->owner);
03754             append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
03755          }
03756       }
03757    }
03758 
03759    if (pkt->method == SIP_BYE) {
03760       /* We're not getting answers on SIP BYE's.  Tear down the call anyway. */
03761       sip_alreadygone(pkt->owner);
03762       if (pkt->owner->owner) {
03763          ast_channel_unlock(pkt->owner->owner);
03764       }
03765       append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
03766       pvt_set_needdestroy(pkt->owner, "no response to BYE");
03767    }
03768 
03769    /* Remove the packet */
03770    for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
03771       if (cur == pkt) {
03772          UNLINK(cur, pkt->owner->packets, prev);
03773          sip_pvt_unlock(pkt->owner);
03774          if (pkt->owner) {
03775             pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
03776          }
03777          if (pkt->data) {
03778             ast_free(pkt->data);
03779          }
03780          pkt->data = NULL;
03781          ast_free(pkt);
03782          return 0;
03783       }
03784    }
03785    /* error case */
03786    ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
03787    sip_pvt_unlock(pkt->owner);
03788    return 0;
03789 }
03790 
03791 /*!
03792  * \internal
03793  * \brief Transmit packet with retransmits
03794  * \return 0 on success, -1 on failure to allocate packet
03795  */
03796 static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, uint32_t seqno, int resp, struct ast_str *data, int fatal, int sipmethod)
03797 {
03798    struct sip_pkt *pkt = NULL;
03799    int siptimer_a = DEFAULT_RETRANS;
03800    int xmitres = 0;
03801    int respid;
03802 
03803    if (sipmethod == SIP_INVITE) {
03804       /* Note this is a pending invite */
03805       p->pendinginvite = seqno;
03806    }
03807 
03808    /* If the transport is something reliable (TCP or TLS) then don't really send this reliably */
03809    /* I removed the code from retrans_pkt that does the same thing so it doesn't get loaded into the scheduler */
03810    /*! \todo According to the RFC some packets need to be retransmitted even if its TCP, so this needs to get revisited */
03811    if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
03812       xmitres = __sip_xmit(p, data);   /* Send packet */
03813       if (xmitres == XMIT_ERROR) {  /* Serious network trouble, no need to try again */
03814          append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
03815          return AST_FAILURE;
03816       } else {
03817          return AST_SUCCESS;
03818       }
03819    }
03820 
03821    if (!(pkt = ast_calloc(1, sizeof(*pkt)))) {
03822       return AST_FAILURE;
03823    }
03824    /* copy data, add a terminator and save length */
03825    if (!(pkt->data = ast_str_create(ast_str_strlen(data)))) {
03826       ast_free(pkt);
03827       return AST_FAILURE;
03828    }
03829    ast_str_set(&pkt->data, 0, "%s%s", data->str, "\0");
03830    /* copy other parameters from the caller */
03831    pkt->method = sipmethod;
03832    pkt->seqno = seqno;
03833    pkt->is_resp = resp;
03834    pkt->is_fatal = fatal;
03835    pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
03836    pkt->next = p->packets;
03837    p->packets = pkt; /* Add it to the queue */
03838    if (resp) {
03839       /* Parse out the response code */
03840       if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
03841          pkt->response_code = respid;
03842       }
03843    }
03844    pkt->timer_t1 = p->timer_t1;  /* Set SIP timer T1 */
03845    pkt->retransid = -1;
03846    if (pkt->timer_t1) {
03847       siptimer_a = pkt->timer_t1;
03848    }
03849 
03850    pkt->time_sent = ast_tvnow(); /* time packet was sent */
03851    pkt->retrans_stop_time = 64 * (pkt->timer_t1 ? pkt->timer_t1 : DEFAULT_TIMER_T1); /* time in ms after pkt->time_sent to stop retransmission */
03852 
03853    /* Schedule retransmission */
03854    AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
03855    if (sipdebug) {
03856       ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id  #%d\n", pkt->retransid);
03857    }
03858 
03859    xmitres = __sip_xmit(pkt->owner, pkt->data); /* Send packet */
03860 
03861    if (xmitres == XMIT_ERROR) {  /* Serious network trouble, no need to try again */
03862       append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03863       ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
03864       AST_SCHED_DEL(sched, pkt->retransid);
03865       p->packets = pkt->next;
03866       pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
03867       ast_free(pkt->data);
03868       ast_free(pkt);
03869       return AST_FAILURE;
03870    } else {
03871       /* This is odd, but since the retrans timer starts at 500ms and the do_monitor thread
03872        * only wakes up every 1000ms by default, we have to poke the thread here to make
03873        * sure it successfully detects this must be retransmitted in less time than
03874        * it usually sleeps for. Otherwise it might not retransmit this packet for 1000ms. */
03875       if (monitor_thread != AST_PTHREADT_NULL) {
03876          pthread_kill(monitor_thread, SIGURG);
03877       }
03878       return AST_SUCCESS;
03879    }
03880 }
03881 
03882 /*! \brief Kill a SIP dialog (called only by the scheduler)
03883  * The scheduler has a reference to this dialog when p->autokillid != -1,
03884  * and we are called using that reference. So if the event is not
03885  * rescheduled, we need to call dialog_unref().
03886  */
03887 static int __sip_autodestruct(const void *data)
03888 {
03889    struct sip_pvt *p = (struct sip_pvt *)data;
03890    struct ast_channel *owner;
03891 
03892    /* If this is a subscription, tell the phone that we got a timeout */
03893    if (p->subscribed && p->subscribed != MWI_NOTIFICATION && p->subscribed != CALL_COMPLETION) {
03894       transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);  /* Send last notification */
03895       p->subscribed = NONE;
03896       append_history(p, "Subscribestatus", "timeout");
03897       ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
03898       return 10000;  /* Reschedule this destruction so that we know that it's gone */
03899    }
03900 
03901    /* If there are packets still waiting for delivery, delay the destruction */
03902    if (p->packets) {
03903       if (!p->needdestroy) {
03904          char method_str[31];
03905          ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
03906          append_history(p, "ReliableXmit", "timeout");
03907          if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
03908             if (p->ongoing_reinvite || method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
03909                pvt_set_needdestroy(p, "autodestruct");
03910             }
03911          }
03912          return 10000;
03913       } else {
03914          /* They've had their chance to respond. Time to bail */
03915          __sip_pretend_ack(p);
03916       }
03917    }
03918 
03919    /* Reset schedule ID */
03920    p->autokillid = -1;
03921 
03922    /*
03923     * Lock both the pvt and the channel safely so that we can queue up a frame.
03924     */
03925    owner = sip_pvt_lock_full(p);
03926    if (owner) {
03927       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);
03928       ast_queue_hangup_with_cause(owner, AST_CAUSE_PROTOCOL_ERROR);
03929       ast_channel_unlock(owner);
03930       ast_channel_unref(owner);
03931       sip_pvt_unlock(p);
03932       return 10000;
03933    } else if (p->refer && !p->alreadygone) {
03934       ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
03935       stop_media_flows(p);
03936       transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
03937       append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
03938       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
03939    } else {
03940       append_history(p, "AutoDestroy", "%s", p->callid);
03941       ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
03942       sip_pvt_unlock(p);
03943       dialog_unlink_all(p); /* once it's unlinked and unrefd everywhere, it'll be freed automagically */
03944       sip_pvt_lock(p);
03945       /* dialog_unref(p, "unref dialog-- no other matching conditions"); -- unlink all now should finish off the dialog's references and free it. */
03946       /* sip_destroy(p); */      /* Go ahead and destroy dialog. All attempts to recover is done */
03947       /* sip_destroy also absorbs the reference */
03948    }
03949 
03950    sip_pvt_unlock(p);
03951 
03952    dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
03953 
03954    return 0;
03955 }
03956 
03957 /*! \brief Schedule final destruction of SIP dialog.  This can not be canceled.
03958  *  This function is used to keep a dialog around for a period of time in order
03959  *  to properly respond to any retransmits. */
03960 void sip_scheddestroy_final(struct sip_pvt *p, int ms)
03961 {
03962    if (p->final_destruction_scheduled) {
03963       return; /* already set final destruction */
03964    }
03965 
03966    sip_scheddestroy(p, ms);
03967    if (p->autokillid != -1) {
03968       p->final_destruction_scheduled = 1;
03969    }
03970 }
03971 
03972 /*! \brief Schedule destruction of SIP dialog */
03973 void sip_scheddestroy(struct sip_pvt *p, int ms)
03974 {
03975    if (p->final_destruction_scheduled) {
03976       return; /* already set final destruction */
03977    }
03978 
03979    if (ms < 0) {
03980       if (p->timer_t1 == 0) {
03981          p->timer_t1 = global_t1;   /* Set timer T1 if not set (RFC 3261) */
03982       }
03983       if (p->timer_b == 0) {
03984          p->timer_b = global_timer_b;  /* Set timer B if not set (RFC 3261) */
03985       }
03986       ms = p->timer_t1 * 64;
03987    }
03988    if (sip_debug_test_pvt(p)) {
03989       ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
03990    }
03991    if (sip_cancel_destroy(p)) {
03992       ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
03993    }
03994 
03995    if (p->do_history) {
03996       append_history(p, "SchedDestroy", "%d ms", ms);
03997    }
03998    p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
03999 
04000    if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0) {
04001       stop_session_timer(p);
04002    }
04003 }
04004 
04005 /*! \brief Cancel destruction of SIP dialog.
04006  * Be careful as this also absorbs the reference - if you call it
04007  * from within the scheduler, this might be the last reference.
04008  */
04009 int sip_cancel_destroy(struct sip_pvt *p)
04010 {
04011    if (p->final_destruction_scheduled) {
04012       return 0;
04013    }
04014 
04015    if (p->autokillid > -1) {
04016       append_history(p, "CancelDestroy", "");
04017       AST_SCHED_DEL_UNREF(sched, p->autokillid, dialog_unref(p, "remove ref for autokillid"));
04018    }
04019    return 0;
04020 }
04021 
04022 /*! \brief Acknowledges receipt of a packet and stops retransmission
04023  * called with p locked*/
04024 int __sip_ack(struct sip_pvt *p, uint32_t seqno, int resp, int sipmethod)
04025 {
04026    struct sip_pkt *cur, *prev = NULL;
04027    const char *msg = "Not Found";   /* used only for debugging */
04028    int res = FALSE;
04029 
04030    /* If we have an outbound proxy for this dialog, then delete it now since
04031      the rest of the requests in this dialog needs to follow the routing.
04032      If obforcing is set, we will keep the outbound proxy during the whole
04033      dialog, regardless of what the SIP rfc says
04034    */
04035    if (p->outboundproxy && !p->outboundproxy->force){
04036       ref_proxy(p, NULL);
04037    }
04038 
04039    for (cur = p->packets; cur; prev = cur, cur = cur->next) {
04040       if (cur->seqno != seqno || cur->is_resp != resp) {
04041          continue;
04042       }
04043       if (cur->is_resp || cur->method == sipmethod) {
04044          res = TRUE;
04045          msg = "Found";
04046          if (!resp && (seqno == p->pendinginvite)) {
04047             ast_debug(1, "Acked pending invite %u\n", p->pendinginvite);
04048             p->pendinginvite = 0;
04049          }
04050          if (cur->retransid > -1) {
04051             if (sipdebug)
04052                ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
04053          }
04054          /* This odd section is designed to thwart a
04055           * race condition in the packet scheduler. There are
04056           * two conditions under which deleting the packet from the
04057           * scheduler can fail.
04058           *
04059           * 1. The packet has been removed from the scheduler because retransmission
04060           * is being attempted. The problem is that if the packet is currently attempting
04061           * retransmission and we are at this point in the code, then that MUST mean
04062           * that retrans_pkt is waiting on p's lock. Therefore we will relinquish the
04063           * lock temporarily to allow retransmission.
04064           *
04065           * 2. The packet has reached its maximum number of retransmissions and has
04066           * been permanently removed from the packet scheduler. If this is the case, then
04067           * the packet's retransid will be set to -1. The atomicity of the setting and checking
04068           * of the retransid to -1 is ensured since in both cases p's lock is held.
04069           */
04070          while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
04071             sip_pvt_unlock(p);
04072             usleep(1);
04073             sip_pvt_lock(p);
04074          }
04075          UNLINK(cur, p->packets, prev);
04076          dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
04077          if (cur->data) {
04078             ast_free(cur->data);
04079          }
04080          ast_free(cur);
04081          break;
04082       }
04083    }
04084    ast_debug(1, "Stopping retransmission on '%s' of %s %u: Match %s\n",
04085       p->callid, resp ? "Response" : "Request", seqno, msg);
04086    return res;
04087 }
04088 
04089 /*! \brief Pretend to ack all packets
04090  * called with p locked */
04091 void __sip_pretend_ack(struct sip_pvt *p)
04092 {
04093    struct sip_pkt *cur = NULL;
04094 
04095    while (p->packets) {
04096       int method;
04097       if (cur == p->packets) {
04098          ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
04099          return;
04100       }
04101       cur = p->packets;
04102       method = (cur->method) ? cur->method : find_sip_method(cur->data->str);
04103       __sip_ack(p, cur->seqno, cur->is_resp, method);
04104    }
04105 }
04106 
04107 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
04108 int __sip_semi_ack(struct sip_pvt *p, uint32_t seqno, int resp, int sipmethod)
04109 {
04110    struct sip_pkt *cur;
04111    int res = FALSE;
04112 
04113    for (cur = p->packets; cur; cur = cur->next) {
04114       if (cur->seqno == seqno && cur->is_resp == resp &&
04115          (cur->is_resp || method_match(sipmethod, cur->data->str))) {
04116          /* this is our baby */
04117          if (cur->retransid > -1) {
04118             if (sipdebug)
04119                ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
04120          }
04121          AST_SCHED_DEL(sched, cur->retransid);
04122          res = TRUE;
04123          break;
04124       }
04125    }
04126    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");
04127    return res;
04128 }
04129 
04130 
04131 /*! \brief Copy SIP request, parse it */
04132 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
04133 {
04134    copy_request(dst, src);
04135    parse_request(dst);
04136 }
04137 
04138 /*! \brief add a blank line if no body */
04139 static void add_blank(struct sip_request *req)
04140 {
04141    if (!req->lines) {
04142       /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
04143       ast_str_append(&req->data, 0, "\r\n");
04144    }
04145 }
04146 
04147 static int send_provisional_keepalive_full(struct sip_pvt *pvt, int with_sdp)
04148 {
04149    const char *msg = NULL;
04150    struct ast_channel *chan;
04151    int res = 0;
04152 
04153    chan = sip_pvt_lock_full(pvt);
04154 
04155    if (!pvt->last_provisional || !strncasecmp(pvt->last_provisional, "100", 3)) {
04156       msg = "183 Session Progress";
04157    }
04158 
04159    if (pvt->invitestate < INV_COMPLETED) {
04160       if (with_sdp) {
04161          transmit_response_with_sdp(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq, XMIT_UNRELIABLE, FALSE, FALSE);
04162       } else {
04163          transmit_response(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq);
04164       }
04165       res = PROVIS_KEEPALIVE_TIMEOUT;
04166    }
04167 
04168    if (chan) {
04169       ast_channel_unlock(chan);
04170       chan = ast_channel_unref(chan);
04171    }
04172 
04173    if (!res) {
04174       pvt->provisional_keepalive_sched_id = -1;
04175    }
04176 
04177    sip_pvt_unlock(pvt);
04178 
04179 #if 0
04180    /*
04181     * XXX BUG TODO
04182     *
04183     * Without this code, it appears as if this function is leaking its
04184     * reference to the sip_pvt.  However, adding it introduces a crash.
04185     * This points to some sort of reference count imbalance elsewhere,
04186     * but I'm not sure where ...
04187     */
04188    if (!res) {
04189       dialog_unref(pvt, "dialog ref for provisional keepalive");
04190    }
04191 #endif
04192 
04193    return res;
04194 }
04195 
04196 static int send_provisional_keepalive(const void *data) {
04197    struct sip_pvt *pvt = (struct sip_pvt *) data;
04198 
04199    return send_provisional_keepalive_full(pvt, 0);
04200 }
04201 
04202 static int send_provisional_keepalive_with_sdp(const void *data) {
04203    struct sip_pvt *pvt = (void *)data;
04204 
04205    return send_provisional_keepalive_full(pvt, 1);
04206 }
04207 
04208 static void update_provisional_keepalive(struct sip_pvt *pvt, int with_sdp)
04209 {
04210    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"));
04211 
04212    pvt->provisional_keepalive_sched_id = ast_sched_add(sched, PROVIS_KEEPALIVE_TIMEOUT,
04213       with_sdp ? send_provisional_keepalive_with_sdp : send_provisional_keepalive, dialog_ref(pvt, "Increment refcount to pass dialog pointer to sched callback"));
04214 }
04215 
04216 /*! \brief Transmit response on SIP request*/
04217 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno)
04218 {
04219    int res;
04220 
04221    finalize_content(req);
04222    add_blank(req);
04223    if (sip_debug_test_pvt(p)) {
04224       const struct ast_sockaddr *dst = sip_real_dst(p);
04225 
04226       ast_verbose("\n<--- %sTransmitting (%s) to %s --->\n%s\n<------------>\n",
04227          reliable ? "Reliably " : "", sip_nat_mode(p),
04228          ast_sockaddr_stringify(dst),
04229          req->data->str);
04230    }
04231    if (p->do_history) {
04232       struct sip_request tmp = { .rlPart1 = 0, };
04233       parse_copy(&tmp, req);
04234       append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"),
04235          (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? REQ_OFFSET_TO_STR(&tmp, rlPart2) : sip_methods[tmp.method].text);
04236       deinit_req(&tmp);
04237    }
04238 
04239    /* If we are sending a final response to an INVITE, stop retransmitting provisional responses */
04240    if (p->initreq.method == SIP_INVITE && reliable == XMIT_CRITICAL) {
04241       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"));
04242    }
04243 
04244    res = (reliable) ?
04245        __sip_reliable_xmit(p, seqno, 1, req->data, (reliable == XMIT_CRITICAL), req->method) :
04246       __sip_xmit(p, req->data);
04247    deinit_req(req);
04248    if (res > 0) {
04249       return 0;
04250    }
04251    return res;
04252 }
04253 
04254 /*!
04255  * \internal
04256  * \brief Send SIP Request to the other part of the dialogue
04257  * \return see \ref __sip_xmit
04258  */
04259 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, uint32_t seqno)
04260 {
04261    int res;
04262 
04263    /* If we have an outbound proxy, reset peer address
04264       Only do this once.
04265    */
04266    if (p->outboundproxy) {
04267       p->sa = p->outboundproxy->ip;
04268    }
04269 
04270    finalize_content(req);
04271    add_blank(req);
04272    if (sip_debug_test_pvt(p)) {
04273       if (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT)) {
04274          ast_verbose("%sTransmitting (NAT) to %s:\n%s\n---\n", reliable ? "Reliably " : "", ast_sockaddr_stringify(&p->recv), req->data->str);
04275       } else {
04276          ast_verbose("%sTransmitting (no NAT) to %s:\n%s\n---\n", reliable ? "Reliably " : "", ast_sockaddr_stringify(&p->sa), req->data->str);
04277       }
04278    }
04279    if (p->do_history) {
04280       struct sip_request tmp = { .rlPart1 = 0, };
04281       parse_copy(&tmp, req);
04282       append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
04283       deinit_req(&tmp);
04284    }
04285    res = (reliable) ?
04286       __sip_reliable_xmit(p, seqno, 0, req->data, (reliable == XMIT_CRITICAL), req->method) :
04287       __sip_xmit(p, req->data);
04288    deinit_req(req);
04289    return res;
04290 }
04291 
04292 static void enable_dsp_detect(struct sip_pvt *p)
04293 {
04294    int features = 0;
04295 
04296    if (p->dsp) {
04297       return;
04298    }
04299 
04300    if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
04301        (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
04302       if (p->rtp) {
04303          ast_rtp_instance_dtmf_mode_set(p->rtp, AST_RTP_DTMF_MODE_INBAND);
04304       }
04305       features |= DSP_FEATURE_DIGIT_DETECT;
04306    }
04307 
04308    if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
04309       features |= DSP_FEATURE_FAX_DETECT;
04310    }
04311 
04312    if (!features) {
04313       return;
04314    }
04315 
04316    if (!(p->dsp = ast_dsp_new())) {
04317       return;
04318    }
04319 
04320    ast_dsp_set_features(p->dsp, features);
04321    if (global_relaxdtmf) {
04322       ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
04323    }
04324 }
04325 
04326 static void disable_dsp_detect(struct sip_pvt *p)
04327 {
04328    if (p->dsp) {
04329       ast_dsp_free(p->dsp);
04330       p->dsp = NULL;
04331    }
04332 }
04333 
04334 /*! \brief Set an option on a SIP dialog */
04335 static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen)
04336 {
04337    int res = -1;
04338    struct sip_pvt *p = chan->tech_pvt;
04339 
04340         if (!p) {
04341          ast_log(LOG_ERROR, "Attempt to Ref a null pointer.  sip private structure is gone!\n");
04342          return -1;
04343         }
04344 
04345    sip_pvt_lock(p);
04346 
04347    switch (option) {
04348    case AST_OPTION_FORMAT_READ:
04349       if (p->rtp) {
04350          res = ast_rtp_instance_set_read_format(p->rtp, *(int *) data);
04351       }
04352       break;
04353    case AST_OPTION_FORMAT_WRITE:
04354       if (p->rtp) {
04355          res = ast_rtp_instance_set_write_format(p->rtp, *(int *) data);
04356       }
04357       break;
04358    case AST_OPTION_MAKE_COMPATIBLE:
04359       if (p->rtp) {
04360          res = ast_rtp_instance_make_compatible(chan, p->rtp, (struct ast_channel *) data);
04361       }
04362       break;
04363    case AST_OPTION_DIGIT_DETECT:
04364       if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
04365           (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
04366          char *cp = (char *) data;
04367 
04368          ast_debug(1, "%sabling digit detection on %s\n", *cp ? "En" : "Dis", chan->name);
04369          if (*cp) {
04370             enable_dsp_detect(p);
04371          } else {
04372             disable_dsp_detect(p);
04373          }
04374          res = 0;
04375       }
04376       break;
04377    case AST_OPTION_SECURE_SIGNALING:
04378       p->req_secure_signaling = *(unsigned int *) data;
04379       res = 0;
04380       break;
04381    case AST_OPTION_SECURE_MEDIA:
04382       ast_set2_flag(&p->flags[1], *(unsigned int *) data, SIP_PAGE2_USE_SRTP);
04383       res = 0;
04384       break;
04385    default:
04386       break;
04387    }
04388 
04389    sip_pvt_unlock(p);
04390 
04391    return res;
04392 }
04393 
04394 /*! \brief Query an option on a SIP dialog */
04395 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
04396 {
04397    int res = -1;
04398    enum ast_t38_state state = T38_STATE_UNAVAILABLE;
04399    struct sip_pvt *p = (struct sip_pvt *) chan->tech_pvt;
04400    char *cp;
04401 
04402    sip_pvt_lock(p);
04403 
04404    switch (option) {
04405    case AST_OPTION_T38_STATE:
04406       /* Make sure we got an ast_t38_state enum passed in */
04407       if (*datalen != sizeof(enum ast_t38_state)) {
04408          ast_log(LOG_ERROR, "Invalid datalen for AST_OPTION_T38_STATE option. Expected %d, got %d\n", (int)sizeof(enum ast_t38_state), *datalen);
04409          break;
04410       }
04411 
04412       /* 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 */
04413       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
04414          switch (p->t38.state) {
04415          case T38_LOCAL_REINVITE:
04416          case T38_PEER_REINVITE:
04417             state = T38_STATE_NEGOTIATING;
04418             break;
04419          case T38_ENABLED:
04420             state = T38_STATE_NEGOTIATED;
04421             break;
04422          default:
04423             state = T38_STATE_UNKNOWN;
04424          }
04425       }
04426 
04427       *((enum ast_t38_state *) data) = state;
04428       res = 0;
04429 
04430       break;
04431    case AST_OPTION_DIGIT_DETECT:
04432       cp = (char *) data;
04433       *cp = p->dsp ? 1 : 0;
04434       ast_debug(1, "Reporting digit detection %sabled on %s\n", *cp ? "en" : "dis", chan->name);
04435       break;
04436    case AST_OPTION_SECURE_SIGNALING:
04437       *((unsigned int *) data) = p->req_secure_signaling;
04438       res = 0;
04439       break;
04440    case AST_OPTION_SECURE_MEDIA:
04441       *((unsigned int *) data) = ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP) ? 1 : 0;
04442       res = 0;
04443       break;
04444    case AST_OPTION_DEVICE_NAME:
04445       if (p && p->outgoing_call) {
04446          cp = (char *) data;
04447          ast_copy_string(cp, p->dialstring, *datalen);
04448          res = 0;
04449       }
04450       /* We purposely break with a return of -1 in the
04451        * implied else case here
04452        */
04453       break;
04454    default:
04455       break;
04456    }
04457 
04458    sip_pvt_unlock(p);
04459 
04460    return res;
04461 }
04462 
04463 /*! \brief Locate closing quote in a string, skipping escaped quotes.
04464  * optionally with a limit on the search.
04465  * start must be past the first quote.
04466  */
04467 const char *find_closing_quote(const char *start, const char *lim)
04468 {
04469    char last_char = '\0';
04470    const char *s;
04471    for (s = start; *s && s != lim; last_char = *s++) {
04472       if (*s == '"' && last_char != '\\')
04473          break;
04474    }
04475    return s;
04476 }
04477 
04478 /*! \brief Send message with Access-URL header, if this is an HTML URL only! */
04479 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
04480 {
04481    struct sip_pvt *p = chan->tech_pvt;
04482 
04483    if (subclass != AST_HTML_URL)
04484       return -1;
04485 
04486    ast_string_field_build(p, url, "<%s>;mode=active", data);
04487 
04488    if (sip_debug_test_pvt(p))
04489       ast_debug(1, "Send URL %s, state = %d!\n", data, chan->_state);
04490 
04491    switch (chan->_state) {
04492    case AST_STATE_RING:
04493       transmit_response(p, "100 Trying", &p->initreq);
04494       break;
04495    case AST_STATE_RINGING:
04496       transmit_response(p, "180 Ringing", &p->initreq);
04497       break;
04498    case AST_STATE_UP:
04499       if (!p->pendinginvite) {      /* We are up, and have no outstanding invite */
04500          transmit_reinvite_with_sdp(p, FALSE, FALSE);
04501       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
04502          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);   
04503       }  
04504       break;
04505    default:
04506       ast_log(LOG_WARNING, "Don't know how to send URI when state is %d!\n", chan->_state);
04507    }
04508 
04509    return 0;
04510 }
04511 
04512 /*! \brief Deliver SIP call ID for the call */
04513 static const char *sip_get_callid(struct ast_channel *chan)
04514 {
04515    return chan->tech_pvt ? ((struct sip_pvt *) chan->tech_pvt)->callid : "";
04516 }
04517 
04518 /*!
04519  * \internal
04520  * \brief Send SIP MESSAGE text within a call
04521  * \note Called from PBX core sendtext() application
04522  */
04523 static int sip_sendtext(struct ast_channel *ast, const char *text)
04524 {
04525    struct sip_pvt *dialog = ast->tech_pvt;
04526    int debug;
04527 
04528    if (!dialog) {
04529       return -1;
04530    }
04531    /* NOT ast_strlen_zero, because a zero-length message is specifically
04532     * allowed by RFC 3428 (See section 10, Examples) */
04533    if (!text) {
04534       return 0;
04535    }
04536    if(!is_method_allowed(&dialog->allowed_methods, SIP_MESSAGE)) {
04537       ast_debug(2, "Trying to send MESSAGE to device that does not support it.\n");
04538       return(0);
04539    }
04540 
04541    debug = sip_debug_test_pvt(dialog);
04542    if (debug) {
04543       ast_verbose("Sending text %s on %s\n", text, ast->name);
04544    }
04545 
04546    transmit_message_with_text(dialog, text);
04547    return 0;   
04548 }
04549 
04550 /*! \brief Update peer object in realtime storage
04551    If the Asterisk system name is set in asterisk.conf, we will use
04552    that name and store that in the "regserver" field in the sippeers
04553    table to facilitate multi-server setups.
04554 */
04555 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)
04556 {
04557    char port[10];
04558    char ipaddr[INET6_ADDRSTRLEN];
04559    char regseconds[20];
04560    char *tablename = NULL;
04561    char str_lastms[20];
04562 
04563    const char *sysname = ast_config_AST_SYSTEM_NAME;
04564    char *syslabel = NULL;
04565 
04566    time_t nowtime = time(NULL) + expirey;
04567    const char *fc = fullcontact ? "fullcontact" : NULL;
04568 
04569    int realtimeregs = ast_check_realtime("sipregs");
04570 
04571    tablename = realtimeregs ? "sipregs" : "sippeers";
04572    
04573 
04574    snprintf(str_lastms, sizeof(str_lastms), "%d", lastms);
04575    snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);  /* Expiration time */
04576    ast_copy_string(ipaddr, ast_sockaddr_isnull(addr) ? "" : ast_sockaddr_stringify_addr(addr), sizeof(ipaddr));
04577    ast_copy_string(port, ast_sockaddr_port(addr) ? ast_sockaddr_stringify_port(addr) : "", sizeof(port));
04578 
04579    if (ast_strlen_zero(sysname)) /* No system name, disable this */
04580       sysname = NULL;
04581    else if (sip_cfg.rtsave_sysname)
04582       syslabel = "regserver";
04583 
04584    /* XXX IMPORTANT: Anytime you add a new parameter to be updated, you
04585          *  must also add it to contrib/scripts/asterisk.ldap-schema,
04586          *  contrib/scripts/asterisk.ldif,
04587          *  and to configs/res_ldap.conf.sample as described in
04588          *  bugs 15156 and 15895 
04589          */
04590    if (fc) {
04591       ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04592          "port", port, "regseconds", regseconds,
04593          deprecated_username ? "username" : "defaultuser", defaultuser,
04594          "useragent", useragent, "lastms", str_lastms,
04595          fc, fullcontact, syslabel, sysname, SENTINEL); /* note fc and syslabel _can_ be NULL */
04596    } else {
04597       ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04598          "port", port, "regseconds", regseconds,
04599          "useragent", useragent, "lastms", str_lastms,
04600          deprecated_username ? "username" : "defaultuser", defaultuser,
04601          syslabel, sysname, SENTINEL); /* note syslabel _can_ be NULL */
04602    }
04603 }
04604 
04605 /*! \brief Automatically add peer extension to dial plan */
04606 static void register_peer_exten(struct sip_peer *peer, int onoff)
04607 {
04608    char multi[256];
04609    char *stringp, *ext, *context;
04610    struct pbx_find_info q = { .stacklen = 0 };
04611 
04612    /* XXX note that sip_cfg.regcontext is both a global 'enable' flag and
04613     * the name of the global regexten context, if not specified
04614     * individually.
04615     */
04616    if (ast_strlen_zero(sip_cfg.regcontext))
04617       return;
04618 
04619    ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
04620    stringp = multi;
04621    while ((ext = strsep(&stringp, "&"))) {
04622       if ((context = strchr(ext, '@'))) {
04623          *context++ = '\0';   /* split ext@context */
04624          if (!ast_context_find(context)) {
04625             ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
04626             continue;
04627          }
04628       } else {
04629          context = sip_cfg.regcontext;
04630       }
04631       if (onoff) {
04632          if (!ast_exists_extension(NULL, context, ext, 1, NULL)) {
04633             ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
04634                 ast_strdup(peer->name), ast_free_ptr, "SIP");
04635          }
04636       } else if (pbx_find_extension(NULL, NULL, &q, context, ext, 1, NULL, "", E_MATCH)) {
04637          ast_context_remove_extension(context, ext, 1, NULL);
04638       }
04639    }
04640 }
04641 
04642 /*! Destroy mailbox subscriptions */
04643 static void destroy_mailbox(struct sip_mailbox *mailbox)
04644 {
04645    if (mailbox->event_sub)
04646       ast_event_unsubscribe(mailbox->event_sub);
04647    ast_free(mailbox);
04648 }
04649 
04650 /*! Destroy all peer-related mailbox subscriptions */
04651 static void clear_peer_mailboxes(struct sip_peer *peer)
04652 {
04653    struct sip_mailbox *mailbox;
04654 
04655    while ((mailbox = AST_LIST_REMOVE_HEAD(&peer->mailboxes, entry)))
04656       destroy_mailbox(mailbox);
04657 }
04658 
04659 static void sip_destroy_peer_fn(void *peer)
04660 {
04661    sip_destroy_peer(peer);
04662 }
04663 
04664 /*! \brief Destroy peer object from memory */
04665 static void sip_destroy_peer(struct sip_peer *peer)
04666 {
04667    ast_debug(3, "Destroying SIP peer %s\n", peer->name);
04668 
04669    /*
04670     * Remove any mailbox event subscriptions for this peer before
04671     * we destroy anything.  An event subscription callback may be
04672     * happening right now.
04673     */
04674    clear_peer_mailboxes(peer);
04675 
04676    if (peer->outboundproxy) {
04677       ao2_ref(peer->outboundproxy, -1);
04678       peer->outboundproxy = NULL;
04679    }
04680 
04681    /* Delete it, it needs to disappear */
04682    if (peer->call) {
04683       dialog_unlink_all(peer->call);
04684       peer->call = dialog_unref(peer->call, "peer->call is being unset");
04685    }
04686 
04687    if (peer->mwipvt) {  /* We have an active subscription, delete it */
04688       dialog_unlink_all(peer->mwipvt);
04689       peer->mwipvt = dialog_unref(peer->mwipvt, "unreffing peer->mwipvt");
04690    }
04691    
04692    if (peer->chanvars) {
04693       ast_variables_destroy(peer->chanvars);
04694       peer->chanvars = NULL;
04695    }
04696    
04697    register_peer_exten(peer, FALSE);
04698    ast_free_ha(peer->ha);
04699    ast_free_ha(peer->directmediaha);
04700    if (peer->selfdestruct)
04701       ast_atomic_fetchadd_int(&apeerobjs, -1);
04702    else if (!ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->is_realtime) {
04703       ast_atomic_fetchadd_int(&rpeerobjs, -1);
04704       ast_debug(3, "-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
04705    } else
04706       ast_atomic_fetchadd_int(&speerobjs, -1);
04707    if (peer->auth) {
04708       ao2_t_ref(peer->auth, -1, "Removing peer authentication");
04709       peer->auth = NULL;
04710    }
04711 
04712    if (peer->socket.tcptls_session) {
04713       ao2_ref(peer->socket.tcptls_session, -1);
04714       peer->socket.tcptls_session = NULL;
04715    }
04716 
04717    ast_cc_config_params_destroy(peer->cc_params);
04718 
04719    ast_string_field_free_memory(peer);
04720 }
04721 
04722 /*! \brief Update peer data in database (if used) */
04723 static void update_peer(struct sip_peer *p, int expire)
04724 {
04725    int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
04726    if (sip_cfg.peer_rtupdate &&
04727        (p->is_realtime || rtcachefriends)) {
04728       realtime_update_peer(p->name, &p->addr, p->username, p->fullcontact, p->useragent, expire, p->deprecated_username, p->lastms);
04729    }
04730 }
04731 
04732 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *cfg)
04733 {
04734    struct ast_variable *var = NULL;
04735    struct ast_flags flags = {0};
04736    char *cat = NULL;
04737    const char *insecure;
04738    while ((cat = ast_category_browse(cfg, cat))) {
04739       insecure = ast_variable_retrieve(cfg, cat, "insecure");
04740       set_insecure_flags(&flags, insecure, -1);
04741       if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
04742          var = ast_category_root(cfg, cat);
04743          break;
04744       }
04745    }
04746    return var;
04747 }
04748 
04749 static struct ast_variable *get_insecure_variable_from_sippeers(const char *column, const char *value)
04750 {
04751    struct ast_config *peerlist;
04752    struct ast_variable *var = NULL;
04753    if ((peerlist = ast_load_realtime_multientry("sippeers", column, value, "insecure LIKE", "%port%", SENTINEL))) {
04754       if ((var = get_insecure_variable_from_config(peerlist))) {
04755          /* Must clone, because var will get freed along with
04756           * peerlist. */
04757          var = ast_variables_dup(var);
04758       }
04759       ast_config_destroy(peerlist);
04760    }
04761    return var;
04762 }
04763 
04764 /* Yes.. the only column that makes sense to pass is "ipaddr", but for
04765  * consistency's sake, we require the column name to be passed. As extra
04766  * argument, we take a pointer to var. We already got the info, so we better
04767  * return it and save the caller a query. If return value is nonzero, then *var
04768  * is nonzero too (and the other way around). */
04769 static struct ast_variable *get_insecure_variable_from_sipregs(const char *column, const char *value, struct ast_variable **var)
04770 {
04771    struct ast_variable *varregs = NULL;
04772    struct ast_config *regs, *peers;
04773    char *regscat;
04774    const char *regname;
04775 
04776    if (!(regs = ast_load_realtime_multientry("sipregs", column, value, SENTINEL))) {
04777       return NULL;
04778    }
04779 
04780    /* Load *all* peers that are probably insecure=port */
04781    if (!(peers = ast_load_realtime_multientry("sippeers", "insecure LIKE", "%port%", SENTINEL))) {
04782       ast_config_destroy(regs);
04783       return NULL;
04784    }
04785 
04786    /* Loop over the sipregs that match IP address and attempt to find an
04787     * insecure=port match to it in sippeers. */
04788    regscat = NULL;
04789    while ((regscat = ast_category_browse(regs, regscat)) && (regname = ast_variable_retrieve(regs, regscat, "name"))) {
04790       char *peerscat;
04791       const char *peername;
04792 
04793       peerscat = NULL;
04794       while ((peerscat = ast_category_browse(peers, peerscat)) && (peername = ast_variable_retrieve(peers, peerscat, "name"))) {
04795          if (!strcasecmp(regname, peername)) {
04796             /* Ensure that it really is insecure=port and
04797              * not something else. */
04798             const char *insecure = ast_variable_retrieve(peers, peerscat, "insecure");
04799             struct ast_flags flags = {0};
04800             set_insecure_flags(&flags, insecure, -1);
04801             if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
04802                /* ENOMEM checks till the bitter end. */
04803                if ((varregs = ast_variables_dup(ast_category_root(regs, regscat)))) {
04804                   if (!(*var = ast_variables_dup(ast_category_root(peers, peerscat)))) {
04805                      ast_variables_destroy(varregs);
04806                      varregs = NULL;
04807                   }
04808                }
04809                goto done;
04810             }
04811          }
04812       }
04813    }
04814 
04815 done:
04816    ast_config_destroy(regs);
04817    ast_config_destroy(peers);
04818    return varregs;
04819 }
04820 
04821 static const char *get_name_from_variable(const struct ast_variable *var)
04822 {
04823    /* Don't expect this to return non-NULL. Both NULL and empty
04824     * values can cause the option to get removed from the variable
04825     * list. This is called on ast_variables gotten from both
04826     * ast_load_realtime and ast_load_realtime_multientry.
04827     * - ast_load_realtime removes options with empty values
04828     * - ast_load_realtime_multientry does not!
04829     * For consistent behaviour, we check for the empty name and
04830     * return NULL instead. */
04831    const struct ast_variable *tmp;
04832    for (tmp = var; tmp; tmp = tmp->next) {
04833       if (!strcasecmp(tmp->name, "name")) {
04834          if (!ast_strlen_zero(tmp->value)) {
04835             return tmp->value;
04836          }
04837          break;
04838       }
04839    }
04840    return NULL;
04841 }
04842 
04843 /* If varregs is NULL, we don't use sipregs.
04844  * Using empty if-bodies instead of goto's while avoiding unnecessary indents */
04845 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)
04846 {
04847    /* Peer by name and host=dynamic */
04848    if ((*var = ast_load_realtime("sippeers", "name", *name, "host", "dynamic", SENTINEL))) {
04849       ;
04850    /* Peer by name and host=IP */
04851    } else if (addr && !(*var = ast_load_realtime("sippeers", "name", *name, "host", ipaddr, SENTINEL))) {
04852       ;
04853    /* Peer by name and host=HOSTNAME */
04854    } else if ((*var = ast_load_realtime("sippeers", "name", *name, SENTINEL))) {
04855       /*!\note
04856        * If this one loaded something, then we need to ensure that the host
04857        * field matched.  The only reason why we can't have this as a criteria
04858        * is because we only have the IP address and the host field might be
04859        * set as a name (and the reverse PTR might not match).
04860        */
04861       if (addr) {
04862          struct ast_variable *tmp;
04863          for (tmp = *var; tmp; tmp = tmp->next) {
04864             if (!strcasecmp(tmp->name, "host")) {
04865                struct ast_sockaddr *addrs = NULL;
04866 
04867                if (ast_sockaddr_resolve(&addrs,
04868                          tmp->value,
04869                          PARSE_PORT_FORBID,
04870                          get_address_family_filter(SIP_TRANSPORT_UDP)) <= 0 ||
04871                          ast_sockaddr_cmp(&addrs[0], addr)) {
04872                   /* No match */
04873                   ast_variables_destroy(*var);
04874                   *var = NULL;
04875                }
04876                ast_free(addrs);
04877                break;
04878             }
04879          }
04880       }
04881    }
04882 
04883    /* Did we find anything? */
04884    if (*var) {
04885       if (varregs) {
04886          *varregs = ast_load_realtime("sipregs", "name", *name, SENTINEL);
04887       }
04888       return 1;
04889    }
04890    return 0;
04891 }
04892 
04893 /* Another little helper function for backwards compatibility: this
04894  * checks/fetches the sippeer that belongs to the sipreg. If none is
04895  * found, we free the sipreg and return false. This way we can do the
04896  * check inside the if-condition below. In the old code, not finding
04897  * the sippeer also had it continue look for another match, so we do
04898  * the same. */
04899 static struct ast_variable *realtime_peer_get_sippeer_helper(const char **name, struct ast_variable **varregs) {
04900    struct ast_variable *var = NULL;
04901    const char *old_name = *name;
04902    *name = get_name_from_variable(*varregs);
04903    if (!*name || !(var = ast_load_realtime("sippeers", "name", *name, SENTINEL))) {
04904       if (!*name) {
04905          ast_log(LOG_WARNING, "Found sipreg but it has no name\n");
04906       }
04907       ast_variables_destroy(*varregs);
04908       *varregs = NULL;
04909       *name = old_name;
04910    }
04911    return var;
04912 }
04913 
04914 /* If varregs is NULL, we don't use sipregs. If we return true, then *name is
04915  * set. Using empty if-bodies instead of goto's while avoiding unnecessary
04916  * indents. */
04917 static int realtime_peer_by_addr(const char **name, struct ast_sockaddr *addr, const char *ipaddr, struct ast_variable **var, struct ast_variable **varregs)
04918 {
04919    char portstring[6]; /* up to 5 digits plus null terminator */
04920    ast_copy_string(portstring, ast_sockaddr_stringify_port(addr), sizeof(portstring));
04921 
04922    /* We're not finding this peer by this name anymore. Reset it. */
04923    *name = NULL;
04924 
04925    /* First check for fixed IP hosts */
04926    if ((*var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, SENTINEL))) {
04927       ;
04928    /* Check for registered hosts (in sipregs) */
04929    } else if (varregs && (*varregs = ast_load_realtime("sipregs", "ipaddr", ipaddr, "port", portstring, SENTINEL)) &&
04930          (*var = realtime_peer_get_sippeer_helper(name, varregs))) {
04931       ;
04932    /* Check for registered hosts (in sippeers) */
04933    } else if (!varregs && (*var = ast_load_realtime("sippeers", "ipaddr", ipaddr, "port", portstring, SENTINEL))) {
04934       ;
04935    /* We couldn't match on ipaddress and port, so we need to check if port is insecure */
04936    } else if ((*var = get_insecure_variable_from_sippeers("host", ipaddr))) {
04937       ;
04938    /* Same as above, but try the IP address field (in sipregs)
04939     * Observe that it fetches the name/var at the same time, without the
04940     * realtime_peer_get_sippeer_helper. Also note that it is quite inefficient.
04941     * Avoid sipregs if possible. */
04942    } else if (varregs && (*varregs = get_insecure_variable_from_sipregs("ipaddr", ipaddr, var))) {
04943       ;
04944    /* Same as above, but try the IP address field (in sippeers) */
04945    } else if (!varregs && (*var = get_insecure_variable_from_sippeers("ipaddr", ipaddr))) {
04946       ;
04947    }
04948 
04949    /* Nothing found? */
04950    if (!*var) {
04951       return 0;
04952    }
04953 
04954    /* Check peer name. It must not be empty. There may exist a
04955     * different match that does have a name, but it's too late for
04956     * that now. */
04957    if (!*name && !(*name = get_name_from_variable(*var))) {
04958       ast_log(LOG_WARNING, "Found peer for IP %s but it has no name\n", ipaddr);
04959       ast_variables_destroy(*var);
04960       *var = NULL;
04961       if (varregs && *varregs) {
04962          ast_variables_destroy(*varregs);
04963          *varregs = NULL;
04964       }
04965       return 0;
04966    }
04967 
04968    /* Make sure varregs is populated if var is. The inverse,
04969     * ensuring that var is set when varregs is, is taken
04970     * care of by realtime_peer_get_sippeer_helper(). */
04971    if (varregs && !*varregs) {
04972       *varregs = ast_load_realtime("sipregs", "name", *name, SENTINEL);
04973    }
04974    return 1;
04975 }
04976 
04977 /*! \brief  realtime_peer: Get peer from realtime storage
04978  * Checks the "sippeers" realtime family from extconfig.conf
04979  * Checks the "sipregs" realtime family from extconfig.conf if it's configured.
04980  * This returns a pointer to a peer and because we use build_peer, we can rest
04981  * assured that the refcount is bumped.
04982  * 
04983  * \note This is never called with both newpeername and addr at the same time.
04984  * If you do, be prepared to get a peer with a different name than newpeername.
04985  */
04986 static struct sip_peer *realtime_peer(const char *newpeername, struct ast_sockaddr *addr, int devstate_only, int which_objects)
04987 {
04988    struct sip_peer *peer = NULL;
04989    struct ast_variable *var = NULL;
04990    struct ast_variable *varregs = NULL;
04991    char ipaddr[INET6_ADDRSTRLEN];
04992    int realtimeregs = ast_check_realtime("sipregs");
04993 
04994    if (addr) {
04995       ast_copy_string(ipaddr, ast_sockaddr_stringify_addr(addr), sizeof(ipaddr));
04996    } else {
04997       ipaddr[0] = '\0';
04998    }
04999 
05000    if (newpeername && realtime_peer_by_name(&newpeername, addr, ipaddr, &var, realtimeregs ? &varregs : NULL)) {
05001       ;
05002    } else if (addr && realtime_peer_by_addr(&newpeername, addr, ipaddr, &var, realtimeregs ? &varregs : NULL)) {
05003       ;
05004    } else {
05005       return NULL;
05006    }
05007 
05008    /* If we're looking for users, don't return peers (although this check
05009     * should probably be done in realtime_peer_by_* instead...) */
05010    if (which_objects == FINDUSERS) {
05011       struct ast_variable *tmp;
05012       for (tmp = var; tmp; tmp = tmp->next) {
05013          if (!strcasecmp(tmp->name, "type") && (!strcasecmp(tmp->value, "peer"))) {
05014             goto cleanup;
05015          }
05016       }
05017    }
05018 
05019    /* Peer found in realtime, now build it in memory */
05020    peer = build_peer(newpeername, var, varregs, TRUE, devstate_only);
05021    if (!peer) {
05022       goto cleanup;
05023    }
05024 
05025    /* Previous versions of Asterisk did not require the type field to be
05026     * set for real time peers.  This statement preserves that behavior. */
05027    if  (peer->type == 0) {
05028       if (which_objects == FINDUSERS) {
05029          peer->type = SIP_TYPE_USER;
05030       } else if (which_objects == FINDPEERS) {
05031          peer->type = SIP_TYPE_PEER;
05032       } else {
05033          peer->type = SIP_TYPE_PEER | SIP_TYPE_USER;
05034       }
05035    }
05036 
05037    ast_debug(3, "-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);
05038 
05039    if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && !devstate_only) {
05040       /* Cache peer */
05041       ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
05042       if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
05043          AST_SCHED_REPLACE_UNREF(peer->expire, sched, sip_cfg.rtautoclear * 1000, expire_register, peer,
05044                unref_peer(_data, "remove registration ref"),
05045                unref_peer(peer, "remove registration ref"),
05046                ref_peer(peer, "add registration ref"));
05047       }
05048       ao2_t_link(peers, peer, "link peer into peers table");
05049       if (!ast_sockaddr_isnull(&peer->addr)) {
05050          ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
05051       }
05052    }
05053    peer->is_realtime = 1;
05054 
05055 cleanup:
05056    ast_variables_destroy(var);
05057    ast_variables_destroy(varregs);
05058    return peer;
05059 }
05060 
05061 /* Function to assist finding peers by name only */
05062 static int find_by_name(void *obj, void *arg, void *data, int flags)
05063 {
05064    struct sip_peer *search = obj, *match = arg;
05065    int *which_objects = data;
05066 
05067    /* Usernames in SIP uri's are case sensitive. Domains are not */
05068    if (strcmp(search->name, match->name)) {
05069       return 0;
05070    }
05071 
05072    switch (*which_objects) {
05073    case FINDUSERS:
05074       if (!(search->type & SIP_TYPE_USER)) {
05075          return 0;
05076       }
05077       break;
05078    case FINDPEERS:
05079       if (!(search->type & SIP_TYPE_PEER)) {
05080          return 0;
05081       }
05082       break;
05083    case FINDALLDEVICES:
05084       break;
05085    }
05086 
05087    return CMP_MATCH | CMP_STOP;
05088 }
05089 
05090 /*!
05091  * \brief Locate device by name or ip address
05092  * \param peer, sin, realtime, devstate_only, transport
05093  * \param which_objects Define which objects should be matched when doing a lookup
05094  *        by name.  Valid options are FINDUSERS, FINDPEERS, or FINDALLDEVICES.
05095  *        Note that this option is not used at all when doing a lookup by IP.
05096  *
05097  * This is used on find matching device on name or ip/port.
05098  * If the device was declared as type=peer, we don't match on peer name on incoming INVITEs.
05099  *
05100  * \note Avoid using this function in new functions if there is a way to avoid it,
05101  * since it might cause a database lookup.
05102  */
05103 static struct sip_peer *find_peer(const char *peer, struct ast_sockaddr *addr, int realtime, int which_objects, int devstate_only, int transport)
05104 {
05105    struct sip_peer *p = NULL;
05106    struct sip_peer tmp_peer;
05107 
05108    if (peer) {
05109       ast_copy_string(tmp_peer.name, peer, sizeof(tmp_peer.name));
05110       p = ao2_t_callback_data(peers, OBJ_POINTER, find_by_name, &tmp_peer, &which_objects, "ao2_find in peers table");
05111    } else if (addr) { /* search by addr? */
05112       ast_sockaddr_copy(&tmp_peer.addr, addr);
05113       tmp_peer.flags[0].flags = 0;
05114       tmp_peer.transports = transport;
05115       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); */
05116       if (!p) {
05117          ast_set_flag(&tmp_peer.flags[0], SIP_INSECURE_PORT);
05118          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); */
05119          if (p) {
05120             return p;
05121          }
05122       }
05123    }
05124 
05125    if (!p && (realtime || devstate_only)) {
05126       p = realtime_peer(peer, addr, devstate_only, which_objects);
05127       if (p) {
05128          switch (which_objects) {
05129          case FINDUSERS:
05130             if (!(p->type & SIP_TYPE_USER)) {
05131                unref_peer(p, "Wrong type of realtime SIP endpoint");
05132                return NULL;
05133             }
05134             break;
05135          case FINDPEERS:
05136             if (!(p->type & SIP_TYPE_PEER)) {
05137                unref_peer(p, "Wrong type of realtime SIP endpoint");
05138                return NULL;
05139             }
05140             break;
05141          case FINDALLDEVICES:
05142             break;
05143          }
05144       }
05145    }
05146 
05147    return p;
05148 }
05149 
05150 /*! \brief Set nat mode on the various data sockets */
05151 static void do_setnat(struct sip_pvt *p)
05152 {
05153    const char *mode;
05154    int natflags;
05155 
05156    natflags = ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
05157    mode = natflags ? "On" : "Off";
05158 
05159    if (p->rtp) {
05160       ast_debug(1, "Setting NAT on RTP to %s\n", mode);
05161       ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_NAT, natflags);
05162    }
05163    if (p->vrtp) {
05164       ast_debug(1, "Setting NAT on VRTP to %s\n", mode);
05165       ast_rtp_instance_set_prop(p->vrtp, AST_RTP_PROPERTY_NAT, natflags);
05166    }
05167    if (p->udptl) {
05168       ast_debug(1, "Setting NAT on UDPTL to %s\n", mode);
05169       ast_udptl_setnat(p->udptl, natflags);
05170    }
05171    if (p->trtp) {
05172       ast_debug(1, "Setting NAT on TRTP to %s\n", mode);
05173       ast_rtp_instance_set_prop(p->trtp, AST_RTP_PROPERTY_NAT, natflags);
05174    }
05175 }
05176 
05177 /*! \brief Change the T38 state on a SIP dialog */
05178 static void change_t38_state(struct sip_pvt *p, int state)
05179 {
05180    int old = p->t38.state;
05181    struct ast_channel *chan = p->owner;
05182    struct ast_control_t38_parameters parameters = { .request_response = 0 };
05183 
05184    /* Don't bother changing if we are already in the state wanted */
05185    if (old == state)
05186       return;
05187 
05188    p->t38.state = state;
05189    ast_debug(2, "T38 state changed to %d on channel %s\n", p->t38.state, chan ? chan->name : "<none>");
05190 
05191    /* If no channel was provided we can't send off a control frame */
05192    if (!chan)
05193       return;
05194 
05195    /* Given the state requested and old state determine what control frame we want to queue up */
05196    switch (state) {
05197    case T38_PEER_REINVITE:
05198       parameters = p->t38.their_parms;
05199       parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05200       parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
05201       ast_udptl_set_tag(p->udptl, "%s", chan->name);
05202       break;
05203    case T38_ENABLED:
05204       parameters = p->t38.their_parms;
05205       parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
05206       parameters.request_response = AST_T38_NEGOTIATED;
05207       ast_udptl_set_tag(p->udptl, "%s", chan->name);
05208       break;
05209    case T38_DISABLED:
05210       if (old == T38_ENABLED) {
05211          parameters.request_response = AST_T38_TERMINATED;
05212       } else if (old == T38_LOCAL_REINVITE) {
05213          parameters.request_response = AST_T38_REFUSED;
05214       }
05215       break;
05216    case T38_LOCAL_REINVITE:
05217       /* wait until we get a peer response before responding to local reinvite */
05218       break;
05219    }
05220 
05221    /* Woot we got a message, create a control frame and send it on! */
05222    if (parameters.request_response)
05223       ast_queue_control_data(chan, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));
05224 }
05225 
05226 /*! \brief Set the global T38 capabilities on a SIP dialog structure */
05227 static void set_t38_capabilities(struct sip_pvt *p)
05228 {
05229    if (p->udptl) {
05230       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY) {
05231                         ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
05232       } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_FEC) {
05233          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
05234       } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL) {
05235          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
05236       }
05237    }
05238 }
05239 
05240 static void copy_socket_data(struct sip_socket *to_sock, const struct sip_socket *from_sock)
05241 {
05242    if (to_sock->tcptls_session) {
05243       ao2_ref(to_sock->tcptls_session, -1);
05244       to_sock->tcptls_session = NULL;
05245    }
05246 
05247    if (from_sock->tcptls_session) {
05248       ao2_ref(from_sock->tcptls_session, +1);
05249    }
05250 
05251    *to_sock = *from_sock;
05252 }
05253 
05254 /*! \brief Initialize RTP portion of a dialog
05255  * \return -1 on failure, 0 on success
05256  */
05257 static int dialog_initialize_rtp(struct sip_pvt *dialog)
05258 {
05259    struct ast_sockaddr bindaddr_tmp;
05260 
05261    if (!sip_methods[dialog->method].need_rtp) {
05262       return 0;
05263    }
05264 
05265    ast_sockaddr_copy(&bindaddr_tmp, &bindaddr);
05266    if (!(dialog->rtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
05267       return -1;
05268    }
05269 
05270    if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) ||
05271          (ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) && (dialog->capability & AST_FORMAT_VIDEO_MASK))) {
05272       if (!(dialog->vrtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
05273          return -1;
05274       }
05275       ast_rtp_instance_set_timeout(dialog->vrtp, dialog->rtptimeout);
05276       ast_rtp_instance_set_hold_timeout(dialog->vrtp, dialog->rtpholdtimeout);
05277       ast_rtp_instance_set_keepalive(dialog->vrtp, dialog->rtpkeepalive);
05278 
05279       ast_rtp_instance_set_prop(dialog->vrtp, AST_RTP_PROPERTY_RTCP, 1);
05280       ast_rtp_instance_set_qos(dialog->vrtp, global_tos_video, global_cos_video, "SIP VIDEO");
05281    }
05282 
05283    if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT)) {
05284       if (!(dialog->trtp = ast_rtp_instance_new(dialog->engine, sched, &bindaddr_tmp, NULL))) {
05285          return -1;
05286       }
05287       /* Do not timeout text as its not constant*/
05288       ast_rtp_instance_set_keepalive(dialog->trtp, dialog->rtpkeepalive);
05289 
05290       ast_rtp_instance_set_prop(dialog->trtp, AST_RTP_PROPERTY_RTCP, 1);
05291    }
05292 
05293    ast_rtp_instance_set_timeout(dialog->rtp, dialog->rtptimeout);
05294    ast_rtp_instance_set_hold_timeout(dialog->rtp, dialog->rtpholdtimeout);
05295    ast_rtp_instance_set_keepalive(dialog->rtp, dialog->rtpkeepalive);
05296 
05297    ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_RTCP, 1);
05298    ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
05299    ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
05300 
05301    ast_rtp_instance_set_qos(dialog->rtp, global_tos_audio, global_cos_audio, "SIP RTP");
05302 
05303    do_setnat(dialog);
05304 
05305    return 0;
05306 }
05307 
05308 /*! \brief Create address structure from peer reference.
05309  * This function copies data from peer to the dialog, so we don't have to look up the peer
05310  * again from memory or database during the life time of the dialog.
05311  *
05312  * \return -1 on error, 0 on success.
05313  *
05314  */
05315 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
05316 {
05317    struct sip_auth_container *credentials;
05318 
05319    /* this checks that the dialog is contacting the peer on a valid
05320     * transport type based on the peers transport configuration,
05321     * otherwise, this function bails out */
05322    if (dialog->socket.type && check_request_transport(peer, dialog))
05323       return -1;
05324    copy_socket_data(&dialog->socket, &peer->socket);
05325 
05326    if (!(ast_sockaddr_isnull(&peer->addr) && ast_sockaddr_isnull(&peer->defaddr)) &&
05327        (!peer->maxms || ((peer->lastms >= 0)  && (peer->lastms <= peer->maxms)))) {
05328       dialog->sa = ast_sockaddr_isnull(&peer->addr) ? peer->defaddr : peer->addr;
05329       dialog->recv = dialog->sa;
05330    } else
05331       return -1;
05332 
05333    /* XXX TODO: get flags directly from peer only as they are needed using dialog->relatedpeer */
05334    ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
05335    ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
05336    ast_copy_flags(&dialog->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
05337    dialog->capability = peer->capability;
05338    dialog->prefs = peer->prefs;
05339    dialog->amaflags = peer->amaflags;
05340 
05341    ast_string_field_set(dialog, engine, peer->engine);
05342 
05343    dialog->rtptimeout = peer->rtptimeout;
05344    dialog->rtpholdtimeout = peer->rtpholdtimeout;
05345    dialog->rtpkeepalive = peer->rtpkeepalive;
05346    if (dialog_initialize_rtp(dialog)) {
05347       return -1;
05348    }
05349 
05350    if (dialog->rtp) { /* Audio */
05351       ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
05352       ast_rtp_instance_set_prop(dialog->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
05353       /* Set Frame packetization */
05354       ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(dialog->rtp), dialog->rtp, &dialog->prefs);
05355       dialog->autoframing = peer->autoframing;
05356    }
05357 
05358    /* XXX TODO: get fields directly from peer only as they are needed using dialog->relatedpeer */
05359    ast_string_field_set(dialog, peername, peer->name);
05360    ast_string_field_set(dialog, authname, peer->username);
05361    ast_string_field_set(dialog, username, peer->username);
05362    ast_string_field_set(dialog, peersecret, peer->secret);
05363    ast_string_field_set(dialog, peermd5secret, peer->md5secret);
05364    ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
05365    ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
05366    ast_string_field_set(dialog, tohost, peer->tohost);
05367    ast_string_field_set(dialog, fullcontact, peer->fullcontact);
05368    ast_string_field_set(dialog, accountcode, peer->accountcode);
05369    ast_string_field_set(dialog, context, peer->context);
05370    ast_string_field_set(dialog, cid_num, peer->cid_num);
05371    ast_string_field_set(dialog, cid_name, peer->cid_name);
05372    ast_string_field_set(dialog, cid_tag, peer->cid_tag);
05373    ast_string_field_set(dialog, mwi_from, peer->mwi_from);
05374    if (!ast_strlen_zero(peer->parkinglot)) {
05375       ast_string_field_set(dialog, parkinglot, peer->parkinglot);
05376    }
05377    ast_string_field_set(dialog, engine, peer->engine);
05378    ref_proxy(dialog, obproxy_get(dialog, peer));
05379    dialog->callgroup = peer->callgroup;
05380    dialog->pickupgroup = peer->pickupgroup;
05381    dialog->allowtransfer = peer->allowtransfer;
05382    dialog->jointnoncodeccapability = dialog->noncodeccapability;
05383 
05384    /* Update dialog authorization credentials */
05385    ao2_lock(peer);
05386    credentials = peer->auth;
05387    if (credentials) {
05388       ao2_t_ref(credentials, +1, "Ref peer auth for dialog");
05389    }
05390    ao2_unlock(peer);
05391    ao2_lock(dialog);
05392    if (dialog->peerauth) {
05393       ao2_t_ref(dialog->peerauth, -1, "Unref old dialog peer auth");
05394    }
05395    dialog->peerauth = credentials;
05396    ao2_unlock(dialog);
05397 
05398    dialog->maxcallbitrate = peer->maxcallbitrate;
05399    dialog->disallowed_methods = peer->disallowed_methods;
05400    ast_cc_copy_config_params(dialog->cc_params, peer->cc_params);
05401    if (ast_strlen_zero(dialog->tohost))
05402       ast_string_field_set(dialog, tohost, ast_sockaddr_stringify_host_remote(&dialog->sa));
05403    if (!ast_strlen_zero(peer->fromdomain)) {
05404       ast_string_field_set(dialog, fromdomain, peer->fromdomain);
05405       if (!dialog->initreq.headers) {
05406          char *new_callid;
05407          char *tmpcall = ast_strdupa(dialog->callid);
05408          /* this sure looks to me like we are going to change the callid on this dialog!! */
05409          new_callid = strchr(tmpcall, '@');
05410          if (new_callid) {
05411             int callid_size;
05412 
05413             *new_callid = '\0';
05414 
05415             /* Change the dialog callid. */
05416             callid_size = strlen(tmpcall) + strlen(peer->fromdomain) + 2;
05417             new_callid = ast_alloca(callid_size);
05418             snprintf(new_callid, callid_size, "%s@%s", tmpcall, peer->fromdomain);
05419             change_callid_pvt(dialog, new_callid);
05420          }
05421       }
05422    }
05423    if (!ast_strlen_zero(peer->fromuser))
05424       ast_string_field_set(dialog, fromuser, peer->fromuser);
05425    if (!ast_strlen_zero(peer->language))
05426       ast_string_field_set(dialog, language, peer->language);
05427    /* Set timer T1 to RTT for this peer (if known by qualify=) */
05428    /* Minimum is settable or default to 100 ms */
05429    /* If there is a maxms and lastms from a qualify use that over a manual T1
05430       value. Otherwise, use the peer's T1 value. */
05431    if (peer->maxms && peer->lastms)
05432       dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
05433    else
05434       dialog->timer_t1 = peer->timer_t1;
05435 
05436    /* Set timer B to control transaction timeouts, the peer setting is the default and overrides
05437       the known timer */
05438    if (peer->timer_b)
05439       dialog->timer_b = peer->timer_b;
05440    else
05441       dialog->timer_b = 64 * dialog->timer_t1;
05442 
05443    if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
05444        (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
05445       dialog->noncodeccapability |= AST_RTP_DTMF;
05446    else
05447       dialog->noncodeccapability &= ~AST_RTP_DTMF;
05448    dialog->directmediaha = ast_duplicate_ha_list(peer->directmediaha);
05449    if (peer->call_limit)
05450       ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
05451    if (!dialog->portinuri)
05452       dialog->portinuri = peer->portinuri;
05453    dialog->chanvars = copy_vars(peer->chanvars);
05454    if (peer->fromdomainport)
05455       dialog->fromdomainport = peer->fromdomainport;
05456 
05457    return 0;
05458 }
05459 
05460 /*! \brief The default sip port for the given transport */
05461 static inline int default_sip_port(enum sip_transport type)
05462 {
05463    return type == SIP_TRANSPORT_TLS ? STANDARD_TLS_PORT : STANDARD_SIP_PORT;
05464 }
05465 
05466 /*! \brief create address structure from device name
05467  *      Or, if peer not found, find it in the global DNS
05468  *      returns TRUE (-1) on failure, FALSE on success */
05469 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct ast_sockaddr *addr, int newdialog)
05470 {
05471    struct sip_peer *peer;
05472    char *peername, *peername2, *hostn;
05473    char host[MAXHOSTNAMELEN];
05474    char service[MAXHOSTNAMELEN];
05475    int srv_ret = 0;
05476    int tportno;
05477 
05478    AST_DECLARE_APP_ARGS(hostport,
05479       AST_APP_ARG(host);
05480       AST_APP_ARG(port);
05481    );
05482 
05483    peername = ast_strdupa(opeer);
05484    peername2 = ast_strdupa(opeer);
05485    AST_NONSTANDARD_RAW_ARGS(hostport, peername2, ':');
05486 
05487    if (hostport.port)
05488       dialog->portinuri = 1;
05489 
05490    dialog->timer_t1 = global_t1; /* Default SIP retransmission timer T1 (RFC 3261) */
05491    dialog->timer_b = global_timer_b; /* Default SIP transaction timer B (RFC 3261) */
05492    peer = find_peer(peername, NULL, TRUE, FINDPEERS, FALSE, 0);
05493 
05494    if (peer) {
05495       int res;
05496       if (newdialog) {
05497          set_socket_transport(&dialog->socket, 0);
05498       }
05499       res = create_addr_from_peer(dialog, peer);
05500       dialog->relatedpeer = ref_peer(peer, "create_addr: setting dialog's relatedpeer pointer");
05501       unref_peer(peer, "create_addr: unref peer from find_peer hashtab lookup");
05502       return res;
05503    } else if (ast_check_digits(peername)) {
05504       /* Although an IPv4 hostname *could* be represented as a 32-bit integer, it is uncommon and
05505        * it makes dialing SIP/${EXTEN} for a peer that isn't defined resolve to an IP that is
05506        * almost certainly not intended. It is much better to just reject purely numeric hostnames */
05507       ast_log(LOG_WARNING, "Purely numeric hostname (%s), and not a peer--rejecting!\n", peername);
05508       return -1;
05509    } else {
05510       dialog->rtptimeout = global_rtptimeout;
05511       dialog->rtpholdtimeout = global_rtpholdtimeout;
05512       dialog->rtpkeepalive = global_rtpkeepalive;
05513       if (dialog_initialize_rtp(dialog)) {
05514          return -1;
05515       }
05516    }
05517 
05518    ast_string_field_set(dialog, tohost, hostport.host);
05519    dialog->allowed_methods &= ~sip_cfg.disallowed_methods;
05520 
05521    /* Get the outbound proxy information */
05522    ref_proxy(dialog, obproxy_get(dialog, NULL));
05523 
05524    if (addr) {
05525       /* This address should be updated using dnsmgr */
05526       ast_sockaddr_copy(&dialog->sa, addr);
05527    } else {
05528 
05529       /* Let's see if we can find the host in DNS. First try DNS SRV records,
05530          then hostname lookup */
05531       /*! \todo Fix this function. When we ask for SRV, we should check all transports
05532            In the future, we should first check NAPTR to find out transport preference
05533        */
05534       hostn = peername;
05535       /* Section 4.2 of RFC 3263 specifies that if a port number is specified, then
05536        * an A record lookup should be used instead of SRV.
05537        */
05538       if (!hostport.port && sip_cfg.srvlookup) {
05539          snprintf(service, sizeof(service), "_%s._%s.%s", 
05540              get_srv_service(dialog->socket.type),
05541              get_srv_protocol(dialog->socket.type), peername);
05542          if ((srv_ret = ast_get_srv(NULL, host, sizeof(host), &tportno,
05543                      service)) > 0) {
05544             hostn = host;
05545          }
05546       }
05547 
05548       if (ast_sockaddr_resolve_first_transport(&dialog->sa, hostn, 0, dialog->socket.type ? dialog->socket.type : SIP_TRANSPORT_UDP)) {
05549          ast_log(LOG_WARNING, "No such host: %s\n", peername);
05550          return -1;
05551       }
05552 
05553       if (srv_ret > 0) {
05554          ast_sockaddr_set_port(&dialog->sa, tportno);
05555       }
05556    }
05557 
05558    if (!dialog->socket.type)
05559       set_socket_transport(&dialog->socket, SIP_TRANSPORT_UDP);
05560    if (!dialog->socket.port) {
05561       dialog->socket.port = htons(ast_sockaddr_port(&bindaddr));
05562    }
05563 
05564    if (!ast_sockaddr_port(&dialog->sa)) {
05565       ast_sockaddr_set_port(&dialog->sa, default_sip_port(dialog->socket.type));
05566    }
05567    ast_sockaddr_copy(&dialog->recv, &dialog->sa);
05568    return 0;
05569 }
05570 
05571 /*! \brief Scheduled congestion on a call.
05572  * Only called by the scheduler, must return the reference when done.
05573  */
05574 static int auto_congest(const void *arg)
05575 {
05576    struct sip_pvt *p = (struct sip_pvt *)arg;
05577 
05578    sip_pvt_lock(p);
05579    p->initid = -1;   /* event gone, will not be rescheduled */
05580    if (p->owner) {
05581       /* XXX fails on possible deadlock */
05582       if (!ast_channel_trylock(p->owner)) {
05583          append_history(p, "Cong", "Auto-congesting (timer)");
05584          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
05585          ast_channel_unlock(p->owner);
05586       }
05587 
05588       /* Give the channel a chance to act before we proceed with destruction */
05589       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05590    }
05591    sip_pvt_unlock(p);
05592    dialog_unref(p, "unreffing arg passed into auto_congest callback (p->initid)");
05593    return 0;
05594 }
05595 
05596 
05597 /*! \brief Initiate SIP call from PBX
05598  *      used from the dial() application      */
05599 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
05600 {
05601    int res;
05602    struct sip_pvt *p = ast->tech_pvt;  /* chan is locked, so the reference cannot go away */
05603    struct varshead *headp;
05604    struct ast_var_t *current;
05605    const char *referer = NULL;   /* SIP referrer */
05606    int cc_core_id;
05607    char uri[SIPBUFSIZE] = "";
05608 
05609    if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
05610       ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
05611       return -1;
05612    }
05613 
05614    if (ast_cc_is_recall(ast, &cc_core_id, "SIP")) {
05615       char device_name[AST_CHANNEL_NAME];
05616       struct ast_cc_monitor *recall_monitor;
05617       struct sip_monitor_instance *monitor_instance;
05618       ast_channel_get_device_name(ast, device_name, sizeof(device_name));
05619       if ((recall_monitor = ast_cc_get_monitor_by_recall_core_id(cc_core_id, device_name))) {
05620          monitor_instance = recall_monitor->private_data;
05621          ast_copy_string(uri, monitor_instance->notify_uri, sizeof(uri));
05622          ao2_t_ref(recall_monitor, -1, "Got the URI we need so unreffing monitor");
05623       }
05624    }
05625 
05626    /* Check whether there is vxml_url, distinctive ring variables */
05627    headp=&ast->varshead;
05628    AST_LIST_TRAVERSE(headp, current, entries) {
05629       /* Check whether there is a VXML_URL variable */
05630       if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
05631          p->options->vxml_url = ast_var_value(current);
05632       } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
05633          p->options->uri_options = ast_var_value(current);
05634       } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
05635          /* Check whether there is a variable with a name starting with SIPADDHEADER */
05636          p->options->addsipheaders = 1;
05637       } else if (!strcasecmp(ast_var_name(current), "SIPFROMDOMAIN")) {
05638          ast_string_field_set(p, fromdomain, ast_var_value(current));
05639       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
05640          /* This is a transfered call */
05641          p->options->transfer = 1;
05642       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
05643          /* This is the referrer */
05644          referer = ast_var_value(current);
05645       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
05646          /* We're replacing a call. */
05647          p->options->replaces = ast_var_value(current);
05648       } else if (!strcasecmp(ast_var_name(current), "SIP_MAX_FORWARDS")) {
05649          if (sscanf(ast_var_value(current), "%d", &(p->maxforwards)) != 1) {
05650             ast_log(LOG_WARNING, "The SIP_MAX_FORWARDS channel variable is not a valid integer.\n");
05651          }
05652       }
05653    }
05654 
05655    /* Check to see if we should try to force encryption */
05656    if (p->req_secure_signaling && p->socket.type != SIP_TRANSPORT_TLS) {
05657       ast_log(LOG_WARNING, "Encrypted signaling is required\n");
05658       ast->hangupcause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05659       return -1;
05660    }
05661 
05662    if (ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP)) {
05663       if (ast_test_flag(&p->flags[0], SIP_REINVITE)) {
05664          ast_debug(1, "Direct media not possible when using SRTP, ignoring canreinvite setting\n");
05665          ast_clear_flag(&p->flags[0], SIP_REINVITE);
05666       }
05667 
05668       if (p->rtp && !p->srtp && setup_srtp(&p->srtp) < 0) {
05669          ast_log(LOG_WARNING, "SRTP audio setup failed\n");
05670          return -1;
05671       }
05672 
05673       if (p->vrtp && !p->vsrtp && setup_srtp(&p->vsrtp) < 0) {
05674          ast_log(LOG_WARNING, "SRTP video setup failed\n");
05675          return -1;
05676       }
05677 
05678       if (p->trtp && !p->tsrtp && setup_srtp(&p->tsrtp) < 0) {
05679          ast_log(LOG_WARNING, "SRTP text setup failed\n");
05680          return -1;
05681       }
05682    }
05683 
05684    res = 0;
05685    ast_set_flag(&p->flags[0], SIP_OUTGOING);
05686 
05687    /* T.38 re-INVITE FAX detection should never be done for outgoing calls,
05688     * so ensure it is disabled.
05689     */
05690    ast_clear_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38);
05691 
05692    if (p->options->transfer) {
05693       char buf[SIPBUFSIZE/2];
05694 
05695       if (referer) {
05696          if (sipdebug)
05697             ast_debug(3, "Call for %s transfered by %s\n", p->username, referer);
05698          snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
05699       } else
05700          snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
05701       ast_string_field_set(p, cid_name, buf);
05702    }
05703    ast_debug(1, "Outgoing Call for %s\n", p->username);
05704 
05705    res = update_call_counter(p, INC_CALL_RINGING);
05706 
05707    if (res == -1) {
05708       ast->hangupcause = AST_CAUSE_USER_BUSY;
05709       return res;
05710    }
05711    p->callingpres = ast_party_id_presentation(&ast->caller.id);
05712    p->jointcapability = ast_rtp_instance_available_formats(p->rtp, p->capability, p->prefcodec);
05713    p->jointnoncodeccapability = p->noncodeccapability;
05714 
05715    /* If there are no audio formats left to offer, punt */
05716    if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
05717       ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
05718       res = -1;
05719    } else {
05720       int xmitres;
05721       struct ast_party_connected_line connected;
05722       struct ast_set_party_connected_line update_connected;
05723 
05724       sip_pvt_lock(p);
05725 
05726       /* Supply initial connected line information if available. */
05727       memset(&update_connected, 0, sizeof(update_connected));
05728       ast_party_connected_line_init(&connected);
05729       if (!ast_strlen_zero(p->cid_num)
05730          || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
05731          update_connected.id.number = 1;
05732          connected.id.number.valid = 1;
05733          connected.id.number.str = (char *) p->cid_num;
05734          connected.id.number.presentation = p->callingpres;
05735       }
05736       if (!ast_strlen_zero(p->cid_name)
05737          || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
05738          update_connected.id.name = 1;
05739          connected.id.name.valid = 1;
05740          connected.id.name.str = (char *) p->cid_name;
05741          connected.id.name.presentation = p->callingpres;
05742       }
05743       if (update_connected.id.number || update_connected.id.name) {
05744          connected.id.tag = (char *) p->cid_tag;
05745          connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
05746          ast_channel_queue_connected_line_update(ast, &connected, &update_connected);
05747       }
05748 
05749       xmitres = transmit_invite(p, SIP_INVITE, 1, 2, uri);
05750       if (xmitres == XMIT_ERROR) {
05751          sip_pvt_unlock(p);
05752          return -1;
05753       }
05754       p->invitestate = INV_CALLING;
05755 
05756       /* Initialize auto-congest time */
05757       AST_SCHED_REPLACE_UNREF(p->initid, sched, p->timer_b, auto_congest, p,
05758                         dialog_unref(_data, "dialog ptr dec when SCHED_REPLACE del op succeeded"),
05759                         dialog_unref(p, "dialog ptr dec when SCHED_REPLACE add failed"),
05760                         dialog_ref(p, "dialog ptr inc when SCHED_REPLACE add succeeded") );
05761       sip_pvt_unlock(p);
05762    }
05763    return res;
05764 }
05765 
05766 /*! \brief Destroy registry object
05767    Objects created with the register= statement in static configuration */
05768 static void sip_registry_destroy(struct sip_registry *reg)
05769 {
05770    /* Really delete */
05771    ast_debug(3, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
05772 
05773    if (reg->call) {
05774       /* Clear registry before destroying to ensure
05775          we don't get reentered trying to grab the registry lock */
05776       reg->call->registry = registry_unref(reg->call->registry, "destroy reg->call->registry");
05777       ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
05778       dialog_unlink_all(reg->call);
05779       reg->call = dialog_unref(reg->call, "unref reg->call");
05780       /* reg->call = sip_destroy(reg->call); */
05781    }
05782    AST_SCHED_DEL(sched, reg->expire);
05783    AST_SCHED_DEL(sched, reg->timeout);
05784 
05785    ast_string_field_free_memory(reg);
05786    ast_atomic_fetchadd_int(&regobjs, -1);
05787    ast_free(reg);
05788 }
05789 
05790 /*! \brief Destroy MWI subscription object */
05791 static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi)
05792 {
05793    if (mwi->call) {
05794       mwi->call->mwi = NULL;
05795       sip_destroy(mwi->call);
05796    }
05797    
05798    AST_SCHED_DEL(sched, mwi->resub);
05799    ast_string_field_free_memory(mwi);
05800    ast_free(mwi);
05801 }
05802 
05803 /*! \brief Execute destruction of SIP dialog structure, release memory */
05804 void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
05805 {
05806    struct sip_request *req;
05807 
05808    /* Destroy Session-Timers if allocated */
05809    if (p->stimer) {
05810       p->stimer->quit_flag = 1;
05811       stop_session_timer(p);
05812       ast_free(p->stimer);
05813       p->stimer = NULL;
05814    }
05815 
05816    if (sip_debug_test_pvt(p))
05817       ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
05818 
05819    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
05820       update_call_counter(p, DEC_CALL_LIMIT);
05821       ast_debug(2, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
05822    }
05823 
05824    /* Unlink us from the owner if we have one */
05825    if (p->owner) {
05826       if (lockowner)
05827          ast_channel_lock(p->owner);
05828       ast_debug(1, "Detaching from %s\n", p->owner->name);
05829       p->owner->tech_pvt = NULL;
05830       /* Make sure that the channel knows its backend is going away */
05831       p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
05832       if (lockowner)
05833          ast_channel_unlock(p->owner);
05834       /* Give the channel a chance to react before deallocation */
05835       usleep(1);
05836    }
05837 
05838    /* Remove link from peer to subscription of MWI */
05839    if (p->relatedpeer && p->relatedpeer->mwipvt == p)
05840       p->relatedpeer->mwipvt = dialog_unref(p->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
05841    if (p->relatedpeer && p->relatedpeer->call == p)
05842       p->relatedpeer->call = dialog_unref(p->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
05843    
05844    if (p->relatedpeer)
05845       p->relatedpeer = unref_peer(p->relatedpeer,"unsetting a dialog relatedpeer field in sip_destroy");
05846    
05847    if (p->registry) {
05848       if (p->registry->call == p)
05849          p->registry->call = dialog_unref(p->registry->call, "nulling out the registry's call dialog field in unlink_all");
05850       p->registry = registry_unref(p->registry, "delete p->registry");
05851    }
05852    
05853    if (p->mwi) {
05854       p->mwi->call = NULL;
05855       p->mwi = NULL;
05856    }
05857 
05858    if (dumphistory)
05859       sip_dump_history(p);
05860 
05861    if (p->options) {
05862       if (p->options->outboundproxy) {
05863          ao2_ref(p->options->outboundproxy, -1);
05864       }
05865       ast_free(p->options);
05866       p->options = NULL;
05867    }
05868 
05869    if (p->notify) {
05870       ast_variables_destroy(p->notify->headers);
05871       ast_free(p->notify->content);
05872       ast_free(p->notify);
05873       p->notify = NULL;
05874    }
05875    if (p->rtp) {
05876       ast_rtp_instance_destroy(p->rtp);
05877       p->rtp = NULL;
05878    }
05879    if (p->vrtp) {
05880       ast_rtp_instance_destroy(p->vrtp);
05881       p->vrtp = NULL;
05882    }
05883    if (p->trtp) {
05884       ast_rtp_instance_destroy(p->trtp);
05885       p->trtp = NULL;
05886    }
05887    if (p->udptl) {
05888       ast_udptl_destroy(p->udptl);
05889       p->udptl = NULL;
05890    }
05891    if (p->refer) {
05892       if (p->refer->refer_call) {
05893          p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
05894       }
05895       ast_free(p->refer);
05896       p->refer = NULL;
05897    }
05898    if (p->route) {
05899       free_old_route(p->route);
05900       p->route = NULL;
05901    }
05902    deinit_req(&p->initreq);
05903 
05904    /* Clear history */
05905    if (p->history) {
05906       struct sip_history *hist;
05907       while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
05908          ast_free(hist);
05909          p->history_entries--;
05910       }
05911       ast_free(p->history);
05912       p->history = NULL;
05913    }
05914 
05915    while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
05916       ast_free(req);
05917    }
05918 
05919    if (p->chanvars) {
05920       ast_variables_destroy(p->chanvars);
05921       p->chanvars = NULL;
05922    }
05923 
05924    if (p->srtp) {
05925       sip_srtp_destroy(p->srtp);
05926       p->srtp = NULL;
05927    }
05928 
05929    if (p->vsrtp) {
05930       sip_srtp_destroy(p->vsrtp);
05931       p->vsrtp = NULL;
05932    }
05933 
05934    if (p->tsrtp) {
05935       sip_srtp_destroy(p->tsrtp);
05936       p->tsrtp = NULL;
05937    }
05938 
05939    if (p->directmediaha) {
05940       ast_free_ha(p->directmediaha);
05941       p->directmediaha = NULL;
05942    }
05943 
05944    ast_string_field_free_memory(p);
05945 
05946    ast_cc_config_params_destroy(p->cc_params);
05947    p->cc_params = NULL;
05948 
05949    if (p->epa_entry) {
05950       ao2_ref(p->epa_entry, -1);
05951       p->epa_entry = NULL;
05952    }
05953 
05954    if (p->socket.tcptls_session) {
05955       ao2_ref(p->socket.tcptls_session, -1);
05956       p->socket.tcptls_session = NULL;
05957    }
05958 
05959    if (p->peerauth) {
05960       ao2_t_ref(p->peerauth, -1, "Removing active peer authentication");
05961       p->peerauth = NULL;
05962    }
05963 }
05964 
05965 /*! \brief  update_call_counter: Handle call_limit for SIP devices
05966  * Setting a call-limit will cause calls above the limit not to be accepted.
05967  *
05968  * Remember that for a type=friend, there's one limit for the user and
05969  * another for the peer, not a combined call limit.
05970  * This will cause unexpected behaviour in subscriptions, since a "friend"
05971  * is *two* devices in Asterisk, not one.
05972  *
05973  * Thought: For realtime, we should probably update storage with inuse counter...
05974  *
05975  * \return 0 if call is ok (no call limit, below threshold)
05976  * -1 on rejection of call
05977  *
05978  */
05979 static int update_call_counter(struct sip_pvt *fup, int event)
05980 {
05981    char name[256];
05982    int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
05983    int outgoing = fup->outgoing_call;
05984    struct sip_peer *p = NULL;
05985 
05986    ast_debug(3, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
05987 
05988 
05989    /* Test if we need to check call limits, in order to avoid
05990       realtime lookups if we do not need it */
05991    if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT) && !ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD))
05992       return 0;
05993 
05994    ast_copy_string(name, fup->username, sizeof(name));
05995 
05996    /* Check the list of devices */
05997    if (fup->relatedpeer) {
05998       p = ref_peer(fup->relatedpeer, "ref related peer for update_call_counter");
05999       inuse = &p->inUse;
06000       call_limit = &p->call_limit;
06001       inringing = &p->inRinging;
06002       ast_copy_string(name, fup->peername, sizeof(name));
06003    }
06004    if (!p) {
06005       ast_debug(2, "%s is not a local device, no call limit\n", name);
06006       return 0;
06007    }
06008 
06009    switch(event) {
06010    /* incoming and outgoing affects the inUse counter */
06011    case DEC_CALL_LIMIT:
06012       /* Decrement inuse count if applicable */
06013       if (inuse) {
06014          sip_pvt_lock(fup);
06015          ao2_lock(p);
06016          if (*inuse > 0) {
06017             if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
06018                (*inuse)--;
06019                ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
06020             }
06021          } else {
06022             *inuse = 0;
06023          }
06024          ao2_unlock(p);
06025          sip_pvt_unlock(fup);
06026       }
06027 
06028       /* Decrement ringing count if applicable */
06029       if (inringing) {
06030          sip_pvt_lock(fup);
06031          ao2_lock(p);
06032          if (*inringing > 0) {
06033             if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
06034                (*inringing)--;
06035                ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
06036             }
06037          } else {
06038             *inringing = 0;
06039          }
06040          ao2_unlock(p);
06041          sip_pvt_unlock(fup);
06042       }
06043 
06044       /* Decrement onhold count if applicable */
06045       sip_pvt_lock(fup);
06046       ao2_lock(p);
06047       if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && sip_cfg.notifyhold) {
06048          ast_clear_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD);
06049          ao2_unlock(p);
06050          sip_pvt_unlock(fup);
06051          sip_peer_hold(fup, FALSE);
06052       } else {
06053          ao2_unlock(p);
06054          sip_pvt_unlock(fup);
06055       }
06056       if (sipdebug)
06057          ast_debug(2, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
06058       break;
06059 
06060    case INC_CALL_RINGING:
06061    case INC_CALL_LIMIT:
06062       /* If call limit is active and we have reached the limit, reject the call */
06063       if (*call_limit > 0 ) {
06064          if (*inuse >= *call_limit) {
06065             ast_log(LOG_NOTICE, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
06066             unref_peer(p, "update_call_counter: unref peer p, call limit exceeded");
06067             return -1;
06068          }
06069       }
06070       if (inringing && (event == INC_CALL_RINGING)) {
06071          sip_pvt_lock(fup);
06072          ao2_lock(p);
06073          if (!ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
06074             (*inringing)++;
06075             ast_set_flag(&fup->flags[0], SIP_INC_RINGING);
06076          }
06077          ao2_unlock(p);
06078          sip_pvt_unlock(fup);
06079       }
06080       if (inuse) {
06081          sip_pvt_lock(fup);
06082          ao2_lock(p);
06083          if (!ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
06084             (*inuse)++;
06085             ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
06086          }
06087          ao2_unlock(p);
06088          sip_pvt_unlock(fup);
06089       }
06090       if (sipdebug) {
06091          ast_debug(2, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", "peer", name, *inuse, *call_limit);
06092       }
06093       break;
06094 
06095    case DEC_CALL_RINGING:
06096       if (inringing) {
06097          sip_pvt_lock(fup);
06098          ao2_lock(p);
06099          if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
06100             if (*inringing > 0) {
06101                (*inringing)--;
06102             }
06103             ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
06104          }
06105          ao2_unlock(p);
06106          sip_pvt_unlock(fup);
06107       }
06108       break;
06109 
06110    default:
06111       ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
06112    }
06113 
06114    if (p) {
06115       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", p->name);
06116       unref_peer(p, "update_call_counter: unref_peer from call counter");
06117    }
06118    return 0;
06119 }
06120 
06121 
06122 static void sip_destroy_fn(void *p)
06123 {
06124    sip_destroy(p);
06125 }
06126 
06127 /*! \brief Destroy SIP call structure.
06128  * Make it return NULL so the caller can do things like
06129  * foo = sip_destroy(foo);
06130  * and reduce the chance of bugs due to dangling pointers.
06131  */
06132 struct sip_pvt *sip_destroy(struct sip_pvt *p)
06133 {
06134    ast_debug(3, "Destroying SIP dialog %s\n", p->callid);
06135    __sip_destroy(p, TRUE, TRUE);
06136    return NULL;
06137 }
06138 
06139 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
06140 int hangup_sip2cause(int cause)
06141 {
06142    /* Possible values taken from causes.h */
06143 
06144    switch(cause) {
06145       case 401:   /* Unauthorized */
06146          return AST_CAUSE_CALL_REJECTED;
06147       case 403:   /* Not found */
06148          return AST_CAUSE_CALL_REJECTED;
06149       case 404:   /* Not found */
06150          return AST_CAUSE_UNALLOCATED;
06151       case 405:   /* Method not allowed */
06152          return AST_CAUSE_INTERWORKING;
06153       case 407:   /* Proxy authentication required */
06154          return AST_CAUSE_CALL_REJECTED;
06155       case 408:   /* No reaction */
06156          return AST_CAUSE_NO_USER_RESPONSE;
06157       case 409:   /* Conflict */
06158          return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
06159       case 410:   /* Gone */
06160          return AST_CAUSE_NUMBER_CHANGED;
06161       case 411:   /* Length required */
06162          return AST_CAUSE_INTERWORKING;
06163       case 413:   /* Request entity too large */
06164          return AST_CAUSE_INTERWORKING;
06165       case 414:   /* Request URI too large */
06166          return AST_CAUSE_INTERWORKING;
06167       case 415:   /* Unsupported media type */
06168          return AST_CAUSE_INTERWORKING;
06169       case 420:   /* Bad extension */
06170          return AST_CAUSE_NO_ROUTE_DESTINATION;
06171       case 480:   /* No answer */
06172          return AST_CAUSE_NO_ANSWER;
06173       case 481:   /* No answer */
06174          return AST_CAUSE_INTERWORKING;
06175       case 482:   /* Loop detected */
06176          return AST_CAUSE_INTERWORKING;
06177       case 483:   /* Too many hops */
06178          return AST_CAUSE_NO_ANSWER;
06179       case 484:   /* Address incomplete */
06180          return AST_CAUSE_INVALID_NUMBER_FORMAT;
06181       case 485:   /* Ambiguous */
06182          return AST_CAUSE_UNALLOCATED;
06183       case 486:   /* Busy everywhere */
06184          return AST_CAUSE_BUSY;
06185       case 487:   /* Request terminated */
06186          return AST_CAUSE_INTERWORKING;
06187       case 488:   /* No codecs approved */
06188          return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
06189       case 491:   /* Request pending */
06190          return AST_CAUSE_INTERWORKING;
06191       case 493:   /* Undecipherable */
06192          return AST_CAUSE_INTERWORKING;
06193       case 500:   /* Server internal failure */
06194          return AST_CAUSE_FAILURE;
06195       case 501:   /* Call rejected */
06196          return AST_CAUSE_FACILITY_REJECTED;
06197       case 502:
06198          return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
06199       case 503:   /* Service unavailable */
06200          return AST_CAUSE_CONGESTION;
06201       case 504:   /* Gateway timeout */
06202          return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
06203       case 505:   /* SIP version not supported */
06204          return AST_CAUSE_INTERWORKING;
06205       case 600:   /* Busy everywhere */
06206          return AST_CAUSE_USER_BUSY;
06207       case 603:   /* Decline */
06208          return AST_CAUSE_CALL_REJECTED;
06209       case 604:   /* Does not exist anywhere */
06210          return AST_CAUSE_UNALLOCATED;
06211       case 606:   /* Not acceptable */
06212          return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
06213       default:
06214          if (cause < 500 && cause >= 400) {
06215             /* 4xx class error that is unknown - someting wrong with our request */
06216             return AST_CAUSE_INTERWORKING;
06217          } else if (cause < 600 && cause >= 500) {
06218             /* 5xx class error - problem in the remote end */
06219             return AST_CAUSE_CONGESTION;
06220          } else if (cause < 700 && cause >= 600) {
06221             /* 6xx - global errors in the 4xx class */
06222             return AST_CAUSE_INTERWORKING;
06223          }
06224          return AST_CAUSE_NORMAL;
06225    }
06226    /* Never reached */
06227    return 0;
06228 }
06229 
06230 /*! \brief Convert Asterisk hangup causes to SIP codes
06231 \verbatim
06232  Possible values from causes.h
06233         AST_CAUSE_NOTDEFINED    AST_CAUSE_NORMAL        AST_CAUSE_BUSY
06234         AST_CAUSE_FAILURE       AST_CAUSE_CONGESTION    AST_CAUSE_UNALLOCATED
06235 
06236    In addition to these, a lot of PRI codes is defined in causes.h
06237    ...should we take care of them too ?
06238 
06239    Quote RFC 3398
06240 
06241    ISUP Cause value                        SIP response
06242    ----------------                        ------------
06243    1  unallocated number                   404 Not Found
06244    2  no route to network                  404 Not found
06245    3  no route to destination              404 Not found
06246    16 normal call clearing                 --- (*)
06247    17 user busy                            486 Busy here
06248    18 no user responding                   408 Request Timeout
06249    19 no answer from the user              480 Temporarily unavailable
06250    20 subscriber absent                    480 Temporarily unavailable
06251    21 call rejected                        403 Forbidden (+)
06252    22 number changed (w/o diagnostic)      410 Gone
06253    22 number changed (w/ diagnostic)       301 Moved Permanently
06254    23 redirection to new destination       410 Gone
06255    26 non-selected user clearing           404 Not Found (=)
06256    27 destination out of order             502 Bad Gateway
06257    28 address incomplete                   484 Address incomplete
06258    29 facility rejected                    501 Not implemented
06259    31 normal unspecified                   480 Temporarily unavailable
06260 \endverbatim
06261 */
06262 const char *hangup_cause2sip(int cause)
06263 {
06264    switch (cause) {
06265       case AST_CAUSE_UNALLOCATED:      /* 1 */
06266       case AST_CAUSE_NO_ROUTE_DESTINATION:   /* 3 IAX2: Can't find extension in context */
06267       case AST_CAUSE_NO_ROUTE_TRANSIT_NET:   /* 2 */
06268          return "404 Not Found";
06269       case AST_CAUSE_CONGESTION:    /* 34 */
06270       case AST_CAUSE_SWITCH_CONGESTION:   /* 42 */
06271          return "503 Service Unavailable";
06272       case AST_CAUSE_NO_USER_RESPONSE: /* 18 */
06273          return "408 Request Timeout";
06274       case AST_CAUSE_NO_ANSWER:     /* 19 */
06275       case AST_CAUSE_UNREGISTERED:        /* 20 */
06276          return "480 Temporarily unavailable";
06277       case AST_CAUSE_CALL_REJECTED:    /* 21 */
06278          return "403 Forbidden";
06279       case AST_CAUSE_NUMBER_CHANGED:      /* 22 */
06280          return "410 Gone";
06281       case AST_CAUSE_NORMAL_UNSPECIFIED:  /* 31 */
06282          return "480 Temporarily unavailable";
06283       case AST_CAUSE_INVALID_NUMBER_FORMAT:
06284          return "484 Address incomplete";
06285       case AST_CAUSE_USER_BUSY:
06286          return "486 Busy here";
06287       case AST_CAUSE_FAILURE:
06288          return "500 Server internal failure";
06289       case AST_CAUSE_FACILITY_REJECTED:   /* 29 */
06290          return "501 Not Implemented";
06291       case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
06292          return "503 Service Unavailable";
06293       /* Used in chan_iax2 */
06294       case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
06295          return "502 Bad Gateway";
06296       case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */
06297          return "488 Not Acceptable Here";
06298          
06299       case AST_CAUSE_NOTDEFINED:
06300       default:
06301          ast_debug(1, "AST hangup cause %d (no match found in SIP)\n", cause);
06302          return NULL;
06303    }
06304 
06305    /* Never reached */
06306    return 0;
06307 }
06308 
06309 static int reinvite_timeout(const void *data)
06310 {
06311    struct sip_pvt *dialog = (struct sip_pvt *) data;
06312    struct ast_channel *owner = sip_pvt_lock_full(dialog);
06313    dialog->reinviteid = -1;
06314    check_pendings(dialog);
06315    if (owner) {
06316       ast_channel_unlock(owner);
06317       ast_channel_unref(owner);
06318    }
06319    ao2_unlock(dialog);
06320    dialog_unref(dialog, "unref for reinvite timeout");
06321    return 0;
06322 }
06323 
06324 /*! \brief  sip_hangup: Hangup SIP call
06325  * Part of PBX interface, called from ast_hangup */
06326 static int sip_hangup(struct ast_channel *ast)
06327 {
06328    struct sip_pvt *p = ast->tech_pvt;
06329    int needcancel = FALSE;
06330    int needdestroy = 0;
06331    struct ast_channel *oldowner = ast;
06332 
06333    if (!p) {
06334       ast_debug(1, "Asked to hangup channel that was not connected\n");
06335       return 0;
06336    }
06337    if (ast_test_flag(ast, AST_FLAG_ANSWERED_ELSEWHERE) || ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
06338       ast_debug(1, "This call was answered elsewhere\n");
06339       if (ast->hangupcause == AST_CAUSE_ANSWERED_ELSEWHERE) {
06340          ast_debug(1, "####### It's the cause code, buddy. The cause code!!!\n");
06341       }
06342       append_history(p, "Cancel", "Call answered elsewhere");
06343       p->answered_elsewhere = TRUE;
06344    }
06345 
06346    /* Store hangupcause locally in PVT so we still have it before disconnect */
06347    if (p->owner)
06348       p->hangupcause = p->owner->hangupcause;
06349 
06350    if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
06351       if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
06352          if (sipdebug)
06353             ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
06354          update_call_counter(p, DEC_CALL_LIMIT);
06355       }
06356       ast_debug(4, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
06357       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06358       ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Really hang up next time */
06359       p->needdestroy = 0;
06360       p->owner->tech_pvt = dialog_unref(p->owner->tech_pvt, "unref p->owner->tech_pvt");
06361       sip_pvt_lock(p);
06362       p->owner = NULL;  /* Owner will be gone after we return, so take it away */
06363       sip_pvt_unlock(p);
06364       ast_module_unref(ast_module_info->self);
06365       return 0;
06366    }
06367 
06368    ast_debug(1, "Hangup call %s, SIP callid %s\n", ast->name, p->callid);
06369 
06370    sip_pvt_lock(p);
06371    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
06372       if (sipdebug)
06373          ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
06374       update_call_counter(p, DEC_CALL_LIMIT);
06375    }
06376 
06377    /* Determine how to disconnect */
06378    if (p->owner != ast) {
06379       ast_log(LOG_WARNING, "Huh?  We aren't the owner? Can't hangup call.\n");
06380       sip_pvt_unlock(p);
06381       return 0;
06382    }
06383    /* If the call is not UP, we need to send CANCEL instead of BYE */
06384    /* In case of re-invites, the call might be UP even though we have an incomplete invite transaction */
06385    if (p->invitestate < INV_COMPLETED && p->owner->_state != AST_STATE_UP) {
06386       needcancel = TRUE;
06387       ast_debug(4, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
06388    }
06389 
06390    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
06391 
06392    append_history(p, needcancel ? "Cancel" : "Hangup", "Cause %s", p->owner ? ast_cause2str(p->hangupcause) : "Unknown");
06393 
06394    /* Disconnect */
06395    disable_dsp_detect(p);
06396 
06397    p->owner = NULL;
06398    ast->tech_pvt = dialog_unref(ast->tech_pvt, "unref ast->tech_pvt");
06399 
06400    ast_module_unref(ast_module_info->self);
06401    /* Do not destroy this pvt until we have timeout or
06402       get an answer to the BYE or INVITE/CANCEL
06403       If we get no answer during retransmit period, drop the call anyway.
06404       (Sorry, mother-in-law, you can't deny a hangup by sending
06405       603 declined to BYE...)
06406    */
06407    if (p->alreadygone)
06408       needdestroy = 1;  /* Set destroy flag at end of this function */
06409    else if (p->invitestate != INV_CALLING)
06410       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06411 
06412    /* Start the process if it's not already started */
06413    if (!p->alreadygone && p->initreq.data && !ast_strlen_zero(p->initreq.data->str)) {
06414       if (needcancel) { /* Outgoing call, not up */
06415          if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06416             /* if we can't send right now, mark it pending */
06417             if (p->invitestate == INV_CALLING) {
06418                /* We can't send anything in CALLING state */
06419                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
06420                /* 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. */
06421                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06422                append_history(p, "DELAY", "Not sending cancel, waiting for timeout");
06423             } else {
06424                struct sip_pkt *cur;
06425 
06426                for (cur = p->packets; cur; cur = cur->next) {
06427                   __sip_semi_ack(p, cur->seqno, cur->is_resp, cur->method ? cur->method : find_sip_method(cur->data->str));
06428                }
06429                p->invitestate = INV_CANCELLED;
06430                /* Send a new request: CANCEL */
06431                transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
06432                /* Actually don't destroy us yet, wait for the 487 on our original
06433                   INVITE, but do set an autodestruct just in case we never get it. */
06434                needdestroy = 0;
06435                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
06436             }
06437          } else { /* Incoming call, not up */
06438             const char *res;
06439             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"));
06440             if (p->hangupcause && (res = hangup_cause2sip(p->hangupcause)))
06441                transmit_response_reliable(p, res, &p->initreq);
06442             else
06443                transmit_response_reliable(p, "603 Declined", &p->initreq);
06444             p->invitestate = INV_TERMINATED;
06445          }
06446       } else { /* Call is in UP state, send BYE */
06447          if (p->stimer->st_active == TRUE) {
06448             stop_session_timer(p);
06449          }
06450 
06451          if (!p->pendinginvite) {
06452             struct ast_channel *bridge = ast_bridged_channel(oldowner);
06453             char quality_buf[AST_MAX_USER_FIELD], *quality;
06454 
06455             /* We need to get the lock on bridge because ast_rtp_instance_set_stats_vars will attempt
06456              * to lock the bridge. This may get hairy...
06457              */
06458             while (bridge && ast_channel_trylock(bridge)) {
06459                sip_pvt_unlock(p);
06460                do {
06461                   CHANNEL_DEADLOCK_AVOIDANCE(oldowner);
06462                } while (sip_pvt_trylock(p));
06463                bridge = ast_bridged_channel(oldowner);
06464             }
06465 
06466             if (p->rtp) {
06467                ast_rtp_instance_set_stats_vars(oldowner, p->rtp);
06468             }
06469 
06470             if (bridge) {
06471                struct sip_pvt *q = bridge->tech_pvt;
06472 
06473                if (IS_SIP_TECH(bridge->tech) && q && q->rtp) {
06474                   ast_rtp_instance_set_stats_vars(bridge, q->rtp);
06475                }
06476                ast_channel_unlock(bridge);
06477             }
06478 
06479             /*
06480              * The channel variables are set below just to get the AMI
06481              * VarSet event because the channel is being hungup.
06482              */
06483             if (p->rtp && (quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
06484                if (p->do_history) {
06485                   append_history(p, "RTCPaudio", "Quality:%s", quality);
06486                }
06487                pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", quality);
06488             }
06489             if (p->vrtp && (quality = ast_rtp_instance_get_quality(p->vrtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
06490                if (p->do_history) {
06491                   append_history(p, "RTCPvideo", "Quality:%s", quality);
06492                }
06493                pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", quality);
06494             }
06495             if (p->trtp && (quality = ast_rtp_instance_get_quality(p->trtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
06496                if (p->do_history) {
06497                   append_history(p, "RTCPtext", "Quality:%s", quality);
06498                }
06499                pbx_builtin_setvar_helper(oldowner, "RTPTEXTQOS", quality);
06500             }
06501 
06502             /* Send a hangup */
06503             if (oldowner->_state == AST_STATE_UP) {
06504                transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
06505             }
06506 
06507          } else {
06508             /* Note we will need a BYE when this all settles out
06509                but we can't send one while we have "INVITE" outstanding. */
06510             ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
06511             ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE); 
06512             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"));
06513             if (sip_cancel_destroy(p)) {
06514                ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
06515             }
06516             /* If we have an ongoing reinvite, there is a chance that we have gotten a provisional
06517              * response, but something weird has happened and we will never receive a final response.
06518              * So, just in case, check for pending actions after a bit of time to trigger the pending
06519              * bye that we are setting above */
06520             if (p->ongoing_reinvite && p->reinviteid < 0) {
06521                p->reinviteid = ast_sched_add(sched, 32 * p->timer_t1, reinvite_timeout, dialog_ref(p, "ref for reinvite_timeout"));
06522             }
06523          }
06524       }
06525    }
06526    if (needdestroy) {
06527       pvt_set_needdestroy(p, "hangup");
06528    }
06529    sip_pvt_unlock(p);
06530    return 0;
06531 }
06532 
06533 /*! \brief Try setting codec suggested by the SIP_CODEC channel variable */
06534 static void try_suggested_sip_codec(struct sip_pvt *p)
06535 {
06536    format_t fmt;
06537    const char *codec;
06538 
06539    if (p->outgoing_call) {
06540       codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC_OUTBOUND");
06541    } else if (!(codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC_INBOUND"))) {
06542       codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
06543    }
06544 
06545    if (!codec) 
06546       return;
06547 
06548    fmt = ast_getformatbyname(codec);
06549    if (fmt) {
06550       ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
06551       if (p->jointcapability & fmt) {
06552          p->jointcapability &= fmt;
06553          p->capability &= fmt;
06554       } else
06555          ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
06556    } else
06557       ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
06558    return;  
06559 }
06560 
06561 /*! \brief  sip_answer: Answer SIP call , send 200 OK on Invite
06562  * Part of PBX interface */
06563 static int sip_answer(struct ast_channel *ast)
06564 {
06565    int res = 0;
06566    struct sip_pvt *p = ast->tech_pvt;
06567 
06568    sip_pvt_lock(p);
06569    if (ast->_state != AST_STATE_UP) {
06570       try_suggested_sip_codec(p);   
06571 
06572       ast_setstate(ast, AST_STATE_UP);
06573       ast_debug(1, "SIP answering channel: %s\n", ast->name);
06574       ast_rtp_instance_update_source(p->rtp);
06575       res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL, FALSE, TRUE);
06576       ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
06577    }
06578    sip_pvt_unlock(p);
06579    return res;
06580 }
06581 
06582 /*! \brief Send frame to media channel (rtp) */
06583 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
06584 {
06585    struct sip_pvt *p = ast->tech_pvt;
06586    int res = 0;
06587 
06588    switch (frame->frametype) {
06589    case AST_FRAME_VOICE:
06590       if (!(frame->subclass.codec & ast->nativeformats)) {
06591          char s1[512], s2[512], s3[512];
06592          ast_log(LOG_WARNING, "Asked to transmit frame type %s, while native formats is %s read/write = %s/%s\n",
06593             ast_getformatname(frame->subclass.codec),
06594             ast_getformatname_multiple(s1, sizeof(s1), ast->nativeformats & AST_FORMAT_AUDIO_MASK),
06595             ast_getformatname_multiple(s2, sizeof(s2), ast->readformat),
06596             ast_getformatname_multiple(s3, sizeof(s3), ast->writeformat));
06597          return 0;
06598       }
06599       if (p) {
06600          sip_pvt_lock(p);
06601          if (p->t38.state == T38_ENABLED) {
06602             /* drop frame, can't sent VOICE frames while in T.38 mode */
06603             sip_pvt_unlock(p);
06604             break;
06605          } else if (p->rtp) {
06606             /* If channel is not up, activate early media session */
06607             if ((ast->_state != AST_STATE_UP) &&
06608                 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06609                 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06610                ast_rtp_instance_update_source(p->rtp);
06611                if (!global_prematuremediafilter) {
06612                   p->invitestate = INV_EARLY_MEDIA;
06613                   transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06614                   ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06615                }
06616             }
06617             p->lastrtptx = time(NULL);
06618             res = ast_rtp_instance_write(p->rtp, frame);
06619          }
06620          sip_pvt_unlock(p);
06621       }
06622       break;
06623    case AST_FRAME_VIDEO:
06624       if (p) {
06625          sip_pvt_lock(p);
06626          if (p->vrtp) {
06627             /* Activate video early media */
06628             if ((ast->_state != AST_STATE_UP) &&
06629                 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06630                 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06631                p->invitestate = INV_EARLY_MEDIA;
06632                transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06633                ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06634             }
06635             p->lastrtptx = time(NULL);
06636             res = ast_rtp_instance_write(p->vrtp, frame);
06637          }
06638          sip_pvt_unlock(p);
06639       }
06640       break;
06641    case AST_FRAME_TEXT:
06642       if (p) {
06643          sip_pvt_lock(p);
06644          if (p->red) {
06645             ast_rtp_red_buffer(p->trtp, frame);
06646          } else {
06647             if (p->trtp) {
06648                /* Activate text early media */
06649                if ((ast->_state != AST_STATE_UP) &&
06650                    !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06651                    !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06652                   p->invitestate = INV_EARLY_MEDIA;
06653                   transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06654                   ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06655                }
06656                p->lastrtptx = time(NULL);
06657                res = ast_rtp_instance_write(p->trtp, frame);
06658             }
06659          }
06660          sip_pvt_unlock(p);
06661       }
06662       break;
06663    case AST_FRAME_IMAGE:
06664       return 0;
06665       break;
06666    case AST_FRAME_MODEM:
06667       if (p) {
06668          sip_pvt_lock(p);
06669          /* UDPTL requires two-way communication, so early media is not needed here.
06670             we simply forget the frames if we get modem frames before the bridge is up.
06671             Fax will re-transmit.
06672          */
06673          if ((ast->_state == AST_STATE_UP) &&
06674              p->udptl &&
06675              (p->t38.state == T38_ENABLED)) {
06676             res = ast_udptl_write(p->udptl, frame);
06677          }
06678          sip_pvt_unlock(p);
06679       }
06680       break;
06681    default:
06682       ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
06683       return 0;
06684    }
06685 
06686    return res;
06687 }
06688 
06689 /*! \brief  sip_fixup: Fix up a channel:  If a channel is consumed, this is called.
06690         Basically update any ->owner links */
06691 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
06692 {
06693    int ret = -1;
06694    struct sip_pvt *p;
06695 
06696    if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE))
06697       ast_debug(1, "New channel is zombie\n");
06698    if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE))
06699       ast_debug(1, "Old channel is zombie\n");
06700 
06701    if (!newchan || !newchan->tech_pvt) {
06702       if (!newchan)
06703          ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", oldchan->name);
06704       else
06705          ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name);
06706       return -1;
06707    }
06708    p = newchan->tech_pvt;
06709 
06710    sip_pvt_lock(p);
06711    append_history(p, "Masq", "Old channel: %s\n", oldchan->name);
06712    append_history(p, "Masq (cont)", "...new owner: %s\n", newchan->name);
06713    if (p->owner != oldchan)
06714       ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
06715    else {
06716       p->owner = newchan;
06717       /* Re-invite RTP back to Asterisk. Needed if channel is masqueraded out of a native
06718          RTP bridge (i.e., RTP not going through Asterisk): RTP bridge code might not be
06719          able to do this if the masquerade happens before the bridge breaks (e.g., AMI
06720          redirect of both channels). Note that a channel can not be masqueraded *into*
06721          a native bridge. So there is no danger that this breaks a native bridge that
06722          should stay up. */
06723       sip_set_rtp_peer(newchan, NULL, NULL, 0, 0, 0);
06724       ret = 0;
06725    }
06726    ast_debug(3, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, p->owner->name, oldchan->name);
06727 
06728    sip_pvt_unlock(p);
06729    return ret;
06730 }
06731 
06732 static int sip_senddigit_begin(struct ast_channel *ast, char digit)
06733 {
06734    struct sip_pvt *p = ast->tech_pvt;
06735    int res = 0;
06736 
06737    sip_pvt_lock(p);
06738    switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
06739    case SIP_DTMF_INBAND:
06740       res = -1; /* Tell Asterisk to generate inband indications */
06741       break;
06742    case SIP_DTMF_RFC2833:
06743       if (p->rtp)
06744          ast_rtp_instance_dtmf_begin(p->rtp, digit);
06745       break;
06746    default:
06747       break;
06748    }
06749    sip_pvt_unlock(p);
06750 
06751    return res;
06752 }
06753 
06754 /*! \brief Send DTMF character on SIP channel
06755    within one call, we're able to transmit in many methods simultaneously */
06756 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
06757 {
06758    struct sip_pvt *p = ast->tech_pvt;
06759    int res = 0;
06760 
06761    sip_pvt_lock(p);
06762    switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
06763    case SIP_DTMF_INFO:
06764    case SIP_DTMF_SHORTINFO:
06765       transmit_info_with_digit(p, digit, duration);
06766       break;
06767    case SIP_DTMF_RFC2833:
06768       if (p->rtp)
06769          ast_rtp_instance_dtmf_end_with_duration(p->rtp, digit, duration);
06770       break;
06771    case SIP_DTMF_INBAND:
06772       res = -1; /* Tell Asterisk to stop inband indications */
06773       break;
06774    }
06775    sip_pvt_unlock(p);
06776 
06777    return res;
06778 }
06779 
06780 /*! \brief Transfer SIP call */
06781 static int sip_transfer(struct ast_channel *ast, const char *dest)
06782 {
06783    struct sip_pvt *p = ast->tech_pvt;
06784    int res;
06785 
06786    if (dest == NULL) /* functions below do not take a NULL */
06787       dest = "";
06788    sip_pvt_lock(p);
06789    if (ast->_state == AST_STATE_RING)
06790       res = sip_sipredirect(p, dest);
06791    else
06792       res = transmit_refer(p, dest);
06793    sip_pvt_unlock(p);
06794    return res;
06795 }
06796 
06797 /*! \brief Helper function which updates T.38 capability information and triggers a reinvite */
06798 static int interpret_t38_parameters(struct sip_pvt *p, const struct ast_control_t38_parameters *parameters)
06799 {
06800    int res = 0;
06801 
06802    if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) || !p->udptl) {
06803       return -1;
06804    }
06805    switch (parameters->request_response) {
06806    case AST_T38_NEGOTIATED:
06807    case AST_T38_REQUEST_NEGOTIATE:         /* Request T38 */
06808       /* Negotiation can not take place without a valid max_ifp value. */
06809       if (!parameters->max_ifp) {
06810          change_t38_state(p, T38_DISABLED);
06811          if (p->t38.state == T38_PEER_REINVITE) {
06812             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"));
06813             transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
06814          }
06815          break;
06816       } else if (p->t38.state == T38_PEER_REINVITE) {
06817          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"));
06818          p->t38.our_parms = *parameters;
06819          /* modify our parameters to conform to the peer's parameters,
06820           * based on the rules in the ITU T.38 recommendation
06821           */
06822          if (!p->t38.their_parms.fill_bit_removal) {
06823             p->t38.our_parms.fill_bit_removal = FALSE;
06824          }
06825          if (!p->t38.their_parms.transcoding_mmr) {
06826             p->t38.our_parms.transcoding_mmr = FALSE;
06827          }
06828          if (!p->t38.their_parms.transcoding_jbig) {
06829             p->t38.our_parms.transcoding_jbig = FALSE;
06830          }
06831          p->t38.our_parms.version = MIN(p->t38.our_parms.version, p->t38.their_parms.version);
06832          p->t38.our_parms.rate_management = p->t38.their_parms.rate_management;
06833          ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
06834          change_t38_state(p, T38_ENABLED);
06835          transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
06836       } else if (p->t38.state != T38_ENABLED) {
06837          p->t38.our_parms = *parameters;
06838          ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
06839          change_t38_state(p, T38_LOCAL_REINVITE);
06840          if (!p->pendinginvite) {
06841             transmit_reinvite_with_sdp(p, TRUE, FALSE);
06842          } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
06843             ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
06844          }
06845       }
06846       break;
06847    case AST_T38_TERMINATED:
06848    case AST_T38_REFUSED:
06849    case AST_T38_REQUEST_TERMINATE:         /* Shutdown T38 */
06850       if (p->t38.state == T38_PEER_REINVITE) {
06851          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"));
06852          change_t38_state(p, T38_DISABLED);
06853          transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
06854       } else if (p->t38.state == T38_ENABLED)
06855          transmit_reinvite_with_sdp(p, FALSE, FALSE);
06856       break;
06857    case AST_T38_REQUEST_PARMS: {    /* Application wants remote's parameters re-sent */
06858       struct ast_control_t38_parameters parameters = p->t38.their_parms;
06859 
06860       if (p->t38.state == T38_PEER_REINVITE) {
06861          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"));
06862          parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
06863          parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
06864          ast_queue_control_data(p->owner, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));
06865          /* we need to return a positive value here, so that applications that
06866           * send this request can determine conclusively whether it was accepted or not...
06867           * older versions of chan_sip would just silently accept it and return zero.
06868           */
06869          res = AST_T38_REQUEST_PARMS;
06870       }
06871       break;
06872    }
06873    default:
06874       res = -1;
06875       break;
06876    }
06877 
06878    return res;
06879 }
06880 
06881 /*! \internal \brief Create and initialize UDPTL for the specified dialog
06882  * \param p SIP private structure to create UDPTL object for
06883  * \pre p is locked
06884  * \pre p->owner is locked
06885  *
06886  * \note In the case of failure, SIP_PAGE2_T38SUPPORT is cleared on p
06887  *
06888  * \return 0 on success, any other value on failure
06889  */
06890 static int initialize_udptl(struct sip_pvt *p)
06891 {
06892    int natflags = ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP);
06893 
06894    if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
06895       return 1;
06896    }
06897 
06898    /* If we've already initialized T38, don't take any further action */
06899    if (p->udptl) {
06900       return 0;
06901    }
06902 
06903    /* T38 can be supported by this dialog, create it and set the derived properties */
06904    if ((p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, &bindaddr))) {
06905       if (p->owner) {
06906          ast_channel_set_fd(p->owner, 5, ast_udptl_fd(p->udptl));
06907       }
06908 
06909       ast_udptl_setqos(p->udptl, global_tos_audio, global_cos_audio);
06910       p->t38_maxdatagram = p->relatedpeer ? p->relatedpeer->t38_maxdatagram : global_t38_maxdatagram;
06911       set_t38_capabilities(p);
06912 
06913       ast_debug(1, "Setting NAT on UDPTL to %s\n", natflags ? "On" : "Off");
06914       ast_udptl_setnat(p->udptl, natflags);
06915    } else {
06916       ast_log(AST_LOG_WARNING, "UDPTL creation failed - disabling T38 for this dialog\n");
06917       ast_clear_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT);
06918       return 1;
06919    }
06920 
06921    return 0;
06922 }
06923 
06924 /*! \brief Play indication to user
06925  * With SIP a lot of indications is sent as messages, letting the device play
06926    the indication - busy signal, congestion etc
06927    \return -1 to force ast_indicate to send indication in audio, 0 if SIP can handle the indication by sending a message
06928 */
06929 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
06930 {
06931    struct sip_pvt *p = ast->tech_pvt;
06932    int res = 0;
06933 
06934    sip_pvt_lock(p);
06935    switch(condition) {
06936    case AST_CONTROL_RINGING:
06937       if (ast->_state == AST_STATE_RING) {
06938          p->invitestate = INV_EARLY_MEDIA;
06939          if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
06940              (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {            
06941             /* Send 180 ringing if out-of-band seems reasonable */
06942             transmit_provisional_response(p, "180 Ringing", &p->initreq, 0);
06943             ast_set_flag(&p->flags[0], SIP_RINGING);
06944             if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
06945                break;
06946          } else {
06947             /* Well, if it's not reasonable, just send in-band */
06948          }
06949       }
06950       res = -1;
06951       break;
06952    case AST_CONTROL_BUSY:
06953       if (ast->_state != AST_STATE_UP) {
06954          transmit_response_reliable(p, "486 Busy Here", &p->initreq);
06955          p->invitestate = INV_COMPLETED;
06956          sip_alreadygone(p);
06957          ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06958          break;
06959       }
06960       res = -1;
06961       break;
06962    case AST_CONTROL_CONGESTION:
06963       if (ast->_state != AST_STATE_UP) {
06964          transmit_response_reliable(p, "503 Service Unavailable", &p->initreq);
06965          p->invitestate = INV_COMPLETED;
06966          sip_alreadygone(p);
06967          ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06968          break;
06969       }
06970       res = -1;
06971       break;
06972    case AST_CONTROL_INCOMPLETE:
06973       if (ast->_state != AST_STATE_UP) {
06974          switch (ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)) {
06975          case SIP_PAGE2_ALLOWOVERLAP_YES:
06976             transmit_response_reliable(p, "484 Address Incomplete", &p->initreq);
06977             p->invitestate = INV_COMPLETED;
06978             sip_alreadygone(p);
06979             ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06980             break;
06981          case SIP_PAGE2_ALLOWOVERLAP_DTMF:
06982             /* Just wait for inband DTMF digits */
06983             break;
06984          default:
06985             /* it actually means no support for overlap */
06986             transmit_response_reliable(p, "404 Not Found", &p->initreq);
06987             p->invitestate = INV_COMPLETED;
06988             sip_alreadygone(p);
06989             ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06990             break;
06991          }
06992       }
06993       break;
06994    case AST_CONTROL_PROCEEDING:
06995       if ((ast->_state != AST_STATE_UP) &&
06996           !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06997           !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06998          transmit_response(p, "100 Trying", &p->initreq);
06999          p->invitestate = INV_PROCEEDING;
07000          break;
07001       }
07002       res = -1;
07003       break;
07004    case AST_CONTROL_PROGRESS:
07005       if ((ast->_state != AST_STATE_UP) &&
07006           !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
07007           !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
07008          p->invitestate = INV_EARLY_MEDIA;
07009          transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
07010          ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
07011          break;
07012       }
07013       res = -1;
07014       break;
07015    case AST_CONTROL_HOLD:
07016       ast_rtp_instance_update_source(p->rtp);
07017       ast_moh_start(ast, data, p->mohinterpret);
07018       break;
07019    case AST_CONTROL_UNHOLD:
07020       ast_rtp_instance_update_source(p->rtp);
07021       ast_moh_stop(ast);
07022       break;
07023    case AST_CONTROL_VIDUPDATE:   /* Request a video frame update */
07024       if (p->vrtp && !p->novideo) {
07025          transmit_info_with_vidupdate(p);
07026          /* ast_rtcp_send_h261fur(p->vrtp); */
07027       } else
07028          res = -1;
07029       break;
07030    case AST_CONTROL_T38_PARAMETERS:
07031       res = -1;
07032       if (datalen != sizeof(struct ast_control_t38_parameters)) {
07033          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);
07034       } else {
07035          const struct ast_control_t38_parameters *parameters = data;
07036          if (!initialize_udptl(p)) {
07037             res = interpret_t38_parameters(p, parameters);
07038          }
07039       }
07040       break;
07041    case AST_CONTROL_SRCUPDATE:
07042       ast_rtp_instance_update_source(p->rtp);
07043       break;
07044    case AST_CONTROL_SRCCHANGE:
07045       ast_rtp_instance_change_source(p->rtp);
07046       break;
07047    case AST_CONTROL_CONNECTED_LINE:
07048       update_connectedline(p, data, datalen);
07049       break;
07050    case AST_CONTROL_REDIRECTING:
07051       update_redirecting(p, data, datalen);
07052       break;
07053    case AST_CONTROL_AOC:
07054       {
07055          struct ast_aoc_decoded *decoded = ast_aoc_decode((struct ast_aoc_encoded *) data, datalen, ast);
07056          if (!decoded) {
07057             ast_log(LOG_ERROR, "Error decoding indicated AOC data\n");
07058             res = -1;
07059             break;
07060          }
07061          switch (ast_aoc_get_msg_type(decoded)) {
07062          case AST_AOC_REQUEST:
07063             if (ast_aoc_get_termination_request(decoded)) {
07064                /* TODO, once there is a way to get AOC-E on hangup, attempt that here
07065                 * before hanging up the channel.*/
07066 
07067                /* The other side has already initiated the hangup. This frame
07068                 * just says they are waiting to get AOC-E before completely tearing
07069                 * the call down.  Since SIP does not support this at the moment go
07070                 * ahead and terminate the call here to avoid an unnecessary timeout. */
07071                ast_debug(1, "AOC-E termination request received on %s. This is not yet supported on sip. Continue with hangup \n", p->owner->name);
07072                ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
07073             }
07074             break;
07075          case AST_AOC_D:
07076          case AST_AOC_E:
07077             if (ast_test_flag(&p->flags[2], SIP_PAGE3_SNOM_AOC)) {
07078                transmit_info_with_aoc(p, decoded);
07079             }
07080             break;
07081          case AST_AOC_S: /* S not supported yet */
07082          default:
07083             break;
07084          }
07085          ast_aoc_destroy_decoded(decoded);
07086       }
07087       break;
07088    case AST_CONTROL_UPDATE_RTP_PEER: /* Absorb this since it is handled by the bridge */
07089       break;
07090    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. */
07091       res = -1;
07092       break;
07093    case -1:
07094       res = -1;
07095       break;
07096    default:
07097       ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
07098       res = -1;
07099       break;
07100    }
07101    sip_pvt_unlock(p);
07102    return res;
07103 }
07104 
07105 /*!
07106  * \brief Initiate a call in the SIP channel
07107  *
07108  * \note called from sip_request_call (calls from the pbx ) for
07109  * outbound channels and from handle_request_invite for inbound
07110  * channels
07111  *
07112  * \pre i is locked
07113  *
07114  * \return New ast_channel locked.
07115  */
07116 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title, const char *linkedid)
07117 {
07118    struct ast_channel *tmp;
07119    struct ast_variable *v = NULL;
07120    format_t fmt;
07121    format_t what;
07122    format_t video;
07123    format_t text;
07124    format_t needvideo = 0;
07125    int needtext = 0;
07126    char buf[SIPBUFSIZE];
07127    char *exten;
07128 
07129    {
07130       const char *my_name; /* pick a good name */
07131    
07132       if (title) {
07133          my_name = title;
07134       } else {
07135          my_name = ast_strdupa(i->fromdomain);
07136       }
07137 
07138       sip_pvt_unlock(i);
07139       /* Don't hold a sip pvt lock while we allocate a channel */
07140       tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, i->accountcode, i->exten, i->context, linkedid, i->amaflags, "SIP/%s-%08x", my_name, ast_atomic_fetchadd_int((int *)&chan_idx, +1));
07141    }
07142    if (!tmp) {
07143       ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
07144       sip_pvt_lock(i);
07145       return NULL;
07146    }
07147    ast_channel_lock(tmp);
07148    sip_pvt_lock(i);
07149    ast_channel_cc_params_init(tmp, i->cc_params);
07150    tmp->caller.id.tag = ast_strdup(i->cid_tag);
07151 
07152    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;
07153 
07154    /* Select our native format based on codec preference until we receive
07155       something from another device to the contrary. */
07156    if (i->jointcapability) {  /* The joint capabilities of us and peer */
07157       what = i->jointcapability;
07158       video = i->jointcapability & AST_FORMAT_VIDEO_MASK;
07159       text = i->jointcapability & AST_FORMAT_TEXT_MASK;
07160    } else if (i->capability) {      /* Our configured capability for this peer */
07161       what = i->capability;
07162       video = i->capability & AST_FORMAT_VIDEO_MASK;
07163       text = i->capability & AST_FORMAT_TEXT_MASK;
07164    } else {
07165       what = sip_cfg.capability; /* Global codec support */
07166       video = sip_cfg.capability & AST_FORMAT_VIDEO_MASK;
07167       text = sip_cfg.capability & AST_FORMAT_TEXT_MASK;
07168    }
07169 
07170    /* Set the native formats for audio  and merge in video */
07171    tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | video | text;
07172    ast_debug(3, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, tmp->nativeformats));
07173    ast_debug(3, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->jointcapability));
07174    ast_debug(3, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->capability));
07175    ast_debug(3, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, ast_codec_choose(&i->prefs, what, 1)));
07176    if (i->prefcodec)
07177       ast_debug(3, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->prefcodec));
07178 
07179    /* XXX Why are we choosing a codec from the native formats?? */
07180    fmt = ast_best_codec(tmp->nativeformats);
07181 
07182    /* If we have a prefcodec setting, we have an inbound channel that set a
07183       preferred format for this call. Otherwise, we check the jointcapability
07184       We also check for vrtp. If it's not there, we are not allowed do any video anyway.
07185     */
07186    if (i->vrtp) {
07187       if (ast_test_flag(&i->flags[1], SIP_PAGE2_VIDEOSUPPORT))
07188          needvideo = AST_FORMAT_VIDEO_MASK;
07189       else if (i->prefcodec)
07190          needvideo = i->prefcodec & AST_FORMAT_VIDEO_MASK;  /* Outbound call */
07191       else
07192          needvideo = i->jointcapability & AST_FORMAT_VIDEO_MASK;  /* Inbound call */
07193    }
07194 
07195    if (i->trtp) {
07196       if (i->prefcodec)
07197          needtext = i->prefcodec & AST_FORMAT_TEXT_MASK; /* Outbound call */
07198       else
07199          needtext = i->jointcapability & AST_FORMAT_TEXT_MASK; /* Inbound call */
07200    }
07201 
07202    if (needvideo)
07203       ast_debug(3, "This channel can handle video! HOLLYWOOD next!\n");
07204    else
07205       ast_debug(3, "This channel will not be able to handle video.\n");
07206 
07207    enable_dsp_detect(i);
07208 
07209    if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
07210        (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
07211       if (i->rtp) {
07212          ast_rtp_instance_dtmf_mode_set(i->rtp, AST_RTP_DTMF_MODE_INBAND);
07213       }
07214    } else if (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) {
07215       if (i->rtp) {
07216          ast_rtp_instance_dtmf_mode_set(i->rtp, AST_RTP_DTMF_MODE_RFC2833);
07217       }
07218    }
07219 
07220    /* Set file descriptors for audio, video, and realtime text.  Since
07221     * UDPTL is created as needed in the lifetime of a dialog, its file
07222     * descriptor is set in initialize_udptl */
07223    if (i->rtp) {
07224       ast_channel_set_fd(tmp, 0, ast_rtp_instance_fd(i->rtp, 0));
07225       ast_channel_set_fd(tmp, 1, ast_rtp_instance_fd(i->rtp, 1));
07226       ast_rtp_instance_set_write_format(i->rtp, fmt);
07227       ast_rtp_instance_set_read_format(i->rtp, fmt);
07228    }
07229    if (needvideo && i->vrtp) {
07230       ast_channel_set_fd(tmp, 2, ast_rtp_instance_fd(i->vrtp, 0));
07231       ast_channel_set_fd(tmp, 3, ast_rtp_instance_fd(i->vrtp, 1));
07232    }
07233    if (needtext && i->trtp) {
07234       ast_channel_set_fd(tmp, 4, ast_rtp_instance_fd(i->trtp, 0));
07235    }
07236    if (i->udptl) {
07237       ast_channel_set_fd(tmp, 5, ast_udptl_fd(i->udptl));
07238    }
07239 
07240    if (state == AST_STATE_RING)
07241       tmp->rings = 1;
07242    tmp->adsicpe = AST_ADSI_UNAVAILABLE;
07243 
07244    tmp->writeformat = fmt;
07245    tmp->rawwriteformat = fmt;
07246 
07247    tmp->readformat = fmt;
07248    tmp->rawreadformat = fmt;
07249 
07250    tmp->tech_pvt = dialog_ref(i, "sip_new: set chan->tech_pvt to i");
07251 
07252    tmp->callgroup = i->callgroup;
07253    tmp->pickupgroup = i->pickupgroup;
07254    tmp->caller.id.name.presentation = i->callingpres;
07255    tmp->caller.id.number.presentation = i->callingpres;
07256    if (!ast_strlen_zero(i->parkinglot))
07257       ast_string_field_set(tmp, parkinglot, i->parkinglot);
07258    if (!ast_strlen_zero(i->accountcode))
07259       ast_string_field_set(tmp, accountcode, i->accountcode);
07260    if (i->amaflags)
07261       tmp->amaflags = i->amaflags;
07262    if (!ast_strlen_zero(i->language))
07263       ast_string_field_set(tmp, language, i->language);
07264    i->owner = tmp;
07265    ast_module_ref(ast_module_info->self);
07266    ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
07267    /*Since it is valid to have extensions in the dialplan that have unescaped characters in them
07268     * we should decode the uri before storing it in the channel, but leave it encoded in the sip_pvt
07269     * structure so that there aren't issues when forming URI's
07270     */
07271    exten = ast_strdupa(i->exten);
07272    sip_pvt_unlock(i);
07273    ast_channel_unlock(tmp);
07274    if (!ast_exists_extension(NULL, i->context, i->exten, 1, i->cid_num)) {
07275       ast_uri_decode(exten);
07276    }
07277    ast_channel_lock(tmp);
07278    sip_pvt_lock(i);
07279    ast_copy_string(tmp->exten, exten, sizeof(tmp->exten));
07280 
07281    /* Don't use ast_set_callerid() here because it will
07282     * generate an unnecessary NewCallerID event  */
07283    if (!ast_strlen_zero(i->cid_num)) {
07284       tmp->caller.ani.number.valid = 1;
07285       tmp->caller.ani.number.str = ast_strdup(i->cid_num);
07286    }
07287    if (!ast_strlen_zero(i->rdnis)) {
07288       tmp->redirecting.from.number.valid = 1;
07289       tmp->redirecting.from.number.str = ast_strdup(i->rdnis);
07290    }
07291 
07292    if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s")) {
07293       tmp->dialed.number.str = ast_strdup(i->exten);
07294    }
07295 
07296    tmp->priority = 1;
07297    if (!ast_strlen_zero(i->uri))
07298       pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
07299    if (!ast_strlen_zero(i->domain))
07300       pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
07301    if (!ast_strlen_zero(i->callid))
07302       pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
07303    if (i->rtp)
07304       ast_jb_configure(tmp, &global_jbconf);
07305 
07306    /* Set channel variables for this call from configuration */
07307    for (v = i->chanvars ; v ; v = v->next) {
07308       char valuebuf[1024];
07309       pbx_builtin_setvar_helper(tmp, v->name, ast_get_encoded_str(v->value, valuebuf, sizeof(valuebuf)));
07310    }
07311 
07312    if (i->do_history)
07313       append_history(i, "NewChan", "Channel %s - from %s", tmp->name, i->callid);
07314 
07315    /* Inform manager user about new channel and their SIP call ID */
07316    if (sip_cfg.callevents)
07317       manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
07318          "Channel: %s\r\nUniqueid: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\n",
07319          tmp->name, tmp->uniqueid, "SIP", i->callid, i->fullcontact);
07320 
07321    return tmp;
07322 }
07323 
07324 /*! \brief Reads one line of SIP message body */
07325 static char *get_body_by_line(const char *line, const char *name, int nameLen, char delimiter)
07326 {
07327    if (!strncasecmp(line, name, nameLen) && line[nameLen] == delimiter)
07328       return ast_skip_blanks(line + nameLen + 1);
07329 
07330    return "";
07331 }
07332 
07333 /*! \brief Lookup 'name' in the SDP starting
07334  * at the 'start' line. Returns the matching line, and 'start'
07335  * is updated with the next line number.
07336  */
07337 static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
07338 {
07339    int len = strlen(name);
07340 
07341    while (*start < (req->sdp_start + req->sdp_count)) {
07342       const char *r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[(*start)++]), name, len, '=');
07343       if (r[0] != '\0')
07344          return r;
07345    }
07346 
07347    /* if the line was not found, ensure that *start points past the SDP */
07348    (*start)++;
07349 
07350    return "";
07351 }
07352 
07353 /*! \brief Fetches the next valid SDP line between the 'start' line
07354  * (inclusive) and the 'stop' line (exclusive). Returns the type
07355  * ('a', 'c', ...) and matching line in reference 'start' is updated
07356  * with the next line number.
07357  */
07358 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value)
07359 {
07360    char type = '\0';
07361    const char *line = NULL;
07362 
07363    if (stop > (req->sdp_start + req->sdp_count)) {
07364       stop = req->sdp_start + req->sdp_count;
07365    }
07366 
07367    while (*start < stop) {
07368       line = REQ_OFFSET_TO_STR(req, line[(*start)++]);
07369       if (line[1] == '=') {
07370          type = line[0];
07371          *value = ast_skip_blanks(line + 2);
07372          break;
07373       }
07374    }
07375 
07376    return type;
07377 }
07378 
07379 /*! \brief Get a specific line from the message body */
07380 static char *get_body(struct sip_request *req, char *name, char delimiter)
07381 {
07382    int x;
07383    int len = strlen(name);
07384    char *r;
07385 
07386    for (x = 0; x < req->lines; x++) {
07387       r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[x]), name, len, delimiter);
07388       if (r[0] != '\0')
07389          return r;
07390    }
07391 
07392    return "";
07393 }
07394 
07395 /*! \brief Find compressed SIP alias */
07396 static const char *find_alias(const char *name, const char *_default)
07397 {
07398    /*! \brief Structure for conversion between compressed SIP and "normal" SIP */
07399    static const struct cfalias {
07400       char * const fullname;
07401       char * const shortname;
07402    } aliases[] = {
07403       { "Content-Type",  "c" },
07404       { "Content-Encoding",    "e" },
07405       { "From",       "f" },
07406       { "Call-ID",       "i" },
07407       { "Contact",       "m" },
07408       { "Content-Length",   "l" },
07409       { "Subject",       "s" },
07410       { "To",         "t" },
07411       { "Supported",     "k" },
07412       { "Refer-To",      "r" },
07413       { "Referred-By",   "b" },
07414       { "Allow-Events",  "u" },
07415       { "Event",      "o" },
07416       { "Via",     "v" },
07417       { "Accept-Contact",      "a" },
07418       { "Reject-Contact",      "j" },
07419       { "Request-Disposition", "d" },
07420       { "Session-Expires",     "x" },
07421       { "Identity",            "y" },
07422       { "Identity-Info",       "n" },
07423    };
07424    int x;
07425 
07426    for (x = 0; x < ARRAY_LEN(aliases); x++) {
07427       if (!strcasecmp(aliases[x].fullname, name))
07428          return aliases[x].shortname;
07429    }
07430 
07431    return _default;
07432 }
07433 
07434 static const char *__get_header(const struct sip_request *req, const char *name, int *start)
07435 {
07436    /*
07437     * Technically you can place arbitrary whitespace both before and after the ':' in
07438     * a header, although RFC3261 clearly says you shouldn't before, and place just
07439     * one afterwards.  If you shouldn't do it, what absolute idiot decided it was
07440     * a good idea to say you can do it, and if you can do it, why in the hell would.
07441     * you say you shouldn't.
07442     * Anyways, pedanticsipchecking controls whether we allow spaces before ':',
07443     * and we always allow spaces after that for compatibility.
07444     */
07445    const char *sname = find_alias(name, NULL);
07446    int x, len = strlen(name), slen = (sname ? 1 : 0);
07447    for (x = *start; x < req->headers; x++) {
07448       const char *header = REQ_OFFSET_TO_STR(req, header[x]);
07449       int smatch = 0, match = !strncasecmp(header, name, len);
07450       if (slen) {
07451          smatch = !strncasecmp(header, sname, slen);
07452       }
07453       if (match || smatch) {
07454          /* skip name */
07455          const char *r = header + (match ? len : slen );
07456          if (sip_cfg.pedanticsipchecking) {
07457             r = ast_skip_blanks(r);
07458          }
07459 
07460          if (*r == ':') {
07461             *start = x+1;
07462             return ast_skip_blanks(r+1);
07463          }
07464       }
07465    }
07466 
07467    /* Don't return NULL, so get_header is always a valid pointer */
07468    return "";
07469 }
07470 
07471 /*! \brief Get header from SIP request
07472    \return Always return something, so don't check for NULL because it won't happen :-)
07473 */
07474 static const char *get_header(const struct sip_request *req, const char *name)
07475 {
07476    int start = 0;
07477    return __get_header(req, name, &start);
07478 }
07479 
07480 /*! \brief Read RTP from network */
07481 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
07482 {
07483    /* Retrieve audio/etc from channel.  Assumes p->lock is already held. */
07484    struct ast_frame *f;
07485    
07486    if (!p->rtp) {
07487       /* We have no RTP allocated for this channel */
07488       return &ast_null_frame;
07489    }
07490 
07491    switch(ast->fdno) {
07492    case 0:
07493       f = ast_rtp_instance_read(p->rtp, 0);  /* RTP Audio */
07494       break;
07495    case 1:
07496       f = ast_rtp_instance_read(p->rtp, 1);  /* RTCP Control Channel */
07497       break;
07498    case 2:
07499       f = ast_rtp_instance_read(p->vrtp, 0); /* RTP Video */
07500       break;
07501    case 3:
07502       f = ast_rtp_instance_read(p->vrtp, 1); /* RTCP Control Channel for video */
07503       break;
07504    case 4:
07505       f = ast_rtp_instance_read(p->trtp, 0); /* RTP Text */
07506       if (sipdebug_text) {
07507          int i;
07508          unsigned char* arr = f->data.ptr;
07509          for (i=0; i < f->datalen; i++)
07510             ast_verbose("%c", (arr[i] > ' ' && arr[i] < '}') ? arr[i] : '.');
07511          ast_verbose(" -> ");
07512          for (i=0; i < f->datalen; i++)
07513             ast_verbose("%02X ", arr[i]);
07514          ast_verbose("\n");
07515       }
07516       break;
07517    case 5:
07518       f = ast_udptl_read(p->udptl); /* UDPTL for T.38 */
07519       break;
07520    default:
07521       f = &ast_null_frame;
07522    }
07523    /* Don't forward RFC2833 if we're not supposed to */
07524    if (f && (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) &&
07525        (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833)) {
07526       ast_debug(1, "Ignoring DTMF (%c) RTP frame because dtmfmode is not RFC2833\n", f->subclass.integer);
07527       ast_frfree(f);
07528       return &ast_null_frame;
07529    }
07530 
07531    /* We already hold the channel lock */
07532    if (!p->owner || (f && f->frametype != AST_FRAME_VOICE))
07533       return f;
07534 
07535    if (f && f->subclass.codec != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
07536       if (!(f->subclass.codec & p->jointcapability)) {
07537          ast_debug(1, "Bogus frame of format '%s' received from '%s'!\n",
07538             ast_getformatname(f->subclass.codec), p->owner->name);
07539          ast_frfree(f);
07540          return &ast_null_frame;
07541       }
07542       ast_debug(1, "Oooh, format changed to %s\n",
07543          ast_getformatname(f->subclass.codec));
07544       p->owner->nativeformats = (p->owner->nativeformats & (AST_FORMAT_VIDEO_MASK | AST_FORMAT_TEXT_MASK)) | f->subclass.codec;
07545       ast_set_read_format(p->owner, p->owner->readformat);
07546       ast_set_write_format(p->owner, p->owner->writeformat);
07547    }
07548 
07549    if (f && p->dsp) {
07550       f = ast_dsp_process(p->owner, p->dsp, f);
07551       if (f && f->frametype == AST_FRAME_DTMF) {
07552          if (f->subclass.integer == 'f') {
07553             ast_debug(1, "Fax CNG detected on %s\n", ast->name);
07554             *faxdetect = 1;
07555             /* If we only needed this DSP for fax detection purposes we can just drop it now */
07556             if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
07557                ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
07558             } else {
07559                ast_dsp_free(p->dsp);
07560                p->dsp = NULL;
07561             }
07562          } else {
07563             ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass.integer);
07564          }
07565       }
07566    }
07567 
07568    return f;
07569 }
07570 
07571 /*! \brief Read SIP RTP from channel */
07572 static struct ast_frame *sip_read(struct ast_channel *ast)
07573 {
07574    struct ast_frame *fr;
07575    struct sip_pvt *p = ast->tech_pvt;
07576    int faxdetected = FALSE;
07577 
07578    sip_pvt_lock(p);
07579    fr = sip_rtp_read(ast, p, &faxdetected);
07580    p->lastrtprx = time(NULL);
07581 
07582    /* If we detect a CNG tone and fax detection is enabled then send us off to the fax extension */
07583    if (faxdetected && ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_CNG)) {
07584       if (strcmp(ast->exten, "fax")) {
07585          const char *target_context = S_OR(ast->macrocontext, ast->context);
07586          /* We need to unlock 'ast' here because
07587           * ast_exists_extension has the potential to start and
07588           * stop an autoservice on the channel. Such action is
07589           * prone to deadlock if the channel is locked.
07590           */
07591          sip_pvt_unlock(p);
07592          ast_channel_unlock(ast);
07593          if (ast_exists_extension(ast, target_context, "fax", 1,
07594             S_COR(ast->caller.id.number.valid, ast->caller.id.number.str, NULL))) {
07595             ast_channel_lock(ast);
07596             sip_pvt_lock(p);
07597             ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to CNG detection\n", ast->name);
07598             pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast->exten);
07599             if (ast_async_goto(ast, target_context, "fax", 1)) {
07600                ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast->name, target_context);
07601             }
07602             ast_frfree(fr);
07603             fr = &ast_null_frame;
07604          } else {
07605             ast_channel_lock(ast);
07606             sip_pvt_lock(p);
07607             ast_log(LOG_NOTICE, "FAX CNG detected but no fax extension\n");
07608          }
07609       }
07610    }
07611 
07612    /* Only allow audio through if they sent progress with SDP, or if the channel is actually answered */
07613    if (fr && fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast->_state != AST_STATE_UP) {
07614       ast_frfree(fr);
07615       fr = &ast_null_frame;
07616    }
07617 
07618    sip_pvt_unlock(p);
07619 
07620    return fr;
07621 }
07622 
07623 
07624 /*! \brief Generate 32 byte random string for callid's etc */
07625 static char *generate_random_string(char *buf, size_t size)
07626 {
07627    long val[4];
07628    int x;
07629 
07630    for (x=0; x<4; x++)
07631       val[x] = ast_random();
07632    snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
07633 
07634    return buf;
07635 }
07636 
07637 static char *generate_uri(struct sip_pvt *pvt, char *buf, size_t size)
07638 {
07639    struct ast_str *uri = ast_str_alloca(size);
07640    ast_str_set(&uri, 0, "%s", pvt->socket.type == SIP_TRANSPORT_TLS ? "sips:" : "sip:");
07641    /* Here would be a great place to generate a UUID, but for now we'll
07642     * use the handy random string generation function we already have
07643     */
07644    ast_str_append(&uri, 0, "%s", generate_random_string(buf, size));
07645    ast_str_append(&uri, 0, "@%s", ast_sockaddr_stringify_remote(&pvt->ourip));
07646    ast_copy_string(buf, ast_str_buffer(uri), size);
07647    return buf;
07648 }
07649 
07650 /*!
07651  * \brief Build SIP Call-ID value for a non-REGISTER transaction
07652  *
07653  * \note The passed in pvt must not be in a dialogs container
07654  * since this function changes the hash key used by the
07655  * container.
07656  */
07657 static void build_callid_pvt(struct sip_pvt *pvt)
07658 {
07659    char buf[33];
07660    const char *host = S_OR(pvt->fromdomain, ast_sockaddr_stringify_remote(&pvt->ourip));
07661 
07662    ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
07663 }
07664 
07665 /*! \brief Unlink the given object from the container and return TRUE if it was in the container. */
07666 #define CONTAINER_UNLINK(container, obj, tag)                        \
07667    ({                                                    \
07668       int found = 0;                                        \
07669       typeof((obj)) __removed_obj;                             \
07670       __removed_obj = ao2_t_callback((container),                    \
07671          OBJ_UNLINK | OBJ_POINTER, ao2_match_by_addr, (obj), (tag));    \
07672       if (__removed_obj) {                                  \
07673          ao2_ref(__removed_obj, -1);                              \
07674          found = 1;                                         \
07675       }                                                  \
07676       found;                                                \
07677    })
07678 
07679 /*!
07680  * \internal
07681  * \brief Safely change the callid of the given SIP dialog.
07682  *
07683  * \param pvt SIP private structure to change callid
07684  * \param callid Specified new callid to use.  NULL if generate new callid.
07685  *
07686  * \return Nothing
07687  */
07688 static void change_callid_pvt(struct sip_pvt *pvt, const char *callid)
07689 {
07690    int in_dialog_container;
07691 
07692    ao2_lock(dialogs);
07693    in_dialog_container = CONTAINER_UNLINK(dialogs, pvt,
07694       "About to change the callid -- remove the old name");
07695    if (callid) {
07696       ast_string_field_set(pvt, callid, callid);
07697    } else {
07698       build_callid_pvt(pvt);
07699    }
07700    if (in_dialog_container) {
07701       ao2_t_link(dialogs, pvt, "New dialog callid -- inserted back into table");
07702    }
07703    ao2_unlock(dialogs);
07704 }
07705 
07706 /*! \brief Build SIP Call-ID value for a REGISTER transaction */
07707 static void build_callid_registry(struct sip_registry *reg, const struct ast_sockaddr *ourip, const char *fromdomain)
07708 {
07709    char buf[33];
07710 
07711    const char *host = S_OR(fromdomain, ast_sockaddr_stringify_host_remote(ourip));
07712 
07713    ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
07714 }
07715 
07716 /*! \brief Make our SIP dialog tag */
07717 static void make_our_tag(struct sip_pvt *pvt)
07718 {
07719    ast_string_field_build(pvt, tag, "as%08lx", ast_random());
07720 }
07721 
07722 /*! \brief Allocate Session-Timers struct w/in dialog */
07723 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p)
07724 {
07725    struct sip_st_dlg *stp;
07726 
07727    if (p->stimer) {
07728       ast_log(LOG_ERROR, "Session-Timer struct already allocated\n");
07729       return p->stimer;
07730    }
07731 
07732    if (!(stp = ast_calloc(1, sizeof(struct sip_st_dlg))))
07733       return NULL;
07734 
07735    p->stimer = stp;
07736 
07737    stp->st_schedid = -1;           /* Session-Timers ast_sched scheduler id */
07738 
07739    return p->stimer;
07740 }
07741 
07742 /*! \brief Allocate sip_pvt structure, set defaults and link in the container.
07743  * Returns a reference to the object so whoever uses it later must
07744  * remember to release the reference.
07745  */
07746 struct sip_pvt *sip_alloc(ast_string_field callid, struct ast_sockaddr *addr,
07747              int useglobal_nat, const int intended_method, struct sip_request *req)
07748 {
07749    struct sip_pvt *p;
07750 
07751    if (!(p = ao2_t_alloc(sizeof(*p), sip_destroy_fn, "allocate a dialog(pvt) struct")))
07752       return NULL;
07753 
07754    if (ast_string_field_init(p, 512)) {
07755       ao2_t_ref(p, -1, "failed to string_field_init, drop p");
07756       return NULL;
07757    }
07758 
07759    if (!(p->cc_params = ast_cc_config_params_init())) {
07760       ao2_t_ref(p, -1, "Yuck, couldn't allocate cc_params struct. Get rid o' p");
07761       return NULL;
07762    }
07763 
07764    /* If this dialog is created as the result of an incoming Request. Lets store
07765     * some information about that request */
07766    if (req) {
07767       struct sip_via *via;
07768       const char *cseq = get_header(req, "Cseq");
07769       uint32_t seqno;
07770 
07771       /* get branch parameter from initial Request that started this dialog */
07772       via = parse_via(get_header(req, "Via"));
07773       if (via) {
07774          /* only store the branch if it begins with the magic prefix "z9hG4bK", otherwise
07775           * it is not useful to us to have it */
07776          if (!ast_strlen_zero(via->branch) && !strncasecmp(via->branch, "z9hG4bK", 7)) {
07777             ast_string_field_set(p, initviabranch, via->branch);
07778             ast_string_field_set(p, initviasentby, via->sent_by);
07779          }
07780          free_via(via);
07781       }
07782 
07783       /* Store initial incoming cseq. An error in sscanf here is ignored.  There is no approperiate
07784        * except not storing the number.  CSeq validation must take place before dialog creation in find_call */
07785       if (!ast_strlen_zero(cseq) && (sscanf(cseq, "%30u", &seqno) == 1)) {
07786          p->init_icseq = seqno;
07787       }
07788       /* Later in ast_sip_ouraddrfor we need this to choose the right ip and port for the specific transport */
07789       set_socket_transport(&p->socket, req->socket.type);
07790    } else {
07791       set_socket_transport(&p->socket, SIP_TRANSPORT_UDP);
07792    }
07793 
07794    p->socket.fd = -1;
07795    p->method = intended_method;
07796    p->initid = -1;
07797    p->waitid = -1;
07798    p->reinviteid = -1;
07799    p->autokillid = -1;
07800    p->request_queue_sched_id = -1;
07801    p->provisional_keepalive_sched_id = -1;
07802    p->t38id = -1;
07803    p->subscribed = NONE;
07804    p->stateid = -1;
07805    p->sessionversion_remote = -1;
07806    p->session_modify = TRUE;
07807    p->stimer = NULL;
07808    p->prefs = default_prefs;     /* Set default codecs for this call */
07809    p->maxforwards = sip_cfg.default_max_forwards;
07810 
07811    if (intended_method != SIP_OPTIONS) {  /* Peerpoke has it's own system */
07812       p->timer_t1 = global_t1;   /* Default SIP retransmission timer T1 (RFC 3261) */
07813       p->timer_b = global_timer_b;  /* Default SIP transaction timer B (RFC 3261) */
07814    }
07815 
07816    if (!addr) {
07817       p->ourip = internip;
07818    } else {
07819       ast_sockaddr_copy(&p->sa, addr);
07820       ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
07821    }
07822 
07823    /* Copy global flags to this PVT at setup. */
07824    ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
07825    ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
07826    ast_copy_flags(&p->flags[2], &global_flags[2], SIP_PAGE3_FLAGS_TO_COPY);
07827 
07828    p->do_history = recordhistory;
07829 
07830    p->branch = ast_random();  
07831    make_our_tag(p);
07832    p->ocseq = INITIAL_CSEQ;
07833    p->allowed_methods = UINT_MAX;
07834 
07835    if (sip_methods[intended_method].need_rtp) {
07836       p->maxcallbitrate = default_maxcallbitrate;
07837       p->autoframing = global_autoframing;
07838    }
07839 
07840    if (useglobal_nat && addr) {
07841       /* Setup NAT structure according to global settings if we have an address */
07842       ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT_FORCE_RPORT);
07843       ast_sockaddr_copy(&p->recv, addr);
07844 
07845       do_setnat(p);
07846    }
07847 
07848    if (p->method != SIP_REGISTER) {
07849       ast_string_field_set(p, fromdomain, default_fromdomain);
07850       p->fromdomainport = default_fromdomainport;
07851    }
07852    build_via(p);
07853    if (!callid)
07854       build_callid_pvt(p);
07855    else
07856       ast_string_field_set(p, callid, callid);
07857    /* Assign default music on hold class */
07858    ast_string_field_set(p, mohinterpret, default_mohinterpret);
07859    ast_string_field_set(p, mohsuggest, default_mohsuggest);
07860    p->capability = sip_cfg.capability;
07861    p->allowtransfer = sip_cfg.allowtransfer;
07862    if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
07863        (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
07864       p->noncodeccapability |= AST_RTP_DTMF;
07865    }
07866    ast_string_field_set(p, context, sip_cfg.default_context);
07867    ast_string_field_set(p, parkinglot, default_parkinglot);
07868    ast_string_field_set(p, engine, default_engine);
07869 
07870    AST_LIST_HEAD_INIT_NOLOCK(&p->request_queue);
07871 
07872    /* Add to active dialog list */
07873 
07874    ao2_t_link(dialogs, p, "link pvt into dialogs table");
07875    
07876    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");
07877    return p;
07878 }
07879 
07880 /*!
07881  * \brief Check if an ip is an multicast IP.
07882  * \parm addr the address to check
07883  *
07884  * This function checks if an address is in the 224.0.0.0/4 network block.
07885  * \return non-zero if this is a multicast address
07886  */
07887 static int addr_is_multicast(const struct ast_sockaddr *addr)
07888 {
07889    return ((ast_sockaddr_ipv4(addr) & 0xf0000000) == 0xe0000000);
07890 }
07891 
07892 /*!
07893  * \brief Process the Via header according to RFC 3261 section 18.2.2.
07894  * \param p a sip_pvt structure that will be modified according to the received
07895  * header
07896  * \param req a sip request with a Via header to process
07897  *
07898  * This function will update the destination of the response according to the
07899  * Via header in the request and RFC 3261 section 18.2.2. We do not have a
07900  * transport layer so we ignore certain values like the 'received' param (we
07901  * set the destination address to the addres the request came from in the
07902  * respprep() function).
07903  *
07904  * \retval -1 error
07905  * \retval 0 success
07906  */
07907 static int process_via(struct sip_pvt *p, const struct sip_request *req)
07908 {
07909    struct sip_via *via = parse_via(get_header(req, "Via"));
07910 
07911    if (!via) {
07912       ast_log(LOG_ERROR, "error processing via header\n");
07913       return -1;
07914    }
07915 
07916    if (via->maddr) {
07917       if (ast_sockaddr_resolve_first_transport(&p->sa, via->maddr, PARSE_PORT_FORBID, p->socket.type)) {
07918          ast_log(LOG_WARNING, "Can't find address for maddr '%s'\n", via->maddr);
07919          ast_log(LOG_ERROR, "error processing via header\n");
07920          free_via(via);
07921          return -1;
07922       }
07923 
07924       if (addr_is_multicast(&p->sa)) {
07925          setsockopt(sipsock, IPPROTO_IP, IP_MULTICAST_TTL, &via->ttl, sizeof(via->ttl));
07926       }
07927    }
07928 
07929    ast_sockaddr_set_port(&p->sa, via->port ? via->port : STANDARD_SIP_PORT);
07930 
07931    free_via(via);
07932    return 0;
07933 }
07934 
07935 /* \brief arguments used for Request/Response to matching */
07936 struct match_req_args {
07937    int method;
07938    const char *callid;
07939    const char *totag;
07940    const char *fromtag;
07941    uint32_t seqno;
07942 
07943    /* Set if the method is a Request */
07944    const char *ruri;
07945    const char *viabranch;
07946    const char *viasentby;
07947 
07948    /* Set this if the Authentication header is present in the Request. */
07949    int authentication_present;
07950 };
07951 
07952 enum match_req_res {
07953    SIP_REQ_MATCH,
07954    SIP_REQ_NOT_MATCH,
07955    SIP_REQ_LOOP_DETECTED,
07956 };
07957 
07958 /*
07959  * \brief Match a incoming Request/Response to a dialog
07960  *
07961  * \retval enum match_req_res indicating if the dialog matches the arg
07962  */
07963 static enum match_req_res match_req_to_dialog(struct sip_pvt *sip_pvt_ptr, struct match_req_args *arg)
07964 {
07965    const char *init_ruri = NULL;
07966    if (sip_pvt_ptr->initreq.headers) {
07967       init_ruri = REQ_OFFSET_TO_STR(&sip_pvt_ptr->initreq, rlPart2);
07968    }
07969 
07970    /*
07971     * Match Tags and call-id to Dialog
07972     */
07973    if (!ast_strlen_zero(arg->callid) && strcmp(sip_pvt_ptr->callid, arg->callid)) {
07974       /* call-id does not match. */
07975       return SIP_REQ_NOT_MATCH;
07976    }
07977    if (arg->method == SIP_RESPONSE) {
07978       /* Verify totag if we have one stored for this dialog, but never be strict about this for
07979        * a response until the dialog is established */
07980       if (!ast_strlen_zero(sip_pvt_ptr->theirtag) && ast_test_flag(&sip_pvt_ptr->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
07981          if (ast_strlen_zero(arg->totag)) {
07982             /* missing totag when they already gave us one earlier */
07983             return SIP_REQ_NOT_MATCH;
07984          }
07985          if (strcmp(arg->totag, sip_pvt_ptr->theirtag)) {
07986             /* The totag of the response does not match the one we have stored */
07987             return SIP_REQ_NOT_MATCH;
07988          }
07989       }
07990       /* Verify fromtag of response matches the tag we gave them. */
07991       if (strcmp(arg->fromtag, sip_pvt_ptr->tag)) {
07992          /* fromtag from response does not match our tag */
07993          return SIP_REQ_NOT_MATCH;
07994       }
07995    } else {
07996       /* Verify the fromtag of Request matches the tag they provided earlier.
07997        * If this is a Request with authentication credentials, forget their old
07998        * tag as it is not valid after the 401 or 407 response. */
07999       if (!arg->authentication_present && strcmp(arg->fromtag, sip_pvt_ptr->theirtag)) {
08000          /* their tag does not match the one was have stored for them */
08001          return SIP_REQ_NOT_MATCH;
08002       }
08003       /* Verify if totag is present in Request, that it matches what we gave them as our tag earlier */
08004       if (!ast_strlen_zero(arg->totag) && (strcmp(arg->totag, sip_pvt_ptr->tag))) {
08005          /* totag from Request does not match our tag */
08006          return SIP_REQ_NOT_MATCH;
08007       }
08008    }
08009 
08010    /*
08011     * Compare incoming request against initial transaction.
08012     * 
08013     * This is a best effort attempt at distinguishing forked requests from
08014     * our initial transaction.  If all the elements are NOT in place to evaluate
08015     * this, this block is ignored and the dialog match is made regardless.
08016     * Once the totag is established after the dialog is confirmed, this is not necessary.
08017     *
08018     * CRITERIA required for initial transaction matching.
08019     * 
08020     * 1. Is a Request
08021     * 2. Callid and theirtag match (this is done in the dialog matching block)
08022     * 3. totag is NOT present
08023     * 4. CSeq matchs our initial transaction's cseq number
08024     * 5. pvt has init via branch parameter stored
08025     */
08026    if ((arg->method != SIP_RESPONSE) &&                 /* must be a Request */
08027       ast_strlen_zero(arg->totag) &&                   /* must not have a totag */
08028       (sip_pvt_ptr->init_icseq == arg->seqno) &&       /* the cseq must be the same as this dialogs initial cseq */
08029       !ast_strlen_zero(sip_pvt_ptr->initviabranch) &&  /* The dialog must have started with a RFC3261 compliant branch tag */
08030       init_ruri) {                                     /* the dialog must have an initial request uri associated with it */
08031       /* This Request matches all the criteria required for Loop/Merge detection.
08032        * Now we must go down the path of comparing VIA's and RURIs. */
08033       if (ast_strlen_zero(arg->viabranch) ||
08034          strcmp(arg->viabranch, sip_pvt_ptr->initviabranch) ||
08035          ast_strlen_zero(arg->viasentby) ||
08036          strcmp(arg->viasentby, sip_pvt_ptr->initviasentby)) {
08037          /* At this point, this request does not match this Dialog.*/
08038 
08039          /* if methods are different this is just a mismatch */
08040          if ((sip_pvt_ptr->method != arg->method)) {
08041             return SIP_REQ_NOT_MATCH;
08042          }
08043 
08044          /* If RUIs are different, this is a forked request to a separate URI.
08045           * Returning a mismatch allows this Request to be processed separately. */
08046          if (sip_uri_cmp(init_ruri, arg->ruri)) {
08047             /* not a match, request uris are different */
08048             return SIP_REQ_NOT_MATCH;
08049          }
08050 
08051          /* Loop/Merge Detected
08052           *
08053           * ---Current Matches to Initial Request---
08054           * request uri
08055           * Call-id
08056           * their-tag
08057           * no totag present
08058           * method
08059           * cseq
08060           *
08061           * --- Does not Match Initial Request ---
08062           * Top Via
08063           *
08064           * Without the same Via, this can not match our initial transaction for this dialog,
08065           * but given that this Request matches everything else associated with that initial
08066           * Request this is most certainly a Forked request in which we have already received
08067           * part of the fork.
08068           */
08069          return SIP_REQ_LOOP_DETECTED;
08070       }
08071    } /* end of Request Via check */
08072 
08073    /* Match Authentication Request.
08074     *
08075     * A Request with an Authentication header must come back with the
08076     * same Request URI.  Otherwise it is not a match.
08077     */
08078    if ((arg->method != SIP_RESPONSE) &&      /* Must be a Request type to even begin checking this */
08079       ast_strlen_zero(arg->totag) &&        /* no totag is present to match */
08080       arg->authentication_present &&        /* Authentication header is present in Request */
08081       sip_uri_cmp(init_ruri, arg->ruri)) {  /* Compare the Request URI of both the last Request and this new one */
08082 
08083       /* Authentication was provided, but the Request URI did not match the last one on this dialog. */
08084       return SIP_REQ_NOT_MATCH;
08085    }
08086 
08087    return SIP_REQ_MATCH;
08088 }
08089 
08090 /*! \internal
08091  *
08092  * \brief Locks both pvt and pvt owner if owner is present.
08093  *
08094  * \note This function gives a ref to pvt->owner if it is present and locked.
08095  *       This reference must be decremented after pvt->owner is unlocked.
08096  *
08097  * \note This function will never give you up,
08098  * \note This function will never let you down.
08099  * \note This function will run around and desert you.
08100  *
08101  * \pre pvt is not locked
08102  * \post pvt is locked
08103  * \post pvt->owner is locked and its reference count is increased (if pvt->owner is not NULL)
08104  *
08105  * \returns a pointer to the locked and reffed pvt->owner channel if it exists.
08106  */
08107 static struct ast_channel *sip_pvt_lock_full(struct sip_pvt *pvt)
08108 {
08109    struct ast_channel *chan;
08110 
08111    /* Locking is simple when it is done right.  If you see a deadlock resulting
08112     * in this function, it is not this function's fault, Your problem exists elsewhere.
08113     * This function is perfect... seriously. */
08114    for (;;) {
08115       /* First, get the channel and grab a reference to it */
08116       sip_pvt_lock(pvt);
08117       chan = pvt->owner;
08118       if (chan) {
08119          /* The channel can not go away while we hold the pvt lock.
08120           * Give the channel a ref so it will not go away after we let
08121           * the pvt lock go. */
08122          ast_channel_ref(chan);
08123       } else {
08124          /* no channel, return pvt locked */
08125          return NULL;
08126       }
08127 
08128       /* We had to hold the pvt lock while getting a ref to the owner channel
08129        * but now we have to let this lock go in order to preserve proper
08130        * locking order when grabbing the channel lock */
08131       sip_pvt_unlock(pvt);
08132 
08133       /* Look, no deadlock avoidance, hooray! */
08134       ast_channel_lock(chan);
08135       sip_pvt_lock(pvt);
08136 
08137       if (pvt->owner == chan) {
08138          /* done */
08139          break;
08140       }
08141 
08142       /* If the owner changed while everything was unlocked, no problem,
08143        * just start over and everthing will work.  This is rare, do not be
08144        * confused by this loop and think this it is an expensive operation.
08145        * The majority of the calls to this function will never involve multiple
08146        * executions of this loop. */
08147       ast_channel_unlock(chan);
08148       ast_channel_unref(chan);
08149       sip_pvt_unlock(pvt);
08150    }
08151 
08152    /* If owner exists, it is locked and reffed */
08153    return pvt->owner;
08154 }
08155 
08156 /*! \brief find or create a dialog structure for an incoming SIP message.
08157  * Connect incoming SIP message to current dialog or create new dialog structure
08158  * Returns a reference to the sip_pvt object, remember to give it back once done.
08159  *     Called by handle_request_do
08160  */
08161 static struct sip_pvt *find_call(struct sip_request *req, struct ast_sockaddr *addr, const int intended_method)
08162 {
08163    char totag[128];
08164    char fromtag[128];
08165    const char *callid = get_header(req, "Call-ID");
08166    const char *from = get_header(req, "From");
08167    const char *to = get_header(req, "To");
08168    const char *cseq = get_header(req, "Cseq");
08169    struct sip_pvt *sip_pvt_ptr;
08170    uint32_t seqno;
08171    /* Call-ID, to, from and Cseq are required by RFC 3261. (Max-forwards and via too - ignored now) */
08172    /* get_header always returns non-NULL so we must use ast_strlen_zero() */
08173    if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
08174          ast_strlen_zero(from) || ast_strlen_zero(cseq) ||
08175          (sscanf(cseq, "%30u", &seqno) != 1)) {
08176 
08177       /* RFC 3261 section 24.4.1.   Send a 400 Bad Request if the request is malformed. */
08178       if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
08179          transmit_response_using_temp(callid, addr, 1, intended_method,
08180                        req, "400 Bad Request");
08181       }
08182       return NULL;   /* Invalid packet */
08183    }
08184 
08185    if (sip_cfg.pedanticsipchecking) {
08186       /* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
08187          we need more to identify a branch - so we have to check branch, from
08188          and to tags to identify a call leg.
08189          For Asterisk to behave correctly, you need to turn on pedanticsipchecking
08190          in sip.conf
08191          */
08192       if (gettag(req, "To", totag, sizeof(totag)))
08193          req->has_to_tag = 1; /* Used in handle_request/response */
08194       gettag(req, "From", fromtag, sizeof(fromtag));
08195 
08196       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);
08197 
08198       /* All messages must always have From: tag */
08199       if (ast_strlen_zero(fromtag)) {
08200          ast_debug(5, "%s request has no from tag, dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
08201          return NULL;
08202       }
08203       /* reject requests that must always have a To: tag */
08204       if (ast_strlen_zero(totag) && (req->method == SIP_ACK || req->method == SIP_BYE || req->method == SIP_INFO )) {
08205          ast_debug(5, "%s must have a to tag. dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
08206          return NULL;
08207       }
08208    }
08209 
08210    if (!sip_cfg.pedanticsipchecking) {
08211       struct sip_pvt tmp_dialog = {
08212          .callid = callid,
08213       };
08214       sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find in dialogs");
08215       if (sip_pvt_ptr) {  /* well, if we don't find it-- what IS in there? */
08216          /* Found the call */
08217          return sip_pvt_ptr;
08218       }
08219    } else { /* in pedantic mode! -- do the fancy search */
08220       struct sip_pvt tmp_dialog = {
08221          .callid = callid,
08222       };
08223       struct match_req_args args = { 0, };
08224       int found;
08225       struct ao2_iterator *iterator = ao2_t_callback(dialogs,
08226          OBJ_POINTER | OBJ_MULTIPLE,
08227          dialog_find_multiple,
08228          &tmp_dialog,
08229          "pedantic ao2_find in dialogs");
08230       struct sip_via *via = NULL;
08231 
08232       args.method = req->method;
08233       args.callid = NULL; /* we already matched this. */
08234       args.totag = totag;
08235       args.fromtag = fromtag;
08236       args.seqno = seqno;
08237 
08238       /* If this is a Request, set the Via and Authorization header arguments */
08239       if (req->method != SIP_RESPONSE) {
08240          args.ruri = REQ_OFFSET_TO_STR(req, rlPart2);
08241          via = parse_via(get_header(req, "Via"));
08242          if (via) {
08243             args.viasentby = via->sent_by;
08244             args.viabranch = via->branch;
08245          }
08246          if (!ast_strlen_zero(get_header(req, "Authorization")) ||
08247             !ast_strlen_zero(get_header(req, "Proxy-Authorization"))) {
08248             args.authentication_present = 1;
08249          }
08250       }
08251 
08252       /* Iterate a list of dialogs already matched by Call-id */
08253       while (iterator && (sip_pvt_ptr = ao2_iterator_next(iterator))) {
08254          sip_pvt_lock(sip_pvt_ptr);
08255          found = match_req_to_dialog(sip_pvt_ptr, &args);
08256          sip_pvt_unlock(sip_pvt_ptr);
08257 
08258          switch (found) {
08259          case SIP_REQ_MATCH:
08260             ao2_iterator_destroy(iterator);
08261             free_via(via);
08262             return sip_pvt_ptr; /* return pvt with ref */
08263          case SIP_REQ_LOOP_DETECTED:
08264             /* This is likely a forked Request that somehow resulted in us receiving multiple parts of the fork.
08265             * RFC 3261 section 8.2.2.2, Indicate that we want to merge requests by sending a 482 response. */
08266             transmit_response_using_temp(callid, addr, 1, intended_method, req, "482 (Loop Detected)");
08267             dialog_unref(sip_pvt_ptr, "pvt did not match incoming SIP msg, unref from search.");
08268             ao2_iterator_destroy(iterator);
08269             free_via(via);
08270             return NULL;
08271          case SIP_REQ_NOT_MATCH:
08272          default:
08273             dialog_unref(sip_pvt_ptr, "pvt did not match incoming SIP msg, unref from search");
08274             break;
08275          }
08276       }
08277       if (iterator) {
08278          ao2_iterator_destroy(iterator);
08279       }
08280 
08281       free_via(via);
08282    } /* end of pedantic mode Request/Reponse to Dialog matching */
08283 
08284    /* See if the method is capable of creating a dialog */
08285    if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
08286       struct sip_pvt *p = NULL;
08287 
08288       if (intended_method == SIP_REFER) {
08289          /* We do support REFER, but not outside of a dialog yet */
08290          transmit_response_using_temp(callid, addr, 1, intended_method, req, "603 Declined (no dialog)");
08291    
08292       /* Ok, time to create a new SIP dialog object, a pvt */
08293       } else if (!(p = sip_alloc(callid, addr, 1, intended_method, req)))  {
08294          /* We have a memory or file/socket error (can't allocate RTP sockets or something) so we're not
08295             getting a dialog from sip_alloc.
08296 
08297             Without a dialog we can't retransmit and handle ACKs and all that, but at least
08298             send an error message.
08299 
08300             Sorry, we apologize for the inconvienience
08301          */
08302          transmit_response_using_temp(callid, addr, 1, intended_method, req, "500 Server internal error");
08303          ast_debug(4, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
08304       }
08305       return p; /* can be NULL */
08306    } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
08307       /* A method we do not support, let's take it on the volley */
08308       transmit_response_using_temp(callid, addr, 1, intended_method, req, "501 Method Not Implemented");
08309       ast_debug(2, "Got a request with unsupported SIP method.\n");
08310    } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
08311       /* This is a request outside of a dialog that we don't know about */
08312       transmit_response_using_temp(callid, addr, 1, intended_method, req, "481 Call leg/transaction does not exist");
08313       ast_debug(2, "That's odd...  Got a request in unknown dialog. Callid %s\n", callid ? callid : "<unknown>");
08314    }
08315    /* We do not respond to responses for dialogs that we don't know about, we just drop
08316       the session quickly */
08317    if (intended_method == SIP_RESPONSE)
08318       ast_debug(2, "That's odd...  Got a response on a call we don't know about. Callid %s\n", callid ? callid : "<unknown>");
08319 
08320    return NULL;
08321 }
08322 
08323 /*! \brief create sip_registry object from register=> line in sip.conf and link into reg container */
08324 static int sip_register(const char *value, int lineno)
08325 {
08326    struct sip_registry *reg;
08327 
08328    if (!(reg = ast_calloc_with_stringfields(1, struct sip_registry, 256))) {
08329       ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
08330       return -1;
08331    }
08332 
08333    ast_atomic_fetchadd_int(&regobjs, 1);
08334    ASTOBJ_INIT(reg);
08335 
08336    if (sip_parse_register_line(reg, default_expiry, value, lineno)) {
08337       registry_unref(reg, "failure to parse, unref the reg pointer");
08338       return -1;
08339    }
08340 
08341    /* set default expiry if necessary */
08342    if (reg->refresh && !reg->expiry && !reg->configured_expiry) {
08343       reg->refresh = reg->expiry = reg->configured_expiry = default_expiry;
08344    }
08345 
08346    /* Add the new registry entry to the list */
08347    ASTOBJ_CONTAINER_LINK(&regl, reg);
08348 
08349    /* release the reference given by ASTOBJ_INIT. The container has another reference */
08350    registry_unref(reg, "unref the reg pointer");
08351 
08352    return 0;
08353 }
08354 
08355 /*! \brief Parse mwi=> line in sip.conf and add to list */
08356 static int sip_subscribe_mwi(const char *value, int lineno)
08357 {
08358    struct sip_subscription_mwi *mwi;
08359    int portnum = 0;
08360    enum sip_transport transport = SIP_TRANSPORT_UDP;
08361    char buf[256] = "";
08362    char *username = NULL, *hostname = NULL, *secret = NULL, *authuser = NULL, *porta = NULL, *mailbox = NULL;
08363 
08364    if (!value) {
08365       return -1;
08366    }
08367 
08368    ast_copy_string(buf, value, sizeof(buf));
08369 
08370    username = buf;
08371 
08372    if ((hostname = strrchr(buf, '@'))) {
08373       *hostname++ = '\0';
08374    } else {
08375       return -1;
08376    }
08377 
08378    if ((secret = strchr(username, ':'))) {
08379       *secret++ = '\0';
08380       if ((authuser = strchr(secret, ':'))) {
08381          *authuser++ = '\0';
08382       }
08383    }
08384 
08385    if ((mailbox = strchr(hostname, '/'))) {
08386       *mailbox++ = '\0';
08387    }
08388 
08389    if (ast_strlen_zero(username) || ast_strlen_zero(hostname) || ast_strlen_zero(mailbox)) {
08390       ast_log(LOG_WARNING, "Format for MWI subscription is user[:secret[:authuser]]@host[:port]/mailbox at line %d\n", lineno);
08391       return -1;
08392    }
08393 
08394    if ((porta = strchr(hostname, ':'))) {
08395       *porta++ = '\0';
08396       if (!(portnum = atoi(porta))) {
08397          ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
08398          return -1;
08399       }
08400    }
08401 
08402    if (!(mwi = ast_calloc_with_stringfields(1, struct sip_subscription_mwi, 256))) {
08403       return -1;
08404    }
08405 
08406    ASTOBJ_INIT(mwi);
08407    ast_string_field_set(mwi, username, username);
08408    if (secret) {
08409       ast_string_field_set(mwi, secret, secret);
08410    }
08411    if (authuser) {
08412       ast_string_field_set(mwi, authuser, authuser);
08413    }
08414    ast_string_field_set(mwi, hostname, hostname);
08415    ast_string_field_set(mwi, mailbox, mailbox);
08416    mwi->resub = -1;
08417    mwi->portno = portnum;
08418    mwi->transport = transport;
08419 
08420    ASTOBJ_CONTAINER_LINK(&submwil, mwi);
08421    ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
08422 
08423    return 0;
08424 }
08425 
08426 static void mark_method_allowed(unsigned int *allowed_methods, enum sipmethod method)
08427 {
08428    (*allowed_methods) |= (1 << method);
08429 }
08430 
08431 static void mark_method_unallowed(unsigned int *allowed_methods, enum sipmethod method)
08432 {
08433    (*allowed_methods) &= ~(1 << method);
08434 }
08435 
08436 /*! \brief Check if method is allowed for a device or a dialog */
08437 static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method)
08438 {
08439    return ((*allowed_methods) >> method) & 1;
08440 }
08441 
08442 static void mark_parsed_methods(unsigned int *methods, char *methods_str)
08443 {
08444    char *method;
08445    for (method = strsep(&methods_str, ","); !ast_strlen_zero(method); method = strsep(&methods_str, ",")) {
08446       int id = find_sip_method(ast_skip_blanks(method));
08447       if (id == SIP_UNKNOWN) {
08448          continue;
08449       }
08450       mark_method_allowed(methods, id);
08451    }
08452 }
08453 /*!
08454  * \brief parse the Allow header to see what methods the endpoint we
08455  * are communicating with allows.
08456  *
08457  * We parse the allow header on incoming Registrations and save the
08458  * result to the SIP peer that is registering. When the registration
08459  * expires, we clear what we know about the peer's allowed methods.
08460  * When the peer re-registers, we once again parse to see if the
08461  * list of allowed methods has changed.
08462  *
08463  * For peers that do not register, we parse the first message we receive
08464  * during a call to see what is allowed, and save the information
08465  * for the duration of the call.
08466  * \param req The SIP request we are parsing
08467  * \retval The methods allowed
08468  */
08469 static unsigned int parse_allowed_methods(struct sip_request *req)
08470 {
08471    char *allow = ast_strdupa(get_header(req, "Allow"));
08472    unsigned int allowed_methods = SIP_UNKNOWN;
08473 
08474    if (ast_strlen_zero(allow)) {
08475       /* I have witnessed that REGISTER requests from Polycom phones do not
08476        * place the phone's allowed methods in an Allow header. Instead, they place the
08477        * allowed methods in a methods= parameter in the Contact header.
08478        */
08479       char *contact = ast_strdupa(get_header(req, "Contact"));
08480       char *methods = strstr(contact, ";methods=");
08481 
08482       if (ast_strlen_zero(methods)) {
08483          /* RFC 3261 states:
08484           *
08485           * "The absence of an Allow header field MUST NOT be
08486           * interpreted to mean that the UA sending the message supports no
08487           * methods.   Rather, it implies that the UA is not providing any
08488           * information on what methods it supports."
08489           *
08490           * For simplicity, we'll assume that the peer allows all known
08491           * SIP methods if they have no Allow header. We can then clear out the necessary
08492           * bits if the peer lets us know that we have sent an unsupported method.
08493           */
08494          return UINT_MAX;
08495       }
08496       allow = ast_strip_quoted(methods + 9, "\"", "\"");
08497    }
08498    mark_parsed_methods(&allowed_methods, allow);
08499    return allowed_methods;
08500 }
08501 
08502 /*! A wrapper for parse_allowed_methods geared toward sip_pvts
08503  *
08504  * This function, in addition to setting the allowed methods for a sip_pvt
08505  * also will take into account the setting of the SIP_PAGE2_RPID_UPDATE flag.
08506  *
08507  * \param pvt The sip_pvt we are setting the allowed_methods for
08508  * \param req The request which we are parsing
08509  * \retval The methods alloweded by the sip_pvt
08510  */
08511 static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req)
08512 {
08513    pvt->allowed_methods = parse_allowed_methods(req);
08514    
08515    if (ast_test_flag(&pvt->flags[1], SIP_PAGE2_RPID_UPDATE)) {
08516       mark_method_allowed(&pvt->allowed_methods, SIP_UPDATE);
08517    }
08518    pvt->allowed_methods &= ~(pvt->disallowed_methods);
08519 
08520    return pvt->allowed_methods;
08521 }
08522 
08523 /*! \brief  Parse multiline SIP headers into one header
08524    This is enabled if pedanticsipchecking is enabled */
08525 static void lws2sws(struct ast_str *data)
08526 {
08527    char *msgbuf = data->str;
08528    int len = ast_str_strlen(data);
08529    int h = 0, t = 0;
08530    int lws = 0;
08531 
08532    for (; h < len;) {
08533       /* Eliminate all CRs */
08534       if (msgbuf[h] == '\r') {
08535          h++;
08536          continue;
08537       }
08538       /* Check for end-of-line */
08539       if (msgbuf[h] == '\n') {
08540          /* Check for end-of-message */
08541          if (h + 1 == len)
08542             break;
08543          /* Check for a continuation line */
08544          if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') {
08545             /* Merge continuation line */
08546             h++;
08547             continue;
08548          }
08549          /* Propagate LF and start new line */
08550          msgbuf[t++] = msgbuf[h++];
08551          lws = 0;
08552          continue;
08553       }
08554       if (msgbuf[h] == ' ' || msgbuf[h] == '\t') {
08555          if (lws) {
08556             h++;
08557             continue;
08558          }
08559          msgbuf[t++] = msgbuf[h++];
08560          lws = 1;
08561          continue;
08562       }
08563       msgbuf[t++] = msgbuf[h++];
08564       if (lws)
08565          lws = 0;
08566    }
08567    msgbuf[t] = '\0';
08568    data->used = t;
08569 }
08570 
08571 /*! \brief Parse a SIP message
08572    \note this function is used both on incoming and outgoing packets
08573 */
08574 static int parse_request(struct sip_request *req)
08575 {
08576    char *c = req->data->str;
08577    ptrdiff_t *dst = req->header;
08578    int i = 0, lim = SIP_MAX_HEADERS - 1;
08579    unsigned int skipping_headers = 0;
08580    ptrdiff_t current_header_offset = 0;
08581    char *previous_header = "";
08582 
08583    req->header[0] = 0;
08584    req->headers = -1;   /* mark that we are working on the header */
08585    for (; *c; c++) {
08586       if (*c == '\r') {    /* remove \r */
08587          *c = '\0';
08588       } else if (*c == '\n') {   /* end of this line */
08589          *c = '\0';
08590          current_header_offset = (c + 1) - req->data->str;
08591          previous_header = req->data->str + dst[i];
08592          if (skipping_headers) {
08593             /* check to see if this line is blank; if so, turn off
08594                the skipping flag, so the next line will be processed
08595                as a body line */
08596             if (ast_strlen_zero(previous_header)) {
08597                skipping_headers = 0;
08598             }
08599             dst[i] = current_header_offset; /* record start of next line */
08600             continue;
08601          }
08602          if (sipdebug) {
08603             ast_debug(4, "%7s %2d [%3d]: %s\n",
08604                  req->headers < 0 ? "Header" : "Body",
08605                  i, (int) strlen(previous_header), previous_header);
08606          }
08607          if (ast_strlen_zero(previous_header) && req->headers < 0) {
08608             req->headers = i; /* record number of header lines */
08609             dst = req->line;  /* start working on the body */
08610             i = 0;
08611             lim = SIP_MAX_LINES - 1;
08612          } else { /* move to next line, check for overflows */
08613             if (i++ == lim) {
08614                /* if we're processing headers, then skip any remaining
08615                   headers and move on to processing the body, otherwise
08616                   we're done */
08617                if (req->headers != -1) {
08618                   break;
08619                } else {
08620                   req->headers = i;
08621                   dst = req->line;
08622                   i = 0;
08623                   lim = SIP_MAX_LINES - 1;
08624                   skipping_headers = 1;
08625                }
08626             }
08627          }
08628          dst[i] = current_header_offset; /* record start of next line */
08629       }
08630    }
08631 
08632    /* Check for last header or body line without CRLF. The RFC for SDP requires CRLF,
08633       but since some devices send without, we'll be generous in what we accept. However,
08634       if we've already reached the maximum number of lines for portion of the message
08635       we were parsing, we can't accept any more, so just ignore it.
08636    */
08637    previous_header = req->data->str + dst[i];
08638    if ((i < lim) && !ast_strlen_zero(previous_header)) {
08639       if (sipdebug) {
08640          ast_debug(4, "%7s %2d [%3d]: %s\n",
08641               req->headers < 0 ? "Header" : "Body",
08642               i, (int) strlen(previous_header), previous_header );
08643       }
08644       i++;
08645    }
08646 
08647    /* update count of header or body lines */
08648    if (req->headers >= 0) {   /* we are in the body */
08649       req->lines = i;
08650    } else {       /* no body */
08651       req->headers = i;
08652       req->lines = 0;
08653       /* req->data->used will be a NULL byte */
08654       req->line[0] = ast_str_strlen(req->data);
08655    }
08656 
08657    if (*c) {
08658       ast_log(LOG_WARNING, "Too many lines, skipping <%s>\n", c);
08659    }
08660 
08661    /* Split up the first line parts */
08662    return determine_firstline_parts(req);
08663 }
08664 
08665 /*!
08666   \brief Determine whether a SIP message contains an SDP in its body
08667   \param req the SIP request to process
08668   \return 1 if SDP found, 0 if not found
08669 
08670   Also updates req->sdp_start and req->sdp_count to indicate where the SDP
08671   lives in the message body.
08672 */
08673 static int find_sdp(struct sip_request *req)
08674 {
08675    const char *content_type;
08676    const char *content_length;
08677    const char *search;
08678    char *boundary;
08679    unsigned int x;
08680    int boundaryisquoted = FALSE;
08681    int found_application_sdp = FALSE;
08682    int found_end_of_headers = FALSE;
08683 
08684    content_length = get_header(req, "Content-Length");
08685 
08686    if (!ast_strlen_zero(content_length)) {
08687       if (sscanf(content_length, "%30u", &x) != 1) {
08688          ast_log(LOG_WARNING, "Invalid Content-Length: %s\n", content_length);
08689          return 0;
08690       }
08691 
08692       /* Content-Length of zero means there can't possibly be an
08693          SDP here, even if the Content-Type says there is */
08694       if (x == 0)
08695          return 0;
08696    }
08697 
08698    content_type = get_header(req, "Content-Type");
08699 
08700    /* if the body contains only SDP, this is easy */
08701    if (!strncasecmp(content_type, "application/sdp", 15)) {
08702       req->sdp_start = 0;
08703       req->sdp_count = req->lines;
08704       return req->lines ? 1 : 0;
08705    }
08706 
08707    /* if it's not multipart/mixed, there cannot be an SDP */
08708    if (strncasecmp(content_type, "multipart/mixed", 15))
08709       return 0;
08710 
08711    /* if there is no boundary marker, it's invalid */
08712    if ((search = strcasestr(content_type, ";boundary=")))
08713       search += 10;
08714    else if ((search = strcasestr(content_type, "; boundary=")))
08715       search += 11;
08716    else
08717       return 0;
08718 
08719    if (ast_strlen_zero(search))
08720       return 0;
08721 
08722    /* If the boundary is quoted with ", remove quote */
08723    if (*search == '\"')  {
08724       search++;
08725       boundaryisquoted = TRUE;
08726    }
08727 
08728    /* make a duplicate of the string, with two extra characters
08729       at the beginning */
08730    boundary = ast_strdupa(search - 2);
08731    boundary[0] = boundary[1] = '-';
08732    /* Remove final quote */
08733    if (boundaryisquoted)
08734       boundary[strlen(boundary) - 1] = '\0';
08735 
08736    /* search for the boundary marker, the empty line delimiting headers from
08737       sdp part and the end boundry if it exists */
08738 
08739    for (x = 0; x < (req->lines); x++) {
08740       const char *line = REQ_OFFSET_TO_STR(req, line[x]);
08741       if (!strncasecmp(line, boundary, strlen(boundary))){
08742          if (found_application_sdp && found_end_of_headers) {
08743             req->sdp_count = (x - 1) - req->sdp_start;
08744             return 1;
08745          }
08746          found_application_sdp = FALSE;
08747       }
08748       if (!strcasecmp(line, "Content-Type: application/sdp"))
08749          found_application_sdp = TRUE;
08750       
08751       if (ast_strlen_zero(line)) {
08752          if (found_application_sdp && !found_end_of_headers){
08753             req->sdp_start = x;
08754             found_end_of_headers = TRUE;
08755          }
08756       }
08757    }
08758    if (found_application_sdp && found_end_of_headers) {
08759       req->sdp_count = x - req->sdp_start;
08760       return TRUE;
08761    }
08762    return FALSE;
08763 }
08764 
08765 /*! \brief Change hold state for a call */
08766 static void change_hold_state(struct sip_pvt *dialog, struct sip_request *req, int holdstate, int sendonly)
08767 {
08768    if (sip_cfg.notifyhold && (!holdstate || !ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD)))
08769       sip_peer_hold(dialog, holdstate);
08770    if (sip_cfg.callevents)
08771       manager_event(EVENT_FLAG_CALL, "Hold",
08772                "Status: %s\r\n"
08773                "Channel: %s\r\n"
08774                "Uniqueid: %s\r\n",
08775                holdstate ? "On" : "Off",
08776                dialog->owner->name,
08777                dialog->owner->uniqueid);
08778    append_history(dialog, holdstate ? "Hold" : "Unhold", "%s", req->data->str);
08779    if (!holdstate) { /* Put off remote hold */
08780       ast_clear_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD);   /* Clear both flags */
08781       return;
08782    }
08783    /* No address for RTP, we're on hold */
08784 
08785    /* Ensure hold flags are cleared so that overlapping flags do not conflict */
08786    ast_clear_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD);
08787 
08788    if (sendonly == 1)   /* One directional hold (sendonly/recvonly) */
08789       ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
08790    else if (sendonly == 2) /* Inactive stream */
08791       ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
08792    else
08793       ast_set_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
08794    return;
08795 }
08796 
08797 
08798 static int get_ip_and_port_from_sdp(struct sip_request *req, const enum media_type media, struct ast_sockaddr *addr)
08799 {
08800    const char *m;
08801    const char *c;
08802    int miterator = req->sdp_start;
08803    int citerator = req->sdp_start;
08804    int x = 0;
08805    int numberofports;
08806    int len;
08807    int af;
08808    char proto[4], host[258] = ""; /*Initialize to empty so we will know if we have any input */
08809 
08810    c = get_sdp_iterate(&citerator, req, "c");
08811    if (sscanf(c, "IN %3s %256s", proto, host) != 2) {
08812          ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
08813          /* Continue since there may be a valid host in a c= line specific to the audio stream */
08814    }
08815    /* We only want the m and c lines for audio */
08816    for (m = get_sdp_iterate(&miterator, req, "m"); !ast_strlen_zero(m); m = get_sdp_iterate(&miterator, req, "m")) {
08817       if ((media == SDP_AUDIO && ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08818           (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0))) ||
08819          (media == SDP_VIDEO && ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
08820           (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len > 0)))) {
08821          /* See if there's a c= line for this media stream.
08822           * XXX There is no guarantee that we'll be grabbing the c= line for this
08823           * particular media stream here. However, this is the same logic used in process_sdp.
08824           */
08825          c = get_sdp_iterate(&citerator, req, "c");
08826          if (!ast_strlen_zero(c)) {
08827             sscanf(c, "IN %3s %256s", proto, host);
08828          }
08829          break;
08830       }
08831    }
08832 
08833    if (!strcmp("IP4", proto)) {
08834       af = AF_INET;
08835    } else if (!strcmp("IP6", proto)) {
08836       af = AF_INET6;
08837    } else {
08838       ast_log(LOG_WARNING, "Unknown protocol '%s'.\n", proto);
08839       return -1;
08840    }
08841 
08842    if (ast_strlen_zero(host) || x == 0) {
08843       ast_log(LOG_WARNING, "Failed to read an alternate host or port in SDP. Expect %s problems\n", media == SDP_AUDIO ? "audio" : "video");
08844       return -1;
08845    }
08846 
08847    if (ast_sockaddr_resolve_first_af(addr, host, 0, af)) {
08848       ast_log(LOG_WARNING, "Could not look up IP address of alternate hostname. Expect %s problems\n", media == SDP_AUDIO? "audio" : "video");
08849       return -1;
08850    }
08851 
08852    return 0;
08853 }
08854 
08855 /*! \internal
08856  * \brief Returns whether or not the address is null or ANY / unspecified (0.0.0.0 or ::)
08857  * \retval TRUE if the address is null or any
08858  * \retval FALSE if the address it not null or any
08859  * \note In some circumstances, calls should be placed on hold if either of these conditions exist.
08860  */
08861 static int sockaddr_is_null_or_any(const struct ast_sockaddr *addr)
08862 {
08863    return ast_sockaddr_isnull(addr) || ast_sockaddr_is_any(addr);
08864 }
08865 
08866 /*! \brief Process SIP SDP offer, select formats and activate media channels
08867    If offer is rejected, we will not change any properties of the call
08868    Return 0 on success, a negative value on errors.
08869    Must be called after find_sdp().
08870 */
08871 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
08872 {
08873    /* Iterators for SDP parsing */
08874    int start = req->sdp_start;
08875    int next = start;
08876    int iterator = start;
08877 
08878    /* Temporary vars for SDP parsing */
08879    char type = '\0';
08880    const char *value = NULL;
08881    const char *m = NULL;           /* SDP media offer */
08882    const char *nextm = NULL;
08883    int len = -1;
08884 
08885    /* Host information */
08886    struct ast_sockaddr sessionsa;
08887    struct ast_sockaddr audiosa;
08888    struct ast_sockaddr videosa;
08889    struct ast_sockaddr textsa;
08890    struct ast_sockaddr imagesa;
08891    struct ast_sockaddr *sa = NULL;     /*!< RTP audio destination IP address */
08892    struct ast_sockaddr *vsa = NULL; /*!< RTP video destination IP address */
08893    struct ast_sockaddr *tsa = NULL; /*!< RTP text destination IP address */
08894    struct ast_sockaddr *isa = NULL; /*!< UDPTL image destination IP address */
08895    int portno = -1;        /*!< RTP audio destination port number */
08896    int vportno = -1;       /*!< RTP video destination port number */
08897    int tportno = -1;       /*!< RTP text destination port number */
08898    int udptlportno = -1;         /*!< UDPTL image destination port number */
08899 
08900    /* Peer capability is the capability in the SDP, non codec is RFC2833 DTMF (101) */
08901    format_t peercapability = 0, vpeercapability = 0, tpeercapability = 0;
08902    int peernoncodeccapability = 0, vpeernoncodeccapability = 0, tpeernoncodeccapability = 0;
08903 
08904    struct ast_rtp_codecs newaudiortp, newvideortp, newtextrtp;
08905    format_t newjointcapability;           /* Negotiated capability */
08906    format_t newpeercapability;
08907    int newnoncodeccapability;
08908 
08909    const char *codecs;
08910    int codec;
08911 
08912    /* SRTP */
08913    int secure_audio = FALSE;
08914    int secure_video = FALSE;
08915 
08916    /* Others */
08917    int sendonly = -1;
08918    int numberofports;
08919    int numberofmediastreams = 0;
08920    int last_rtpmap_codec = 0;
08921    int red_data_pt[10];    /* For T.140 RED */
08922    int red_num_gen = 0;    /* For T.140 RED */
08923    char red_fmtp[100] = "empty"; /* For T.140 RED */
08924    int debug = sip_debug_test_pvt(p);
08925 
08926    /* START UNKNOWN */
08927    char buf[SIPBUFSIZE];
08928    /* END UNKNOWN */
08929 
08930    /* Initial check */
08931    if (!p->rtp) {
08932       ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
08933       return -1;
08934    }
08935 
08936    /* Make sure that the codec structures are all cleared out */
08937    ast_rtp_codecs_payloads_clear(&newaudiortp, NULL);
08938    ast_rtp_codecs_payloads_clear(&newvideortp, NULL);
08939    ast_rtp_codecs_payloads_clear(&newtextrtp, NULL);
08940 
08941    /* Update our last rtprx when we receive an SDP, too */
08942    p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
08943 
08944    memset(p->offered_media, 0, sizeof(p->offered_media));
08945 
08946    /* default: novideo and notext set */
08947    p->novideo = TRUE;
08948    p->notext = TRUE;
08949 
08950    /* Scan for the first media stream (m=) line to limit scanning of globals */
08951    nextm = get_sdp_iterate(&next, req, "m");
08952    if (ast_strlen_zero(nextm)) {
08953       ast_log(LOG_WARNING, "Insufficient information for SDP (m= not found)\n");
08954       return -1;
08955    }
08956 
08957    /* Scan session level SDP parameters (lines before first media stream) */
08958    while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
08959       int processed = FALSE;
08960       switch (type) {
08961       case 'o':
08962          /* If we end up receiving SDP that doesn't actually modify the session we don't want to treat this as a fatal
08963           * error. We just want to ignore the SDP and let the rest of the packet be handled as normal.
08964           */
08965          if (!process_sdp_o(value, p))
08966             return (p->session_modify == FALSE) ? 0 : -1;
08967          break;
08968       case 'c':
08969          if (process_sdp_c(value, &sessionsa)) {
08970             processed = TRUE;
08971             sa = &sessionsa;
08972             vsa = sa;
08973             tsa = sa;
08974             isa = sa;
08975          }
08976          break;
08977       case 'a':
08978          if (process_sdp_a_sendonly(value, &sendonly)) {
08979             processed = TRUE;
08980          }
08981          else if (process_sdp_a_audio(value, p, &newaudiortp, &last_rtpmap_codec))
08982             processed = TRUE;
08983          else if (process_sdp_a_video(value, p, &newvideortp, &last_rtpmap_codec))
08984             processed = TRUE;
08985          else if (process_sdp_a_text(value, p, &newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
08986             processed = TRUE;
08987          else if (process_sdp_a_image(value, p))
08988             processed = TRUE;
08989          break;
08990       }
08991 
08992       ast_debug(3, "Processing session-level SDP %c=%s... %s\n", type, value, (processed == TRUE)? "OK." : "UNSUPPORTED OR FAILED.");
08993    }
08994 
08995    /* Scan media stream (m=) specific parameters loop */
08996    while (!ast_strlen_zero(nextm)) {
08997       int audio = FALSE;
08998       int video = FALSE;
08999       int image = FALSE;
09000       int text = FALSE;
09001       int processed_crypto = FALSE;
09002       char protocol[5] = {0,};
09003       int x;
09004 
09005       numberofports = 0;
09006       len = -1;
09007       start = next;
09008       m = nextm;
09009       iterator = next;
09010       nextm = get_sdp_iterate(&next, req, "m");
09011 
09012       /* Check for 'audio' media offer */
09013       if (strncmp(m, "audio ", 6) == 0) {
09014          if ((sscanf(m, "audio %30u/%30u RTP/%4s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||
09015              (sscanf(m, "audio %30u RTP/%4s %n", &x, protocol, &len) == 2 && len > 0)) {
09016             if (x == 0) {
09017                ast_log(LOG_WARNING, "Ignoring audio media offer because port number is zero\n");
09018                continue;
09019             }
09020 
09021             /* Check number of ports offered for stream */
09022             if (numberofports > 1) {
09023                ast_log(LOG_WARNING, "%d ports offered for audio media, not supported by Asterisk. Will try anyway...\n", numberofports);
09024             }
09025 
09026             if (!strcmp(protocol, "SAVP")) {
09027                secure_audio = 1;
09028             } else if (strcmp(protocol, "AVP")) {
09029                ast_log(LOG_WARNING, "Unknown RTP profile in audio offer: %s\n", m);
09030                continue;
09031             }
09032 
09033             if (p->offered_media[SDP_AUDIO].order_offered) {
09034                ast_log(LOG_WARNING, "Rejecting non-primary audio stream: %s\n", m);
09035                return -1;
09036             }
09037 
09038             audio = TRUE;
09039             p->offered_media[SDP_AUDIO].order_offered = ++numberofmediastreams;
09040             portno = x;
09041 
09042             /* Scan through the RTP payload types specified in a "m=" line: */
09043             codecs = m + len;
09044             ast_copy_string(p->offered_media[SDP_AUDIO].codecs, codecs, sizeof(p->offered_media[SDP_AUDIO].codecs));
09045             for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
09046                if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
09047                   ast_log(LOG_WARNING, "Invalid syntax in RTP audio format list: %s\n", codecs);
09048                   return -1;
09049                }
09050                if (debug) {
09051                   ast_verbose("Found RTP audio format %d\n", codec);
09052                }
09053 
09054                ast_rtp_codecs_payloads_set_m_type(&newaudiortp, NULL, codec);
09055             }
09056          } else {
09057             ast_log(LOG_WARNING, "Rejecting audio media offer due to invalid or unsupported syntax: %s\n", m);
09058             return -1;
09059          }
09060       }
09061       /* Check for 'video' media offer */
09062       else if (strncmp(m, "video ", 6) == 0) {
09063          if ((sscanf(m, "video %30u/%30u RTP/%4s %n", &x, &numberofports, protocol, &len) == 3 && len > 0) ||
09064              (sscanf(m, "video %30u RTP/%4s %n", &x, protocol, &len) == 2 && len > 0)) {
09065             if (x == 0) {
09066                ast_log(LOG_WARNING, "Ignoring video media offer because port number is zero\n");
09067                continue;
09068             }
09069 
09070             /* Check number of ports offered for stream */
09071             if (numberofports > 1) {
09072                ast_log(LOG_WARNING, "%d ports offered for video media, not supported by Asterisk. Will try anyway...\n", numberofports);
09073             }
09074 
09075             if (!strcmp(protocol, "SAVP")) {
09076                secure_video = 1;
09077             } else if (strcmp(protocol, "AVP")) {
09078                ast_log(LOG_WARNING, "Unknown RTP profile in video offer: %s\n", m);
09079                continue;
09080             }
09081 
09082             if (p->offered_media[SDP_VIDEO].order_offered) {
09083                ast_log(LOG_WARNING, "Rejecting non-primary video stream: %s\n", m);
09084                return -1;
09085             }
09086 
09087             video = TRUE;
09088             p->novideo = FALSE;
09089             p->offered_media[SDP_VIDEO].order_offered = ++numberofmediastreams;
09090             vportno = x;
09091 
09092             /* Scan through the RTP payload types specified in a "m=" line: */
09093             codecs = m + len;
09094             ast_copy_string(p->offered_media[SDP_VIDEO].codecs, codecs, sizeof(p->offered_media[SDP_VIDEO].codecs));
09095             for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
09096                if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
09097                   ast_log(LOG_WARNING, "Invalid syntax in RTP video format list: %s\n", codecs);
09098                   return -1;
09099                }
09100                if (debug) {
09101                   ast_verbose("Found RTP video format %d\n", codec);
09102                }
09103                ast_rtp_codecs_payloads_set_m_type(&newvideortp, NULL, codec);
09104             }
09105          } else {
09106             ast_log(LOG_WARNING, "Rejecting video media offer due to invalid or unsupported syntax: %s\n", m);
09107             return -1;
09108          }
09109       }
09110       /* Check for 'text' media offer */
09111       else if (strncmp(m, "text ", 5) == 0) {
09112          if ((sscanf(m, "text %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
09113              (sscanf(m, "text %30u RTP/AVP %n", &x, &len) == 1 && len > 0)) {
09114             if (x == 0) {
09115                ast_log(LOG_WARNING, "Ignoring text media offer because port number is zero\n");
09116                continue;
09117             }
09118 
09119             /* Check number of ports offered for stream */
09120             if (numberofports > 1) {
09121                ast_log(LOG_WARNING, "%d ports offered for text media, not supported by Asterisk. Will try anyway...\n", numberofports);
09122             }
09123 
09124             if (p->offered_media[SDP_TEXT].order_offered) {
09125                ast_log(LOG_WARNING, "Rejecting non-primary text stream: %s\n", m);
09126                return -1;
09127             }
09128 
09129             text = TRUE;
09130             p->notext = FALSE;
09131             p->offered_media[SDP_TEXT].order_offered = ++numberofmediastreams;
09132             tportno = x;
09133 
09134             /* Scan through the RTP payload types specified in a "m=" line: */
09135             codecs = m + len;
09136             ast_copy_string(p->offered_media[SDP_TEXT].codecs, codecs, sizeof(p->offered_media[SDP_TEXT].codecs));
09137             for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
09138                if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
09139                   ast_log(LOG_WARNING, "Invalid syntax in RTP video format list: %s\n", codecs);
09140                   return -1;
09141                }
09142                if (debug) {
09143                   ast_verbose("Found RTP text format %d\n", codec);
09144                }
09145                ast_rtp_codecs_payloads_set_m_type(&newtextrtp, NULL, codec);
09146             }
09147          } else {
09148             ast_log(LOG_WARNING, "Rejecting text media offer due to invalid or unsupported syntax: %s\n", m);
09149             return -1;
09150          }
09151       }
09152       /* Check for 'image' media offer */
09153       else if (strncmp(m, "image ", 6) == 0) {
09154          if (((sscanf(m, "image %30u udptl t38%n", &x, &len) == 1 && len > 0) ||
09155               (sscanf(m, "image %30u UDPTL t38%n", &x, &len) == 1 && len > 0))) {
09156             if (x == 0) {
09157                ast_log(LOG_WARNING, "Ignoring image media offer because port number is zero\n");
09158                continue;
09159             }
09160 
09161             if (initialize_udptl(p)) {
09162                ast_log(LOG_WARNING, "Rejecting offer with image stream due to UDPTL initialization failure\n");
09163                return -1;
09164             }
09165 
09166             if (p->offered_media[SDP_IMAGE].order_offered) {
09167                ast_log(LOG_WARNING, "Rejecting non-primary image stream: %s\n", m);
09168                return -1;
09169             }
09170 
09171             image = TRUE;
09172             if (debug) {
09173                ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
09174             }
09175 
09176             p->offered_media[SDP_IMAGE].order_offered = ++numberofmediastreams;
09177             udptlportno = x;
09178 
09179             if (p->t38.state != T38_ENABLED) {
09180                memset(&p->t38.their_parms, 0, sizeof(p->t38.their_parms));
09181 
09182                /* default EC to none, the remote end should
09183                 * respond with the EC they want to use */
09184                ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
09185             }
09186          } else {
09187             ast_log(LOG_WARNING, "Rejecting image media offer due to invalid or unsupported syntax: %s\n", m);
09188             return -1;
09189          }
09190       } else {
09191          ast_log(LOG_WARNING, "Unsupported top-level media type in offer: %s\n", m);
09192          continue;
09193       }
09194 
09195       /* Media stream specific parameters */
09196       while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
09197          int processed = FALSE;
09198 
09199          switch (type) {
09200          case 'c':
09201             if (audio) {
09202                if (process_sdp_c(value, &audiosa)) {
09203                   processed = TRUE;
09204                   sa = &audiosa;
09205                }
09206             } else if (video) {
09207                if (process_sdp_c(value, &videosa)) {
09208                   processed = TRUE;
09209                   vsa = &videosa;
09210                }
09211             } else if (text) {
09212                if (process_sdp_c(value, &textsa)) {
09213                   processed = TRUE;
09214                   tsa = &textsa;
09215                }
09216             } else if (image) {
09217                if (process_sdp_c(value, &imagesa)) {
09218                   processed = TRUE;
09219                   isa = &imagesa;
09220                }
09221             }
09222             break;
09223          case 'a':
09224             /* Audio specific scanning */
09225             if (audio) {
09226                if (process_sdp_a_sendonly(value, &sendonly)) {
09227                   processed = TRUE;
09228                } else if (!processed_crypto && process_crypto(p, p->rtp, &p->srtp, value)) {
09229                   processed_crypto = TRUE;
09230                   processed = TRUE;
09231                } else if (process_sdp_a_audio(value, p, &newaudiortp, &last_rtpmap_codec)) {
09232                   processed = TRUE;
09233                }
09234             }
09235             /* Video specific scanning */
09236             else if (video) {
09237                if (!processed_crypto && process_crypto(p, p->vrtp, &p->vsrtp, value)) {
09238                   processed_crypto = TRUE;
09239                   processed = TRUE;
09240                } else if (process_sdp_a_video(value, p, &newvideortp, &last_rtpmap_codec)) {
09241                   processed = TRUE;
09242                }
09243             }
09244             /* Text (T.140) specific scanning */
09245             else if (text) {
09246                if (process_sdp_a_text(value, p, &newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec)) {
09247                   processed = TRUE;
09248                } else if (!processed_crypto && process_crypto(p, p->trtp, &p->tsrtp, value)) {
09249                   processed_crypto = TRUE;
09250                   processed = TRUE;
09251                }
09252             }
09253             /* Image (T.38 FAX) specific scanning */
09254             else if (image) {
09255                if (process_sdp_a_image(value, p))
09256                   processed = TRUE;
09257             }
09258             break;
09259          }
09260 
09261          ast_debug(3, "Processing media-level (%s) SDP %c=%s... %s\n",
09262               (audio == TRUE)? "audio" : (video == TRUE)? "video" : (text == TRUE)? "text" : "image",
09263               type, value,
09264               (processed == TRUE)? "OK." : "UNSUPPORTED OR FAILED.");
09265       }
09266    }
09267 
09268    /* Sanity checks */
09269    if (!sa && !vsa && !tsa && !isa) {
09270       ast_log(LOG_WARNING, "Insufficient information in SDP (c=)...\n");
09271       return -1;
09272    }
09273 
09274    if ((portno == -1) &&
09275        (vportno == -1) &&
09276        (tportno == -1) &&
09277        (udptlportno == -1)) {
09278       ast_log(LOG_WARNING, "Failing due to no acceptable offer found\n");
09279       return -1;
09280    }
09281 
09282    if (secure_audio && !(p->srtp && (ast_test_flag(p->srtp, SRTP_CRYPTO_OFFER_OK)))) {
09283       ast_log(LOG_WARNING, "Can't provide secure audio requested in SDP offer\n");
09284       return -1;
09285    }
09286 
09287    if (!secure_audio && p->srtp) {
09288       ast_log(LOG_WARNING, "We are requesting SRTP for audio, but they responded without it!\n");
09289       return -1;
09290    }
09291 
09292    if (secure_video && !(p->vsrtp && (ast_test_flag(p->vsrtp, SRTP_CRYPTO_OFFER_OK)))) {
09293       ast_log(LOG_WARNING, "Can't provide secure video requested in SDP offer\n");
09294       return -1;
09295    }
09296 
09297    if (!p->novideo && !secure_video && p->vsrtp) {
09298       ast_log(LOG_WARNING, "We are requesting SRTP for video, but they responded without it!\n");
09299       return -1;
09300    }
09301 
09302    if (!(secure_audio || secure_video) && ast_test_flag(&p->flags[1], SIP_PAGE2_USE_SRTP)) {
09303       ast_log(LOG_WARNING, "Matched device setup to use SRTP, but request was not!\n");
09304       return -1;
09305    }
09306 
09307    if (udptlportno == -1) {
09308       change_t38_state(p, T38_DISABLED);
09309    }
09310 
09311    /* Now gather all of the codecs that we are asked for: */
09312    ast_rtp_codecs_payload_formats(&newaudiortp, &peercapability, &peernoncodeccapability);
09313    ast_rtp_codecs_payload_formats(&newvideortp, &vpeercapability, &vpeernoncodeccapability);
09314    ast_rtp_codecs_payload_formats(&newtextrtp, &tpeercapability, &tpeernoncodeccapability);
09315 
09316    newjointcapability = p->capability & (peercapability | vpeercapability | tpeercapability);
09317    newpeercapability = (peercapability | vpeercapability | tpeercapability);
09318    newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
09319 
09320    if (debug) {
09321       /* shame on whoever coded this.... */
09322       char s1[SIPBUFSIZE], s2[SIPBUFSIZE], s3[SIPBUFSIZE], s4[SIPBUFSIZE], s5[SIPBUFSIZE];
09323 
09324       ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s/text=%s, combined - %s\n",
09325              ast_getformatname_multiple(s1, SIPBUFSIZE, p->capability),
09326              ast_getformatname_multiple(s2, SIPBUFSIZE, peercapability),
09327              ast_getformatname_multiple(s3, SIPBUFSIZE, vpeercapability),
09328              ast_getformatname_multiple(s4, SIPBUFSIZE, tpeercapability),
09329              ast_getformatname_multiple(s5, SIPBUFSIZE, newjointcapability));
09330    }
09331    if (debug) {
09332       struct ast_str *s1 = ast_str_alloca(SIPBUFSIZE);
09333       struct ast_str *s2 = ast_str_alloca(SIPBUFSIZE);
09334       struct ast_str *s3 = ast_str_alloca(SIPBUFSIZE);
09335 
09336       ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
09337              ast_rtp_lookup_mime_multiple2(s1, p->noncodeccapability, 0, 0),
09338              ast_rtp_lookup_mime_multiple2(s2, peernoncodeccapability, 0, 0),
09339              ast_rtp_lookup_mime_multiple2(s3, newnoncodeccapability, 0, 0));
09340    }
09341    if (!newjointcapability && udptlportno == -1) {
09342       ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
09343       /* Do NOT Change current setting */
09344       return -1;
09345    }
09346 
09347    if (portno != -1 || vportno != -1 || tportno != -1) {
09348       /* We are now ready to change the sip session and RTP structures with the offered codecs, since
09349          they are acceptable */
09350       p->jointcapability = newjointcapability;                /* Our joint codec profile for this call */
09351       p->peercapability = newpeercapability;                  /* The other side's capability in latest offer */
09352       p->jointnoncodeccapability = newnoncodeccapability;     /* DTMF capabilities */
09353 
09354       /* respond with single most preferred joint codec, limiting the other side's choice */
09355       if (ast_test_flag(&p->flags[1], SIP_PAGE2_PREFERRED_CODEC)) {
09356          p->jointcapability = ast_codec_choose(&p->prefs, p->jointcapability, 1);
09357       }
09358    }
09359 
09360    /* Setup audio address and port */
09361    if (p->rtp) {
09362       if (portno > 0) {
09363          ast_sockaddr_set_port(sa, portno);
09364          ast_rtp_instance_set_remote_address(p->rtp, sa);
09365          if (debug) {
09366             ast_verbose("Peer audio RTP is at port %s\n",
09367                    ast_sockaddr_stringify(sa));
09368          }
09369 
09370          ast_rtp_codecs_payloads_copy(&newaudiortp, ast_rtp_instance_get_codecs(p->rtp), p->rtp);
09371          /* Ensure RTCP is enabled since it may be inactive
09372             if we're coming back from a T.38 session */
09373          ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 1);
09374          /* Ensure audio RTCP reads are enabled */
09375          if (p->owner) {
09376             ast_channel_set_fd(p->owner, 1, ast_rtp_instance_fd(p->rtp, 1));
09377          }
09378 
09379          if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
09380             ast_clear_flag(&p->flags[0], SIP_DTMF);
09381             if (newnoncodeccapability & AST_RTP_DTMF) {
09382                /* XXX Would it be reasonable to drop the DSP at this point? XXX */
09383                ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
09384                /* Since RFC2833 is now negotiated we need to change some properties of the RTP stream */
09385                ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, 1);
09386                ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
09387             } else {
09388                ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
09389             }
09390          }
09391       } else if (udptlportno > 0) {
09392          if (debug)
09393             ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session.\n");
09394          /* Prevent audio RTCP reads */
09395          if (p->owner) {
09396             ast_channel_set_fd(p->owner, 1, -1);
09397          }
09398          /* Silence RTCP while audio RTP is inactive */
09399          ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 0);
09400       } else {
09401          ast_rtp_instance_stop(p->rtp);
09402          if (debug)
09403             ast_verbose("Peer doesn't provide audio\n");
09404       }
09405    }
09406 
09407    /* Setup video address and port */
09408    if (p->vrtp) {
09409       if (vportno > 0) {
09410          ast_sockaddr_set_port(vsa, vportno);
09411          ast_rtp_instance_set_remote_address(p->vrtp, vsa);
09412          if (debug) {
09413             ast_verbose("Peer video RTP is at port %s\n",
09414                    ast_sockaddr_stringify(vsa));
09415          }
09416          ast_rtp_codecs_payloads_copy(&newvideortp, ast_rtp_instance_get_codecs(p->vrtp), p->vrtp);
09417       } else {
09418          ast_rtp_instance_stop(p->vrtp);
09419          if (debug)
09420             ast_verbose("Peer doesn't provide video\n");
09421       }
09422    }
09423 
09424    /* Setup text address and port */
09425    if (p->trtp) {
09426       if (tportno > 0) {
09427          ast_sockaddr_set_port(tsa, tportno);
09428          ast_rtp_instance_set_remote_address(p->trtp, tsa);
09429          if (debug) {
09430             ast_verbose("Peer T.140 RTP is at port %s\n",
09431                    ast_sockaddr_stringify(tsa));
09432          }
09433          if ((p->jointcapability & AST_FORMAT_T140RED)) {
09434             p->red = 1;
09435             ast_rtp_red_init(p->trtp, 300, red_data_pt, 2);
09436          } else {
09437             p->red = 0;
09438          }
09439          ast_rtp_codecs_payloads_copy(&newtextrtp, ast_rtp_instance_get_codecs(p->trtp), p->trtp);
09440       } else {
09441          ast_rtp_instance_stop(p->trtp);
09442          if (debug)
09443             ast_verbose("Peer doesn't provide T.140\n");
09444       }
09445    }
09446 
09447    /* Setup image address and port */
09448    if (p->udptl) {
09449       if (udptlportno > 0) {
09450          if (ast_test_flag(&p->flags[1], SIP_PAGE2_SYMMETRICRTP) && ast_test_flag(&p->flags[1], SIP_PAGE2_UDPTL_DESTINATION)) {
09451             ast_rtp_instance_get_remote_address(p->rtp, isa);
09452             if (!ast_sockaddr_isnull(isa) && debug) {
09453                ast_debug(1, "Peer T.38 UDPTL is set behind NAT and with destination, destination address now %s\n", ast_sockaddr_stringify(isa));
09454             }
09455          }
09456          ast_sockaddr_set_port(isa, udptlportno);
09457          ast_udptl_set_peer(p->udptl, isa);
09458          if (debug)
09459             ast_debug(1,"Peer T.38 UDPTL is at port %s\n", ast_sockaddr_stringify(isa));
09460 
09461          /* verify the far max ifp can be calculated. this requires far max datagram to be set. */
09462          if (!ast_udptl_get_far_max_datagram(p->udptl)) {
09463             /* setting to zero will force a default if none was provided by the SDP */
09464             ast_udptl_set_far_max_datagram(p->udptl, 0);
09465          }
09466 
09467          /* Remote party offers T38, we need to update state */
09468          if ((t38action == SDP_T38_ACCEPT) &&
09469              (p->t38.state == T38_LOCAL_REINVITE)) {
09470             change_t38_state(p, T38_ENABLED);
09471          } else if ((t38action == SDP_T38_INITIATE) &&
09472                p->owner && p->lastinvite) {
09473             change_t38_state(p, T38_PEER_REINVITE); /* T38 Offered in re-invite from remote party */
09474             /* If fax detection is enabled then send us off to the fax extension */
09475             if (ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT_T38)) {
09476                ast_channel_lock(p->owner);
09477                if (strcmp(p->owner->exten, "fax")) {
09478                   const char *target_context = S_OR(p->owner->macrocontext, p->owner->context);
09479                   ast_channel_unlock(p->owner);
09480                   if (ast_exists_extension(p->owner, target_context, "fax", 1,
09481                      S_COR(p->owner->caller.id.number.valid, p->owner->caller.id.number.str, NULL))) {
09482                      ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension due to peer T.38 re-INVITE\n", p->owner->name);
09483                      pbx_builtin_setvar_helper(p->owner, "FAXEXTEN", p->owner->exten);
09484                      if (ast_async_goto(p->owner, target_context, "fax", 1)) {
09485                         ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", p->owner->name, target_context);
09486                      }
09487                   } else {
09488                      ast_log(LOG_NOTICE, "T.38 re-INVITE detected but no fax extension\n");
09489                   }
09490                } else {
09491                   ast_channel_unlock(p->owner);
09492                }
09493             }
09494          }
09495       } else {
09496          change_t38_state(p, T38_DISABLED);
09497          ast_udptl_stop(p->udptl);
09498          if (debug)
09499             ast_debug(1, "Peer doesn't provide T.38 UDPTL\n");
09500       }
09501    }
09502 
09503    if ((portno == -1) && (p->t38.state != T38_DISABLED)) {
09504       ast_debug(3, "Have T.38 but no audio, accepting offer anyway\n");
09505       return 0;
09506         }
09507 
09508    /* Ok, we're going with this offer */
09509    ast_debug(2, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, p->jointcapability));
09510 
09511    if (!p->owner)    /* There's no open channel owning us so we can return here. For a re-invite or so, we proceed */
09512       return 0;
09513 
09514    ast_debug(4, "We have an owner, now see if we need to change this call\n");
09515 
09516    if (!(p->owner->nativeformats & p->jointcapability) && (p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
09517       if (debug) {
09518          char s1[SIPBUFSIZE], s2[SIPBUFSIZE];
09519          ast_debug(1, "Oooh, we need to change our audio formats since our peer supports only %s and not %s\n",
09520             ast_getformatname_multiple(s1, SIPBUFSIZE, p->jointcapability),
09521             ast_getformatname_multiple(s2, SIPBUFSIZE, p->owner->nativeformats));
09522       }
09523       p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1) | (p->capability & vpeercapability) | (p->capability & tpeercapability);
09524       ast_set_read_format(p->owner, p->owner->readformat);
09525       ast_set_write_format(p->owner, p->owner->writeformat);
09526    }
09527 
09528    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)) {
09529       ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
09530       /* Activate a re-invite */
09531       ast_queue_frame(p->owner, &ast_null_frame);
09532       change_hold_state(p, req, FALSE, sendonly);
09533    } 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)) {
09534       ast_queue_control_data(p->owner, AST_CONTROL_HOLD,
09535                    S_OR(p->mohsuggest, NULL),
09536                    !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
09537       if (sendonly)
09538          ast_rtp_instance_stop(p->rtp);
09539       /* RTCP needs to go ahead, even if we're on hold!!! */
09540       /* Activate a re-invite */
09541       ast_queue_frame(p->owner, &ast_null_frame);
09542       change_hold_state(p, req, TRUE, sendonly);
09543    }
09544 
09545    return 0;
09546 }
09547 
09548 static int process_sdp_o(const char *o, struct sip_pvt *p)
09549 {
09550    char *o_copy;
09551    char *token;
09552    int64_t rua_version;
09553 
09554    /* Store the SDP version number of remote UA. This will allow us to
09555    distinguish between session modifications and session refreshes. If
09556    the remote UA does not send an incremented SDP version number in a
09557    subsequent RE-INVITE then that means its not changing media session.
09558    The RE-INVITE may have been sent to update connected party, remote
09559    target or to refresh the session (Session-Timers).  Asterisk must not
09560    change media session and increment its own version number in answer
09561    SDP in this case. */
09562 
09563    p->session_modify = TRUE;
09564 
09565    if (ast_strlen_zero(o)) {
09566       ast_log(LOG_WARNING, "SDP syntax error. SDP without an o= line\n");
09567       return FALSE;
09568    }
09569 
09570    o_copy = ast_strdupa(o);
09571    token = strsep(&o_copy, " ");  /* Skip username   */
09572    if (!o_copy) {
09573       ast_log(LOG_WARNING, "SDP syntax error in o= line username\n");
09574       return FALSE;
09575    }
09576    token = strsep(&o_copy, " ");  /* Skip session-id */
09577    if (!o_copy) {
09578       ast_log(LOG_WARNING, "SDP syntax error in o= line session-id\n");
09579       return FALSE;
09580    }
09581    token = strsep(&o_copy, " ");  /* Version         */
09582    if (!o_copy) {
09583       ast_log(LOG_WARNING, "SDP syntax error in o= line\n");
09584       return FALSE;
09585    }
09586    if (!sscanf(token, "%30" SCNd64, &rua_version)) {
09587       ast_log(LOG_WARNING, "SDP syntax error in o= line version\n");
09588       return FALSE;
09589    }
09590 
09591    /* we need to check the SDP version number the other end sent us;
09592     * our rules for deciding what to accept are a bit complex.
09593     *
09594     * 1) if 'ignoresdpversion' has been set for this dialog, then
09595     *    we will just accept whatever they sent and assume it is
09596     *    a modification of the session, even if it is not
09597     * 2) otherwise, if this is the first SDP we've seen from them
09598     *    we accept it
09599     * 3) otherwise, if the new SDP version number is higher than the
09600     *    old one, we accept it
09601     * 4) otherwise, if this SDP is in response to us requesting a switch
09602     *    to T.38, we accept the SDP, but also generate a warning message
09603     *    that this peer should have the 'ignoresdpversion' option set,
09604     *    because it is not following the SDP offer/answer RFC; if we did
09605     *    not request a switch to T.38, then we stop parsing the SDP, as it
09606     *    has not changed from the previous version
09607     */
09608 
09609    if (ast_test_flag(&p->flags[1], SIP_PAGE2_IGNORESDPVERSION) ||
09610        (p->sessionversion_remote < 0) ||
09611        (p->sessionversion_remote < rua_version)) {
09612       p->sessionversion_remote = rua_version;
09613    } else {
09614       if (p->t38.state == T38_LOCAL_REINVITE) {
09615          p->sessionversion_remote = rua_version;
09616          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);
09617       } else {
09618          p->session_modify = FALSE;
09619          ast_debug(2, "Call %s responded to our reinvite without changing SDP version; ignoring SDP.\n", p->callid);
09620          return FALSE;
09621       }
09622    }
09623 
09624    return TRUE;
09625 }
09626 
09627 static int process_sdp_c(const char *c, struct ast_sockaddr *addr)
09628 {
09629    char proto[4], host[258];
09630    int af;
09631 
09632    /* Check for Media-description-level-address */
09633    if (sscanf(c, "IN %3s %255s", proto, host) == 2) {
09634       if (!strcmp("IP4", proto)) {
09635          af = AF_INET;
09636       } else if (!strcmp("IP6", proto)) {
09637          af = AF_INET6;
09638       } else {
09639          ast_log(LOG_WARNING, "Unknown protocol '%s'.\n", proto);
09640          return FALSE;
09641       }
09642       if (ast_sockaddr_resolve_first_af(addr, host, 0, af)) {
09643          ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in c= line, '%s'\n", c);
09644          return FALSE;
09645       }
09646       return TRUE;
09647    } else {
09648       ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
09649       return FALSE;
09650    }
09651    return FALSE;
09652 }
09653 
09654 static int process_sdp_a_sendonly(const char *a, int *sendonly)
09655 {
09656    int found = FALSE;
09657 
09658    if (!strcasecmp(a, "sendonly")) {
09659       if (*sendonly == -1)
09660          *sendonly = 1;
09661       found = TRUE;
09662    } else if (!strcasecmp(a, "inactive")) {
09663       if (*sendonly == -1)
09664          *sendonly = 2;
09665       found = TRUE;
09666    }  else if (!strcasecmp(a, "sendrecv")) {
09667       if (*sendonly == -1)
09668          *sendonly = 0;
09669       found = TRUE;
09670    }
09671    return found;
09672 }
09673 
09674 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec)
09675 {
09676    int found = FALSE;
09677    int codec;
09678    char mimeSubtype[128];
09679    char fmtp_string[64];
09680    unsigned int sample_rate;
09681    int debug = sip_debug_test_pvt(p);
09682 
09683    if (!strncasecmp(a, "ptime", 5)) {
09684       char *tmp = strrchr(a, ':');
09685       long int framing = 0;
09686       if (tmp) {
09687          tmp++;
09688          framing = strtol(tmp, NULL, 10);
09689          if (framing == LONG_MIN || framing == LONG_MAX) {
09690             framing = 0;
09691             ast_debug(1, "Can't read framing from SDP: %s\n", a);
09692          }
09693       }
09694       if (framing && p->autoframing) {
09695          struct ast_codec_pref *pref = &ast_rtp_instance_get_codecs(p->rtp)->pref;
09696          int codec_n;
09697          for (codec_n = 0; codec_n < AST_RTP_MAX_PT; codec_n++) {
09698             struct ast_rtp_payload_type format = ast_rtp_codecs_payload_lookup(ast_rtp_instance_get_codecs(p->rtp), codec_n);
09699             if (!format.asterisk_format || !format.code) /* non-codec or not found */
09700                continue;
09701             ast_debug(1, "Setting framing for %s to %ld\n", ast_getformatname(format.code), framing);
09702             ast_codec_pref_setsize(pref, format.code, framing);
09703          }
09704          ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, pref);
09705       }
09706       found = TRUE;
09707    } else if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
09708       /* We have a rtpmap to handle */
09709       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
09710          if (!(ast_rtp_codecs_payloads_set_rtpmap_type_rate(newaudiortp, NULL, codec, "audio", mimeSubtype,
09711              ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0, sample_rate))) {
09712             if (debug)
09713                ast_verbose("Found audio description format %s for ID %d\n", mimeSubtype, codec);
09714             //found_rtpmap_codecs[last_rtpmap_codec] = codec;
09715             (*last_rtpmap_codec)++;
09716             found = TRUE;
09717          } else {
09718             ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
09719             if (debug)
09720                ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
09721          }
09722       } else {
09723          if (debug)
09724             ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
09725       }
09726    } else if (sscanf(a, "fmtp: %30u %63s", &codec, fmtp_string) == 2) {
09727       struct ast_rtp_payload_type payload;
09728 
09729       payload = ast_rtp_codecs_payload_lookup(newaudiortp, codec);
09730       if (payload.code && payload.asterisk_format) {
09731          unsigned int bit_rate;
09732 
09733          switch (payload.code) {
09734          case AST_FORMAT_SIREN7:
09735             if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
09736                if (bit_rate != 32000) {
09737                   ast_log(LOG_WARNING, "Got Siren7 offer at %d bps, but only 32000 bps supported; ignoring.\n", bit_rate);
09738                   ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
09739                } else {
09740                   found = TRUE;
09741                }
09742             }
09743             break;
09744          case AST_FORMAT_SIREN14:
09745             if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
09746                if (bit_rate != 48000) {
09747                   ast_log(LOG_WARNING, "Got Siren14 offer at %d bps, but only 48000 bps supported; ignoring.\n", bit_rate);
09748                   ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
09749                } else {
09750                   found = TRUE;
09751                }
09752             }
09753             break;
09754          case AST_FORMAT_G719:
09755             if (sscanf(fmtp_string, "bitrate=%30u", &bit_rate) == 1) {
09756                if (bit_rate != 64000) {
09757                   ast_log(LOG_WARNING, "Got G.719 offer at %d bps, but only 64000 bps supported; ignoring.\n", bit_rate);
09758                   ast_rtp_codecs_payloads_unset(newaudiortp, NULL, codec);
09759                } else {
09760                   found = TRUE;
09761                }
09762             }
09763          }
09764       }
09765    }
09766 
09767    return found;
09768 }
09769 
09770 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec)
09771 {
09772    int found = FALSE;
09773    int codec;
09774    char mimeSubtype[128];
09775    unsigned int sample_rate;
09776    int debug = sip_debug_test_pvt(p);
09777 
09778    if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
09779       /* We have a rtpmap to handle */
09780       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
09781          /* Note: should really look at the '#chans' params too */
09782          if (!strncasecmp(mimeSubtype, "H26", 3) || !strncasecmp(mimeSubtype, "MP4", 3)) {
09783             if (!(ast_rtp_codecs_payloads_set_rtpmap_type_rate(newvideortp, NULL, codec, "video", mimeSubtype, 0, sample_rate))) {
09784                if (debug)
09785                   ast_verbose("Found video description format %s for ID %d\n", mimeSubtype, codec);
09786                //found_rtpmap_codecs[last_rtpmap_codec] = codec;
09787                (*last_rtpmap_codec)++;
09788                found = TRUE;
09789             } else {
09790                ast_rtp_codecs_payloads_unset(newvideortp, NULL, codec);
09791                if (debug)
09792                   ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
09793             }
09794          }
09795       } else {
09796          if (debug)
09797             ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
09798       }
09799    }
09800 
09801    return found;
09802 }
09803 
09804 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)
09805 {
09806    int found = FALSE;
09807    int codec;
09808    char mimeSubtype[128];
09809    unsigned int sample_rate;
09810    char *red_cp;
09811    int debug = sip_debug_test_pvt(p);
09812 
09813    if (sscanf(a, "rtpmap: %30u %127[^/]/%30u", &codec, mimeSubtype, &sample_rate) == 3) {
09814       /* We have a rtpmap to handle */
09815       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
09816          if (!strncasecmp(mimeSubtype, "T140", 4)) { /* Text */
09817             if (p->trtp) {
09818                /* ast_verbose("Adding t140 mimeSubtype to textrtp struct\n"); */
09819                ast_rtp_codecs_payloads_set_rtpmap_type_rate(newtextrtp, NULL, codec, "text", mimeSubtype, 0, sample_rate);
09820                found = TRUE;
09821             }
09822          } else if (!strncasecmp(mimeSubtype, "RED", 3)) { /* Text with Redudancy */
09823             if (p->trtp) {
09824                ast_rtp_codecs_payloads_set_rtpmap_type_rate(newtextrtp, NULL, codec, "text", mimeSubtype, 0, sample_rate);
09825                sprintf(red_fmtp, "fmtp:%d ", codec);
09826                if (debug)
09827                   ast_verbose("RED submimetype has payload type: %d\n", codec);
09828                found = TRUE;
09829             }
09830          }
09831       } else {
09832          if (debug)
09833             ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
09834       }
09835    } else if (!strncmp(a, red_fmtp, strlen(red_fmtp))) {
09836       /* count numbers of generations in fmtp */
09837       red_cp = &red_fmtp[strlen(red_fmtp)];
09838       strncpy(red_fmtp, a, 100);
09839 
09840       sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
09841       red_cp = strtok(red_cp, "/");
09842       while (red_cp && (*red_num_gen)++ < AST_RED_MAX_GENERATION) {
09843          sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
09844          red_cp = strtok(NULL, "/");
09845       }
09846       red_cp = red_fmtp;
09847       found = TRUE;
09848    }
09849 
09850    return found;
09851 }
09852 
09853 static int process_sdp_a_image(const char *a, struct sip_pvt *p)
09854 {
09855    int found = FALSE;
09856    char s[256];
09857    unsigned int x;
09858 
09859    if (initialize_udptl(p)) {
09860       return found;
09861    }
09862 
09863    if ((sscanf(a, "T38FaxMaxBuffer:%30u", &x) == 1)) {
09864       ast_debug(3, "MaxBufferSize:%d\n", x);
09865       found = TRUE;
09866    } else if ((sscanf(a, "T38MaxBitRate:%30u", &x) == 1) || (sscanf(a, "T38FaxMaxRate:%30u", &x) == 1)) {
09867       ast_debug(3, "T38MaxBitRate: %d\n", x);
09868       switch (x) {
09869       case 14400:
09870          p->t38.their_parms.rate = AST_T38_RATE_14400;
09871          break;
09872       case 12000:
09873          p->t38.their_parms.rate = AST_T38_RATE_12000;
09874          break;
09875       case 9600:
09876          p->t38.their_parms.rate = AST_T38_RATE_9600;
09877          break;
09878       case 7200:
09879          p->t38.their_parms.rate = AST_T38_RATE_7200;
09880          break;
09881       case 4800:
09882          p->t38.their_parms.rate = AST_T38_RATE_4800;
09883          break;
09884       case 2400:
09885          p->t38.their_parms.rate = AST_T38_RATE_2400;
09886          break;
09887       }
09888       found = TRUE;
09889    } else if ((sscanf(a, "T38FaxVersion:%30u", &x) == 1)) {
09890       ast_debug(3, "FaxVersion: %u\n", x);
09891       p->t38.their_parms.version = x;
09892       found = TRUE;
09893    } else if ((sscanf(a, "T38FaxMaxDatagram:%30u", &x) == 1) || (sscanf(a, "T38MaxDatagram:%30u", &x) == 1)) {
09894       /* override the supplied value if the configuration requests it */
09895       if (((signed int) p->t38_maxdatagram >= 0) && ((unsigned int) p->t38_maxdatagram > x)) {
09896          ast_debug(1, "Overriding T38FaxMaxDatagram '%d' with '%d'\n", x, p->t38_maxdatagram);
09897          x = p->t38_maxdatagram;
09898       }
09899       ast_debug(3, "FaxMaxDatagram: %u\n", x);
09900       ast_udptl_set_far_max_datagram(p->udptl, x);
09901       found = TRUE;
09902    } else if ((strncmp(a, "T38FaxFillBitRemoval", 20) == 0)) {
09903       if (sscanf(a, "T38FaxFillBitRemoval:%30u", &x) == 1) {
09904          ast_debug(3, "FillBitRemoval: %d\n", x);
09905          if (x == 1) {
09906             p->t38.their_parms.fill_bit_removal = TRUE;
09907          }
09908       } else {
09909          ast_debug(3, "FillBitRemoval\n");
09910          p->t38.their_parms.fill_bit_removal = TRUE;
09911       }
09912       found = TRUE;
09913    } else if ((strncmp(a, "T38FaxTranscodingMMR", 20) == 0)) {
09914       if (sscanf(a, "T38FaxTranscodingMMR:%30u", &x) == 1) {
09915          ast_debug(3, "Transcoding MMR: %d\n", x);
09916          if (x == 1) {
09917             p->t38.their_parms.transcoding_mmr = TRUE;
09918          }
09919       } else {
09920          ast_debug(3, "Transcoding MMR\n");
09921          p->t38.their_parms.transcoding_mmr = TRUE;
09922       }
09923       found = TRUE;
09924    } else if ((strncmp(a, "T38FaxTranscodingJBIG", 21) == 0)) {
09925       if (sscanf(a, "T38FaxTranscodingJBIG:%30u", &x) == 1) {
09926          ast_debug(3, "Transcoding JBIG: %d\n", x);
09927          if (x == 1) {
09928             p->t38.their_parms.transcoding_jbig = TRUE;
09929          }
09930       } else {
09931          ast_debug(3, "Transcoding JBIG\n");
09932          p->t38.their_parms.transcoding_jbig = TRUE;
09933       }
09934       found = TRUE;
09935    } else if ((sscanf(a, "T38FaxRateManagement:%255s", s) == 1)) {
09936       ast_debug(3, "RateManagement: %s\n", s);
09937       if (!strcasecmp(s, "localTCF"))
09938          p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_LOCAL_TCF;
09939       else if (!strcasecmp(s, "transferredTCF"))
09940          p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF;
09941       found = TRUE;
09942    } else if ((sscanf(a, "T38FaxUdpEC:%255s", s) == 1)) {
09943       ast_debug(3, "UDP EC: %s\n", s);
09944       if (!strcasecmp(s, "t38UDPRedundancy")) {
09945          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
09946       } else if (!strcasecmp(s, "t38UDPFEC")) {
09947          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
09948       } else {
09949          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
09950       }
09951       found = TRUE;
09952    }
09953 
09954    return found;
09955 }
09956 
09957 /*! \brief Add "Supported" header to sip message.  Since some options may
09958  *  be disabled in the config, the sip_pvt must be inspected to determine what
09959  *  is supported for this dialog. */
09960 static int add_supported_header(struct sip_pvt *pvt, struct sip_request *req)
09961 {
09962    int res;
09963    if (st_get_mode(pvt, 0) != SESSION_TIMER_MODE_REFUSE) {
09964       res = add_header(req, "Supported", "replaces, timer");
09965    } else {
09966       res = add_header(req, "Supported", "replaces");
09967    }
09968    return res;
09969 }
09970 
09971 /*! \brief Add header to SIP message */
09972 static int add_header(struct sip_request *req, const char *var, const char *value)
09973 {
09974    if (req->headers == SIP_MAX_HEADERS) {
09975       ast_log(LOG_WARNING, "Out of SIP header space\n");
09976       return -1;
09977    }
09978 
09979    if (req->lines) {
09980       ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
09981       return -1;
09982    }
09983 
09984    if (sip_cfg.compactheaders) {
09985       var = find_alias(var, var);
09986    }
09987 
09988    ast_str_append(&req->data, 0, "%s: %s\r\n", var, value);
09989    req->header[req->headers] = ast_str_strlen(req->data);
09990 
09991    req->headers++;
09992 
09993    return 0;   
09994 }
09995 
09996 /*! 
09997  * \pre dialog is assumed to be locked while calling this function
09998  * \brief Add 'Max-Forwards' header to SIP message 
09999  */
10000 static int add_header_max_forwards(struct sip_pvt *dialog, struct sip_request *req)
10001 {
10002    char clen[10];
10003 
10004    snprintf(clen, sizeof(clen), "%d", dialog->maxforwards);
10005 
10006    return add_header(req, "Max-Forwards", clen);
10007 }
10008 
10009 /*! \brief Add 'Content-Length' header and content to SIP message */
10010 static int finalize_content(struct sip_request *req)
10011 {
10012    char clen[10];
10013 
10014    if (req->lines) {
10015       ast_log(LOG_WARNING, "finalize_content() called on a message that has already been finalized\n");
10016       return -1;
10017    }
10018 
10019    snprintf(clen, sizeof(clen), "%zd", ast_str_strlen(req->content));
10020    add_header(req, "Content-Length", clen);
10021 
10022    if (ast_str_strlen(req->content)) {
10023       ast_str_append(&req->data, 0, "\r\n%s", ast_str_buffer(req->content));
10024    }
10025    req->lines = ast_str_strlen(req->content) ? 1 : 0;
10026    return 0;
10027 }
10028 
10029 /*! \brief Add content (not header) to SIP message */
10030 static int add_content(struct sip_request *req, const char *line)
10031 {
10032    if (req->lines) {
10033       ast_log(LOG_WARNING, "Can't add more content when the content has been finalized\n");
10034       return -1;
10035    }
10036 
10037    ast_str_append(&req->content, 0, "%s", line);
10038    return 0;
10039 }
10040 
10041 /*! \brief Copy one header field from one request to another */
10042 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
10043 {
10044    const char *tmp = get_header(orig, field);
10045 
10046    if (!ast_strlen_zero(tmp)) /* Add what we're responding to */
10047       return add_header(req, field, tmp);
10048    ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
10049    return -1;
10050 }
10051 
10052 /*! \brief Copy all headers from one request to another */
10053 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
10054 {
10055    int start = 0;
10056    int copied = 0;
10057    for (;;) {
10058       const char *tmp = __get_header(orig, field, &start);
10059 
10060       if (ast_strlen_zero(tmp))
10061          break;
10062       /* Add what we're responding to */
10063       add_header(req, field, tmp);
10064       copied++;
10065    }
10066    return copied ? 0 : -1;
10067 }
10068 
10069 /*! \brief Copy SIP VIA Headers from the request to the response
10070 \note If the client indicates that it wishes to know the port we received from,
10071    it adds ;rport without an argument to the topmost via header. We need to
10072    add the port number (from our point of view) to that parameter.
10073 \verbatim
10074    We always add ;received=<ip address> to the topmost via header.
10075 \endverbatim
10076    Received: RFC 3261, rport RFC 3581 */
10077 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
10078 {
10079    int copied = 0;
10080    int start = 0;
10081 
10082    for (;;) {
10083       char new[512];
10084       const char *oh = __get_header(orig, field, &start);
10085 
10086       if (ast_strlen_zero(oh))
10087          break;
10088 
10089       if (!copied) { /* Only check for empty rport in topmost via header */
10090          char leftmost[512], *others, *rport;
10091 
10092          /* Only work on leftmost value */
10093          ast_copy_string(leftmost, oh, sizeof(leftmost));
10094          others = strchr(leftmost, ',');
10095          if (others)
10096              *others++ = '\0';
10097 
10098          /* Find ;rport;  (empty request) */
10099          rport = strstr(leftmost, ";rport");
10100          if (rport && *(rport+6) == '=')
10101             rport = NULL;     /* We already have a parameter to rport */
10102 
10103          if (((ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT)) || (rport && ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)))) {
10104             /* We need to add received port - rport */
10105             char *end;
10106 
10107             rport = strstr(leftmost, ";rport");
10108 
10109             if (rport) {
10110                end = strchr(rport + 1, ';');
10111                if (end)
10112                   memmove(rport, end, strlen(end) + 1);
10113                else
10114                   *rport = '\0';
10115             }
10116 
10117             /* Add rport to first VIA header if requested */
10118             snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
10119                leftmost, ast_sockaddr_stringify_addr_remote(&p->recv),
10120                ast_sockaddr_port(&p->recv),
10121                others ? "," : "", others ? others : "");
10122          } else {
10123             /* We should *always* add a received to the topmost via */
10124             snprintf(new, sizeof(new), "%s;received=%s%s%s",
10125                leftmost, ast_sockaddr_stringify_addr_remote(&p->recv),
10126                others ? "," : "", others ? others : "");
10127          }
10128          oh = new;   /* the header to copy */
10129       }  /* else add the following via headers untouched */
10130       add_header(req, field, oh);
10131       copied++;
10132    }
10133    if (!copied) {
10134       ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
10135       return -1;
10136    }
10137    return 0;
10138 }
10139 
10140 /*! \brief Add route header into request per learned route */
10141 static void add_route(struct sip_request *req, struct sip_route *route)
10142 {
10143    char r[SIPBUFSIZE*2], *p;
10144    int n, rem = sizeof(r);
10145 
10146    if (!route)
10147       return;
10148 
10149    p = r;
10150    for (;route ; route = route->next) {
10151       n = strlen(route->hop);
10152       if (rem < n+3) /* we need room for ",<route>" */
10153          break;
10154       if (p != r) {  /* add a separator after fist route */
10155          *p++ = ',';
10156          --rem;
10157       }
10158       *p++ = '<';
10159       ast_copy_string(p, route->hop, rem); /* cannot fail */
10160       p += n;
10161       *p++ = '>';
10162       rem -= (n+2);
10163    }
10164    *p = '\0';
10165    add_header(req, "Route", r);
10166 }
10167 
10168 /*! \brief Set destination from SIP URI
10169  *
10170  * Parse uri to h (host) and port - uri is already just the part inside the <>
10171  * general form we are expecting is sip[s]:username[:password][;parameter]@host[:port][;...]
10172  * If there's a port given, turn NAPTR/SRV off. NAPTR might indicate SIPS preference even
10173  * for SIP: uri's
10174  *
10175  * If there's a sips: uri scheme, TLS will be required.
10176  */
10177 static void set_destination(struct sip_pvt *p, char *uri)
10178 {
10179    char *h, *maddr, hostname[256];
10180    int hn;
10181    int debug=sip_debug_test_pvt(p);
10182    int tls_on = FALSE;
10183 
10184    if (debug)
10185       ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
10186 
10187    /* Find and parse hostname */
10188    h = strchr(uri, '@');
10189    if (h)
10190       ++h;
10191    else {
10192       h = uri;
10193       if (!strncasecmp(h, "sip:", 4)) {
10194          h += 4;
10195       } else if (!strncasecmp(h, "sips:", 5)) {
10196          h += 5;
10197          tls_on = TRUE;
10198       }
10199    }
10200    hn = strcspn(h, ";>") + 1;
10201    if (hn > sizeof(hostname))
10202       hn = sizeof(hostname);
10203    ast_copy_string(hostname, h, hn);
10204    /* XXX bug here if string has been trimmed to sizeof(hostname) */
10205    h += hn - 1;
10206 
10207    /*! \todo XXX If we have sip_cfg.srvlookup on, then look for NAPTR/SRV,
10208     * otherwise, just look for A records */
10209    if (ast_sockaddr_resolve_first_transport(&p->sa, hostname, 0, p->socket.type)) {
10210       ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
10211       return;
10212    }
10213 
10214    /* Got the hostname - but maybe there's a "maddr=" to override address? */
10215    maddr = strstr(h, "maddr=");
10216    if (maddr) {
10217       int port;
10218 
10219       maddr += 6;
10220       hn = strspn(maddr, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
10221                     "0123456789-.:[]") + 1;
10222       if (hn > sizeof(hostname))
10223          hn = sizeof(hostname);
10224       ast_copy_string(hostname, maddr, hn);
10225 
10226       port = ast_sockaddr_port(&p->sa);
10227 
10228       /*! \todo XXX If we have sip_cfg.srvlookup on, then look for
10229        * NAPTR/SRV, otherwise, just look for A records */
10230       if (ast_sockaddr_resolve_first_transport(&p->sa, hostname, PARSE_PORT_FORBID, p->socket.type)) {
10231          ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
10232          return;
10233       }
10234 
10235       ast_sockaddr_set_port(&p->sa, port);
10236    }
10237 
10238    if (!ast_sockaddr_port(&p->sa)) {
10239       ast_sockaddr_set_port(&p->sa, tls_on ?
10240                   STANDARD_TLS_PORT : STANDARD_SIP_PORT);
10241    }
10242 
10243    if (debug) {
10244       ast_verbose("set_destination: set destination to %s\n",
10245              ast_sockaddr_stringify(&p->sa));
10246    }
10247 }
10248 
10249 /*! \brief Initialize SIP response, based on SIP request */
10250 static int init_resp(struct sip_request *resp, const char *msg)
10251 {
10252    /* Initialize a response */
10253    memset(resp, 0, sizeof(*resp));
10254    resp->method = SIP_RESPONSE;
10255    if (!(resp->data = ast_str_create(SIP_MIN_PACKET)))
10256       goto e_return;
10257    if (!(resp->content = ast_str_create(SIP_MIN_PACKET)))
10258       goto e_free_data;
10259    resp->header[0] = 0;
10260    ast_str_set(&resp->data, 0, "SIP/2.0 %s\r\n", msg);
10261    resp->headers++;
10262    return 0;
10263 
10264 e_free_data:
10265    ast_free(resp->data);
10266    resp->data = NULL;
10267 e_return:
10268    return -1;
10269 }
10270 
10271 /*! \brief Initialize SIP request */
10272 static int init_req(struct sip_request *req, int sipmethod, const char *recip)
10273 {
10274    /* Initialize a request */
10275    memset(req, 0, sizeof(*req));
10276    if (!(req->data = ast_str_create(SIP_MIN_PACKET)))
10277       goto e_return;
10278    if (!(req->content = ast_str_create(SIP_MIN_PACKET)))
10279       goto e_free_data;
10280    req->method = sipmethod;
10281    req->header[0] = 0;
10282    ast_str_set(&req->data, 0, "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
10283    req->headers++;
10284    return 0;
10285 
10286 e_free_data:
10287    ast_free(req->data);
10288    req->data = NULL;
10289 e_return:
10290    return -1;
10291 }
10292 
10293 /*! \brief Deinitialize SIP response/request */
10294 static void deinit_req(struct sip_request *req)
10295 {
10296    if (req->data) {
10297       ast_free(req->data);
10298       req->data = NULL;
10299    }
10300    if (req->content) {
10301       ast_free(req->content);
10302       req->content = NULL;
10303    }
10304 }
10305 
10306 
10307 /*! \brief Test if this response needs a contact header */
10308 static inline int resp_needs_contact(const char *msg, enum sipmethod method) {
10309    /* Requirements for Contact header inclusion in responses generated
10310     * from the header tables found in the following RFCs.  Where the
10311     * Contact header was marked mandatory (m) or optional (o) this
10312     * function returns 1.
10313     *
10314     * - RFC 3261 (ACK, BYE, CANCEL, INVITE, OPTIONS, REGISTER)
10315     * - RFC 2976 (INFO)
10316     * - RFC 3262 (PRACK)
10317     * - RFC 3265 (SUBSCRIBE, NOTIFY)
10318     * - RFC 3311 (UPDATE)
10319     * - RFC 3428 (MESSAGE)
10320     * - RFC 3515 (REFER)
10321     * - RFC 3903 (PUBLISH)
10322     */
10323 
10324    switch (method) {
10325       /* 1xx, 2xx, 3xx, 485 */
10326       case SIP_INVITE:
10327       case SIP_UPDATE:
10328       case SIP_SUBSCRIBE:
10329       case SIP_NOTIFY:
10330          if ((msg[0] >= '1' && msg[0] <= '3') || !strncmp(msg, "485", 3))
10331             return 1;
10332          break;
10333 
10334       /* 2xx, 3xx, 485 */
10335       case SIP_REGISTER:
10336       case SIP_OPTIONS:
10337          if (msg[0] == '2' || msg[0] == '3' || !strncmp(msg, "485", 3))
10338             return 1;
10339          break;
10340 
10341       /* 3xx, 485 */
10342       case SIP_BYE:
10343       case SIP_PRACK:
10344       case SIP_MESSAGE:
10345       case SIP_PUBLISH:
10346          if (msg[0] == '3' || !strncmp(msg, "485", 3))
10347             return 1;
10348          break;
10349 
10350       /* 2xx, 3xx, 4xx, 5xx, 6xx */
10351       case SIP_REFER:
10352          if (msg[0] >= '2' && msg[0] <= '6')
10353             return 1;
10354          break;
10355 
10356       /* contact will not be included for everything else */
10357       case SIP_ACK:
10358       case SIP_CANCEL:
10359       case SIP_INFO:
10360       case SIP_PING:
10361       default:
10362          return 0;
10363    }
10364    return 0;
10365 }
10366 
10367 /*! \brief Prepare SIP response packet */
10368 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
10369 {
10370    char newto[256];
10371    const char *ot;
10372 
10373    init_resp(resp, msg);
10374    copy_via_headers(p, resp, req, "Via");
10375    if (msg[0] == '1' || msg[0] == '2')
10376       copy_all_header(resp, req, "Record-Route");
10377    copy_header(resp, req, "From");
10378    ot = get_header(req, "To");
10379    if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
10380       /* Add the proper tag if we don't have it already.  If they have specified
10381          their tag, use it.  Otherwise, use our own tag */
10382       if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
10383          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
10384       else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
10385          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
10386       else
10387          ast_copy_string(newto, ot, sizeof(newto));
10388       ot = newto;
10389    }
10390    add_header(resp, "To", ot);
10391    copy_header(resp, req, "Call-ID");
10392    copy_header(resp, req, "CSeq");
10393    if (!ast_strlen_zero(global_useragent))
10394       add_header(resp, "Server", global_useragent);
10395    add_header(resp, "Allow", ALLOWED_METHODS);
10396    add_supported_header(p, resp);
10397 
10398    /* If this is an invite, add Session-Timers related headers if the feature is active for this session */
10399    if (p->method == SIP_INVITE && p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE) {
10400       char se_hdr[256];
10401       snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
10402          p->stimer->st_ref == SESSION_TIMER_REFRESHER_US ? "uas" : "uac");
10403       add_header(resp, "Session-Expires", se_hdr);
10404    }
10405 
10406    if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_PUBLISH)) {
10407       /* For registration responses, we also need expiry and
10408          contact info */
10409       char tmp[256];
10410 
10411       snprintf(tmp, sizeof(tmp), "%d", p->expiry);
10412       add_header(resp, "Expires", tmp);
10413       if (p->expiry) {  /* Only add contact if we have an expiry time */
10414          char contact[SIPBUFSIZE];
10415          const char *contact_uri = p->method == SIP_SUBSCRIBE ? p->our_contact : p->fullcontact;
10416          char *brackets = strchr(contact_uri, '<');
10417          snprintf(contact, sizeof(contact), "%s%s%s;expires=%d", brackets ? "" : "<", contact_uri, brackets ? "" : ">", p->expiry);
10418          add_header(resp, "Contact", contact);  /* Not when we unregister */
10419       }
10420    } else if (!ast_strlen_zero(p->our_contact) && resp_needs_contact(msg, p->method)) {
10421       add_header(resp, "Contact", p->our_contact);
10422    }
10423 
10424    if (!ast_strlen_zero(p->url)) {
10425       add_header(resp, "Access-URL", p->url);
10426       ast_string_field_set(p, url, NULL);
10427    }
10428 
10429    /* default to routing the response to the address where the request
10430     * came from.  Since we don't have a transport layer, we do this here.
10431     * The process_via() function will update the port to either the port
10432     * specified in the via header or the default port later on (per RFC
10433     * 3261 section 18.2.2).
10434     */
10435    p->sa = p->recv;
10436 
10437    if (process_via(p, req)) {
10438       ast_log(LOG_WARNING, "error processing via header, will send response to originating address\n");
10439    }
10440 
10441    return 0;
10442 }
10443 
10444 /*! \brief Initialize a SIP request message (not the initial one in a dialog) */
10445 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, uint32_t seqno, int newbranch)
10446 {
10447    struct sip_request *orig = &p->initreq;
10448    char stripped[80];
10449    char tmp[80];
10450    char newto[256];
10451    const char *c;
10452    const char *ot, *of;
10453    int is_strict = FALSE;     /*!< Strict routing flag */
10454    int is_outbound = ast_test_flag(&p->flags[0], SIP_OUTGOING);   /* Session direction */
10455 
10456    snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
10457    
10458    if (!seqno) {
10459       p->ocseq++;
10460       seqno = p->ocseq;
10461    }
10462    
10463    /* A CANCEL must have the same branch as the INVITE that it is canceling. */
10464    if (sipmethod == SIP_CANCEL) {
10465       p->branch = p->invite_branch;
10466       build_via(p);
10467    } else if (newbranch && (sipmethod == SIP_INVITE)) {
10468       p->branch ^= ast_random();
10469       p->invite_branch = p->branch;
10470       build_via(p);
10471    } else if (newbranch) {
10472       p->branch ^= ast_random();
10473       build_via(p);
10474    }
10475 
10476    /* Check for strict or loose router */
10477    if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop, ";lr") == NULL) {
10478       is_strict = TRUE;
10479       if (sipdebug)
10480          ast_debug(1, "Strict routing enforced for session %s\n", p->callid);
10481    }
10482    
10483    if (sipmethod == SIP_CANCEL)
10484       c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2); /* Use original URI */
10485    else if (sipmethod == SIP_ACK) {
10486       /* Use URI from Contact: in 200 OK (if INVITE)
10487       (we only have the contacturi on INVITEs) */
10488       if (!ast_strlen_zero(p->okcontacturi))
10489          c = is_strict ? p->route->hop : p->okcontacturi;
10490       else
10491          c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
10492    } else if (!ast_strlen_zero(p->okcontacturi))
10493       c = is_strict ? p->route->hop : p->okcontacturi; /* Use for BYE or REINVITE */
10494    else if (!ast_strlen_zero(p->uri))
10495       c = p->uri;
10496    else {
10497       char *n;
10498       /* We have no URI, use To: or From:  header as URI (depending on direction) */
10499       ast_copy_string(stripped, get_header(orig, is_outbound ? "To" : "From"),
10500             sizeof(stripped));
10501       n = get_in_brackets(stripped);
10502       c = remove_uri_parameters(n);
10503    }  
10504    init_req(req, sipmethod, c);
10505 
10506    snprintf(tmp, sizeof(tmp), "%u %s", seqno, sip_methods[sipmethod].text);
10507 
10508    add_header(req, "Via", p->via);
10509    /*
10510     * Use the learned route set unless this is a CANCEL on an ACK for a non-2xx
10511     * final response. For a CANCEL or ACK, we have to send to the same destination
10512     * as the original INVITE.
10513     */
10514    if (p->route &&
10515          !(sipmethod == SIP_CANCEL ||
10516             (sipmethod == SIP_ACK && (p->invitestate == INV_COMPLETED || p->invitestate == INV_CANCELLED)))) {
10517       set_destination(p, p->route->hop);
10518       add_route(req, is_strict ? p->route->next : p->route);
10519    }
10520    add_header_max_forwards(p, req);
10521 
10522    ot = get_header(orig, "To");
10523    of = get_header(orig, "From");
10524 
10525    /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
10526       as our original request, including tag (or presumably lack thereof) */
10527    if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
10528       /* Add the proper tag if we don't have it already.  If they have specified
10529          their tag, use it.  Otherwise, use our own tag */
10530       if (is_outbound && !ast_strlen_zero(p->theirtag))
10531          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
10532       else if (!is_outbound)
10533          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
10534       else
10535          snprintf(newto, sizeof(newto), "%s", ot);
10536       ot = newto;
10537    }
10538 
10539    if (is_outbound) {
10540       add_header(req, "From", of);
10541       add_header(req, "To", ot);
10542    } else {
10543       add_header(req, "From", ot);
10544       add_header(req, "To", of);
10545    }
10546    /* Do not add Contact for MESSAGE, BYE and Cancel requests */
10547    if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
10548       add_header(req, "Contact", p->our_contact);
10549 
10550    copy_header(req, orig, "Call-ID");
10551    add_header(req, "CSeq", tmp);
10552 
10553    if (!ast_strlen_zero(global_useragent))
10554       add_header(req, "User-Agent", global_useragent);
10555 
10556    if (!ast_strlen_zero(p->url)) {
10557       add_header(req, "Access-URL", p->url);
10558       ast_string_field_set(p, url, NULL);
10559    }
10560 
10561    /* Add Session-Timers related headers if the feature is active for this session.
10562       An exception to this behavior is the ACK request. Since Asterisk never requires
10563       session-timers support from a remote end-point (UAS) in an INVITE, it must
10564       not send 'Require: timer' header in the ACK request.
10565       This should only be added in the INVITE transactions, not MESSAGE or REFER or other
10566       in-dialog messages.
10567    */
10568    if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE
10569        && sipmethod == SIP_INVITE) {
10570       char se_hdr[256];
10571       snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval,
10572          p->stimer->st_ref == SESSION_TIMER_REFRESHER_US ? "uac" : "uas");
10573       add_header(req, "Session-Expires", se_hdr);
10574       snprintf(se_hdr, sizeof(se_hdr), "%d", st_get_se(p, FALSE));
10575       add_header(req, "Min-SE", se_hdr);
10576    }
10577 
10578    return 0;
10579 }
10580 
10581 /*! \brief Base transmit response function */
10582 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
10583 {
10584    struct sip_request resp;
10585    uint32_t seqno = 0;
10586 
10587    if (reliable && (sscanf(get_header(req, "CSeq"), "%30u ", &seqno) != 1)) {
10588       ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
10589       return -1;
10590    }
10591    respprep(&resp, p, msg, req);
10592 
10593    if (ast_test_flag(&p->flags[0], SIP_SENDRPID)
10594          && ast_test_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND)
10595          && (!strncmp(msg, "180", 3) || !strncmp(msg, "183", 3))) {
10596       ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
10597       add_rpid(&resp, p);
10598    }
10599    if (ast_test_flag(&p->flags[0], SIP_OFFER_CC)) {
10600       add_cc_call_info_to_response(p, &resp);
10601    }
10602 
10603    /* If we are sending a 302 Redirect we can add a diversion header if the redirect information is set */
10604    if (!strncmp(msg, "302", 3)) {
10605       add_diversion_header(&resp, p);
10606    }
10607 
10608    /* If we are cancelling an incoming invite for some reason, add information
10609       about the reason why we are doing this in clear text */
10610    if (p->method == SIP_INVITE && msg[0] != '1') {
10611       char buf[20];
10612 
10613       if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON)) {
10614          int hangupcause = 0;
10615 
10616          if (p->owner && p->owner->hangupcause) {
10617             hangupcause = p->owner->hangupcause;
10618          } else if (p->hangupcause) {
10619             hangupcause = p->hangupcause;
10620          } else {
10621             int respcode;
10622             if (sscanf(msg, "%30d ", &respcode))
10623                hangupcause = hangup_sip2cause(respcode);
10624          }
10625 
10626          if (hangupcause) {
10627             sprintf(buf, "Q.850;cause=%i", hangupcause & 0x7f);
10628             add_header(&resp, "Reason", buf);
10629          }
10630       }
10631 
10632       if (p->owner && p->owner->hangupcause) {
10633          add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
10634          snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
10635          add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
10636       }
10637    }
10638    return send_response(p, &resp, reliable, seqno);
10639 }
10640 
10641 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)
10642 {
10643    struct sip_request resp;
10644 
10645    if (need_new_etag) {
10646       create_new_sip_etag(esc_entry, 1);
10647    }
10648    respprep(&resp, p, msg, req);
10649    add_header(&resp, "SIP-ETag", esc_entry->entity_tag);
10650 
10651    return send_response(p, &resp, 0, 0);
10652 }
10653 
10654 static int temp_pvt_init(void *data)
10655 {
10656    struct sip_pvt *p = data;
10657 
10658    p->do_history = 0;   /* XXX do we need it ? isn't already all 0 ? */
10659    return ast_string_field_init(p, 512);
10660 }
10661 
10662 static void temp_pvt_cleanup(void *data)
10663 {
10664    struct sip_pvt *p = data;
10665 
10666    ast_string_field_free_memory(p);
10667 
10668    ast_free(data);
10669 }
10670 
10671 /*! \brief Transmit response, no retransmits, using a temporary pvt structure */
10672 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)
10673 {
10674    struct sip_pvt *p = NULL;
10675 
10676    if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
10677       ast_log(LOG_ERROR, "Failed to get temporary pvt\n");
10678       return -1;
10679    }
10680 
10681    /* XXX the structure may be dirty from previous usage.
10682     * Here we should state clearly how we should reinitialize it
10683     * before using it.
10684     * E.g. certainly the threadstorage should be left alone,
10685     * but other thihngs such as flags etc. maybe need cleanup ?
10686     */
10687 
10688    /* Initialize the bare minimum */
10689    p->method = intended_method;
10690 
10691    if (!addr) {
10692       ast_sockaddr_copy(&p->ourip, &internip);
10693    } else {
10694       ast_sockaddr_copy(&p->sa, addr);
10695       ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
10696    }
10697 
10698    p->branch = ast_random();
10699    make_our_tag(p);
10700    p->ocseq = INITIAL_CSEQ;
10701 
10702    if (useglobal_nat && addr) {
10703       ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT_FORCE_RPORT);
10704       ast_sockaddr_copy(&p->recv, addr);
10705       do_setnat(p);
10706    }
10707 
10708    ast_string_field_set(p, fromdomain, default_fromdomain);
10709    p->fromdomainport = default_fromdomainport;
10710    build_via(p);
10711    ast_string_field_set(p, callid, callid);
10712 
10713    copy_socket_data(&p->socket, &req->socket);
10714 
10715    /* Use this temporary pvt structure to send the message */
10716    __transmit_response(p, msg, req, XMIT_UNRELIABLE);
10717 
10718    /* Free the string fields, but not the pool space */
10719    ast_string_field_init(p, 0);
10720 
10721    return 0;
10722 }
10723 
10724 /*! \brief Transmit response, no retransmits */
10725 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req)
10726 {
10727    return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
10728 }
10729 
10730 /*! \brief Transmit response, no retransmits */
10731 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported)
10732 {
10733    struct sip_request resp;
10734    respprep(&resp, p, msg, req);
10735    append_date(&resp);
10736    add_header(&resp, "Unsupported", unsupported);
10737    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
10738 }
10739 
10740 /*! \brief Transmit 422 response with Min-SE header (Session-Timers)  */
10741 static int transmit_response_with_minse(struct sip_pvt *p, const char *msg, const struct sip_request *req, int minse_int)
10742 {
10743    struct sip_request resp;
10744    char minse_str[20];
10745 
10746    respprep(&resp, p, msg, req);
10747    append_date(&resp);
10748 
10749    snprintf(minse_str, sizeof(minse_str), "%d", minse_int);
10750    add_header(&resp, "Min-SE", minse_str);
10751    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
10752 }
10753 
10754 
10755 /*! \brief Transmit response, Make sure you get an ACK
10756    This is only used for responses to INVITEs, where we need to make sure we get an ACK
10757 */
10758 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
10759 {
10760    return __transmit_response(p, msg, req, req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL);
10761 }
10762 
10763 /*! \brief Append date to SIP message */
10764 static void append_date(struct sip_request *req)
10765 {
10766    char tmpdat[256];
10767    struct tm tm;
10768    time_t t = time(NULL);
10769 
10770    gmtime_r(&t, &tm);
10771    strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
10772    add_header(req, "Date", tmpdat);
10773 }
10774 
10775 /*! \brief Append Retry-After header field when transmitting response */
10776 static int transmit_response_with_retry_after(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *seconds)
10777 {
10778    struct sip_request resp;
10779    respprep(&resp, p, msg, req);
10780    add_header(&resp, "Retry-After", seconds);
10781    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
10782 }
10783 
10784 /*! \brief Append date and content length before transmitting response */
10785 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
10786 {
10787    struct sip_request resp;
10788    respprep(&resp, p, msg, req);
10789    append_date(&resp);
10790    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
10791 }
10792 
10793 /*! \brief Append Accept header, content length before transmitting response */
10794 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
10795 {
10796    struct sip_request resp;
10797    respprep(&resp, p, msg, req);
10798    add_header(&resp, "Accept", "application/sdp");
10799    return send_response(p, &resp, reliable, 0);
10800 }
10801 
10802 /*! \brief Append Min-Expires header, content length before transmitting response */
10803 static int transmit_response_with_minexpires(struct sip_pvt *p, const char *msg, const struct sip_request *req)
10804 {
10805    struct sip_request resp;
10806    char tmp[32];
10807 
10808    snprintf(tmp, sizeof(tmp), "%d", min_expiry);
10809    respprep(&resp, p, msg, req);
10810    add_header(&resp, "Min-Expires", tmp);
10811    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
10812 }
10813 
10814 /*! \brief Respond with authorization request */
10815 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)
10816 {
10817    struct sip_request resp;
10818    char tmp[512];
10819    uint32_t seqno = 0;
10820 
10821    if (reliable && (sscanf(get_header(req, "CSeq"), "%30u ", &seqno) != 1)) {
10822       ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
10823       return -1;
10824    }
10825    /* Choose Realm */
10826    get_realm(p, req);
10827 
10828    /* Stale means that they sent us correct authentication, but
10829       based it on an old challenge (nonce) */
10830    snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", p->realm, randdata, stale ? ", stale=true" : "");
10831    respprep(&resp, p, msg, req);
10832    add_header(&resp, header, tmp);
10833    append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
10834    return send_response(p, &resp, reliable, seqno);
10835 }
10836 
10837 /*!
10838  \brief Extract domain from SIP To/From header
10839  \return -1 on error, 1 if domain string is empty, 0 if domain was properly extracted
10840  \note TODO: Such code is all over SIP channel, there is a sense to organize
10841       this patern in one function
10842 */
10843 static int get_domain(const char *str, char *domain, int len)
10844 {
10845    char tmpf[256];
10846    char *a, *from;
10847 
10848    *domain = '\0';
10849    ast_copy_string(tmpf, str, sizeof(tmpf));
10850    from = get_in_brackets(tmpf);
10851    if (!ast_strlen_zero(from)) {
10852       if (strncasecmp(from, "sip:", 4)) {
10853          ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", from);
10854          return -1;
10855       }
10856       from += 4;
10857    } else
10858       from = NULL;
10859 
10860    if (from) {
10861       int bracket = 0;
10862 
10863       /* Strip any params or options from user */
10864       if ((a = strchr(from, ';')))
10865          *a = '\0';
10866       /* Strip port from domain if present */
10867       for (a = from; *a != '\0'; ++a) {
10868          if (*a == ':' && bracket == 0) {
10869             *a = '\0';
10870             break;
10871          } else if (*a == '[') {
10872             ++bracket;
10873          } else if (*a == ']') {
10874             --bracket;
10875          }
10876       }
10877       if ((a = strchr(from, '@'))) {
10878          *a = '\0';
10879          ast_copy_string(domain, a + 1, len);
10880       } else
10881          ast_copy_string(domain, from, len);
10882    }
10883 
10884    return ast_strlen_zero(domain);
10885 }
10886 
10887 /*!
10888   \brief Choose realm based on From header and then To header or use globaly configured realm.
10889   Realm from From/To header should be listed among served domains in config file: domain=...
10890 */
10891 static void get_realm(struct sip_pvt *p, const struct sip_request *req)
10892 {
10893    char domain[MAXHOSTNAMELEN];
10894 
10895    if (!ast_strlen_zero(p->realm))
10896       return;
10897 
10898    if (sip_cfg.domainsasrealm &&
10899        !AST_LIST_EMPTY(&domain_list))
10900    {
10901       /* Check From header first */
10902       if (!get_domain(get_header(req, "From"), domain, sizeof(domain))) {
10903          if (check_sip_domain(domain, NULL, 0)) {
10904             ast_string_field_set(p, realm, domain);
10905             return;
10906          }
10907       }
10908       /* Check To header */
10909       if (!get_domain(get_header(req, "To"), domain, sizeof(domain))) {
10910          if (check_sip_domain(domain, NULL, 0)) {
10911             ast_string_field_set(p, realm, domain);
10912             return;
10913          }
10914       }
10915    }
10916    
10917    /* Use default realm from config file */
10918    ast_string_field_set(p, realm, sip_cfg.realm);
10919 }
10920 
10921 /*!
10922  * \internal
10923  *
10924  * \arg msg Only use a string constant for the msg, here, it is shallow copied
10925  *
10926  * \note assumes the sip_pvt is locked.
10927  */
10928 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp)
10929 {
10930    int res;
10931 
10932    if (!(res = with_sdp ? transmit_response_with_sdp(p, msg, req, XMIT_UNRELIABLE, FALSE, FALSE) : transmit_response(p, msg, req))) {
10933       p->last_provisional = msg;
10934       update_provisional_keepalive(p, with_sdp);
10935    }
10936 
10937    return res;
10938 }
10939 
10940 /*! \brief Add text body to SIP message */
10941 static int add_text(struct sip_request *req, const char *text)
10942 {
10943    /* XXX Convert \n's to \r\n's XXX */
10944    add_header(req, "Content-Type", "text/plain;charset=UTF-8");
10945    add_content(req, text);
10946    return 0;
10947 }
10948 
10949 /*! \brief Add DTMF INFO tone to sip message
10950    Mode =   0 for application/dtmf-relay (Cisco)
10951       1 for application/dtmf
10952 */
10953 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode)
10954 {
10955    char tmp[256];
10956    int event;
10957    if (mode) {
10958       /* Application/dtmf short version used by some implementations */
10959       if ('0' <= digit && digit <= '9') {
10960          event = digit - '0';
10961       } else if (digit == '*') {
10962          event = 10;
10963       } else if (digit == '#') {
10964          event = 11;
10965       } else if ('A' <= digit && digit <= 'D') {
10966          event = 12 + digit - 'A';
10967       } else if ('a' <= digit && digit <= 'd') {
10968          event = 12 + digit - 'a';
10969       } else {
10970          /* Unknown digit */
10971          event = 0;
10972       }
10973       snprintf(tmp, sizeof(tmp), "%d\r\n", event);
10974       add_header(req, "Content-Type", "application/dtmf");
10975       add_content(req, tmp);
10976    } else {
10977       /* Application/dtmf-relay as documented by Cisco */
10978       snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
10979       add_header(req, "Content-Type", "application/dtmf-relay");
10980       add_content(req, tmp);
10981    }
10982    return 0;
10983 }
10984 
10985 /*!
10986  * \pre if p->owner exists, it must be locked
10987  * \brief Add Remote-Party-ID header to SIP message
10988  */
10989 static int add_rpid(struct sip_request *req, struct sip_pvt *p)
10990 {
10991    struct ast_str *tmp = ast_str_alloca(256);
10992    char tmp2[256];
10993    char *lid_num = NULL;
10994    char *lid_name = NULL;
10995    int lid_pres;
10996    const char *fromdomain;
10997    const char *privacy = NULL;
10998    const char *screen = NULL;
10999    const char *anonymous_string = "\"Anonymous\" <sip:anonymous@anonymous.invalid>";
11000 
11001    if (!ast_test_flag(&p->flags[0], SIP_SENDRPID)) {
11002       return 0;
11003    }
11004 
11005    if (p->owner && p->owner->connected.id.number.valid
11006       && p->owner->connected.id.number.str) {
11007       lid_num = p->owner->connected.id.number.str;
11008    }
11009    if (p->owner && p->owner->connected.id.name.valid
11010       && p->owner->connected.id.name.str) {
11011       lid_name = p->owner->connected.id.name.str;
11012    }
11013    lid_pres = (p->owner) ? ast_party_id_presentation(&p->owner->connected.id) : AST_PRES_NUMBER_NOT_AVAILABLE;
11014 
11015    if (ast_strlen_zero(lid_num))
11016       return 0;
11017    if (ast_strlen_zero(lid_name))
11018       lid_name = lid_num;
11019    fromdomain = S_OR(p->fromdomain, ast_sockaddr_stringify_host_remote(&p->ourip));
11020 
11021    lid_num = ast_uri_encode(lid_num, tmp2, sizeof(tmp2), 0);
11022 
11023    if (ast_test_flag(&p->flags[0], SIP_SENDRPID_PAI)) {
11024       if ((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
11025          ast_str_set(&tmp, -1, "%s", anonymous_string);
11026       } else {
11027          ast_str_set(&tmp, -1, "\"%s\" <sip:%s@%s>", lid_name, lid_num, fromdomain);
11028       }
11029       add_header(req, "P-Asserted-Identity", ast_str_buffer(tmp));
11030    } else {
11031       ast_str_set(&tmp, -1, "\"%s\" <sip:%s@%s>;party=%s", lid_name, lid_num, fromdomain, p->outgoing_call ? "calling" : "called");
11032 
11033       switch (lid_pres) {
11034       case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
11035       case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
11036          privacy = "off";
11037          screen = "no";
11038          break;
11039       case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
11040       case AST_PRES_ALLOWED_NETWORK_NUMBER:
11041          privacy = "off";
11042          screen = "yes";
11043          break;
11044       case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
11045       case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
11046          privacy = "full";
11047          screen = "no";
11048          break;
11049       case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
11050       case AST_PRES_PROHIB_NETWORK_NUMBER:
11051          privacy = "full";
11052          screen = "yes";
11053          break;
11054       case AST_PRES_NUMBER_NOT_AVAILABLE:
11055          break;
11056       default:
11057          if ((lid_pres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
11058             privacy = "full";
11059          }
11060          else
11061             privacy = "off";
11062          screen = "no";
11063          break;
11064       }
11065 
11066       if (!ast_strlen_zero(privacy) && !ast_strlen_zero(screen)) {
11067          ast_str_append(&tmp, -1, ";privacy=%s;screen=%s", privacy, screen);
11068       }
11069 
11070       add_header(req, "Remote-Party-ID", ast_str_buffer(tmp));
11071    }
11072    return 0;
11073 }
11074 
11075 /*! \brief add XML encoded media control with update
11076    \note XML: The only way to turn 0 bits of information into a few hundred. (markster) */
11077 static int add_vidupdate(struct sip_request *req)
11078 {
11079    const char *xml_is_a_huge_waste_of_space =
11080       "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
11081       " <media_control>\r\n"
11082       "  <vc_primitive>\r\n"
11083       "   <to_encoder>\r\n"
11084       "    <picture_fast_update>\r\n"
11085       "    </picture_fast_update>\r\n"
11086       "   </to_encoder>\r\n"
11087       "  </vc_primitive>\r\n"
11088       " </media_control>\r\n";
11089    add_header(req, "Content-Type", "application/media_control+xml");
11090    add_content(req, xml_is_a_huge_waste_of_space);
11091    return 0;
11092 }
11093 
11094 /*! \brief Add codec offer to SDP offer/answer body in INVITE or 200 OK */
11095 static void add_codec_to_sdp(const struct sip_pvt *p, format_t codec,
11096               struct ast_str **m_buf, struct ast_str **a_buf,
11097               int debug, int *min_packet_size)
11098 {
11099    int rtp_code;
11100    struct ast_format_list fmt;
11101 
11102 
11103    if (debug)
11104       ast_verbose("Adding codec 0x%" PRIx64 " (%s) to SDP\n", codec, ast_getformatname(codec));
11105    if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->rtp), 1, codec)) == -1)
11106       return;
11107 
11108    if (p->rtp) {
11109       struct ast_codec_pref *pref = &ast_rtp_instance_get_codecs(p->rtp)->pref;
11110       fmt = ast_codec_pref_getsize(pref, codec);
11111    } 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 */
11112       return;
11113    ast_str_append(m_buf, 0, " %d", rtp_code);
11114    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
11115              ast_rtp_lookup_mime_subtype2(1, codec,
11116                      ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0),
11117              ast_rtp_lookup_sample_rate2(1, codec));
11118 
11119    switch (codec) {
11120    case AST_FORMAT_G729A:
11121       /* Indicate that we don't support VAD (G.729 annex B) */
11122       ast_str_append(a_buf, 0, "a=fmtp:%d annexb=no\r\n", rtp_code);
11123       break;
11124    case AST_FORMAT_G723_1:
11125       /* Indicate that we don't support VAD (G.723.1 annex A) */
11126       ast_str_append(a_buf, 0, "a=fmtp:%d annexa=no\r\n", rtp_code);
11127       break;
11128    case AST_FORMAT_ILBC:
11129       /* Add information about us using only 20/30 ms packetization */
11130       ast_str_append(a_buf, 0, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
11131       break;
11132    case AST_FORMAT_SIREN7:
11133       /* Indicate that we only expect 32Kbps */
11134       ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=32000\r\n", rtp_code);
11135       break;
11136    case AST_FORMAT_SIREN14:
11137       /* Indicate that we only expect 48Kbps */
11138       ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=48000\r\n", rtp_code);
11139       break;
11140    case AST_FORMAT_G719:
11141       /* Indicate that we only expect 64Kbps */
11142       ast_str_append(a_buf, 0, "a=fmtp:%d bitrate=64000\r\n", rtp_code);
11143       break;
11144    }
11145 
11146    if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
11147       *min_packet_size = fmt.cur_ms;
11148 
11149    /* Our first codec packetization processed cannot be zero */
11150    if ((*min_packet_size)==0 && fmt.cur_ms)
11151       *min_packet_size = fmt.cur_ms;
11152 }
11153 
11154 /*! \brief Add video codec offer to SDP offer/answer body in INVITE or 200 OK */
11155 /* This is different to the audio one now so we can add more caps later */
11156 static void add_vcodec_to_sdp(const struct sip_pvt *p, format_t codec,
11157               struct ast_str **m_buf, struct ast_str **a_buf,
11158               int debug, int *min_packet_size)
11159 {
11160    int rtp_code;
11161 
11162    if (!p->vrtp)
11163       return;
11164 
11165    if (debug)
11166       ast_verbose("Adding video codec 0x%" PRIx64 " (%s) to SDP\n", codec, ast_getformatname(codec));
11167 
11168    if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->vrtp), 1, codec)) == -1)
11169       return;
11170 
11171    ast_str_append(m_buf, 0, " %d", rtp_code);
11172    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
11173              ast_rtp_lookup_mime_subtype2(1, codec, 0),
11174              ast_rtp_lookup_sample_rate2(1, codec));
11175    /* Add fmtp code here */
11176 }
11177 
11178 /*! \brief Add text codec offer to SDP offer/answer body in INVITE or 200 OK */
11179 static void add_tcodec_to_sdp(const struct sip_pvt *p, int codec,
11180               struct ast_str **m_buf, struct ast_str **a_buf,
11181               int debug, int *min_packet_size)
11182 {
11183    int rtp_code;
11184 
11185    if (!p->trtp)
11186       return;
11187 
11188    if (debug)
11189       ast_verbose("Adding text codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
11190 
11191    if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->trtp), 1, codec)) == -1)
11192       return;
11193 
11194    ast_str_append(m_buf, 0, " %d", rtp_code);
11195    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
11196              ast_rtp_lookup_mime_subtype2(1, codec, 0),
11197              ast_rtp_lookup_sample_rate2(1, codec));
11198    /* Add fmtp code here */
11199 
11200    if (codec == AST_FORMAT_T140RED) {
11201       int t140code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->trtp), 1, AST_FORMAT_T140);
11202       ast_str_append(a_buf, 0, "a=fmtp:%d %d/%d/%d\r\n", rtp_code,
11203           t140code,
11204           t140code,
11205           t140code);
11206 
11207    }
11208 }
11209 
11210 
11211 /*! \brief Get Max T.38 Transmission rate from T38 capabilities */
11212 static unsigned int t38_get_rate(enum ast_control_t38_rate rate)
11213 {
11214    switch (rate) {
11215    case AST_T38_RATE_2400:
11216       return 2400;
11217    case AST_T38_RATE_4800:
11218       return 4800;
11219    case AST_T38_RATE_7200:
11220       return 7200;
11221    case AST_T38_RATE_9600:
11222       return 9600;
11223    case AST_T38_RATE_12000:
11224       return 12000;
11225    case AST_T38_RATE_14400:
11226       return 14400;
11227    default:
11228       return 0;
11229    }
11230 }
11231 
11232 /*! \brief Add RFC 2833 DTMF offer to SDP */
11233 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
11234             struct ast_str **m_buf, struct ast_str **a_buf,
11235             int debug)
11236 {
11237    int rtp_code;
11238 
11239    if (debug)
11240       ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype2(0, format, 0));
11241    if ((rtp_code = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(p->rtp), 0, format)) == -1)
11242       return;
11243 
11244    ast_str_append(m_buf, 0, " %d", rtp_code);
11245    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
11246              ast_rtp_lookup_mime_subtype2(0, format, 0),
11247              ast_rtp_lookup_sample_rate2(0, format));
11248    if (format == AST_RTP_DTMF)   /* Indicate we support DTMF and FLASH... */
11249       ast_str_append(a_buf, 0, "a=fmtp:%d 0-16\r\n", rtp_code);
11250 }
11251 
11252 /*! \brief Set all IP media addresses for this call
11253    \note called from add_sdp()
11254 */
11255 static void get_our_media_address(struct sip_pvt *p, int needvideo, int needtext,
11256               struct ast_sockaddr *addr, struct ast_sockaddr *vaddr,
11257               struct ast_sockaddr *taddr, struct ast_sockaddr *dest,
11258               struct ast_sockaddr *vdest, struct ast_sockaddr *tdest)
11259 {
11260    int use_externip = 0;
11261 
11262    /* First, get our address */
11263    ast_rtp_instance_get_local_address(p->rtp, addr);
11264    if (p->vrtp) {
11265       ast_rtp_instance_get_local_address(p->vrtp, vaddr);
11266    }
11267    if (p->trtp) {
11268       ast_rtp_instance_get_local_address(p->trtp, taddr);
11269    }
11270 
11271    /* If our real IP differs from the local address returned by the RTP engine, use it. */
11272    /* The premise is that if we are already using that IP to communicate with the client, */
11273    /* we should be using it for RTP too. */
11274         use_externip = ast_sockaddr_cmp_addr(&p->ourip, addr);
11275 
11276    /* Now, try to figure out where we want them to send data */
11277    /* Is this a re-invite to move the media out, then use the original offer from caller  */
11278    if (!ast_sockaddr_isnull(&p->redirip)) {  /* If we have a redirection IP, use it */
11279       ast_sockaddr_copy(dest, &p->redirip);
11280    } else {
11281       /*
11282        * Audio Destination IP:
11283        *
11284        * 1. Specifically configured media address.
11285        * 2. Local address as specified by the RTP engine.
11286        * 3. The local IP as defined by chan_sip.
11287        *
11288        * Audio Destination Port:
11289        *
11290        * 1. Provided by the RTP engine.
11291        */
11292       ast_sockaddr_copy(dest,
11293               !ast_sockaddr_isnull(&media_address) ? &media_address :
11294               !ast_sockaddr_is_any(addr) && !use_externip ? addr    :
11295               &p->ourip);
11296       ast_sockaddr_set_port(dest, ast_sockaddr_port(addr));
11297    }
11298 
11299    if (needvideo) {
11300       /* Determine video destination */
11301       if (!ast_sockaddr_isnull(&p->vredirip)) {
11302          ast_sockaddr_copy(vdest, &p->vredirip);
11303       } else {
11304          /*
11305           * Video Destination IP:
11306           *
11307           * 1. Specifically configured media address.
11308           * 2. Local address as specified by the RTP engine.
11309           * 3. The local IP as defined by chan_sip.
11310           *
11311           * Video Destination Port:
11312           *
11313           * 1. Provided by the RTP engine.
11314           */
11315          ast_sockaddr_copy(vdest,
11316                  !ast_sockaddr_isnull(&media_address) ? &media_address :
11317                  !ast_sockaddr_is_any(vaddr) && !use_externip ? vaddr  :
11318                  &p->ourip);
11319          ast_sockaddr_set_port(vdest, ast_sockaddr_port(vaddr));
11320       }
11321    }
11322 
11323    if (needtext) {
11324       /* Determine text destination */
11325       if (!ast_sockaddr_isnull(&p->tredirip)) {
11326          ast_sockaddr_copy(tdest, &p->tredirip);
11327       } else {
11328          /*
11329           * Text Destination IP:
11330           *
11331           * 1. Specifically configured media address.
11332           * 2. Local address as specified by the RTP engine.
11333           * 3. The local IP as defined by chan_sip.
11334           *
11335           * Text Destination Port:
11336           *
11337           * 1. Provided by the RTP engine.
11338           */
11339          ast_sockaddr_copy(tdest,
11340                  !ast_sockaddr_isnull(&media_address) ? &media_address  :
11341                  !ast_sockaddr_is_any(taddr) && !use_externip ? taddr   :
11342                  &p->ourip);
11343          ast_sockaddr_set_port(tdest, ast_sockaddr_port(taddr));
11344       }
11345    }
11346 }
11347 
11348 static void get_crypto_attrib(struct sip_srtp *srtp, const char **a_crypto)
11349 {
11350    /* Set encryption properties */
11351    if (srtp) {
11352       if (!srtp->crypto) {
11353          srtp->crypto = sdp_crypto_setup();
11354       }
11355       if (srtp->crypto && (sdp_crypto_offer(srtp->crypto) >= 0)) {
11356          *a_crypto = sdp_crypto_attrib(srtp->crypto);
11357       }
11358 
11359       if (!*a_crypto) {
11360          ast_log(LOG_WARNING, "No SRTP key management enabled\n");
11361       }
11362    }
11363 }
11364 
11365 /*! \brief Add Session Description Protocol message
11366 
11367     If oldsdp is TRUE, then the SDP version number is not incremented. This mechanism
11368     is used in Session-Timers where RE-INVITEs are used for refreshing SIP sessions
11369     without modifying the media session in any way.
11370 */
11371 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38)
11372 {
11373    format_t alreadysent = 0;
11374    int doing_directmedia = FALSE;
11375 
11376    struct ast_sockaddr addr = { {0,} };
11377    struct ast_sockaddr vaddr = { {0,} };
11378    struct ast_sockaddr taddr = { {0,} };
11379    struct ast_sockaddr udptladdr = { {0,} };
11380    struct ast_sockaddr dest = { {0,} };
11381    struct ast_sockaddr vdest = { {0,} };
11382    struct ast_sockaddr tdest = { {0,} };
11383    struct ast_sockaddr udptldest = { {0,} };
11384 
11385    /* SDP fields */
11386    char *version =   "v=0\r\n";     /* Protocol version */
11387    char subject[256];            /* Subject of the session */
11388    char owner[256];           /* Session owner/creator */
11389    char connection[256];            /* Connection data */
11390    char *session_time = "t=0 0\r\n";         /* Time the session is active */
11391    char bandwidth[256] = "";        /* Max bitrate */
11392    char *hold = "";
11393    struct ast_str *m_audio = ast_str_alloca(256);  /* Media declaration line for audio */
11394    struct ast_str *m_video = ast_str_alloca(256);  /* Media declaration line for video */
11395    struct ast_str *m_text = ast_str_alloca(256);   /* Media declaration line for text */
11396    struct ast_str *m_modem = ast_str_alloca(256);  /* Media declaration line for modem */
11397    struct ast_str *a_audio = ast_str_alloca(1024); /* Attributes for audio */
11398    struct ast_str *a_video = ast_str_alloca(1024); /* Attributes for video */
11399    struct ast_str *a_text = ast_str_alloca(1024);  /* Attributes for text */
11400    struct ast_str *a_modem = ast_str_alloca(1024); /* Attributes for modem */
11401    const char *a_crypto = NULL;
11402    const char *v_a_crypto = NULL;
11403    const char *t_a_crypto = NULL;
11404 
11405    format_t x;
11406    format_t capability = 0;
11407    int needaudio = FALSE;
11408    int needvideo = FALSE;
11409    int needtext = FALSE;
11410    int debug = sip_debug_test_pvt(p);
11411    int min_audio_packet_size = 0;
11412    int min_video_packet_size = 0;
11413    int min_text_packet_size = 0;
11414 
11415    char codecbuf[SIPBUFSIZE];
11416    char buf[SIPBUFSIZE];
11417    char dummy_answer[256];
11418 
11419    /* Set the SDP session name */
11420    snprintf(subject, sizeof(subject), "s=%s\r\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
11421 
11422    if (!p->rtp) {
11423       ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
11424       return AST_FAILURE;
11425    }
11426    /* XXX We should not change properties in the SIP dialog until
11427       we have acceptance of the offer if this is a re-invite */
11428 
11429    /* Set RTP Session ID and version */
11430    if (!p->sessionid) {
11431       p->sessionid = (int)ast_random();
11432       p->sessionversion = p->sessionid;
11433    } else {
11434       if (oldsdp == FALSE)
11435          p->sessionversion++;
11436    }
11437 
11438    if (add_audio) {
11439       doing_directmedia = (!ast_sockaddr_isnull(&p->redirip) && p->redircodecs) ? TRUE : FALSE;
11440       /* Check if we need video in this call */
11441       if ((p->jointcapability & AST_FORMAT_VIDEO_MASK) && !p->novideo) {
11442          if (doing_directmedia && !(p->jointcapability & AST_FORMAT_VIDEO_MASK & p->redircodecs)) {
11443             ast_debug(2, "This call needs video offers, but caller probably did not offer it!\n");
11444          } else if (p->vrtp) {
11445             needvideo = TRUE;
11446             ast_debug(2, "This call needs video offers!\n");
11447          } else {
11448             ast_debug(2, "This call needs video offers, but there's no video support enabled!\n");
11449          }
11450       }
11451       /* Check if we need text in this call */
11452       if ((p->jointcapability & AST_FORMAT_TEXT_MASK) && !p->notext) {
11453          if (sipdebug_text)
11454             ast_verbose("We think we can do text\n");
11455          if (p->trtp) {
11456             if (sipdebug_text) {
11457                ast_verbose("And we have a text rtp object\n");
11458             }
11459             needtext = TRUE;
11460             ast_debug(2, "This call needs text offers! \n");
11461          } else {
11462             ast_debug(2, "This call needs text offers, but there's no text support enabled ! \n");
11463          }
11464       }
11465    }
11466 
11467    get_our_media_address(p, needvideo, needtext, &addr, &vaddr, &taddr, &dest, &vdest, &tdest);
11468 
11469    snprintf(owner, sizeof(owner), "o=%s %d %d IN %s %s\r\n",
11470        ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner,
11471        p->sessionid, p->sessionversion,
11472        (ast_sockaddr_is_ipv6(&dest) && !ast_sockaddr_is_ipv4_mapped(&dest)) ?
11473          "IP6" : "IP4",
11474        ast_sockaddr_stringify_addr_remote(&dest));
11475 
11476    snprintf(connection, sizeof(connection), "c=IN %s %s\r\n",
11477        (ast_sockaddr_is_ipv6(&dest) && !ast_sockaddr_is_ipv4_mapped(&dest)) ?
11478          "IP6" : "IP4",
11479        ast_sockaddr_stringify_addr_remote(&dest));
11480 
11481    if (add_audio) {
11482       if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR) {
11483          hold = "a=recvonly\r\n";
11484          doing_directmedia = FALSE;
11485       } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE) {
11486          hold = "a=inactive\r\n";
11487          doing_directmedia = FALSE;
11488       } else {
11489          hold = "a=sendrecv\r\n";
11490       }
11491 
11492       capability = p->jointcapability;
11493 
11494       /* XXX note, Video and Text are negated - 'true' means 'no' */
11495       ast_debug(1, "** Our capability: %s Video flag: %s Text flag: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability),
11496            p->novideo ? "True" : "False", p->notext ? "True" : "False");
11497       ast_debug(1, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcodec));
11498 
11499       if (doing_directmedia) {
11500          capability &= p->redircodecs;
11501          ast_debug(1, "** Our native-bridge filtered capablity: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability));
11502       }
11503 
11504       /* Check if we need audio */
11505       if (capability & AST_FORMAT_AUDIO_MASK)
11506          needaudio = TRUE;
11507 
11508       if (debug) {
11509          ast_verbose("Audio is at %s\n", ast_sockaddr_stringify_port(&addr));
11510       }
11511 
11512       /* Ok, we need video. Let's add what we need for video and set codecs.
11513          Video is handled differently than audio since we can not transcode. */
11514       if (needvideo) {
11515          get_crypto_attrib(p->vsrtp, &v_a_crypto);
11516          ast_str_append(&m_video, 0, "m=video %d RTP/%s", ast_sockaddr_port(&vdest),
11517             v_a_crypto ? "SAVP" : "AVP");
11518 
11519          /* Build max bitrate string */
11520          if (p->maxcallbitrate)
11521             snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
11522          if (debug) {
11523             ast_verbose("Video is at %s\n", ast_sockaddr_stringify(&vdest));
11524          }
11525       }
11526 
11527       /* Ok, we need text. Let's add what we need for text and set codecs.
11528          Text is handled differently than audio since we can not transcode. */
11529       if (needtext) {
11530          if (sipdebug_text)
11531             ast_verbose("Lets set up the text sdp\n");
11532          get_crypto_attrib(p->tsrtp, &t_a_crypto);
11533          ast_str_append(&m_text, 0, "m=text %d RTP/%s", ast_sockaddr_port(&tdest),
11534             t_a_crypto ? "SAVP" : "AVP");
11535          if (debug) {  /* XXX should I use tdest below ? */
11536             ast_verbose("Text is at %s\n", ast_sockaddr_stringify(&taddr));
11537          }
11538       }
11539 
11540       /* Start building generic SDP headers */
11541 
11542       /* We break with the "recommendation" and send our IP, in order that our
11543          peer doesn't have to ast_gethostbyname() us */
11544 
11545       get_crypto_attrib(p->srtp, &a_crypto);
11546       ast_str_append(&m_audio, 0, "m=audio %d RTP/%s", ast_sockaddr_port(&dest),
11547          a_crypto ? "SAVP" : "AVP");
11548 
11549       /* Now, start adding audio codecs. These are added in this order:
11550          - First what was requested by the calling channel
11551          - Then preferences in order from sip.conf device config for this peer/user
11552          - Then other codecs in capabilities, including video
11553       */
11554 
11555       /* Prefer the audio codec we were requested to use, first, no matter what
11556          Note that p->prefcodec can include video codecs, so mask them out
11557       */
11558       if (capability & p->prefcodec) {
11559          format_t codec = p->prefcodec & AST_FORMAT_AUDIO_MASK;
11560 
11561          add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
11562          alreadysent |= codec;
11563       }
11564 
11565       /* Start by sending our preferred audio/video codecs */
11566       for (x = 0; x < 64; x++) {
11567          format_t codec;
11568 
11569          if (!(codec = ast_codec_pref_index(&p->prefs, x)))
11570             break;
11571 
11572          if (!(capability & codec))
11573             continue;
11574 
11575          if (alreadysent & codec)
11576             continue;
11577 
11578          add_codec_to_sdp(p, codec, &m_audio, &a_audio, debug, &min_audio_packet_size);
11579          alreadysent |= codec;
11580       }
11581 
11582       /* Now send any other common audio and video codecs, and non-codec formats: */
11583       for (x = 1ULL; x <= (needtext ? AST_FORMAT_TEXT_MASK : (needvideo ? AST_FORMAT_VIDEO_MASK : AST_FORMAT_AUDIO_MASK)); x <<= 1) {
11584          if (!(capability & x))  /* Codec not requested */
11585             continue;
11586 
11587          if (alreadysent & x) /* Already added to SDP */
11588             continue;
11589 
11590          if (x & AST_FORMAT_AUDIO_MASK)
11591             add_codec_to_sdp(p, x, &m_audio, &a_audio, debug, &min_audio_packet_size);
11592          else if (x & AST_FORMAT_VIDEO_MASK)
11593             add_vcodec_to_sdp(p, x, &m_video, &a_video, debug, &min_video_packet_size);
11594          else if (x & AST_FORMAT_TEXT_MASK)
11595             add_tcodec_to_sdp(p, x, &m_text, &a_text, debug, &min_text_packet_size);
11596       }
11597 
11598       /* Now add DTMF RFC2833 telephony-event as a codec */
11599       for (x = 1LL; x <= AST_RTP_MAX; x <<= 1) {
11600          if (!(p->jointnoncodeccapability & x))
11601             continue;
11602 
11603          add_noncodec_to_sdp(p, x, &m_audio, &a_audio, debug);
11604       }
11605 
11606       ast_debug(3, "-- Done with adding codecs to SDP\n");
11607 
11608       if (!p->owner || !ast_internal_timing_enabled(p->owner))
11609          ast_str_append(&a_audio, 0, "a=silenceSupp:off - - - -\r\n");
11610 
11611       if (min_audio_packet_size)
11612          ast_str_append(&a_audio, 0, "a=ptime:%d\r\n", min_audio_packet_size);
11613 
11614       /* XXX don't think you can have ptime for video */
11615       if (min_video_packet_size)
11616          ast_str_append(&a_video, 0, "a=ptime:%d\r\n", min_video_packet_size);
11617 
11618       /* XXX don't think you can have ptime for text */
11619       if (min_text_packet_size)
11620          ast_str_append(&a_text, 0, "a=ptime:%d\r\n", min_text_packet_size);
11621 
11622       if (m_audio->len - m_audio->used < 2 || m_video->len - m_video->used < 2 ||
11623           m_text->len - m_text->used < 2 || a_text->len - a_text->used < 2 ||
11624           a_audio->len - a_audio->used < 2 || a_video->len - a_video->used < 2)
11625          ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
11626    }
11627 
11628    if (add_t38) {
11629       /* Our T.38 end is */
11630       ast_udptl_get_us(p->udptl, &udptladdr);
11631 
11632       /* Determine T.38 UDPTL destination */
11633       if (!ast_sockaddr_isnull(&p->udptlredirip)) {
11634          ast_sockaddr_copy(&udptldest, &p->udptlredirip);
11635       } else {
11636          ast_sockaddr_copy(&udptldest, &p->ourip);
11637          ast_sockaddr_set_port(&udptldest, ast_sockaddr_port(&udptladdr));
11638       }
11639 
11640       if (debug) {
11641          ast_debug(1, "T.38 UDPTL is at %s port %d\n", ast_sockaddr_stringify_addr(&p->ourip), ast_sockaddr_port(&udptladdr));
11642       }
11643 
11644       /* We break with the "recommendation" and send our IP, in order that our
11645          peer doesn't have to ast_gethostbyname() us */
11646 
11647       ast_str_append(&m_modem, 0, "m=image %d udptl t38\r\n", ast_sockaddr_port(&udptldest));
11648 
11649       if (!ast_sockaddr_cmp(&udptldest, &dest)) {
11650          ast_str_append(&m_modem, 0, "c=IN %s %s\r\n",
11651                (ast_sockaddr_is_ipv6(&dest) && !ast_sockaddr_is_ipv4_mapped(&dest)) ?
11652                "IP6" : "IP4", ast_sockaddr_stringify_addr_remote(&udptldest));
11653       }
11654 
11655       ast_str_append(&a_modem, 0, "a=T38FaxVersion:%d\r\n", p->t38.our_parms.version);
11656       ast_str_append(&a_modem, 0, "a=T38MaxBitRate:%d\r\n", t38_get_rate(p->t38.our_parms.rate));
11657       if (p->t38.our_parms.fill_bit_removal) {
11658          ast_str_append(&a_modem, 0, "a=T38FaxFillBitRemoval\r\n");
11659       }
11660       if (p->t38.our_parms.transcoding_mmr) {
11661          ast_str_append(&a_modem, 0, "a=T38FaxTranscodingMMR\r\n");
11662       }
11663       if (p->t38.our_parms.transcoding_jbig) {
11664          ast_str_append(&a_modem, 0, "a=T38FaxTranscodingJBIG\r\n");
11665       }
11666       switch (p->t38.our_parms.rate_management) {
11667       case AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF:
11668          ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:transferredTCF\r\n");
11669          break;
11670       case AST_T38_RATE_MANAGEMENT_LOCAL_TCF:
11671          ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:localTCF\r\n");
11672          break;
11673       }
11674       ast_str_append(&a_modem, 0, "a=T38FaxMaxDatagram:%u\r\n", ast_udptl_get_local_max_datagram(p->udptl));
11675       switch (ast_udptl_get_error_correction_scheme(p->udptl)) {
11676       case UDPTL_ERROR_CORRECTION_NONE:
11677          break;
11678       case UDPTL_ERROR_CORRECTION_FEC:
11679          ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPFEC\r\n");
11680          break;
11681       case UDPTL_ERROR_CORRECTION_REDUNDANCY:
11682          ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPRedundancy\r\n");
11683          break;
11684       }
11685    }
11686 
11687    if (needaudio)
11688       ast_str_append(&m_audio, 0, "\r\n");
11689    if (needvideo)
11690       ast_str_append(&m_video, 0, "\r\n");
11691    if (needtext)
11692       ast_str_append(&m_text, 0, "\r\n");
11693 
11694    add_header(resp, "Content-Type", "application/sdp");
11695    add_content(resp, version);
11696    add_content(resp, owner);
11697    add_content(resp, subject);
11698    add_content(resp, connection);
11699    /* only if video response is appropriate */
11700    if (needvideo) {
11701       add_content(resp, bandwidth);
11702    }
11703    add_content(resp, session_time);
11704    /* if this is a response to an invite, order our offers properly */
11705    if (p->offered_media[SDP_AUDIO].order_offered ||
11706       p->offered_media[SDP_VIDEO].order_offered ||
11707       p->offered_media[SDP_TEXT].order_offered ||
11708       p->offered_media[SDP_IMAGE].order_offered) {
11709       int i;
11710       /* we have up to 3 streams as limited by process_sdp */
11711       for (i = 1; i <= 3; i++) {
11712          if (p->offered_media[SDP_AUDIO].order_offered == i) {
11713             if (needaudio) {
11714                add_content(resp, m_audio->str);
11715                add_content(resp, a_audio->str);
11716                add_content(resp, hold);
11717                if (a_crypto) {
11718                   add_content(resp, a_crypto);
11719                }
11720             } else {
11721                snprintf(dummy_answer, sizeof(dummy_answer), "m=audio 0 RTP/AVP %s\r\n", p->offered_media[SDP_AUDIO].codecs);
11722                add_content(resp, dummy_answer);
11723             }
11724          } else if (p->offered_media[SDP_VIDEO].order_offered == i) {
11725             if (needvideo) { /* only if video response is appropriate */
11726                add_content(resp, m_video->str);
11727                add_content(resp, a_video->str);
11728                add_content(resp, hold);   /* Repeat hold for the video stream */
11729                if (v_a_crypto) {
11730                   add_content(resp, v_a_crypto);
11731                }
11732             } else {
11733                snprintf(dummy_answer, sizeof(dummy_answer), "m=video 0 RTP/AVP %s\r\n", p->offered_media[SDP_VIDEO].codecs);
11734                add_content(resp, dummy_answer);
11735             }
11736          } else if (p->offered_media[SDP_TEXT].order_offered == i) {
11737             if (needtext) { /* only if text response is appropriate */
11738                add_content(resp, m_text->str);
11739                add_content(resp, a_text->str);
11740                add_content(resp, hold);   /* Repeat hold for the text stream */
11741                if (t_a_crypto) {
11742                   add_content(resp, t_a_crypto);
11743                }
11744             } else {
11745                snprintf(dummy_answer, sizeof(dummy_answer), "m=text 0 RTP/AVP %s\r\n", p->offered_media[SDP_TEXT].codecs);
11746                add_content(resp, dummy_answer);
11747             }
11748          } else if (p->offered_media[SDP_IMAGE].order_offered == i) {
11749             if (add_t38) {
11750                add_content(resp, m_modem->str);
11751                add_content(resp, a_modem->str);
11752             } else {
11753                add_content(resp, "m=image 0 udptl t38\r\n");
11754             }
11755          }
11756       }
11757    } else {
11758       /* generate new SDP from scratch, no offers */
11759       if (needaudio) {
11760          add_content(resp, m_audio->str);
11761          add_content(resp, a_audio->str);
11762          add_content(resp, hold);
11763          if (a_crypto) {
11764             add_content(resp, a_crypto);
11765          }
11766       }
11767       if (needvideo) { /* only if video response is appropriate */
11768          add_content(resp, m_video->str);
11769          add_content(resp, a_video->str);
11770          add_content(resp, hold);   /* Repeat hold for the video stream */
11771          if (v_a_crypto) {
11772             add_content(resp, v_a_crypto);
11773          }
11774       }
11775       if (needtext) { /* only if text response is appropriate */
11776          add_content(resp, m_text->str);
11777          add_content(resp, a_text->str);
11778          add_content(resp, hold);   /* Repeat hold for the text stream */
11779          if (t_a_crypto) {
11780             add_content(resp, t_a_crypto);
11781          }
11782       }
11783       if (add_t38) {
11784          add_content(resp, m_modem->str);
11785          add_content(resp, a_modem->str);
11786       }
11787    }
11788 
11789    /* Update lastrtprx when we send our SDP */
11790    p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
11791 
11792    ast_debug(3, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, capability));
11793 
11794    return AST_SUCCESS;
11795 }
11796 
11797 /*! \brief Used for 200 OK and 183 early media */
11798 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
11799 {
11800    struct sip_request resp;
11801    uint32_t seqno;
11802    
11803    if (sscanf(get_header(req, "CSeq"), "%30u ", &seqno) != 1) {
11804       ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
11805       return -1;
11806    }
11807    respprep(&resp, p, msg, req);
11808    if (p->udptl) {
11809       add_sdp(&resp, p, 0, 0, 1);
11810    } else
11811       ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
11812    if (retrans && !p->pendinginvite)
11813       p->pendinginvite = seqno;     /* Buggy clients sends ACK on RINGING too */
11814    return send_response(p, &resp, retrans, seqno);
11815 }
11816 
11817 /*! \brief copy SIP request (mostly used to save request for responses) */
11818 static void copy_request(struct sip_request *dst, const struct sip_request *src)
11819 {
11820    /* XXX this function can encounter memory allocation errors, perhaps it
11821     * should return a value */
11822 
11823    struct ast_str *duplicate = dst->data;
11824    struct ast_str *duplicate_content = dst->content;
11825 
11826    /* copy the entire request then restore the original data and content
11827     * members from the dst request */
11828    *dst = *src;
11829    dst->data = duplicate;
11830    dst->content = duplicate_content;
11831 
11832    /* copy the data into the dst request */
11833    if (!dst->data && !(dst->data = ast_str_create(ast_str_strlen(src->data) + 1))) {
11834       return;
11835    }
11836    ast_str_copy_string(&dst->data, src->data);
11837 
11838    /* copy the content into the dst request (if it exists) */
11839    if (src->content) {
11840       if (!dst->content && !(dst->content = ast_str_create(ast_str_strlen(src->content) + 1))) {
11841          return;
11842       }
11843       ast_str_copy_string(&dst->content, src->content);
11844    }
11845 }
11846 
11847 static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp)
11848 {
11849    char uri[SIPBUFSIZE];
11850    struct ast_str *header = ast_str_alloca(SIPBUFSIZE);
11851    struct ast_cc_agent *agent = find_sip_cc_agent_by_original_callid(p);
11852    struct sip_cc_agent_pvt *agent_pvt;
11853 
11854    if (!agent) {
11855       /* Um, what? How could the SIP_OFFER_CC flag be set but there not be an
11856        * agent? Oh well, we'll just warn and return without adding the header.
11857        */
11858       ast_log(LOG_WARNING, "Can't find SIP CC agent for call '%s' even though OFFER_CC flag was set?\n", p->callid);
11859       return;
11860    }
11861 
11862    agent_pvt = agent->private_data;
11863 
11864    if (!ast_strlen_zero(agent_pvt->subscribe_uri)) {
11865       ast_copy_string(uri, agent_pvt->subscribe_uri, sizeof(uri));
11866    } else {
11867       generate_uri(p, uri, sizeof(uri));
11868       ast_copy_string(agent_pvt->subscribe_uri, uri, sizeof(agent_pvt->subscribe_uri));
11869    }
11870    /* XXX Hardcode "NR" as the m reason for now. This should perhaps be changed
11871     * to be more accurate. This parameter has no bearing on the actual operation
11872     * of the feature; it's just there for informational purposes.
11873     */
11874    ast_str_set(&header, 0, "<%s>;purpose=call-completion;m=%s", uri, "NR");
11875    add_header(resp, "Call-Info", ast_str_buffer(header));
11876    ao2_ref(agent, -1);
11877 }
11878 
11879 /*! \brief Used for 200 OK and 183 early media
11880    \return Will return XMIT_ERROR for network errors.
11881 */
11882 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)
11883 {
11884    struct sip_request resp;
11885    uint32_t seqno;
11886    if (sscanf(get_header(req, "CSeq"), "%30u ", &seqno) != 1) {
11887       ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
11888       return -1;
11889    }
11890    respprep(&resp, p, msg, req);
11891    if (rpid == TRUE) {
11892       add_rpid(&resp, p);
11893    }
11894    if (ast_test_flag(&p->flags[0], SIP_OFFER_CC)) {
11895       add_cc_call_info_to_response(p, &resp);
11896    }
11897    if (p->rtp) {
11898       if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
11899          ast_debug(1, "Setting framing from config on incoming call\n");
11900          ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &p->prefs);
11901       }
11902       ast_rtp_instance_activate(p->rtp);
11903       try_suggested_sip_codec(p);
11904       if (p->t38.state == T38_ENABLED) {
11905          add_sdp(&resp, p, oldsdp, TRUE, TRUE);
11906       } else {
11907          add_sdp(&resp, p, oldsdp, TRUE, FALSE);
11908       }
11909    } else
11910       ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
11911    if (reliable && !p->pendinginvite)
11912       p->pendinginvite = seqno;     /* Buggy clients sends ACK on RINGING too */
11913    return send_response(p, &resp, reliable, seqno);
11914 }
11915 
11916 /*! \brief Parse first line of incoming SIP request */
11917 static int determine_firstline_parts(struct sip_request *req)
11918 {
11919    char *e = ast_skip_blanks(req->data->str);   /* there shouldn't be any */
11920    char *local_rlPart1;
11921 
11922    if (!*e)
11923       return -1;
11924    req->rlPart1 = e - req->data->str;  /* method or protocol */
11925    local_rlPart1 = e;
11926    e = ast_skip_nonblanks(e);
11927    if (*e)
11928       *e++ = '\0';
11929    /* Get URI or status code */
11930    e = ast_skip_blanks(e);
11931    if ( !*e )
11932       return -1;
11933    ast_trim_blanks(e);
11934 
11935    if (!strcasecmp(local_rlPart1, "SIP/2.0") ) { /* We have a response */
11936       if (strlen(e) < 3)   /* status code is 3 digits */
11937          return -1;
11938       req->rlPart2 = e - req->data->str;
11939    } else { /* We have a request */
11940       if ( *e == '<' ) { /* XXX the spec says it must not be in <> ! */
11941          ast_debug(3, "Oops. Bogus uri in <> %s\n", e);
11942          e++;
11943          if (!*e)
11944             return -1;
11945       }
11946       req->rlPart2 = e - req->data->str;  /* URI */
11947       e = ast_skip_nonblanks(e);
11948       if (*e)
11949          *e++ = '\0';
11950       e = ast_skip_blanks(e);
11951       if (strcasecmp(e, "SIP/2.0") ) {
11952          ast_debug(3, "Skipping packet - Bad request protocol %s\n", e);
11953          return -1;
11954       }
11955    }
11956    return 1;
11957 }
11958 
11959 /*! \brief Transmit reinvite with SDP
11960 \note    A re-invite is basically a new INVITE with the same CALL-ID and TAG as the
11961    INVITE that opened the SIP dialogue
11962    We reinvite so that the audio stream (RTP) go directly between
11963    the SIP UAs. SIP Signalling stays with * in the path.
11964    
11965    If t38version is TRUE, we send T38 SDP for re-invite from audio/video to
11966    T38 UDPTL transmission on the channel
11967 
11968     If oldsdp is TRUE then the SDP version number is not incremented. This
11969     is needed for Session-Timers so we can send a re-invite to refresh the
11970     SIP session without modifying the media session.
11971 */
11972 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp)
11973 {
11974    struct sip_request req;
11975    
11976    reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ?  SIP_UPDATE : SIP_INVITE, 0, 1);
11977 
11978    add_header(&req, "Allow", ALLOWED_METHODS);
11979    add_supported_header(p, &req);
11980    if (sipdebug) {
11981       if (oldsdp == TRUE)
11982          add_header(&req, "X-asterisk-Info", "SIP re-invite (Session-Timers)");
11983       else
11984          add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
11985    }
11986 
11987    if (ast_test_flag(&p->flags[0], SIP_SENDRPID))
11988       add_rpid(&req, p);
11989 
11990    if (p->do_history) {
11991       append_history(p, "ReInv", "Re-invite sent");
11992    }
11993    memset(p->offered_media, 0, sizeof(p->offered_media));
11994 
11995    try_suggested_sip_codec(p);
11996    if (t38version) {
11997       add_sdp(&req, p, oldsdp, FALSE, TRUE);
11998    } else {
11999       add_sdp(&req, p, oldsdp, TRUE, FALSE);
12000    }
12001 
12002    /* Use this as the basis */
12003    initialize_initreq(p, &req);
12004    p->lastinvite = p->ocseq;
12005    ast_set_flag(&p->flags[0], SIP_OUTGOING);       /* Change direction of this dialog */
12006    p->ongoing_reinvite = 1;
12007    return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
12008 }
12009 
12010 /* \brief Remove URI parameters at end of URI, not in username part though */
12011 static char *remove_uri_parameters(char *uri)
12012 {
12013    char *atsign;
12014    atsign = strchr(uri, '@'); /* First, locate the at sign */
12015    if (!atsign) {
12016       atsign = uri;  /* Ok hostname only, let's stick with the rest */
12017    }
12018    atsign = strchr(atsign, ';'); /* Locate semi colon */
12019    if (atsign)
12020       *atsign = '\0';   /* Kill at the semi colon */
12021    return uri;
12022 }
12023 
12024 /*! \brief Check Contact: URI of SIP message */
12025 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
12026 {
12027    char stripped[SIPBUFSIZE];
12028    char *c;
12029 
12030    ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
12031    c = get_in_brackets(stripped);
12032    /* Cut the URI at the at sign after the @, not in the username part */
12033    c = remove_uri_parameters(c);
12034    if (!ast_strlen_zero(c)) {
12035       ast_string_field_set(p, uri, c);
12036    }
12037 
12038 }
12039 
12040 /*! \brief Build contact header - the contact header we send out */
12041 static void build_contact(struct sip_pvt *p)
12042 {
12043    char tmp[SIPBUFSIZE];
12044    char *user = ast_uri_encode(p->exten, tmp, sizeof(tmp), 0);
12045 
12046    if (p->socket.type == SIP_TRANSPORT_UDP) {
12047       ast_string_field_build(p, our_contact, "<sip:%s%s%s>", user,
12048          ast_strlen_zero(user) ? "" : "@", ast_sockaddr_stringify_remote(&p->ourip));
12049    } else {
12050       ast_string_field_build(p, our_contact, "<sip:%s%s%s;transport=%s>", user,
12051          ast_strlen_zero(user) ? "" : "@", ast_sockaddr_stringify_remote(&p->ourip),
12052          get_transport(p->socket.type));
12053    }
12054 }
12055 
12056 /*! \brief Initiate new SIP request to peer/user */
12057 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri)
12058 {
12059    struct ast_str *invite = ast_str_alloca(256);
12060    char from[256];
12061    char to[256];
12062    char tmp_n[SIPBUFSIZE/2];  /* build a local copy of 'n' if needed */
12063    char tmp_l[SIPBUFSIZE/2];  /* build a local copy of 'l' if needed */
12064    const char *l = NULL;   /* XXX what is this, exactly ? */
12065    const char *n = NULL;   /* XXX what is this, exactly ? */
12066    const char *d = NULL;   /* domain in from header */
12067    const char *urioptions = "";
12068    int ourport;
12069 
12070    if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
12071       const char *s = p->username;  /* being a string field, cannot be NULL */
12072 
12073       /* Test p->username against allowed characters in AST_DIGIT_ANY
12074          If it matches the allowed characters list, then sipuser = ";user=phone"
12075          If not, then sipuser = ""
12076       */
12077       /* + is allowed in first position in a tel: uri */
12078       if (*s == '+')
12079          s++;
12080       for (; *s; s++) {
12081          if (!strchr(AST_DIGIT_ANYNUM, *s) )
12082             break;
12083       }
12084       /* If we have only digits, add ;user=phone to the uri */
12085       if (!*s)
12086          urioptions = ";user=phone";
12087    }
12088 
12089 
12090    snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
12091 
12092    d = S_OR(p->fromdomain, ast_sockaddr_stringify_host_remote(&p->ourip));
12093    if (p->owner) {
12094       if ((ast_party_id_presentation(&p->owner->connected.id) & AST_PRES_RESTRICTION) == AST_PRES_ALLOWED) {
12095          l = p->owner->connected.id.number.valid ? p->owner->connected.id.number.str : NULL;
12096          n = p->owner->connected.id.name.valid ? p->owner->connected.id.name.str : NULL;
12097       } else {
12098          /* Even if we are using RPID, we shouldn't leak information in the From if the user wants
12099           * their callerid restricted */
12100          l = "anonymous";
12101          n = CALLERID_UNKNOWN;
12102          d = FROMDOMAIN_INVALID;
12103       }
12104    }
12105 
12106    /* Hey, it's a NOTIFY! See if they've configured a mwi_from.
12107     * XXX Right now, this logic works because the only place that mwi_from
12108     * is set on the sip_pvt is in sip_send_mwi_to_peer. If things changed, then
12109     * we might end up putting the mwi_from setting into other types of NOTIFY
12110     * messages as well.
12111     */
12112    if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->mwi_from)) {
12113       l = p->mwi_from;
12114    }
12115 
12116    if (ast_strlen_zero(l))
12117       l = default_callerid;
12118    if (ast_strlen_zero(n))
12119       n = l;
12120    /* Allow user to be overridden */
12121    if (!ast_strlen_zero(p->fromuser))
12122       l = p->fromuser;
12123    else /* Save for any further attempts */
12124       ast_string_field_set(p, fromuser, l);
12125 
12126    /* Allow user to be overridden */
12127    if (!ast_strlen_zero(p->fromname))
12128       n = p->fromname;
12129    else /* Save for any further attempts */
12130       ast_string_field_set(p, fromname, n);
12131 
12132    ast_copy_string(tmp_l, l, sizeof(tmp_l));
12133    if (sip_cfg.pedanticsipchecking) {
12134       ast_escape_quoted(n, tmp_n, sizeof(tmp_n));
12135       n = tmp_n;
12136       ast_uri_encode(l, tmp_l, sizeof(tmp_l), 0);
12137    }
12138 
12139    ourport = (p->fromdomainport) ? p->fromdomainport : ast_sockaddr_port(&p->ourip);
12140    if (!sip_standard_port(p->socket.type, ourport)) {
12141       snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=%s", n, tmp_l, d, ourport, p->tag);
12142    } else {
12143       snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%s", n, tmp_l, d, p->tag);
12144    }
12145 
12146    if (!ast_strlen_zero(explicit_uri)) {
12147       ast_str_set(&invite, 0, "%s", explicit_uri);
12148    } else {
12149       /* If we're calling a registered SIP peer, use the fullcontact to dial to the peer */
12150       if (!ast_strlen_zero(p->fullcontact)) {
12151          /* If we have full contact, trust it */
12152          ast_str_append(&invite, 0, "%s", p->fullcontact);
12153       } else {
12154          /* Otherwise, use the username while waiting for registration */
12155          ast_str_append(&invite, 0, "sip:");
12156          if (!ast_strlen_zero(p->username)) {
12157             n = p->username;
12158             if (sip_cfg.pedanticsipchecking) {
12159                ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
12160                n = tmp_n;
12161             }
12162             ast_str_append(&invite, 0, "%s@", n);
12163          }
12164          ast_str_append(&invite, 0, "%s", p->tohost);
12165          if (p->portinuri) {
12166             ast_str_append(&invite, 0, ":%d", ast_sockaddr_port(&p->sa));
12167          }
12168          ast_str_append(&invite, 0, "%s", urioptions);
12169       }
12170    }
12171 
12172    /* If custom URI options have been provided, append them */
12173    if (p->options && !ast_strlen_zero(p->options->uri_options))
12174       ast_str_append(&invite, 0, ";%s", p->options->uri_options);
12175    
12176    /* This is the request URI, which is the next hop of the call
12177       which may or may not be the destination of the call
12178    */
12179    ast_string_field_set(p, uri, invite->str);
12180 
12181    if (!ast_strlen_zero(p->todnid)) {
12182       /*! \todo Need to add back the VXML URL here at some point, possibly use build_string for all this junk */
12183       if (!strchr(p->todnid, '@')) {
12184          /* We have no domain in the dnid */
12185          snprintf(to, sizeof(to), "<sip:%s@%s>%s%s", p->todnid, p->tohost, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
12186       } else {
12187          snprintf(to, sizeof(to), "<sip:%s>%s%s", p->todnid, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
12188       }
12189    } else {
12190       if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) {
12191          /* If this is a NOTIFY, use the From: tag in the subscribe (RFC 3265) */
12192          snprintf(to, sizeof(to), "<%s%s>;tag=%s", (strncasecmp(p->uri, "sip:", 4) ? "sip:" : ""), p->uri, p->theirtag);
12193       } else if (p->options && p->options->vxml_url) {
12194          /* If there is a VXML URL append it to the SIP URL */
12195          snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
12196       } else {
12197          snprintf(to, sizeof(to), "<%s>", p->uri);
12198       }
12199    }
12200 
12201    init_req(req, sipmethod, p->uri);
12202    /* now tmp_n is available so reuse it to build the CSeq */
12203    snprintf(tmp_n, sizeof(tmp_n), "%u %s", ++p->ocseq, sip_methods[sipmethod].text);
12204 
12205    add_header(req, "Via", p->via);
12206    add_header_max_forwards(p, req);
12207    /* This will be a no-op most of the time. However, under certain circumstances,
12208     * NOTIFY messages will use this function for preparing the request and should
12209     * have Route headers present.
12210     */
12211    add_route(req, p->route);
12212 
12213    add_header(req, "From", from);
12214    add_header(req, "To", to);
12215    ast_string_field_set(p, exten, l);
12216    build_contact(p);
12217    add_header(req, "Contact", p->our_contact);
12218    add_header(req, "Call-ID", p->callid);
12219    add_header(req, "CSeq", tmp_n);
12220    if (!ast_strlen_zero(global_useragent)) {
12221       add_header(req, "User-Agent", global_useragent);
12222    }
12223 }
12224 
12225 /*! \brief Add "Diversion" header to outgoing message
12226  *
12227  * We need to add a Diversion header if the owner channel of
12228  * this dialog has redirecting information associated with it.
12229  *
12230  * \param req The request/response to which we will add the header
12231  * \param pvt The sip_pvt which represents the call-leg
12232  */
12233 static void add_diversion_header(struct sip_request *req, struct sip_pvt *pvt)
12234 {
12235    const char *diverting_number;
12236    const char *diverting_name;
12237    const char *reason;
12238    char header_text[256];
12239 
12240    if (!pvt->owner) {
12241       return;
12242    }
12243 
12244    diverting_number = pvt->owner->redirecting.from.number.str;
12245    if (!pvt->owner->redirecting.from.number.valid
12246       || ast_strlen_zero(diverting_number)) {
12247       return;
12248    }
12249 
12250    reason = sip_reason_code_to_str(pvt->owner->redirecting.reason);
12251 
12252    /* We at least have a number to place in the Diversion header, which is enough */
12253    diverting_name = pvt->owner->redirecting.from.name.str;
12254    if (!pvt->owner->redirecting.from.name.valid
12255       || ast_strlen_zero(diverting_name)) {
12256       snprintf(header_text, sizeof(header_text), "<sip:%s@%s>;reason=%s", diverting_number,
12257             ast_sockaddr_stringify_host_remote(&pvt->ourip), reason);
12258    } else {
12259       snprintf(header_text, sizeof(header_text), "\"%s\" <sip:%s@%s>;reason=%s",
12260             diverting_name, diverting_number,
12261             ast_sockaddr_stringify_host_remote(&pvt->ourip), reason);
12262    }
12263 
12264    add_header(req, "Diversion", header_text);
12265 }
12266 
12267 static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri)
12268 {
12269    struct sip_pvt *pvt;
12270    int expires;
12271 
12272    epa_entry->publish_type = publish_type;
12273 
12274    if (!(pvt = sip_alloc(NULL, NULL, 0, SIP_PUBLISH, NULL))) {
12275       return -1;
12276    }
12277 
12278    sip_pvt_lock(pvt);
12279 
12280    if (create_addr(pvt, epa_entry->destination, NULL, TRUE)) {
12281       sip_pvt_unlock(pvt);
12282       dialog_unlink_all(pvt);
12283       dialog_unref(pvt, "create_addr failed in transmit_publish. Unref dialog");
12284       return -1;
12285    }
12286    ast_sip_ouraddrfor(&pvt->sa, &pvt->ourip, pvt);
12287    ast_set_flag(&pvt->flags[0], SIP_OUTGOING);
12288    expires = (publish_type == SIP_PUBLISH_REMOVE) ? 0 : DEFAULT_PUBLISH_EXPIRES;
12289    pvt->expiry = expires;
12290 
12291    /* Bump refcount for sip_pvt's reference */
12292    ao2_ref(epa_entry, +1);
12293    pvt->epa_entry = epa_entry;
12294 
12295    transmit_invite(pvt, SIP_PUBLISH, FALSE, 2, explicit_uri);
12296    sip_pvt_unlock(pvt);
12297    sip_scheddestroy(pvt, DEFAULT_TRANS_TIMEOUT);
12298    dialog_unref(pvt, "Done with the sip_pvt allocated for transmitting PUBLISH");
12299    return 0;
12300 }
12301 
12302 /*! 
12303  * \brief Build REFER/INVITE/OPTIONS/SUBSCRIBE message and transmit it
12304  * \param p sip_pvt structure
12305  * \param sipmethod
12306  * \param sdp unknown
12307  * \param init 0 = Prepare request within dialog, 1= prepare request, new branch,
12308  *  2= prepare new request and new dialog. do_proxy_auth calls this with init!=2
12309  * \param explicit_uri
12310 */
12311 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri)
12312 {
12313    struct sip_request req;
12314    struct ast_variable *var;
12315 
12316    if (init) {/* Bump branch even on initial requests */
12317       p->branch ^= ast_random();
12318       p->invite_branch = p->branch;
12319       build_via(p);
12320    }
12321    if (init > 1) {
12322       initreqprep(&req, p, sipmethod, explicit_uri);
12323    } else {
12324       /* If init=1, we should not generate a new branch. If it's 0, we need a new branch. */
12325       reqprep(&req, p, sipmethod, 0, init ? 0 : 1);
12326    }
12327 
12328    if (p->options && p->options->auth) {
12329       add_header(&req, p->options->authheader, p->options->auth);
12330    }
12331    append_date(&req);
12332    if (sipmethod == SIP_REFER) { /* Call transfer */
12333       if (p->refer) {
12334          char buf[SIPBUFSIZE];
12335          if (!ast_strlen_zero(p->refer->refer_to)) {
12336             add_header(&req, "Refer-To", p->refer->refer_to);
12337          }
12338          if (!ast_strlen_zero(p->refer->referred_by)) {
12339             snprintf(buf, sizeof(buf), "%s <%s>", p->refer->referred_by_name, p->refer->referred_by);
12340             add_header(&req, "Referred-By", buf);
12341          }
12342       }
12343    } else if (sipmethod == SIP_SUBSCRIBE) {
12344       char buf[SIPBUFSIZE];
12345       if (p->subscribed == MWI_NOTIFICATION) {
12346          add_header(&req, "Event", "message-summary");
12347          add_header(&req, "Accept", "application/simple-message-summary");
12348       } else if (p->subscribed == CALL_COMPLETION) {
12349          add_header(&req, "Event", "call-completion");
12350          add_header(&req, "Accept", "application/call-completion");
12351       }
12352       snprintf(buf, sizeof(buf), "%d", p->expiry);
12353       add_header(&req, "Expires", buf);
12354    }
12355 
12356    /* This new INVITE is part of an attended transfer. Make sure that the
12357    other end knows and replace the current call with this new call */
12358    if (p->options && !ast_strlen_zero(p->options->replaces)) {
12359       add_header(&req, "Replaces", p->options->replaces);
12360       add_header(&req, "Require", "replaces");
12361    }
12362 
12363    /* Add Session-Timers related headers */
12364    if (st_get_mode(p, 0) == SESSION_TIMER_MODE_ORIGINATE) {
12365       char i2astr[10];
12366 
12367       if (!p->stimer->st_interval) {
12368          p->stimer->st_interval = st_get_se(p, TRUE);
12369       }
12370 
12371       p->stimer->st_active = TRUE;
12372       
12373       snprintf(i2astr, sizeof(i2astr), "%d", p->stimer->st_interval);
12374       add_header(&req, "Session-Expires", i2astr);
12375       snprintf(i2astr, sizeof(i2astr), "%d", st_get_se(p, FALSE));
12376       add_header(&req, "Min-SE", i2astr);
12377    }
12378 
12379    add_header(&req, "Allow", ALLOWED_METHODS);
12380    add_supported_header(p, &req);
12381 
12382    if (p->options && p->options->addsipheaders && p->owner) {
12383       struct ast_channel *chan = p->owner; /* The owner channel */
12384       struct varshead *headp;
12385    
12386       ast_channel_lock(chan);
12387 
12388       headp = &chan->varshead;
12389 
12390       if (!headp) {
12391          ast_log(LOG_WARNING, "No Headp for the channel...ooops!\n");
12392       } else {
12393          const struct ast_var_t *current;
12394          AST_LIST_TRAVERSE(headp, current, entries) {
12395             /* SIPADDHEADER: Add SIP header to outgoing call */
12396             if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
12397                char *content, *end;
12398                const char *header = ast_var_value(current);
12399                char *headdup = ast_strdupa(header);
12400 
12401                /* Strip of the starting " (if it's there) */
12402                if (*headdup == '"') {
12403                   headdup++;
12404                }
12405                if ((content = strchr(headdup, ':'))) {
12406                   *content++ = '\0';
12407                   content = ast_skip_blanks(content); /* Skip white space */
12408                   /* Strip the ending " (if it's there) */
12409                   end = content + strlen(content) -1; 
12410                   if (*end == '"') {
12411                      *end = '\0';
12412                   }
12413                
12414                   add_header(&req, headdup, content);
12415                   if (sipdebug) {
12416                      ast_debug(1, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
12417                   }
12418                }
12419             }
12420          }
12421       }
12422 
12423       ast_channel_unlock(chan);
12424    }
12425    if ((sipmethod == SIP_INVITE || sipmethod == SIP_UPDATE) && ast_test_flag(&p->flags[0], SIP_SENDRPID))
12426       add_rpid(&req, p);
12427    if (sipmethod == SIP_INVITE) {
12428       add_diversion_header(&req, p);
12429    }
12430    if (sdp) {
12431       memset(p->offered_media, 0, sizeof(p->offered_media));
12432       if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
12433          ast_debug(1, "T38 is in state %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
12434          add_sdp(&req, p, FALSE, FALSE, TRUE);
12435       } else if (p->rtp) {
12436          try_suggested_sip_codec(p);
12437          add_sdp(&req, p, FALSE, TRUE, FALSE);
12438       }
12439    } else if (p->notify) {
12440       for (var = p->notify->headers; var; var = var->next) {
12441          add_header(&req, var->name, var->value);
12442       }
12443       if (ast_str_strlen(p->notify->content)) {
12444          add_content(&req, ast_str_buffer(p->notify->content));
12445       }
12446    } else if (sipmethod == SIP_PUBLISH) {
12447       char expires[SIPBUFSIZE];
12448 
12449       switch (p->epa_entry->static_data->event) {
12450       case CALL_COMPLETION:
12451          snprintf(expires, sizeof(expires), "%d", p->expiry);
12452          add_header(&req, "Event", "call-completion");
12453          add_header(&req, "Expires", expires);
12454          if (p->epa_entry->publish_type != SIP_PUBLISH_INITIAL) {
12455             add_header(&req, "SIP-If-Match", p->epa_entry->entity_tag);
12456          }
12457 
12458          if (!ast_strlen_zero(p->epa_entry->body)) {
12459             add_header(&req, "Content-Type", "application/pidf+xml");
12460             add_content(&req, p->epa_entry->body);
12461          }
12462       default:
12463          break;
12464       }
12465    }
12466 
12467    if (!p->initreq.headers || init > 2) {
12468       initialize_initreq(p, &req);
12469    }
12470    if (sipmethod == SIP_INVITE || sipmethod == SIP_SUBSCRIBE) {
12471       p->lastinvite = p->ocseq;
12472    }
12473    return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
12474 }
12475 
12476 /*! \brief Send a subscription or resubscription for MWI */
12477 static int sip_subscribe_mwi_do(const void *data)
12478 {
12479    struct sip_subscription_mwi *mwi = (struct sip_subscription_mwi*)data;
12480    
12481    if (!mwi) {
12482       return -1;
12483    }
12484    
12485    mwi->resub = -1;
12486    __sip_subscribe_mwi_do(mwi);
12487    ASTOBJ_UNREF(mwi, sip_subscribe_mwi_destroy);
12488    
12489    return 0;
12490 }
12491 
12492 static void on_dns_update_registry(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
12493 {
12494    struct sip_registry *reg = data;
12495    const char *old_str;
12496 
12497    /* This shouldn't happen, but just in case */
12498    if (ast_sockaddr_isnull(new)) {
12499       ast_debug(1, "Empty sockaddr change...ignoring!\n");
12500       return;
12501    }
12502 
12503    if (!ast_sockaddr_port(new)) {
12504       ast_sockaddr_set_port(new, reg->portno);
12505    }
12506 
12507    old_str = ast_strdupa(ast_sockaddr_stringify(old));
12508 
12509    ast_debug(1, "Changing registry %s from %s to %s\n", S_OR(reg->peername, reg->hostname), old_str, ast_sockaddr_stringify(new));
12510    ast_sockaddr_copy(&reg->us, new);
12511 }
12512 
12513 static void on_dns_update_peer(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
12514 {
12515    struct sip_peer *peer = data;
12516    const char *old_str;
12517 
12518    /* This shouldn't happen, but just in case */
12519    if (ast_sockaddr_isnull(new)) {
12520       ast_debug(1, "Empty sockaddr change...ignoring!\n");
12521       return;
12522    }
12523 
12524    if (!ast_sockaddr_isnull(&peer->addr)) {
12525       ao2_unlink(peers_by_ip, peer);
12526    }
12527 
12528    if (!ast_sockaddr_port(new)) {
12529       ast_sockaddr_set_port(new, default_sip_port(peer->socket.type));
12530    }
12531 
12532    old_str = ast_strdupa(ast_sockaddr_stringify(old));
12533    ast_debug(1, "Changing peer %s address from %s to %s\n", peer->name, old_str, ast_sockaddr_stringify(new));
12534 
12535    ao2_lock(peer);
12536    ast_sockaddr_copy(&peer->addr, new);
12537    ao2_unlock(peer);
12538 
12539    ao2_link(peers_by_ip, peer);
12540 }
12541 
12542 static void on_dns_update_mwi(struct ast_sockaddr *old, struct ast_sockaddr *new, void *data)
12543 {
12544    struct sip_subscription_mwi *mwi = data;
12545    const char *old_str;
12546 
12547    /* This shouldn't happen, but just in case */
12548    if (ast_sockaddr_isnull(new)) {
12549       ast_debug(1, "Empty sockaddr change...ignoring!\n");
12550       return;
12551    }
12552 
12553    old_str = ast_strdupa(ast_sockaddr_stringify(old));
12554    ast_debug(1, "Changing mwi %s from %s to %s\n", mwi->hostname, old_str, ast_sockaddr_stringify(new));
12555    ast_sockaddr_copy(&mwi->us, new);
12556 }
12557 
12558 /*! \brief Actually setup an MWI subscription or resubscribe */
12559 static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi)
12560 {
12561    /* If we have no DNS manager let's do a lookup */
12562    if (!mwi->dnsmgr) {
12563       char transport[MAXHOSTNAMELEN];
12564       struct sip_subscription_mwi *saved;
12565       snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(mwi->transport), get_srv_protocol(mwi->transport));
12566 
12567       mwi->us.ss.ss_family = get_address_family_filter(mwi->transport); /* Filter address family */
12568       saved = ASTOBJ_REF(mwi);
12569       ast_dnsmgr_lookup_cb(mwi->hostname, &mwi->us, &mwi->dnsmgr, sip_cfg.srvlookup ? transport : NULL, on_dns_update_mwi, saved);
12570       if (!mwi->dnsmgr) {
12571          ASTOBJ_UNREF(saved, sip_subscribe_mwi_destroy); /* dnsmgr disabled, remove reference */
12572       }
12573    }
12574 
12575    /* If we already have a subscription up simply send a resubscription */
12576    if (mwi->call) {
12577       transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 0, NULL);
12578       return 0;
12579    }
12580    
12581    /* Create a dialog that we will use for the subscription */
12582    if (!(mwi->call = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
12583       return -1;
12584    }
12585 
12586    ref_proxy(mwi->call, obproxy_get(mwi->call, NULL));
12587 
12588    if (!ast_sockaddr_port(&mwi->us) && mwi->portno) {
12589       ast_sockaddr_set_port(&mwi->us, mwi->portno);
12590    }
12591    
12592    /* Setup the destination of our subscription */
12593    if (create_addr(mwi->call, mwi->hostname, &mwi->us, 0)) {
12594       dialog_unlink_all(mwi->call);
12595       mwi->call = dialog_unref(mwi->call, "unref dialog after unlink_all");
12596       return 0;
12597    }
12598 
12599    mwi->call->expiry = mwi_expiry;
12600    
12601    if (!mwi->dnsmgr && mwi->portno) {
12602       ast_sockaddr_set_port(&mwi->call->sa, mwi->portno);
12603       ast_sockaddr_set_port(&mwi->call->recv, mwi->portno);
12604    } else {
12605       mwi->portno = ast_sockaddr_port(&mwi->call->sa);
12606    }
12607    
12608    /* Set various other information */
12609    if (!ast_strlen_zero(mwi->authuser)) {
12610       ast_string_field_set(mwi->call, peername, mwi->authuser);
12611       ast_string_field_set(mwi->call, authname, mwi->authuser);
12612       ast_string_field_set(mwi->call, fromuser, mwi->authuser);
12613    } else {
12614       ast_string_field_set(mwi->call, peername, mwi->username);
12615       ast_string_field_set(mwi->call, authname, mwi->username);
12616       ast_string_field_set(mwi->call, fromuser, mwi->username);
12617    }
12618    ast_string_field_set(mwi->call, username, mwi->username);
12619    if (!ast_strlen_zero(mwi->secret)) {
12620       ast_string_field_set(mwi->call, peersecret, mwi->secret);
12621    }
12622    set_socket_transport(&mwi->call->socket, mwi->transport);
12623    mwi->call->socket.port = htons(mwi->portno);
12624    ast_sip_ouraddrfor(&mwi->call->sa, &mwi->call->ourip, mwi->call);
12625    build_contact(mwi->call);
12626    build_via(mwi->call);
12627 
12628    /* Change the dialog callid. */
12629    change_callid_pvt(mwi->call, NULL);
12630 
12631    ast_set_flag(&mwi->call->flags[0], SIP_OUTGOING);
12632    
12633    /* Associate the call with us */
12634    mwi->call->mwi = ASTOBJ_REF(mwi);
12635 
12636    mwi->call->subscribed = MWI_NOTIFICATION;
12637 
12638    /* Actually send the packet */
12639    transmit_invite(mwi->call, SIP_SUBSCRIBE, 0, 2, NULL);
12640 
12641    return 0;
12642 }
12643 
12644 /*! \brief Find the channel that is causing the RINGING update */
12645 static int find_calling_channel(void *obj, void *arg, void *data, int flags)
12646 {
12647    struct ast_channel *c = obj;
12648    struct sip_pvt *p = data;
12649    int res;
12650 
12651    ast_channel_lock(c);
12652 
12653    res = (c->pbx &&
12654          (!strcasecmp(c->macroexten, p->exten) || !strcasecmp(c->exten, p->exten)) &&
12655          (sip_cfg.notifycid == IGNORE_CONTEXT || !strcasecmp(c->context, p->context)));
12656 
12657    ast_channel_unlock(c);
12658 
12659    return res ? CMP_MATCH | CMP_STOP : 0;
12660 }
12661 
12662 /*! \brief Builds XML portion of NOTIFY messages for presence or dialog updates */
12663 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)
12664 {
12665    enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
12666    const char *statestring = "terminated";
12667    const char *pidfstate = "--";
12668    const char *pidfnote= "Ready";
12669    char hint[AST_MAX_EXTENSION];
12670 
12671    switch (state) {
12672    case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
12673       statestring = (sip_cfg.notifyringing) ? "early" : "confirmed";
12674       local_state = NOTIFY_INUSE;
12675       pidfstate = "busy";
12676       pidfnote = "Ringing";
12677       break;
12678    case AST_EXTENSION_RINGING:
12679       statestring = "early";
12680       local_state = NOTIFY_INUSE;
12681       pidfstate = "busy";
12682       pidfnote = "Ringing";
12683       break;
12684    case AST_EXTENSION_INUSE:
12685       statestring = "confirmed";
12686       local_state = NOTIFY_INUSE;
12687       pidfstate = "busy";
12688       pidfnote = "On the phone";
12689       break;
12690    case AST_EXTENSION_BUSY:
12691       statestring = "confirmed";
12692       local_state = NOTIFY_CLOSED;
12693       pidfstate = "busy";
12694       pidfnote = "On the phone";
12695       break;
12696    case AST_EXTENSION_UNAVAILABLE:
12697       statestring = "terminated";
12698       local_state = NOTIFY_CLOSED;
12699       pidfstate = "away";
12700       pidfnote = "Unavailable";
12701       break;
12702    case AST_EXTENSION_ONHOLD:
12703       statestring = "confirmed";
12704       local_state = NOTIFY_CLOSED;
12705       pidfstate = "busy";
12706       pidfnote = "On hold";
12707       break;
12708    case AST_EXTENSION_NOT_INUSE:
12709    default:
12710       /* Default setting */
12711       break;
12712    }
12713 
12714    /* Check which device/devices we are watching  and if they are registered */
12715    if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, context, exten)) {
12716       char *hint2 = hint, *individual_hint = NULL;
12717       int hint_count = 0, unavailable_count = 0;
12718 
12719       while ((individual_hint = strsep(&hint2, "&"))) {
12720          hint_count++;
12721 
12722          if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
12723             unavailable_count++;
12724       }
12725 
12726       /* If none of the hinted devices are registered, we will
12727        * override notification and show no availability.
12728        */
12729       if (hint_count > 0 && hint_count == unavailable_count) {
12730          local_state = NOTIFY_CLOSED;
12731          pidfstate = "away";
12732          pidfnote = "Not online";
12733       }
12734    }
12735 
12736    switch (subscribed) {
12737    case XPIDF_XML:
12738    case CPIM_PIDF_XML:
12739       ast_str_append(tmp, 0,
12740          "<?xml version=\"1.0\"?>\n"
12741          "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n"
12742          "<presence>\n");
12743       ast_str_append(tmp, 0, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
12744       ast_str_append(tmp, 0, "<atom id=\"%s\">\n", exten);
12745       ast_str_append(tmp, 0, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
12746       ast_str_append(tmp, 0, "<status status=\"%s\" />\n", (local_state ==  NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
12747       ast_str_append(tmp, 0, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
12748       ast_str_append(tmp, 0, "</address>\n</atom>\n</presence>\n");
12749       break;
12750    case PIDF_XML: /* Eyebeam supports this format */
12751       ast_str_append(tmp, 0,
12752          "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
12753          "<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);
12754       ast_str_append(tmp, 0, "<pp:person><status>\n");
12755       if (pidfstate[0] != '-') {
12756          ast_str_append(tmp, 0, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
12757       }
12758       ast_str_append(tmp, 0, "</status></pp:person>\n");
12759       ast_str_append(tmp, 0, "<note>%s</note>\n", pidfnote); /* Note */
12760       ast_str_append(tmp, 0, "<tuple id=\"%s\">\n", exten); /* Tuple start */
12761       ast_str_append(tmp, 0, "<contact priority=\"1\">%s</contact>\n", mto);
12762       if (pidfstate[0] == 'b') /* Busy? Still open ... */
12763          ast_str_append(tmp, 0, "<status><basic>open</basic></status>\n");
12764       else
12765          ast_str_append(tmp, 0, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
12766       ast_str_append(tmp, 0, "</tuple>\n</presence>\n");
12767       break;
12768    case DIALOG_INFO_XML: /* SNOM subscribes in this format */
12769       ast_str_append(tmp, 0, "<?xml version=\"1.0\"?>\n");
12770       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);
12771       if ((state & AST_EXTENSION_RINGING) && sip_cfg.notifyringing) {
12772          const char *local_display = exten;
12773          char *local_target = ast_strdupa(mto);
12774          const char *remote_display = exten;
12775          /* It may seem odd to base the remote_target on the To header here,
12776           * but testing by reporters on issue ASTERISK-16735 found that basing
12777           * on the From header would cause ringing state hints to not work
12778           * properly on certain SNOM devices. If you are using notifycid properly
12779           * (i.e. in the same extension and context as the dialed call) then this
12780           * should not be an issue since the data will be overwritten shortly
12781           * with channel caller ID
12782           */
12783          char *remote_target = ast_strdupa(mto);
12784 
12785          /* There are some limitations to how this works.  The primary one is that the
12786             callee must be dialing the same extension that is being monitored.  Simply dialing
12787             the hint'd device is not sufficient. */
12788          if (sip_cfg.notifycid) {
12789             struct ast_channel *caller;
12790 
12791             if ((caller = ast_channel_callback(find_calling_channel, NULL, p, 0))) {
12792                char *cid_num;
12793                char *connected_num;
12794                int need;
12795 
12796                ast_channel_lock(caller);
12797                cid_num = S_COR(caller->caller.id.number.valid,
12798                   caller->caller.id.number.str, "");
12799                need = strlen(cid_num) + strlen(p->fromdomain) + sizeof("sip:@");
12800                remote_target = ast_alloca(need);
12801                snprintf(remote_target, need, "sip:%s@%s", cid_num, p->fromdomain);
12802 
12803                remote_display = ast_strdupa(S_COR(caller->caller.id.name.valid,
12804                   caller->caller.id.name.str, ""));
12805 
12806                connected_num = S_COR(caller->connected.id.number.valid,
12807                   caller->connected.id.number.str, "");
12808                need = strlen(connected_num) + strlen(p->fromdomain) + sizeof("sip:@");
12809                local_target = ast_alloca(need);
12810                snprintf(local_target, need, "sip:%s@%s", connected_num, p->fromdomain);
12811 
12812                local_display = ast_strdupa(S_COR(caller->connected.id.name.valid,
12813                   caller->connected.id.name.str, ""));
12814 
12815                ast_channel_unlock(caller);
12816                caller = ast_channel_unref(caller);
12817             }
12818 
12819             /* We create a fake call-id which the phone will send back in an INVITE
12820                Replaces header which we can grab and do some magic with. */
12821             if (sip_cfg.pedanticsipchecking) {
12822                ast_str_append(tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" local-tag=\"%s\" remote-tag=\"%s\" direction=\"recipient\">\n",
12823                   exten, p->callid, p->theirtag, p->tag);
12824             } else {
12825                ast_str_append(tmp, 0, "<dialog id=\"%s\" call-id=\"pickup-%s\" direction=\"recipient\">\n",
12826                   exten, p->callid);
12827             }
12828             ast_str_append(tmp, 0,
12829                   "<remote>\n"
12830                   /* See the limitations of this above.  Luckily the phone seems to still be
12831                      happy when these values are not correct. */
12832                   "<identity display=\"%s\">%s</identity>\n"
12833                   "<target uri=\"%s\"/>\n"
12834                   "</remote>\n"
12835                   "<local>\n"
12836                   "<identity display=\"%s\">%s</identity>\n"
12837                   "<target uri=\"%s\"/>\n"
12838                   "</local>\n",
12839                   remote_display, remote_target, remote_target, local_display, local_target, local_target);
12840          } else {
12841             ast_str_append(tmp, 0, "<dialog id=\"%s\" direction=\"recipient\">\n", exten);
12842          }
12843 
12844       } else {
12845          ast_str_append(tmp, 0, "<dialog id=\"%s\">\n", exten);
12846       }
12847       ast_str_append(tmp, 0, "<state>%s</state>\n", statestring);
12848       if (state == AST_EXTENSION_ONHOLD) {
12849             ast_str_append(tmp, 0, "<local>\n<target uri=\"%s\">\n"
12850                                              "<param pname=\"+sip.rendering\" pvalue=\"no\"/>\n"
12851                                              "</target>\n</local>\n", mto);
12852       }
12853       ast_str_append(tmp, 0, "</dialog>\n</dialog-info>\n");
12854       break;
12855    case NONE:
12856    default:
12857       break;
12858    }
12859 }
12860 
12861 static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state)
12862 {
12863    struct sip_request req;
12864    struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
12865    char uri[SIPBUFSIZE];
12866    char state_str[64];
12867    char subscription_state_hdr[64];
12868 
12869    if (state < CC_QUEUED || state > CC_READY) {
12870       ast_log(LOG_WARNING, "Invalid state provided for transmit_cc_notify (%d)\n", state);
12871       return -1;
12872    }
12873 
12874    reqprep(&req, subscription, SIP_NOTIFY, 0, TRUE);
12875    snprintf(state_str, sizeof(state_str), "%s\r\n", sip_cc_notify_state_map[state].state_string);
12876    add_header(&req, "Event", "call-completion");
12877    add_header(&req, "Content-Type", "application/call-completion");
12878    snprintf(subscription_state_hdr, sizeof(subscription_state_hdr), "active;expires=%d", subscription->expiry);
12879    add_header(&req, "Subscription-State", subscription_state_hdr);
12880    if (state == CC_READY) {
12881       generate_uri(subscription, agent_pvt->notify_uri, sizeof(agent_pvt->notify_uri));
12882       snprintf(uri, sizeof(uri) - 1, "cc-URI: %s\r\n", agent_pvt->notify_uri);
12883    }
12884    add_content(&req, state_str);
12885    if (state == CC_READY) {
12886       add_content(&req, uri);
12887    }
12888    return send_request(subscription, &req, XMIT_RELIABLE, subscription->ocseq);
12889 }
12890 
12891 /*! \brief Used in the SUBSCRIBE notification subsystem (RFC3265) */
12892 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout)
12893 {
12894    struct ast_str *tmp = ast_str_alloca(4000);
12895    char from[256], to[256];
12896    char *c, *mfrom, *mto;
12897    struct sip_request req;
12898    const struct cfsubscription_types *subscriptiontype;
12899 
12900    /* If the subscription has not yet been accepted do not send a NOTIFY */
12901    if (!ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
12902       return 0;
12903    }
12904 
12905    memset(from, 0, sizeof(from));
12906    memset(to, 0, sizeof(to));
12907 
12908    subscriptiontype = find_subscription_type(p->subscribed);
12909 
12910    ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
12911    c = get_in_brackets(from);
12912    if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
12913       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
12914       return -1;
12915    }
12916 
12917    mfrom = remove_uri_parameters(c);
12918 
12919    ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
12920    c = get_in_brackets(to);
12921    if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
12922       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
12923       return -1;
12924    }
12925    mto = remove_uri_parameters(c);
12926 
12927    reqprep(&req, p, SIP_NOTIFY, 0, 1);
12928 
12929    switch(state) {
12930    case AST_EXTENSION_DEACTIVATED:
12931       if (timeout)
12932          add_header(&req, "Subscription-State", "terminated;reason=timeout");
12933       else {
12934          add_header(&req, "Subscription-State", "terminated;reason=probation");
12935          add_header(&req, "Retry-After", "60");
12936       }
12937       break;
12938    case AST_EXTENSION_REMOVED:
12939       add_header(&req, "Subscription-State", "terminated;reason=noresource");
12940       break;
12941    default:
12942       if (p->expiry)
12943          add_header(&req, "Subscription-State", "active");
12944       else  /* Expired */
12945          add_header(&req, "Subscription-State", "terminated;reason=timeout");
12946    }
12947 
12948    switch (p->subscribed) {
12949    case XPIDF_XML:
12950    case CPIM_PIDF_XML:
12951       add_header(&req, "Event", subscriptiontype->event);
12952       state_notify_build_xml(state, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
12953       add_header(&req, "Content-Type", subscriptiontype->mediatype);
12954       p->dialogver++;
12955       break;
12956    case PIDF_XML: /* Eyebeam supports this format */
12957       add_header(&req, "Event", subscriptiontype->event);
12958       state_notify_build_xml(state, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
12959       add_header(&req, "Content-Type", subscriptiontype->mediatype);
12960       p->dialogver++;
12961       break;
12962    case DIALOG_INFO_XML: /* SNOM subscribes in this format */
12963       add_header(&req, "Event", subscriptiontype->event);
12964       state_notify_build_xml(state, full, p->exten, p->context, &tmp, p, p->subscribed, mfrom, mto);
12965       add_header(&req, "Content-Type", subscriptiontype->mediatype);
12966       p->dialogver++;
12967       break;
12968    case NONE:
12969    default:
12970       break;
12971    }
12972 
12973    add_content(&req, tmp->str);
12974 
12975    p->pendinginvite = p->ocseq;  /* Remember that we have a pending NOTIFY in order not to confuse the NOTIFY subsystem */
12976 
12977    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
12978 }
12979 
12980 /*! \brief Notify user of messages waiting in voicemail (RFC3842)
12981 \note - Notification only works for registered peers with mailbox= definitions
12982    in sip.conf
12983    - We use the SIP Event package message-summary
12984     MIME type defaults to  "application/simple-message-summary";
12985  */
12986 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten)
12987 {
12988    struct sip_request req;
12989    struct ast_str *out = ast_str_alloca(500);
12990    int ourport = (p->fromdomainport) ? p->fromdomainport : ast_sockaddr_port(&p->ourip);
12991    const char *domain;
12992    const char *exten = S_OR(vmexten, default_vmexten);
12993 
12994    initreqprep(&req, p, SIP_NOTIFY, NULL);
12995    add_header(&req, "Event", "message-summary");
12996    add_header(&req, "Content-Type", default_notifymime);
12997    ast_str_append(&out, 0, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
12998 
12999    /* domain initialization occurs here because initreqprep changes ast_sockaddr_stringify string. */
13000    domain = S_OR(p->fromdomain, ast_sockaddr_stringify_host_remote(&p->ourip));
13001 
13002    if (!sip_standard_port(p->socket.type, ourport)) {
13003       if (p->socket.type == SIP_TRANSPORT_UDP) {
13004          ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d\r\n", exten, domain, ourport);
13005       } else {
13006          ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d;transport=%s\r\n", exten, domain, ourport, get_transport(p->socket.type));
13007       }
13008    } else {
13009       if (p->socket.type == SIP_TRANSPORT_UDP) {
13010          ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, domain);
13011       } else {
13012          ast_str_append(&out, 0, "Message-Account: sip:%s@%s;transport=%s\r\n", exten, domain, get_transport(p->socket.type));
13013       }
13014    }
13015    /* Cisco has a bug in the SIP stack where it can't accept the
13016       (0/0) notification. This can temporarily be disabled in
13017       sip.conf with the "buggymwi" option */
13018    ast_str_append(&out, 0, "Voice-Message: %d/%d%s\r\n",
13019       newmsgs, oldmsgs, (ast_test_flag(&p->flags[1], SIP_PAGE2_BUGGY_MWI) ? "" : " (0/0)"));
13020 
13021    if (p->subscribed) {
13022       if (p->expiry) {
13023          add_header(&req, "Subscription-State", "active");
13024       } else { /* Expired */
13025          add_header(&req, "Subscription-State", "terminated;reason=timeout");
13026       }
13027    }
13028 
13029    add_content(&req, out->str);
13030 
13031    if (!p->initreq.headers) {
13032       initialize_initreq(p, &req);
13033    }
13034    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
13035 }
13036 
13037 /*! \brief Notify a transferring party of the status of transfer (RFC3515) */
13038 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
13039 {
13040    struct sip_request req;
13041    char tmp[SIPBUFSIZE/2];
13042    
13043    reqprep(&req, p, SIP_NOTIFY, 0, 1);
13044    snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
13045    add_header(&req, "Event", tmp);
13046    add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
13047    add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
13048    add_header(&req, "Allow", ALLOWED_METHODS);
13049    add_supported_header(p, &req);
13050 
13051    snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
13052    add_content(&req, tmp);
13053 
13054    if (!p->initreq.headers) {
13055       initialize_initreq(p, &req);
13056    }
13057 
13058    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
13059 }
13060 
13061 static int manager_sipnotify(struct mansession *s, const struct message *m)
13062 {
13063    const char *channame = astman_get_header(m, "Channel");
13064    struct ast_variable *vars = astman_get_variables(m);
13065    struct sip_pvt *p;
13066    struct ast_variable *header, *var;
13067 
13068    if (ast_strlen_zero(channame)) {
13069       astman_send_error(s, m, "SIPNotify requires a channel name");
13070       return 0;
13071    }
13072 
13073    if (!strncasecmp(channame, "sip/", 4)) {
13074       channame += 4;
13075    }
13076 
13077    if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
13078       astman_send_error(s, m, "Unable to build sip pvt data for notify (memory/socket error)");
13079       return 0;
13080    }
13081 
13082    if (create_addr(p, channame, NULL, 0)) {
13083       /* Maybe they're not registered, etc. */
13084       dialog_unlink_all(p);
13085       dialog_unref(p, "unref dialog inside for loop" );
13086       /* sip_destroy(p); */
13087       astman_send_error(s, m, "Could not create address");
13088       return 0;
13089    }
13090 
13091    /* Notify is outgoing call */
13092    ast_set_flag(&p->flags[0], SIP_OUTGOING);
13093    sip_notify_allocate(p);
13094 
13095    p->notify->headers = header = ast_variable_new("Subscription-State", "terminated", "");
13096 
13097    for (var = vars; var; var = var->next) {
13098       if (!strcasecmp(var->name, "Content")) {
13099          if (ast_str_strlen(p->notify->content))
13100             ast_str_append(&p->notify->content, 0, "\r\n");
13101          ast_str_append(&p->notify->content, 0, "%s", var->value);
13102       } else if (!strcasecmp(var->name, "Content-Length")) {
13103          ast_log(LOG_WARNING, "it is not necessary to specify Content-Length, ignoring\n");
13104       } else {
13105          header->next = ast_variable_new(var->name, var->value, "");
13106          header = header->next;
13107       }
13108    }
13109 
13110    sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
13111    transmit_invite(p, SIP_NOTIFY, 0, 2, NULL);
13112    dialog_unref(p, "bump down the count of p since we're done with it.");
13113 
13114    astman_send_ack(s, m, "Notify Sent");
13115    ast_variables_destroy(vars);
13116    return 0;
13117 }
13118 
13119 /*! \brief Send a provisional response indicating that a call was redirected
13120  */
13121 static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen)
13122 {
13123    struct sip_request resp;
13124 
13125    if (p->owner->_state == AST_STATE_UP || ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
13126       return;
13127    }
13128 
13129    respprep(&resp, p, "181 Call is being forwarded", &p->initreq);
13130    add_diversion_header(&resp, p);
13131    send_response(p, &resp, XMIT_UNRELIABLE, 0);
13132 }
13133 
13134 /*! \brief Notify peer that the connected line has changed */
13135 static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen)
13136 {
13137 
13138    if (!ast_test_flag(&p->flags[0], SIP_SENDRPID)) {
13139       return;
13140    }
13141    if (!p->owner->connected.id.number.valid
13142       || ast_strlen_zero(p->owner->connected.id.number.str)) {
13143       return;
13144    }
13145 
13146    append_history(p, "ConnectedLine", "%s party is now %s <%s>",
13147       ast_test_flag(&p->flags[0], SIP_OUTGOING) ? "Calling" : "Called",
13148       S_COR(p->owner->connected.id.name.valid, p->owner->connected.id.name.str, ""),
13149       S_COR(p->owner->connected.id.number.valid, p->owner->connected.id.number.str, ""));
13150 
13151    if (p->owner->_state == AST_STATE_UP || ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
13152       struct sip_request req;
13153 
13154       if (!p->pendinginvite && (p->invitestate == INV_CONFIRMED || p->invitestate == INV_TERMINATED)) {
13155          reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ? SIP_UPDATE : SIP_INVITE, 0, 1);
13156 
13157          add_header(&req, "Allow", ALLOWED_METHODS);
13158          add_supported_header(p, &req);
13159          add_rpid(&req, p);
13160          add_sdp(&req, p, FALSE, TRUE, FALSE);
13161 
13162          initialize_initreq(p, &req);
13163          p->lastinvite = p->ocseq;
13164          ast_set_flag(&p->flags[0], SIP_OUTGOING);
13165          p->invitestate = INV_CALLING;
13166          send_request(p, &req, XMIT_CRITICAL, p->ocseq);
13167       } else if ((is_method_allowed(&p->allowed_methods, SIP_UPDATE)) && (!ast_strlen_zero(p->okcontacturi))) { 
13168          reqprep(&req, p, SIP_UPDATE, 0, 1);
13169          add_rpid(&req, p);
13170          add_header(&req, "X-Asterisk-rpid-update", "Yes");
13171          send_request(p, &req, XMIT_CRITICAL, p->ocseq);
13172       } else {
13173          /* We cannot send the update yet, so we have to wait until we can */
13174          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
13175       }
13176    } else {
13177       ast_set_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
13178       if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPID_IMMEDIATE)) {
13179          struct sip_request resp;
13180 
13181          if ((p->owner->_state == AST_STATE_RING) && !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT)) {
13182             ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
13183             respprep(&resp, p, "180 Ringing", &p->initreq);
13184             add_rpid(&resp, p);
13185             send_response(p, &resp, XMIT_UNRELIABLE, 0);
13186             ast_set_flag(&p->flags[0], SIP_RINGING);
13187          } else if (p->owner->_state == AST_STATE_RINGING) {
13188             ast_clear_flag(&p->flags[1], SIP_PAGE2_CONNECTLINEUPDATE_PEND);
13189             respprep(&resp, p, "183 Session Progress", &p->initreq);
13190             add_rpid(&resp, p);
13191             send_response(p, &resp, XMIT_UNRELIABLE, 0);
13192             ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
13193          } else {
13194             ast_debug(1, "Unable able to send update to '%s' in state '%s'\n", p->owner->name, ast_state2str(p->owner->_state));
13195          }
13196       }
13197    }
13198 }
13199 
13200 static const struct _map_x_s regstatestrings[] = {
13201    { REG_STATE_FAILED,     "Failed" },
13202    { REG_STATE_UNREGISTERED, "Unregistered"},
13203    { REG_STATE_REGSENT, "Request Sent"},
13204    { REG_STATE_AUTHSENT, "Auth. Sent"},
13205    { REG_STATE_REGISTERED, "Registered"},
13206    { REG_STATE_REJECTED, "Rejected"},
13207    { REG_STATE_TIMEOUT, "Timeout"},
13208    { REG_STATE_NOAUTH, "No Authentication"},
13209    { -1, NULL } /* terminator */
13210 };
13211 
13212 /*! \brief Convert registration state status to string */
13213 static const char *regstate2str(enum sipregistrystate regstate)
13214 {
13215    return map_x_s(regstatestrings, regstate, "Unknown");
13216 }
13217 
13218 /*! \brief Update registration with SIP Proxy.
13219  * Called from the scheduler when the previous registration expires,
13220  * so we don't have to cancel the pending event.
13221  * We assume the reference so the sip_registry is valid, since it
13222  * is stored in the scheduled event anyways.
13223  */
13224 static int sip_reregister(const void *data)
13225 {
13226    /* if we are here, we know that we need to reregister. */
13227    struct sip_registry *r = (struct sip_registry *) data;
13228 
13229    /* if we couldn't get a reference to the registry object, punt */
13230    if (!r) {
13231       return 0;
13232    }
13233 
13234    if (r->call && r->call->do_history) {
13235       append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
13236    }
13237    /* Since registry's are only added/removed by the the monitor thread, this
13238       may be overkill to reference/dereference at all here */
13239    if (sipdebug) {
13240       ast_log(LOG_NOTICE, "   -- Re-registration for  %s@%s\n", r->username, r->hostname);
13241    }
13242 
13243    r->expire = -1;
13244    r->expiry = r->configured_expiry;
13245    __sip_do_register(r);
13246    registry_unref(r, "unref the re-register scheduled event");
13247    return 0;
13248 }
13249 
13250 /*! \brief Register with SIP proxy 
13251    \return see \ref __sip_xmit 
13252 */
13253 static int __sip_do_register(struct sip_registry *r)
13254 {
13255    int res;
13256 
13257    res = transmit_register(r, SIP_REGISTER, NULL, NULL);
13258    return res;
13259 }
13260 
13261 /*! \brief Registration timeout, register again
13262  * Registered as a timeout handler during transmit_register(),
13263  * to retransmit the packet if a reply does not come back.
13264  * This is called by the scheduler so the event is not pending anymore when
13265  * we are called.
13266  */
13267 static int sip_reg_timeout(const void *data)
13268 {
13269 
13270    /* if we are here, our registration timed out, so we'll just do it over */
13271    struct sip_registry *r = (struct sip_registry *)data; /* the ref count should have been bumped when the sched item was added */
13272    struct sip_pvt *p;
13273 
13274    /* if we couldn't get a reference to the registry object, punt */
13275    if (!r) {
13276       return 0;
13277    }
13278 
13279    if (r->dnsmgr) {
13280       /* If the registration has timed out, maybe the IP changed.  Force a refresh. */
13281       ast_dnsmgr_refresh(r->dnsmgr);
13282    }
13283 
13284    /* If the initial tranmission failed, we may not have an existing dialog,
13285     * so it is possible that r->call == NULL.
13286     * Otherwise destroy it, as we have a timeout so we don't want it.
13287     */
13288    if (r->call) {
13289       /* Unlink us, destroy old call.  Locking is not relevant here because all this happens
13290          in the single SIP manager thread. */
13291       p = r->call;
13292       sip_pvt_lock(p);
13293       pvt_set_needdestroy(p, "registration timeout");
13294       /* Pretend to ACK anything just in case */
13295       __sip_pretend_ack(p);
13296       sip_pvt_unlock(p);
13297 
13298       /* decouple the two objects */
13299       /* p->registry == r, so r has 2 refs, and the unref won't take the object away */
13300       if (p->registry) {
13301          p->registry = registry_unref(p->registry, "p->registry unreffed");
13302       }
13303       r->call = dialog_unref(r->call, "unrefing r->call");
13304    }
13305    /* If we have a limit, stop registration and give up */
13306    r->timeout = -1;
13307    if (global_regattempts_max && r->regattempts >= global_regattempts_max) {
13308       /* Ok, enough is enough. Don't try any more */
13309       /* We could add an external notification here...
13310          steal it from app_voicemail :-) */
13311       ast_log(LOG_NOTICE, "   -- Last Registration Attempt #%d failed, Giving up forever trying to register '%s@%s'\n", r->regattempts, r->username, r->hostname);
13312       r->regstate = REG_STATE_FAILED;
13313    } else {
13314       r->regstate = REG_STATE_UNREGISTERED;
13315       transmit_register(r, SIP_REGISTER, NULL, NULL);
13316       ast_log(LOG_NOTICE, "   -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts);
13317    }
13318    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));
13319    registry_unref(r, "unreffing registry_unref r");
13320    return 0;
13321 }
13322 
13323 static const char *sip_sanitized_host(const char *host)
13324 {
13325    struct ast_sockaddr addr = { { 0, 0, }, };
13326 
13327    /* peer/sip_pvt->tohost and sip_registry->hostname should never have a port
13328     * in them, so we use PARSE_PORT_FORBID here. If this lookup fails, we return
13329     * the original host which is most likely a host name and not an IP. */
13330    if (!ast_sockaddr_parse(&addr, host, PARSE_PORT_FORBID)) {
13331       return host;
13332    }
13333    return ast_sockaddr_stringify_host_remote(&addr);
13334 }
13335 
13336 /*! \brief Transmit register to SIP proxy or UA
13337  * auth = NULL on the initial registration (from sip_reregister())
13338  */
13339 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
13340 {
13341    struct sip_request req;
13342    char from[256];
13343    char to[256];
13344    char tmp[80];
13345    char addr[80];
13346    struct sip_pvt *p;
13347    struct sip_peer *peer = NULL;
13348    int res;
13349    int portno = 0;
13350 
13351    /* exit if we are already in process with this registrar ?*/
13352    if (r == NULL || ((auth == NULL) && (r->regstate == REG_STATE_REGSENT || r->regstate == REG_STATE_AUTHSENT))) {
13353       if (r) {
13354          ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
13355       }
13356       return 0;
13357    }
13358 
13359    if (r->dnsmgr == NULL) {
13360       char transport[MAXHOSTNAMELEN];
13361       peer = find_peer(r->hostname, NULL, TRUE, FINDPEERS, FALSE, 0);
13362       snprintf(transport, sizeof(transport), "_%s._%s",get_srv_service(r->transport), get_srv_protocol(r->transport)); /* have to use static get_transport function */
13363       r->us.ss.ss_family = get_address_family_filter(r->transport); /* Filter address family */
13364 
13365       /* No point in doing a DNS lookup of the register hostname if we're just going to
13366        * end up using an outbound proxy. obproxy_get is safe to call with either of r->call
13367        * or peer NULL. Since we're only concerned with its existence, we're not going to
13368        * bother getting a ref to the proxy*/
13369       if (!obproxy_get(r->call, peer)) {
13370          registry_addref(r, "add reg ref for dnsmgr");
13371          ast_dnsmgr_lookup_cb(peer ? peer->tohost : r->hostname, &r->us, &r->dnsmgr, sip_cfg.srvlookup ? transport : NULL, on_dns_update_registry, r);
13372          if (!r->dnsmgr) {
13373             /*dnsmgr refresh disabled, no reference added! */
13374             registry_unref(r, "remove reg ref, dnsmgr disabled");
13375          }
13376       }
13377       if (peer) {
13378          peer = unref_peer(peer, "removing peer ref for dnsmgr_lookup");
13379       }
13380    }
13381 
13382    if (r->call) { /* We have a registration */
13383       if (!auth) {
13384          ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
13385          return 0;
13386       } else {
13387          p = dialog_ref(r->call, "getting a copy of the r->call dialog in transmit_register");
13388          make_our_tag(p);  /* create a new local tag for every register attempt */
13389          ast_string_field_set(p, theirtag, NULL);  /* forget their old tag, so we don't match tags when getting response */
13390       }
13391    } else {
13392       /* Build callid for registration if we haven't registered before */
13393       if (!r->callid_valid) {
13394          build_callid_registry(r, &internip, default_fromdomain);
13395          r->callid_valid = TRUE;
13396       }
13397       /* Allocate SIP dialog for registration */
13398       if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER, NULL))) {
13399          ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
13400          return 0;
13401       }
13402       
13403       if (p->do_history) {
13404          append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
13405       }
13406 
13407       /* Use port number specified if no SRV record was found */
13408       if (!ast_sockaddr_isnull(&r->us)) {
13409          if (!ast_sockaddr_port(&r->us) && r->portno) {
13410             ast_sockaddr_set_port(&r->us, r->portno);
13411          }
13412 
13413          /* It is possible that DNS was unavailable at the time the peer was created.
13414           * Here, if we've updated the address in the registry via manually calling
13415           * ast_dnsmgr_lookup_cb() above, then we call the same function that dnsmgr would
13416           * call if it was updating a peer's address */
13417          if ((peer = find_peer(S_OR(r->peername, r->hostname), NULL, TRUE, FINDPEERS, FALSE, 0))) {
13418             if (ast_sockaddr_cmp(&peer->addr, &r->us)) {
13419                on_dns_update_peer(&peer->addr, &r->us, peer);
13420             }
13421             peer = unref_peer(peer, "unref after find_peer");
13422          }
13423       }
13424 
13425       /* Find address to hostname */
13426       if (create_addr(p, S_OR(r->peername, r->hostname), &r->us, 0)) {
13427          /* we have what we hope is a temporary network error,
13428           * probably DNS.  We need to reschedule a registration try */
13429          dialog_unlink_all(p);
13430          p = dialog_unref(p, "unref dialog after unlink_all");
13431          if (r->timeout > -1) {
13432             AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
13433                               registry_unref(_data, "del for REPLACE of registry ptr"),
13434                               registry_unref(r, "object ptr dec when SCHED_REPLACE add failed"),
13435                               registry_addref(r,"add for REPLACE registry ptr"));
13436             ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
13437          } else {
13438             r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, registry_addref(r, "add for REPLACE registry ptr"));
13439             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);
13440          }
13441          r->regattempts++;
13442          return 0;
13443       }
13444 
13445       /* Copy back Call-ID in case create_addr changed it */
13446       ast_string_field_set(r, callid, p->callid);
13447 
13448       if (!r->dnsmgr && r->portno) {
13449          ast_sockaddr_set_port(&p->sa, r->portno);
13450          ast_sockaddr_set_port(&p->recv, r->portno);
13451       }
13452       if (!ast_strlen_zero(p->fromdomain)) {
13453          portno = (p->fromdomainport) ? p->fromdomainport : STANDARD_SIP_PORT;
13454       } else if (!ast_strlen_zero(r->regdomain)) {
13455          portno = (r->regdomainport) ? r->regdomainport : STANDARD_SIP_PORT;
13456       } else {
13457          portno = ast_sockaddr_port(&p->sa);
13458       }
13459 
13460       ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Registration is outgoing call */
13461       r->call = dialog_ref(p, "copying dialog into registry r->call");     /* Save pointer to SIP dialog */
13462       p->registry = registry_addref(r, "transmit_register: addref to p->registry in transmit_register"); /* Add pointer to registry in packet */
13463       if (!ast_strlen_zero(r->secret)) {  /* Secret (password) */
13464          ast_string_field_set(p, peersecret, r->secret);
13465       }
13466       if (!ast_strlen_zero(r->md5secret))
13467          ast_string_field_set(p, peermd5secret, r->md5secret);
13468       /* User name in this realm
13469       - if authuser is set, use that, otherwise use username */
13470       if (!ast_strlen_zero(r->authuser)) {
13471          ast_string_field_set(p, peername, r->authuser);
13472          ast_string_field_set(p, authname, r->authuser);
13473       } else if (!ast_strlen_zero(r->username)) {
13474          ast_string_field_set(p, peername, r->username);
13475          ast_string_field_set(p, authname, r->username);
13476          ast_string_field_set(p, fromuser, r->username);
13477       }
13478       if (!ast_strlen_zero(r->username)) {
13479          ast_string_field_set(p, username, r->username);
13480       }
13481       /* Save extension in packet */
13482       if (!ast_strlen_zero(r->callback)) {
13483          ast_string_field_set(p, exten, r->callback);
13484       }
13485 
13486       /* Set transport and port so the correct contact is built */
13487       set_socket_transport(&p->socket, r->transport);
13488       if (r->transport == SIP_TRANSPORT_TLS || r->transport == SIP_TRANSPORT_TCP) {
13489          p->socket.port =
13490              htons(ast_sockaddr_port(&sip_tcp_desc.local_address));
13491       }
13492 
13493       /*
13494         check which address we should use in our contact header
13495         based on whether the remote host is on the external or
13496         internal network so we can register through nat
13497        */
13498       ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
13499       build_contact(p);
13500    }
13501 
13502    /* set up a timeout */
13503    if (auth == NULL)  {
13504       if (r->timeout > -1) {
13505          ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
13506       }
13507       AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
13508                         registry_unref(_data,"reg ptr unrefed from del in SCHED_REPLACE"),
13509                         registry_unref(r,"reg ptr unrefed from add failure in SCHED_REPLACE"),
13510                         registry_addref(r,"reg ptr reffed from add in SCHED_REPLACE"));
13511       ast_debug(1, "Scheduled a registration timeout for %s id  #%d \n", r->hostname, r->timeout);
13512    }
13513 
13514    snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)), p->tag);
13515    if (!ast_strlen_zero(p->theirtag)) {
13516       snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)), p->theirtag);
13517    } else {
13518       snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, S_OR(r->regdomain, sip_sanitized_host(p->tohost)));
13519    }
13520 
13521    /* Fromdomain is what we are registering to, regardless of actual
13522       host name from SRV */
13523    if (portno && portno != STANDARD_SIP_PORT) {
13524       snprintf(addr, sizeof(addr), "sip:%s:%d", S_OR(p->fromdomain,S_OR(r->regdomain, sip_sanitized_host(r->hostname))), portno);
13525    } else {
13526       snprintf(addr, sizeof(addr), "sip:%s", S_OR(p->fromdomain,S_OR(r->regdomain, sip_sanitized_host(r->hostname))));
13527    }
13528 
13529    ast_string_field_set(p, uri, addr);
13530 
13531    p->branch ^= ast_random();
13532 
13533    init_req(&req, sipmethod, addr);
13534 
13535    /* Add to CSEQ */
13536    snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
13537    p->ocseq = r->ocseq;
13538 
13539    build_via(p);
13540    add_header(&req, "Via", p->via);
13541    add_header_max_forwards(p, &req);
13542    add_header(&req, "From", from);
13543    add_header(&req, "To", to);
13544    add_header(&req, "Call-ID", p->callid);
13545    add_header(&req, "CSeq", tmp);
13546    if (!ast_strlen_zero(global_useragent))
13547       add_header(&req, "User-Agent", global_useragent);
13548 
13549    if (auth) {    /* Add auth header */
13550       add_header(&req, authheader, auth);
13551    } else if (!ast_strlen_zero(r->nonce)) {
13552       char digest[1024];
13553 
13554       /* We have auth data to reuse, build a digest header.
13555        * Note, this is not always useful because some parties do not
13556        * like nonces to be reused (for good reasons!) so they will
13557        * challenge us anyways.
13558        */
13559       if (sipdebug) {
13560          ast_debug(1, "   >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
13561       }
13562       ast_string_field_set(p, realm, r->realm);
13563       ast_string_field_set(p, nonce, r->nonce);
13564       ast_string_field_set(p, domain, r->authdomain);
13565       ast_string_field_set(p, opaque, r->opaque);
13566       ast_string_field_set(p, qop, r->qop);
13567       p->noncecount = ++r->noncecount;
13568 
13569       memset(digest, 0, sizeof(digest));
13570       if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
13571          add_header(&req, "Authorization", digest);
13572       } else {
13573          ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
13574       }
13575    }
13576 
13577    snprintf(tmp, sizeof(tmp), "%d", r->expiry);
13578    add_header(&req, "Expires", tmp);
13579    add_header(&req, "Contact", p->our_contact);
13580 
13581    initialize_initreq(p, &req);
13582    if (sip_debug_test_pvt(p)) {
13583       ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
13584    }
13585    r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
13586    r->regattempts++; /* Another attempt */
13587    ast_debug(4, "REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
13588    res = send_request(p, &req, XMIT_CRITICAL, p->ocseq);
13589    dialog_unref(p, "p is finished here at the end of transmit_register");
13590    return res;
13591 }
13592 
13593 /*! \brief Transmit text with SIP MESSAGE method */
13594 static int transmit_message_with_text(struct sip_pvt *p, const char *text)
13595 {
13596    struct sip_request req;
13597    
13598    reqprep(&req, p, SIP_MESSAGE, 0, 1);
13599    add_text(&req, text);
13600    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
13601 }
13602 
13603 /*! \brief Allocate SIP refer structure */
13604 static int sip_refer_allocate(struct sip_pvt *p)
13605 {
13606    p->refer = ast_calloc(1, sizeof(struct sip_refer));
13607    return p->refer ? 1 : 0;
13608 }
13609 
13610 /*! \brief Allocate SIP refer structure */
13611 static int sip_notify_allocate(struct sip_pvt *p)
13612 {
13613    p->notify = ast_calloc(1, sizeof(struct sip_notify));
13614    if (p->notify) {
13615       p->notify->content = ast_str_create(128);
13616    }
13617    return p->notify ? 1 : 0;
13618 }
13619 
13620 /*! \brief Transmit SIP REFER message (initiated by the transfer() dialplan application
13621    \note this is currently broken as we have no way of telling the dialplan
13622    engine whether a transfer succeeds or fails.
13623    \todo Fix the transfer() dialplan function so that a transfer may fail
13624 */
13625 static int transmit_refer(struct sip_pvt *p, const char *dest)
13626 {
13627    struct sip_request req = {
13628       .headers = 0,  
13629    };
13630    char from[256];
13631    const char *of;
13632    char *c;
13633    char referto[256];
13634    int   use_tls=FALSE;
13635 
13636    if (sipdebug) {
13637       ast_debug(1, "SIP transfer of %s to %s\n", p->callid, dest);
13638    }
13639 
13640    /* Are we transfering an inbound or outbound call ? */
13641    if (ast_test_flag(&p->flags[0], SIP_OUTGOING))  {
13642       of = get_header(&p->initreq, "To");
13643    } else {
13644       of = get_header(&p->initreq, "From");
13645    }
13646 
13647    ast_copy_string(from, of, sizeof(from));
13648    of = get_in_brackets(from);
13649    ast_string_field_set(p, from, of);
13650    if (!strncasecmp(of, "sip:", 4)) {
13651       of += 4;
13652    } else if (!strncasecmp(of, "sips:", 5)) {
13653       of += 5;
13654       use_tls = TRUE;
13655    } else {
13656       ast_log(LOG_NOTICE, "From address missing 'sip(s):', assuming sip:\n");
13657    }
13658    /* Get just the username part */
13659    if (strchr(dest, '@')) {
13660       c = NULL;
13661    } else if ((c = strchr(of, '@'))) {
13662       *c++ = '\0';
13663    }
13664    if (c) {
13665       snprintf(referto, sizeof(referto), "<sip%s:%s@%s>", use_tls ? "s" : "", dest, c);
13666    } else {
13667       snprintf(referto, sizeof(referto), "<sip%s:%s>", use_tls ? "s" : "", dest);
13668    }
13669 
13670    /* save in case we get 407 challenge */
13671    sip_refer_allocate(p);
13672    ast_copy_string(p->refer->refer_to, referto, sizeof(p->refer->refer_to));
13673    ast_copy_string(p->refer->referred_by, p->our_contact, sizeof(p->refer->referred_by));
13674    p->refer->status = REFER_SENT;   /* Set refer status */
13675 
13676    reqprep(&req, p, SIP_REFER, 0, 1);
13677 
13678    add_header(&req, "Refer-To", referto);
13679    add_header(&req, "Allow", ALLOWED_METHODS);
13680    add_supported_header(p, &req);
13681    if (!ast_strlen_zero(p->our_contact)) {
13682       add_header(&req, "Referred-By", p->our_contact);
13683    }
13684 
13685    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
13686 
13687    /* We should propably wait for a NOTIFY here until we ack the transfer */
13688    /* Maybe fork a new thread and wait for a STATUS of REFER_200OK on the refer status before returning to app_transfer */
13689 
13690    /*! \todo In theory, we should hang around and wait for a reply, before
13691    returning to the dial plan here. Don't know really how that would
13692    affect the transfer() app or the pbx, but, well, to make this
13693    useful we should have a STATUS code on transfer().
13694    */
13695 }
13696 
13697 /*! \brief Send SIP INFO advice of charge message */
13698 static int transmit_info_with_aoc(struct sip_pvt *p, struct ast_aoc_decoded *decoded)
13699 {
13700    struct sip_request req;
13701    struct ast_str *str = ast_str_alloca(512);
13702    const struct ast_aoc_unit_entry *unit_entry = ast_aoc_get_unit_info(decoded, 0);
13703    enum ast_aoc_charge_type charging = ast_aoc_get_charge_type(decoded);
13704 
13705    reqprep(&req, p, SIP_INFO, 0, 1);
13706 
13707    if (ast_aoc_get_msg_type(decoded) == AST_AOC_D) {
13708       ast_str_append(&str, 0, "type=active;");
13709    } else if (ast_aoc_get_msg_type(decoded) == AST_AOC_E) {
13710       ast_str_append(&str, 0, "type=terminated;");
13711    } else {
13712       /* unsupported message type */
13713       return -1;
13714    }
13715 
13716    switch (charging) {
13717    case AST_AOC_CHARGE_FREE:
13718       ast_str_append(&str, 0, "free-of-charge;");
13719       break;
13720    case AST_AOC_CHARGE_CURRENCY:
13721       ast_str_append(&str, 0, "charging;");
13722       ast_str_append(&str, 0, "charging-info=currency;");
13723       ast_str_append(&str, 0, "amount=%u;", ast_aoc_get_currency_amount(decoded));
13724       ast_str_append(&str, 0, "multiplier=%s;", ast_aoc_get_currency_multiplier_decimal(decoded));
13725       if (!ast_strlen_zero(ast_aoc_get_currency_name(decoded))) {
13726          ast_str_append(&str, 0, "currency=%s;", ast_aoc_get_currency_name(decoded));
13727       }
13728       break;
13729    case AST_AOC_CHARGE_UNIT:
13730       ast_str_append(&str, 0, "charging;");
13731       ast_str_append(&str, 0, "charging-info=pulse;");
13732       if (unit_entry) {
13733          ast_str_append(&str, 0, "recorded-units=%u;", unit_entry->amount);
13734       }
13735       break;
13736    default:
13737       ast_str_append(&str, 0, "not-available;");
13738    };
13739 
13740    add_header(&req, "AOC", ast_str_buffer(str));
13741 
13742    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
13743 }
13744 
13745 /*! \brief Send SIP INFO dtmf message, see Cisco documentation on cisco.com */
13746 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
13747 {
13748    struct sip_request req;
13749    
13750    reqprep(&req, p, SIP_INFO, 0, 1);
13751    add_digit(&req, digit, duration, (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO));
13752    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
13753 }
13754 
13755 /*! \brief Send SIP INFO with video update request */
13756 static int transmit_info_with_vidupdate(struct sip_pvt *p)
13757 {
13758    struct sip_request req;
13759    
13760    reqprep(&req, p, SIP_INFO, 0, 1);
13761    add_vidupdate(&req);
13762    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
13763 }
13764 
13765 /*! \brief Transmit generic SIP request
13766    returns XMIT_ERROR if transmit failed with a critical error (don't retry)
13767 */
13768 static int transmit_request(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch)
13769 {
13770    struct sip_request resp;
13771    
13772    reqprep(&resp, p, sipmethod, seqno, newbranch);
13773    if (sipmethod == SIP_CANCEL && p->answered_elsewhere) {
13774       add_header(&resp, "Reason", "SIP;cause=200;text=\"Call completed elsewhere\"");
13775    }
13776 
13777    if (sipmethod == SIP_ACK) {
13778       p->invitestate = INV_CONFIRMED;
13779    }
13780 
13781    return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
13782 }
13783 
13784 /*! \brief return the request and response header for a 401 or 407 code */
13785 static void auth_headers(enum sip_auth_type code, char **header, char **respheader)
13786 {
13787    if (code == WWW_AUTH) {       /* 401 */
13788       *header = "WWW-Authenticate";
13789       *respheader = "Authorization";
13790    } else if (code == PROXY_AUTH) { /* 407 */
13791       *header = "Proxy-Authenticate";
13792       *respheader = "Proxy-Authorization";
13793    } else {
13794       ast_verbose("-- wrong response code %d\n", code);
13795       *header = *respheader = "Invalid";
13796    }
13797 }
13798 
13799 /*! \brief Transmit SIP request, auth added */
13800 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, uint32_t seqno, enum xmittype reliable, int newbranch)
13801 {
13802    struct sip_request resp;
13803    
13804    reqprep(&resp, p, sipmethod, seqno, newbranch);
13805    if (!ast_strlen_zero(p->realm)) {
13806       char digest[1024];
13807 
13808       memset(digest, 0, sizeof(digest));
13809       if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
13810          char *dummy, *response;
13811          enum sip_auth_type code = p->options ? p->options->auth_type : PROXY_AUTH; /* XXX force 407 if unknown */
13812          auth_headers(code, &dummy, &response);
13813          add_header(&resp, response, digest);
13814       } else {
13815          ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
13816       }
13817    }
13818    /* If we are hanging up and know a cause for that, send it in clear text to make
13819       debugging easier. */
13820    if (sipmethod == SIP_BYE)  {
13821       char buf[20];
13822 
13823       if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON) && p->hangupcause) {
13824          sprintf(buf, "Q.850;cause=%i", p->hangupcause & 0x7f);
13825          add_header(&resp, "Reason", buf);
13826       }
13827 
13828       add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->hangupcause));
13829       snprintf(buf, sizeof(buf), "%d", p->hangupcause);
13830       add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
13831    }
13832 
13833    return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);   
13834 }
13835 
13836 /*! \brief Remove registration data from realtime database or AST/DB when registration expires */
13837 static void destroy_association(struct sip_peer *peer)
13838 {
13839    int realtimeregs = ast_check_realtime("sipregs");
13840    char *tablename = (realtimeregs) ? "sipregs" : "sippeers";
13841 
13842    if (!sip_cfg.ignore_regexpire) {
13843       if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
13844          ast_update_realtime(tablename, "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", "regserver", "", "useragent", "", "lastms", "0", SENTINEL);
13845       } else {
13846          ast_db_del("SIP/Registry", peer->name);
13847          ast_db_del("SIP/PeerMethods", peer->name);
13848       }
13849    }
13850 }
13851 
13852 static void set_socket_transport(struct sip_socket *socket, int transport)
13853 {
13854    /* if the transport type changes, clear all socket data */
13855    if (socket->type != transport) {
13856       socket->fd = -1;
13857       socket->type = transport;
13858       if (socket->tcptls_session) {
13859          ao2_ref(socket->tcptls_session, -1);
13860          socket->tcptls_session = NULL;
13861       }
13862    }
13863 }
13864 
13865 /*! \brief Expire registration of SIP peer */
13866 static int expire_register(const void *data)
13867 {
13868    struct sip_peer *peer = (struct sip_peer *)data;
13869 
13870    if (!peer) {      /* Hmmm. We have no peer. Weird. */
13871       return 0;
13872    }
13873 
13874    peer->expire = -1;
13875    peer->portinuri = 0;
13876 
13877    destroy_association(peer); /* remove registration data from storage */
13878    set_socket_transport(&peer->socket, peer->default_outbound_transport);
13879 
13880    if (peer->socket.tcptls_session) {
13881       ao2_ref(peer->socket.tcptls_session, -1);
13882       peer->socket.tcptls_session = NULL;
13883    }
13884 
13885    manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
13886    register_peer_exten(peer, FALSE);   /* Remove regexten */
13887    ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
13888 
13889    /* Do we need to release this peer from memory?
13890       Only for realtime peers and autocreated peers
13891    */
13892    if (peer->is_realtime) {
13893       ast_debug(3, "-REALTIME- peer expired registration. Name: %s. Realtime peer objects now %d\n", peer->name, rpeerobjs);
13894    }
13895 
13896    if (peer->selfdestruct ||
13897        ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
13898       unlink_peer_from_tables(peer);
13899    } else if (!ast_sockaddr_isnull(&peer->addr)) {
13900       /* If we aren't self-destructing a temp_peer, we still need to unlink the peer
13901        * from the peers_by_ip table, otherwise we end up with multiple copies hanging
13902        * around each time a registration expires and the peer re-registers. */
13903       ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
13904    }
13905 
13906    /* Only clear the addr after we check for destruction.  The addr must remain
13907     * in order to unlink from the peers_by_ip container correctly */
13908    memset(&peer->addr, 0, sizeof(peer->addr));
13909 
13910    unref_peer(peer, "removing peer ref for expire_register");
13911 
13912    return 0;
13913 }
13914 
13915 /*! \brief Poke peer (send qualify to check if peer is alive and well) */
13916 static int sip_poke_peer_s(const void *data)
13917 {
13918    struct sip_peer *peer = (struct sip_peer *)data;
13919    struct sip_peer *foundpeer;
13920 
13921    peer->pokeexpire = -1;
13922 
13923    foundpeer = ao2_find(peers, peer, OBJ_POINTER);
13924    if (!foundpeer) {
13925       unref_peer(peer, "removing poke peer ref");
13926       return 0;
13927    } else if (foundpeer->name != peer->name) {
13928       unref_peer(foundpeer, "removing above peer ref");
13929       unref_peer(peer, "removing poke peer ref");
13930       return 0;
13931    }
13932 
13933    unref_peer(foundpeer, "removing above peer ref");
13934    sip_poke_peer(peer, 0);
13935    unref_peer(peer, "removing poke peer ref");
13936 
13937    return 0;
13938 }
13939 
13940 /*! \brief Get registration details from Asterisk DB */
13941 static void reg_source_db(struct sip_peer *peer)
13942 {
13943    char data[256];
13944    struct ast_sockaddr sa;
13945    int expire;
13946    char full_addr[128];
13947    AST_DECLARE_APP_ARGS(args,
13948       AST_APP_ARG(addr);
13949       AST_APP_ARG(port);
13950       AST_APP_ARG(expiry_str);
13951       AST_APP_ARG(username);
13952       AST_APP_ARG(contact);
13953    );
13954 
13955    /* If read-only RT backend, then refresh from local DB cache */
13956    if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
13957       return;
13958    }
13959    if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data))) {
13960       return;
13961    }
13962 
13963    AST_NONSTANDARD_RAW_ARGS(args, data, ':');
13964 
13965    snprintf(full_addr, sizeof(full_addr), "%s:%s", args.addr, args.port);
13966 
13967    if (!ast_sockaddr_parse(&sa, full_addr, 0)) {
13968       return;
13969    }
13970 
13971    if (args.expiry_str) {
13972       expire = atoi(args.expiry_str);
13973    } else {
13974       return;
13975    }
13976 
13977    if (args.username) {
13978       ast_string_field_set(peer, username, args.username);
13979    }
13980    if (args.contact) {
13981       ast_string_field_set(peer, fullcontact, args.contact);
13982    }
13983 
13984    ast_debug(2, "SIP Seeding peer from astdb: '%s' at %s@%s for %d\n",
13985        peer->name, peer->username, ast_sockaddr_stringify_host(&sa), expire);
13986 
13987    ast_sockaddr_copy(&peer->addr, &sa);
13988    if (peer->maxms) {
13989       /* Don't poke peer immediately, just schedule it within qualifyfreq */
13990       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
13991             ast_random() % ((peer->qualifyfreq) ? peer->qualifyfreq : global_qualifyfreq) + 1,
13992             sip_poke_peer_s, peer,
13993             unref_peer(_data, "removing poke peer ref"),
13994             unref_peer(peer, "removing poke peer ref"),
13995             ref_peer(peer, "adding poke peer ref"));
13996    }
13997    AST_SCHED_REPLACE_UNREF(peer->expire, sched, (expire + 10) * 1000, expire_register, peer,
13998          unref_peer(_data, "remove registration ref"),
13999          unref_peer(peer, "remove registration ref"),
14000          ref_peer(peer, "add registration ref"));
14001    register_peer_exten(peer, TRUE);
14002 }
14003 
14004 /*! \brief Save contact header for 200 OK on INVITE */
14005 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
14006 {
14007    char contact[SIPBUFSIZE];
14008    char *c;
14009 
14010    /* Look for brackets */
14011    ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
14012    c = get_in_brackets(contact);
14013 
14014    /* Save full contact to call pvt for later bye or re-invite */
14015    ast_string_field_set(pvt, fullcontact, c);
14016 
14017    /* Save URI for later ACKs, BYE or RE-invites */
14018    ast_string_field_set(pvt, okcontacturi, c);
14019 
14020    /* We should return false for URI:s we can't handle,
14021       like tel:, mailto:,ldap: etc */
14022    return TRUE;      
14023 }
14024 
14025 /*! \brief parse uri in a way that allows semicolon stripping if legacy mode is enabled
14026  *
14027  * \note This calls parse_uri which has the unexpected property that passing more
14028  *       arguments results in more splitting. Most common is to leave out the pass
14029  *       argument, causing user to contain user:pass if available.
14030  */
14031 static int parse_uri_legacy_check(char *uri, const char *scheme, char **user, char **pass, char **hostport, char **transport)
14032 {
14033    int ret = parse_uri(uri, scheme, user, pass, hostport, transport);
14034    if (sip_cfg.legacy_useroption_parsing) { /* if legacy mode is active, strip semis from the user field */
14035       char *p;
14036       if ((p = strchr(uri, (int)';'))) {
14037          *p = '\0';
14038       }
14039    }
14040    return ret;
14041 }
14042 
14043 static int __set_address_from_contact(const char *fullcontact, struct ast_sockaddr *addr, int tcp)
14044 {
14045    char *hostport, *transport;
14046    char contact_buf[256];
14047    char *contact;
14048 
14049    /* Work on a copy */
14050    ast_copy_string(contact_buf, fullcontact, sizeof(contact_buf));
14051    contact = contact_buf;
14052 
14053    /* 
14054     * We have only the part in <brackets> here so we just need to parse a SIP URI.
14055     *
14056     * Note: The outbound proxy could be using UDP between the proxy and Asterisk.
14057     * We still need to be able to send to the remote agent through the proxy.
14058     */
14059 
14060    if (parse_uri_legacy_check(contact, "sip:,sips:", &contact, NULL, &hostport,
14061             &transport)) {
14062       ast_log(LOG_WARNING, "Invalid contact uri %s (missing sip: or sips:), attempting to use anyway\n", fullcontact);
14063    }
14064 
14065    /* XXX This could block for a long time XXX */
14066    /* We should only do this if it's a name, not an IP */
14067    /* \todo - if there's no PORT number in contact - we are required to check NAPTR/SRV records
14068       to find transport, port address and hostname. If there's a port number, we have to
14069       assume that the hostport part is a host name and only look for an A/AAAA record in DNS.
14070    */
14071 
14072    /* If we took in an invalid URI, hostport may not have been initialized */
14073    /* ast_sockaddr_resolve requires an initialized hostport string. */
14074    if (ast_strlen_zero(hostport)) {
14075       ast_log(LOG_WARNING, "Invalid URI: parse_uri failed to acquire hostport\n");
14076       return -1;
14077    }
14078 
14079    if (ast_sockaddr_resolve_first_transport(addr, hostport, 0, get_transport_str2enum(transport))) {
14080       ast_log(LOG_WARNING, "Invalid host name in Contact: (can't "
14081          "resolve in DNS) : '%s'\n", hostport);
14082       return -1;
14083    }
14084 
14085    /* set port */
14086    if (!ast_sockaddr_port(addr)) {
14087       ast_sockaddr_set_port(addr,
14088                   (get_transport_str2enum(transport) ==
14089                    SIP_TRANSPORT_TLS ||
14090                    !strncasecmp(fullcontact, "sips", 4)) ?
14091                   STANDARD_TLS_PORT : STANDARD_SIP_PORT);
14092    }
14093 
14094    return 0;
14095 }
14096 
14097 /*! \brief Change the other partys IP address based on given contact */
14098 static int set_address_from_contact(struct sip_pvt *pvt)
14099 {
14100    if (ast_test_flag(&pvt->flags[0], SIP_NAT_FORCE_RPORT)) {
14101       /* NAT: Don't trust the contact field.  Just use what they came to us
14102          with. */
14103       /*! \todo We need to save the TRANSPORT here too */
14104       pvt->sa = pvt->recv;
14105       return 0;
14106    }
14107 
14108    return __set_address_from_contact(pvt->fullcontact, &pvt->sa, pvt->socket.type == SIP_TRANSPORT_TLS ? 1 : 0);
14109 }
14110 
14111 /*! \brief Parse contact header and save registration (peer registration) */
14112 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
14113 {
14114    char contact[SIPBUFSIZE];
14115    char data[SIPBUFSIZE];
14116    const char *expires = get_header(req, "Expires");
14117    int expire = atoi(expires);
14118    char *curi = NULL, *hostport = NULL, *transport = NULL;
14119    int transport_type;
14120    const char *useragent;
14121    struct ast_sockaddr oldsin, testsa;
14122    char *firstcuri = NULL;
14123    int start = 0;
14124    int wildcard_found = 0;
14125    int single_binding_found = 0;
14126 
14127    ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
14128 
14129    if (ast_strlen_zero(expires)) {  /* No expires header, try look in Contact: */
14130       char *s = strcasestr(contact, ";expires=");
14131       if (s) {
14132          expires = strsep(&s, ";"); /* trim ; and beyond */
14133          if (sscanf(expires + 9, "%30d", &expire) != 1) {
14134             expire = default_expiry;
14135          }
14136       } else {
14137          /* Nothing has been specified */
14138          expire = default_expiry;
14139       }
14140    }
14141 
14142    copy_socket_data(&pvt->socket, &req->socket);
14143 
14144    do {
14145       /* Look for brackets */
14146       curi = contact;
14147       if (strchr(contact, '<') == NULL)   /* No <, check for ; and strip it */
14148          strsep(&curi, ";");  /* This is Header options, not URI options */
14149       curi = get_in_brackets(contact);
14150       if (!firstcuri) {
14151          firstcuri = ast_strdupa(curi);
14152       }
14153 
14154       if (!strcasecmp(curi, "*")) {
14155          wildcard_found = 1;
14156       } else {
14157          single_binding_found = 1;
14158       }
14159 
14160       if (wildcard_found && (ast_strlen_zero(expires) || expire != 0 || single_binding_found)) {
14161          /* Contact header parameter "*" detected, so punt if: Expires header is missing,
14162           * Expires value is not zero, or another Contact header is present. */
14163          return PARSE_REGISTER_FAILED;
14164       }
14165 
14166       ast_copy_string(contact, __get_header(req, "Contact", &start), sizeof(contact));
14167    } while (!ast_strlen_zero(contact));
14168    curi = firstcuri;
14169 
14170    /* if they did not specify Contact: or Expires:, they are querying
14171       what we currently have stored as their contact address, so return
14172       it
14173    */
14174    if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
14175       /* If we have an active registration, tell them when the registration is going to expire */
14176       if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact)) {
14177          pvt->expiry = ast_sched_when(sched, peer->expire);
14178       }
14179       return PARSE_REGISTER_QUERY;
14180    } else if (!strcasecmp(curi, "*") || !expire) { /* Unregister this peer */
14181       /* This means remove all registrations and return OK */
14182       AST_SCHED_DEL_UNREF(sched, peer->expire,
14183             unref_peer(peer, "remove register expire ref"));
14184       ast_verb(3, "Unregistered SIP '%s'\n", peer->name);
14185       expire_register(ref_peer(peer,"add ref for explicit expire_register"));
14186       return PARSE_REGISTER_UPDATE;
14187    }
14188 
14189    /* Store whatever we got as a contact from the client */
14190    ast_string_field_set(peer, fullcontact, curi);
14191 
14192    /* For the 200 OK, we should use the received contact */
14193    ast_string_field_build(pvt, our_contact, "<%s>", curi);
14194 
14195    /* Make sure it's a SIP URL */
14196    if (ast_strlen_zero(curi) || parse_uri_legacy_check(curi, "sip:,sips:", &curi, NULL, &hostport, &transport)) {
14197       ast_log(LOG_NOTICE, "Not a valid SIP contact (missing sip:/sips:) trying to use anyway\n");
14198    }
14199 
14200    /* handle the transport type specified in Contact header. */
14201    if (!(transport_type = get_transport_str2enum(transport))) {
14202       transport_type = pvt->socket.type;
14203    }
14204 
14205    /* if the peer's socket type is different than the Registration
14206     * transport type, change it.  If it got this far, it is a
14207     * supported type, but check just in case */
14208    if ((peer->socket.type != transport_type) && (peer->transports & transport_type)) {
14209       set_socket_transport(&peer->socket, transport_type);
14210    }
14211 
14212    oldsin = peer->addr;
14213 
14214    /* If we were already linked into the peers_by_ip container unlink ourselves so nobody can find us */
14215    if (!ast_sockaddr_isnull(&peer->addr) && (!peer->is_realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS))) {
14216       ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
14217    }
14218 
14219    if (!ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) && !ast_test_flag(&peer->flags[0], SIP_NAT_RPORT_PRESENT)) {
14220        /* use the data provided in the Contact header for call routing */
14221       ast_debug(1, "Store REGISTER's Contact header for call routing.\n");
14222       /* XXX This could block for a long time XXX */
14223       /*! \todo Check NAPTR/SRV if we have not got a port in the URI */
14224       if (ast_sockaddr_resolve_first_transport(&testsa, hostport, 0, peer->socket.type)) {
14225          ast_log(LOG_WARNING, "Invalid hostport '%s'\n", hostport);
14226          ast_string_field_set(peer, fullcontact, "");
14227          ast_string_field_set(pvt, our_contact, "");
14228          return PARSE_REGISTER_FAILED;
14229       }
14230 
14231       /* If we have a port number in the given URI, make sure we do remember to not check for NAPTR/SRV records.
14232          The hostport part is actually a host. */
14233       peer->portinuri = ast_sockaddr_port(&testsa) ? TRUE : FALSE;
14234 
14235       if (!ast_sockaddr_port(&testsa)) {
14236          ast_sockaddr_set_port(&testsa, default_sip_port(transport_type));
14237       }
14238 
14239       ast_sockaddr_copy(&peer->addr, &testsa);
14240    } else {
14241       /* Don't trust the contact field.  Just use what they came to us
14242          with */
14243       ast_debug(1, "Store REGISTER's src-IP:port for call routing.\n");
14244       peer->addr = pvt->recv;
14245    }
14246 
14247    /* Check that they're allowed to register at this IP */
14248    if (ast_apply_ha(sip_cfg.contact_ha, &peer->addr) != AST_SENSE_ALLOW ||
14249          ast_apply_ha(peer->contactha, &peer->addr) != AST_SENSE_ALLOW) {
14250       ast_log(LOG_WARNING, "Domain '%s' disallowed by contact ACL (violating IP %s)\n", hostport,
14251          ast_sockaddr_stringify_addr(&testsa));
14252       ast_string_field_set(peer, fullcontact, "");
14253       ast_string_field_set(pvt, our_contact, "");
14254       return PARSE_REGISTER_DENIED;
14255    }
14256 
14257    /* if the Contact header information copied into peer->addr matches the
14258     * received address, and the transport types are the same, then copy socket
14259     * data into the peer struct */
14260    if ((peer->socket.type == pvt->socket.type) &&
14261       !ast_sockaddr_cmp(&peer->addr, &pvt->recv)) {
14262       copy_socket_data(&peer->socket, &pvt->socket);
14263    }
14264 
14265    /* Now that our address has been updated put ourselves back into the container for lookups */
14266    if (!peer->is_realtime || ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
14267       ao2_t_link(peers_by_ip, peer, "ao2_link into peers_by_ip table");
14268    }
14269 
14270    /* Save SIP options profile */
14271    peer->sipoptions = pvt->sipoptions;
14272 
14273    if (!ast_strlen_zero(curi) && ast_strlen_zero(peer->username)) {
14274       ast_string_field_set(peer, username, curi);
14275    }
14276 
14277    AST_SCHED_DEL_UNREF(sched, peer->expire,
14278          unref_peer(peer, "remove register expire ref"));
14279 
14280    if (expire > max_expiry) {
14281       expire = max_expiry;
14282    }
14283    if (expire < min_expiry) {
14284       expire = min_expiry;
14285    }
14286    if (peer->is_realtime && !ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
14287       peer->expire = -1;
14288    } else {
14289       peer->expire = ast_sched_add(sched, (expire + 10) * 1000, expire_register,
14290             ref_peer(peer, "add registration ref"));
14291       if (peer->expire == -1) {
14292          unref_peer(peer, "remote registration ref");
14293       }
14294    }
14295    pvt->expiry = expire;
14296    snprintf(data, sizeof(data), "%s:%d:%s:%s", ast_sockaddr_stringify(&peer->addr),
14297        expire, peer->username, peer->fullcontact);
14298    /* We might not immediately be able to reconnect via TCP, but try caching it anyhow */
14299    if (!peer->rt_fromcontact || !sip_cfg.peer_rtupdate)
14300       ast_db_put("SIP/Registry", peer->name, data);
14301    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));
14302 
14303    /* Is this a new IP address for us? */
14304    if (VERBOSITY_ATLEAST(2) && ast_sockaddr_cmp(&peer->addr, &oldsin)) {
14305       ast_verbose(VERBOSE_PREFIX_3 "Registered SIP '%s' at %s\n", peer->name,
14306             ast_sockaddr_stringify(&peer->addr));
14307    }
14308    sip_poke_peer(peer, 0);
14309    register_peer_exten(peer, 1);
14310    
14311    /* Save User agent */
14312    useragent = get_header(req, "User-Agent");
14313    if (strcasecmp(useragent, peer->useragent)) {
14314       ast_string_field_set(peer, useragent, useragent);
14315       ast_verb(4, "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
14316    }
14317    return PARSE_REGISTER_UPDATE;
14318 }
14319 
14320 /*! \brief Remove route from route list */
14321 static void free_old_route(struct sip_route *route)
14322 {
14323    struct sip_route *next;
14324 
14325    while (route) {
14326       next = route->next;
14327       ast_free(route);
14328       route = next;
14329    }
14330 }
14331 
14332 /*! \brief List all routes - mostly for debugging */
14333 static void list_route(struct sip_route *route)
14334 {
14335    if (!route) {
14336       ast_verbose("list_route: no route\n");
14337    } else {
14338       for (;route; route = route->next)
14339          ast_verbose("list_route: hop: <%s>\n", route->hop);
14340    }
14341 }
14342 
14343 /*! \brief Build route list from Record-Route header 
14344     \param resp the SIP response code or 0 for a request */
14345 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards, int resp)
14346 {
14347    struct sip_route *thishop, *head, *tail;
14348    int start = 0;
14349    int len;
14350    const char *rr, *c;
14351 
14352    /* Once a persistent route is set, don't fool with it */
14353    if (p->route && p->route_persistent) {
14354       ast_debug(1, "build_route: Retaining previous route: <%s>\n", p->route->hop);
14355       return;
14356    }
14357 
14358    if (p->route) {
14359       free_old_route(p->route);
14360       p->route = NULL;
14361    }
14362 
14363    /* We only want to create the route set the first time this is called except
14364       it is called from a provisional response.*/
14365    if ((resp < 100) || (resp > 199)) {
14366       p->route_persistent = 1;
14367    }
14368 
14369    /* Build a tailq, then assign it to p->route when done.
14370     * If backwards, we add entries from the head so they end up
14371     * in reverse order. However, we do need to maintain a correct
14372     * tail pointer because the contact is always at the end.
14373     */
14374    head = NULL;
14375    tail = head;
14376    /* 1st we pass through all the hops in any Record-Route headers */
14377    for (;;) {
14378       /* Each Record-Route header */
14379       char rr_copy[256];
14380       char *rr_copy_ptr;
14381       char *rr_iter;
14382       rr = __get_header(req, "Record-Route", &start);
14383       if (*rr == '\0') {
14384          break;
14385       }
14386       ast_copy_string(rr_copy, rr, sizeof(rr_copy));
14387       rr_copy_ptr = rr_copy;
14388       while ((rr_iter = strsep(&rr_copy_ptr, ","))) { /* Each route entry */
14389          char *uri = get_in_brackets(rr_iter);
14390          len = strlen(uri) + 1;
14391          /* Make a struct route */
14392          if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
14393             /* ast_calloc is not needed because all fields are initialized in this block */
14394             ast_copy_string(thishop->hop, uri, len);
14395             ast_debug(2, "build_route: Record-Route hop: <%s>\n", thishop->hop);
14396             /* Link in */
14397             if (backwards) {
14398                /* Link in at head so they end up in reverse order */
14399                thishop->next = head;
14400                head = thishop;
14401                /* If this was the first then it'll be the tail */
14402                if (!tail) {
14403                   tail = thishop;
14404                }
14405             } else {
14406                thishop->next = NULL;
14407                /* Link in at the end */
14408                if (tail) {
14409                   tail->next = thishop;
14410                } else {
14411                   head = thishop;
14412                }
14413                tail = thishop;
14414             }
14415          }
14416       }
14417    }
14418 
14419    /* Only append the contact if we are dealing with a strict router */
14420    if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop, ";lr") == NULL) ) {
14421       /* 2nd append the Contact: if there is one */
14422       /* Can be multiple Contact headers, comma separated values - we just take the first */
14423       char *contact = ast_strdupa(get_header(req, "Contact"));
14424       if (!ast_strlen_zero(contact)) {
14425          ast_debug(2, "build_route: Contact hop: %s\n", contact);
14426          /* Look for <: delimited address */
14427          c = get_in_brackets(contact);
14428          len = strlen(c) + 1;
14429          if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
14430             /* ast_calloc is not needed because all fields are initialized in this block */
14431             ast_copy_string(thishop->hop, c, len);
14432             thishop->next = NULL;
14433             /* Goes at the end */
14434             if (tail) {
14435                tail->next = thishop;
14436             } else {
14437                head = thishop;
14438             }
14439          }
14440       }
14441    }
14442 
14443    /* Store as new route */
14444    p->route = head;
14445 
14446    /* For debugging dump what we ended up with */
14447    if (sip_debug_test_pvt(p)) {
14448       list_route(p->route);
14449    }
14450 }
14451 
14452 /*! \brief builds the sip_pvt's randdata field which is used for the nonce
14453  *  challenge.  When forceupdate is not set, the nonce is only updated if
14454  *  the current one is stale.  In this case, a stalenonce is one which
14455  *  has already received a response, if a nonce has not received a response
14456  *  it is not always necessary or beneficial to create a new one. */
14457 
14458 static void set_nonce_randdata(struct sip_pvt *p, int forceupdate)
14459 {
14460    if (p->stalenonce || forceupdate || ast_strlen_zero(p->randdata)) {
14461       ast_string_field_build(p, randdata, "%08lx", ast_random()); /* Create nonce for challenge */
14462       p->stalenonce = 0;
14463    }
14464 }
14465 
14466 AST_THREADSTORAGE(check_auth_buf);
14467 #define CHECK_AUTH_BUF_INITLEN   256
14468 
14469 /*! \brief  Check user authorization from peer definition
14470    Some actions, like REGISTER and INVITEs from peers require
14471    authentication (if peer have secret set)
14472     \return 0 on success, non-zero on error
14473 */
14474 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
14475                 const char *secret, const char *md5secret, int sipmethod,
14476                 const char *uri, enum xmittype reliable, int ignore)
14477 {
14478    const char *response;
14479    char *reqheader, *respheader;
14480    const char *authtoken;
14481    char a1_hash[256];
14482    char resp_hash[256]="";
14483    char *c;
14484    int  wrongnonce = FALSE;
14485    int  good_response;
14486    const char *usednonce = p->randdata;
14487    struct ast_str *buf;
14488    int res;
14489 
14490    /* table of recognised keywords, and their value in the digest */
14491    enum keys { K_RESP, K_URI, K_USER, K_NONCE, K_LAST };
14492    struct x {
14493       const char *key;
14494       const char *s;
14495    } *i, keys[] = {
14496       [K_RESP] = { "response=", "" },
14497       [K_URI] = { "uri=", "" },
14498       [K_USER] = { "username=", "" },
14499       [K_NONCE] = { "nonce=", "" },
14500       [K_LAST] = { NULL, NULL}
14501    };
14502 
14503    /* Always OK if no secret */
14504    if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret))
14505       return AUTH_SUCCESSFUL;
14506 
14507    /* Always auth with WWW-auth since we're NOT a proxy */
14508    /* Using proxy-auth in a B2BUA may block proxy authorization in the same transaction */
14509    response = "401 Unauthorized";
14510 
14511    /*
14512     * Note the apparent swap of arguments below, compared to other
14513     * usages of auth_headers().
14514     */
14515    auth_headers(WWW_AUTH, &respheader, &reqheader);
14516 
14517    authtoken =  get_header(req, reqheader);  
14518    if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
14519       /* This is a retransmitted invite/register/etc, don't reconstruct authentication
14520          information */
14521       if (!reliable) {
14522          /* Resend message if this was NOT a reliable delivery.   Otherwise the
14523             retransmission should get it */
14524          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
14525          /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
14526          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14527       }
14528       return AUTH_CHALLENGE_SENT;
14529    } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
14530       /* We have no auth, so issue challenge and request authentication */
14531       set_nonce_randdata(p, 1); /* Create nonce for challenge */
14532       transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
14533       /* Schedule auto destroy in 32 seconds */
14534       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14535       return AUTH_CHALLENGE_SENT;
14536    }
14537 
14538    /* --- We have auth, so check it */
14539 
14540    /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
14541       an example in the spec of just what it is you're doing a hash on. */
14542 
14543    if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
14544       return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
14545    }
14546 
14547    /* Make a copy of the response and parse it */
14548    res = ast_str_set(&buf, 0, "%s", authtoken);
14549 
14550    if (res == AST_DYNSTR_BUILD_FAILED) {
14551       return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
14552    }
14553 
14554    c = buf->str;
14555 
14556    while(c && *(c = ast_skip_blanks(c)) ) { /* lookup for keys */
14557       for (i = keys; i->key != NULL; i++) {
14558          const char *separator = ",";  /* default */
14559 
14560          if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
14561             continue;
14562          }
14563          /* Found. Skip keyword, take text in quotes or up to the separator. */
14564          c += strlen(i->key);
14565          if (*c == '"') { /* in quotes. Skip first and look for last */
14566             c++;
14567             separator = "\"";
14568          }
14569          i->s = c;
14570          strsep(&c, separator);
14571          break;
14572       }
14573       if (i->key == NULL) { /* not found, jump after space or comma */
14574          strsep(&c, " ,");
14575       }
14576    }
14577 
14578    /* Verify that digest username matches  the username we auth as */
14579    if (strcmp(username, keys[K_USER].s)) {
14580       ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
14581          username, keys[K_USER].s);
14582       /* Oops, we're trying something here */
14583       return AUTH_USERNAME_MISMATCH;
14584    }
14585 
14586    /* Verify nonce from request matches our nonce, and the nonce has not already been responded to.
14587     * If this check fails, send 401 with new nonce */
14588    if (strcasecmp(p->randdata, keys[K_NONCE].s) || p->stalenonce) { /* XXX it was 'n'casecmp ? */
14589       wrongnonce = TRUE;
14590       usednonce = keys[K_NONCE].s;
14591    } else {
14592       p->stalenonce = 1; /* now, since the nonce has a response, mark it as stale so it can't be sent or responded to again */
14593    }
14594 
14595    if (!ast_strlen_zero(md5secret)) {
14596       ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
14597    } else {
14598       char a1[256];
14599 
14600       snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
14601       ast_md5_hash(a1_hash, a1);
14602    }
14603 
14604    /* compute the expected response to compare with what we received */
14605    {
14606       char a2[256];
14607       char a2_hash[256];
14608       char resp[256];
14609 
14610       snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
14611             S_OR(keys[K_URI].s, uri));
14612       ast_md5_hash(a2_hash, a2);
14613       snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
14614       ast_md5_hash(resp_hash, resp);
14615    }
14616 
14617    good_response = keys[K_RESP].s &&
14618          !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash));
14619    if (wrongnonce) {
14620       if (good_response) {
14621          if (sipdebug)
14622             ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", get_header(req, "From"));
14623          /* We got working auth token, based on stale nonce . */
14624          set_nonce_randdata(p, 0);
14625          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, TRUE);
14626       } else {
14627          /* Everything was wrong, so give the device one more try with a new challenge */
14628          if (!req->ignore) {
14629             if (sipdebug) {
14630                ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", get_header(req, "To"));
14631             }
14632             set_nonce_randdata(p, 1);
14633          } else {
14634             if (sipdebug) {
14635                ast_log(LOG_NOTICE, "Duplicate authentication received from '%s'\n", get_header(req, "To"));
14636             }
14637          }
14638          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
14639       }
14640 
14641       /* Schedule auto destroy in 32 seconds */
14642       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14643       return AUTH_CHALLENGE_SENT;
14644    }
14645    if (good_response) {
14646       append_history(p, "AuthOK", "Auth challenge successful for %s", username);
14647       return AUTH_SUCCESSFUL;
14648    }
14649 
14650    /* Ok, we have a bad username/secret pair */
14651    /* Tell the UAS not to re-send this authentication data, because
14652       it will continue to fail
14653    */
14654 
14655    return AUTH_SECRET_FAILED;
14656 }
14657 
14658 /*! \brief Change onhold state of a peer using a pvt structure */
14659 static void sip_peer_hold(struct sip_pvt *p, int hold)
14660 {
14661    if (!p->relatedpeer) {
14662       return;
14663    }
14664 
14665    /* If they put someone on hold, increment the value... otherwise decrement it */
14666    ast_atomic_fetchadd_int(&p->relatedpeer->onHold, (hold ? +1 : -1));
14667 
14668    /* Request device state update */
14669    ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", p->relatedpeer->name);
14670    
14671    return;
14672 }
14673 
14674 /*! \brief Receive MWI events that we have subscribed to */
14675 static void mwi_event_cb(const struct ast_event *event, void *userdata)
14676 {
14677    struct sip_peer *peer = userdata;
14678 
14679    sip_send_mwi_to_peer(peer, 0);
14680 }
14681 
14682 static void network_change_event_subscribe(void)
14683 {
14684    if (!network_change_event_subscription) {
14685       network_change_event_subscription = ast_event_subscribe(AST_EVENT_NETWORK_CHANGE,
14686          network_change_event_cb, "SIP Network Change", NULL, AST_EVENT_IE_END);
14687    }
14688 }
14689 
14690 static void network_change_event_unsubscribe(void)
14691 {
14692    if (network_change_event_subscription) {
14693       network_change_event_subscription = ast_event_unsubscribe(network_change_event_subscription);
14694    }
14695 }
14696 
14697 static int network_change_event_sched_cb(const void *data)
14698 {
14699    network_change_event_sched_id = -1;
14700    sip_send_all_registers();
14701    sip_send_all_mwi_subscriptions();
14702    return 0;
14703 }
14704 
14705 static void network_change_event_cb(const struct ast_event *event, void *userdata)
14706 {
14707    ast_debug(1, "SIP, got a network change event, renewing all SIP registrations.\n");
14708    if (network_change_event_sched_id == -1) {
14709       network_change_event_sched_id = ast_sched_add(sched, 1000, network_change_event_sched_cb, NULL);
14710    }
14711 }
14712 
14713 static void cb_extensionstate_destroy(int id, void *data)
14714 {
14715    struct sip_pvt *p = data;
14716 
14717    dialog_unref(p, "the extensionstate containing this dialog ptr was destroyed");
14718 }
14719 
14720 /*! \brief Callback for the devicestate notification (SUBSCRIBE) support subsystem
14721 \note If you add an "hint" priority to the extension in the dial plan,
14722    you will get notifications on device state changes */
14723 static int cb_extensionstate(char *context, char* exten, int state, void *data)
14724 {
14725    struct sip_pvt *p = data;
14726 
14727    sip_pvt_lock(p);
14728 
14729    switch(state) {
14730    case AST_EXTENSION_DEACTIVATED:  /* Retry after a while */
14731    case AST_EXTENSION_REMOVED:   /* Extension is gone */
14732       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);  /* Delete subscription in 32 secs */
14733       ast_verb(2, "Extension state: Watcher for hint %s %s. Notify User %s\n", exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", p->username);
14734       p->subscribed = NONE;
14735       append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
14736       break;
14737    default: /* Tell user */
14738       p->laststate = state;
14739       break;
14740    }
14741    if (p->subscribed != NONE) {  /* Only send state NOTIFY if we know the format */
14742       if (!p->pendinginvite) {
14743          transmit_state_notify(p, state, 1, FALSE);
14744       } else {
14745          /* We already have a NOTIFY sent that is not answered. Queue the state up.
14746             if many state changes happen meanwhile, we will only send a notification of the last one */
14747          ast_set_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
14748       }
14749    }
14750    ast_verb(2, "Extension Changed %s[%s] new state %s for Notify User %s %s\n", exten, context, ast_extension_state2str(state), p->username,
14751          ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE) ? "(queued)" : "");
14752 
14753    sip_pvt_unlock(p);
14754 
14755    return 0;
14756 }
14757 
14758 /*! \brief Send a fake 401 Unauthorized response when the administrator
14759   wants to hide the names of local devices  from fishers
14760  */
14761 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable)
14762 {
14763    /* We have to emulate EXACTLY what we'd get with a good peer
14764     * and a bad password, or else we leak information. */
14765    const char *response = "401 Unauthorized";
14766    const char *reqheader = "Authorization";
14767    const char *respheader = "WWW-Authenticate";
14768    const char *authtoken;
14769    struct ast_str *buf;
14770    char *c;
14771 
14772    /* table of recognised keywords, and their value in the digest */
14773    enum keys { K_NONCE, K_LAST };
14774    struct x {
14775       const char *key;
14776       const char *s;
14777    } *i, keys[] = {
14778       [K_NONCE] = { "nonce=", "" },
14779       [K_LAST] = { NULL, NULL}
14780    };
14781 
14782    authtoken = get_header(req, reqheader);
14783    if (req->ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
14784       /* This is a retransmitted invite/register/etc, don't reconstruct authentication
14785        * information */
14786       transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
14787       /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
14788       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14789       return;
14790    } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
14791       /* We have no auth, so issue challenge and request authentication */
14792       set_nonce_randdata(p, 1);
14793       transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
14794       /* Schedule auto destroy in 32 seconds */
14795       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14796       return;
14797    }
14798 
14799    if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
14800       transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
14801       return;
14802    }
14803 
14804    /* Make a copy of the response and parse it */
14805    if (ast_str_set(&buf, 0, "%s", authtoken) == AST_DYNSTR_BUILD_FAILED) {
14806       transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
14807       return;
14808    }
14809 
14810    c = buf->str;
14811 
14812    while (c && *(c = ast_skip_blanks(c))) { /* lookup for keys */
14813       for (i = keys; i->key != NULL; i++) {
14814          const char *separator = ",";  /* default */
14815 
14816          if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
14817             continue;
14818          }
14819          /* Found. Skip keyword, take text in quotes or up to the separator. */
14820          c += strlen(i->key);
14821          if (*c == '"') { /* in quotes. Skip first and look for last */
14822             c++;
14823             separator = "\"";
14824          }
14825          i->s = c;
14826          strsep(&c, separator);
14827          break;
14828       }
14829       if (i->key == NULL) { /* not found, jump after space or comma */
14830          strsep(&c, " ,");
14831       }
14832    }
14833 
14834    /* Verify nonce from request matches our nonce.  If not, send 401 with new nonce */
14835    if (strcasecmp(p->randdata, keys[K_NONCE].s)) {
14836       if (!req->ignore) {
14837          set_nonce_randdata(p, 1);
14838       }
14839       transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
14840 
14841       /* Schedule auto destroy in 32 seconds */
14842       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
14843    } else {
14844       transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
14845    }
14846 }
14847 
14848 /*!
14849  * Terminate the uri at the first ';' or space.
14850  * Technically we should ignore escaped space per RFC3261 (19.1.1 etc)
14851  * but don't do it for the time being. Remember the uri format is:
14852  * (User-parameters was added after RFC 3261)
14853  *\verbatim
14854  *
14855  * sip:user:password;user-parameters@host:port;uri-parameters?headers
14856  * sips:user:password;user-parameters@host:port;uri-parameters?headers
14857  *
14858  *\endverbatim
14859  * \todo As this function does not support user-parameters, it's considered broken
14860  * and needs fixing.
14861  */
14862 static char *terminate_uri(char *uri)
14863 {
14864    char *t = uri;
14865    while (*t && *t > ' ' && *t != ';') {
14866       t++;
14867    }
14868    *t = '\0';
14869    return uri;
14870 }
14871 
14872 /*! \brief Terminate a host:port at the ':'
14873  * \param hostport The address of the hostport string
14874  *
14875  * \note In the case of a bracket-enclosed IPv6 address, the hostport variable
14876  * will contain the non-bracketed host as a result of calling this function.
14877  */
14878 static void extract_host_from_hostport(char **hostport)
14879 {
14880    char *dont_care;
14881    ast_sockaddr_split_hostport(*hostport, hostport, &dont_care, PARSE_PORT_IGNORE);
14882 }
14883 
14884 /*! \internal \brief Helper function to update a peer's lastmsgssent value
14885  */
14886 static void update_peer_lastmsgssent(struct sip_peer *peer, int value, int locked)
14887 {
14888    if (!locked) {
14889       ao2_lock(peer);
14890    }
14891    peer->lastmsgssent = value;
14892    if (!locked) {
14893       ao2_unlock(peer);
14894    }
14895 }
14896 
14897 
14898 /*! \brief Verify registration of user
14899    - Registration is done in several steps, first a REGISTER without auth
14900      to get a challenge (nonce) then a second one with auth
14901    - Registration requests are only matched with peers that are marked as "dynamic"
14902  */
14903 static enum check_auth_result register_verify(struct sip_pvt *p, struct ast_sockaddr *addr,
14904                      struct sip_request *req, const char *uri)
14905 {
14906    enum check_auth_result res = AUTH_NOT_FOUND;
14907    struct sip_peer *peer;
14908    char tmp[256];
14909    char *c, *name, *unused_password, *domain;
14910    char *uri2 = ast_strdupa(uri);
14911    int send_mwi = 0;
14912 
14913    terminate_uri(uri2);
14914 
14915    ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
14916 
14917    c = get_in_brackets(tmp);
14918    c = remove_uri_parameters(c);
14919 
14920    if (parse_uri_legacy_check(c, "sip:,sips:", &name, &unused_password, &domain, NULL)) {
14921       ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_sockaddr_stringify_addr(addr));
14922       return -1;
14923    }
14924 
14925    SIP_PEDANTIC_DECODE(name);
14926    SIP_PEDANTIC_DECODE(domain);
14927 
14928    extract_host_from_hostport(&domain);
14929 
14930    if (ast_strlen_zero(domain)) {
14931       /* <sip:name@[EMPTY]>, never good */
14932       transmit_response(p, "404 Not found", &p->initreq);
14933       return AUTH_UNKNOWN_DOMAIN;
14934    }
14935 
14936    if (ast_strlen_zero(name)) {
14937       /* <sip:[EMPTY][@]hostport>, unsure whether valid for
14938        * registration. RFC 3261, 10.2 states:
14939        * "The To header field and the Request-URI field typically
14940        * differ, as the former contains a user name."
14941        * But, Asterisk has always treated the domain-only uri as a
14942        * username: we allow admins to create accounts described by
14943        * domain name. */
14944       name = domain;
14945    }
14946 
14947    /* This here differs from 1.4 and 1.6: the domain matching ACLs were
14948     * skipped if it was a domain-only URI (used as username). Here we treat
14949     * <sip:hostport> as <sip:host@hostport> and won't forget to test the
14950     * domain ACLs against host. */
14951    if (!AST_LIST_EMPTY(&domain_list)) {
14952       if (!check_sip_domain(domain, NULL, 0)) {
14953          if (sip_cfg.alwaysauthreject) {
14954             transmit_fake_auth_response(p, SIP_REGISTER, &p->initreq, XMIT_UNRELIABLE);
14955          } else {
14956             transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
14957          }
14958          return AUTH_UNKNOWN_DOMAIN;
14959       }
14960    }
14961 
14962    ast_string_field_set(p, exten, name);
14963    build_contact(p);
14964    if (req->ignore) {
14965       /* Expires is a special case, where we only want to load the peer if this isn't a deregistration attempt */
14966       const char *expires = get_header(req, "Expires");
14967       int expire = atoi(expires);
14968 
14969       if (ast_strlen_zero(expires)) { /* No expires header; look in Contact */
14970          if ((expires = strcasestr(get_header(req, "Contact"), ";expires="))) {
14971             expire = atoi(expires + 9);
14972          }
14973       }
14974       if (!ast_strlen_zero(expires) && expire == 0) {
14975          transmit_response_with_date(p, "200 OK", req);
14976          return 0;
14977       }
14978    }
14979    peer = find_peer(name, NULL, TRUE, FINDPEERS, FALSE, 0);
14980 
14981    if (!(peer && ast_apply_ha(peer->ha, addr))) {
14982       /* Peer fails ACL check */
14983       if (peer) {
14984          unref_peer(peer, "register_verify: unref_peer: from find_peer operation");
14985          peer = NULL;
14986          res = AUTH_ACL_FAILED;
14987       } else {
14988          res = AUTH_NOT_FOUND;
14989       }
14990    }
14991 
14992    if (peer) {
14993       ao2_lock(peer);
14994       if (!peer->host_dynamic) {
14995          ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
14996          res = AUTH_PEER_NOT_DYNAMIC;
14997       } else {
14998          ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT_FORCE_RPORT);
14999          if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri2, XMIT_UNRELIABLE, req->ignore))) {
15000             if (sip_cancel_destroy(p))
15001                ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
15002 
15003             if (check_request_transport(peer, req)) {
15004                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
15005                transmit_response_with_date(p, "403 Forbidden", req);
15006                res = AUTH_BAD_TRANSPORT;
15007             } else {
15008 
15009                /* We have a successful registration attempt with proper authentication,
15010                   now, update the peer */
15011                switch (parse_register_contact(p, peer, req)) {
15012                case PARSE_REGISTER_DENIED:
15013                   ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
15014                   transmit_response_with_date(p, "603 Denied", req);
15015                   res = 0;
15016                   break;
15017                case PARSE_REGISTER_FAILED:
15018                   ast_log(LOG_WARNING, "Failed to parse contact info\n");
15019                   transmit_response_with_date(p, "400 Bad Request", req);
15020                   res = 0;
15021                   break;
15022                case PARSE_REGISTER_QUERY:
15023                   ast_string_field_set(p, fullcontact, peer->fullcontact);
15024                   transmit_response_with_date(p, "200 OK", req);
15025                   res = 0;
15026                   break;
15027                case PARSE_REGISTER_UPDATE:
15028                   ast_string_field_set(p, fullcontact, peer->fullcontact);
15029                   update_peer(peer, p->expiry);
15030                   /* Say OK and ask subsystem to retransmit msg counter */
15031                   transmit_response_with_date(p, "200 OK", req);
15032                   send_mwi = 1;
15033                   res = 0;
15034                   break;
15035                }
15036             }
15037 
15038          }
15039       }
15040       ao2_unlock(peer);
15041    }
15042    if (!peer && sip_cfg.autocreatepeer) {
15043       /* Create peer if we have autocreate mode enabled */
15044       peer = temp_peer(name);
15045       if (peer) {
15046          ao2_t_link(peers, peer, "link peer into peer table");
15047          if (!ast_sockaddr_isnull(&peer->addr)) {
15048             ao2_t_link(peers_by_ip, peer, "link peer into peers-by-ip table");
15049          }
15050          ao2_lock(peer);
15051          if (sip_cancel_destroy(p))
15052             ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
15053          switch (parse_register_contact(p, peer, req)) {
15054          case PARSE_REGISTER_DENIED:
15055             ast_log(LOG_WARNING, "Registration denied because of contact ACL\n");
15056             transmit_response_with_date(p, "403 Forbidden (ACL)", req);
15057             res = 0;
15058             break;
15059          case PARSE_REGISTER_FAILED:
15060             ast_log(LOG_WARNING, "Failed to parse contact info\n");
15061             transmit_response_with_date(p, "400 Bad Request", req);
15062             res = 0;
15063             break;
15064          case PARSE_REGISTER_QUERY:
15065             ast_string_field_set(p, fullcontact, peer->fullcontact);
15066             transmit_response_with_date(p, "200 OK", req);
15067             send_mwi = 1;
15068             res = 0;
15069             break;
15070          case PARSE_REGISTER_UPDATE:
15071             ast_string_field_set(p, fullcontact, peer->fullcontact);
15072             /* Say OK and ask subsystem to retransmit msg counter */
15073             transmit_response_with_date(p, "200 OK", req);
15074             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));
15075             send_mwi = 1;
15076             res = 0;
15077             break;
15078          }
15079          ao2_unlock(peer);
15080       }
15081    }
15082    if (!res) {
15083       if (send_mwi) {
15084          sip_send_mwi_to_peer(peer, 0);
15085       } else {
15086          update_peer_lastmsgssent(peer, -1, 0);
15087       }
15088       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
15089    }
15090    if (res < 0) {
15091       switch (res) {
15092       case AUTH_SECRET_FAILED:
15093          /* Wrong password in authentication. Go away, don't try again until you fixed it */
15094          transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
15095          if (global_authfailureevents) {
15096             const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
15097             const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
15098             manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
15099                      "ChannelType: SIP\r\n"
15100                      "Peer: SIP/%s\r\n"
15101                      "PeerStatus: Rejected\r\n"
15102                      "Cause: AUTH_SECRET_FAILED\r\n"
15103                      "Address: %s\r\n"
15104                      "Port: %s\r\n",
15105                      name, peer_addr, peer_port);
15106          }
15107          break;
15108       case AUTH_USERNAME_MISMATCH:
15109          /* Username and digest username does not match.
15110             Asterisk uses the From: username for authentication. We need the
15111             devices to use the same authentication user name until we support
15112             proper authentication by digest auth name */
15113       case AUTH_NOT_FOUND:
15114       case AUTH_PEER_NOT_DYNAMIC:
15115       case AUTH_ACL_FAILED:
15116          if (sip_cfg.alwaysauthreject) {
15117             transmit_fake_auth_response(p, SIP_REGISTER, &p->initreq, XMIT_UNRELIABLE);
15118             if (global_authfailureevents) {
15119                const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
15120                const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
15121                manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
15122                         "ChannelType: SIP\r\n"
15123                         "Peer: SIP/%s\r\n"
15124                         "PeerStatus: Rejected\r\n"
15125                         "Cause: %s\r\n"
15126                         "Address: %s\r\n"
15127                         "Port: %s\r\n",
15128                         name,
15129                         res == AUTH_PEER_NOT_DYNAMIC ? "AUTH_PEER_NOT_DYNAMIC" : "URI_NOT_FOUND",
15130                         peer_addr, peer_port);
15131             }
15132          } else {
15133             /* URI not found */
15134             if (res == AUTH_PEER_NOT_DYNAMIC) {
15135                transmit_response(p, "403 Forbidden", &p->initreq);
15136                if (global_authfailureevents) {
15137                   const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
15138                   const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
15139                   manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
15140                      "ChannelType: SIP\r\n"
15141                      "Peer: SIP/%s\r\n"
15142                      "PeerStatus: Rejected\r\n"
15143                      "Cause: AUTH_PEER_NOT_DYNAMIC\r\n"
15144                      "Address: %s\r\n"
15145                      "Port: %s\r\n",
15146                      name, peer_addr, peer_port);
15147                }
15148             } else {
15149                transmit_response(p, "404 Not found", &p->initreq);
15150                if (global_authfailureevents) {
15151                   const char *peer_addr = ast_strdupa(ast_sockaddr_stringify_addr(addr));
15152                   const char *peer_port = ast_strdupa(ast_sockaddr_stringify_port(addr));
15153                   manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
15154                      "ChannelType: SIP\r\n"
15155                      "Peer: SIP/%s\r\n"
15156                      "PeerStatus: Rejected\r\n"
15157                      "Cause: %s\r\n"
15158                      "Address: %s\r\n"
15159                      "Port: %s\r\n",
15160                      name,
15161                      (res == AUTH_USERNAME_MISMATCH) ? "AUTH_USERNAME_MISMATCH" : "URI_NOT_FOUND",
15162                      peer_addr, peer_port);
15163                }
15164             }
15165          }
15166          break;
15167       case AUTH_BAD_TRANSPORT:
15168       default:
15169          break;
15170       }
15171    }
15172    if (peer) {
15173       unref_peer(peer, "register_verify: unref_peer: tossing stack peer pointer at end of func");
15174    }
15175 
15176    return res;
15177 }
15178 
15179 /*! \brief Translate referring cause */
15180 static void sip_set_redirstr(struct sip_pvt *p, char *reason) {
15181 
15182    if (!strcmp(reason, "unknown")) {
15183       ast_string_field_set(p, redircause, "UNKNOWN");
15184    } else if (!strcmp(reason, "user-busy")) {
15185       ast_string_field_set(p, redircause, "BUSY");
15186    } else if (!strcmp(reason, "no-answer")) {
15187       ast_string_field_set(p, redircause, "NOANSWER");
15188    } else if (!strcmp(reason, "unavailable")) {
15189       ast_string_field_set(p, redircause, "UNREACHABLE");
15190    } else if (!strcmp(reason, "unconditional")) {
15191       ast_string_field_set(p, redircause, "UNCONDITIONAL");
15192    } else if (!strcmp(reason, "time-of-day")) {
15193       ast_string_field_set(p, redircause, "UNKNOWN");
15194    } else if (!strcmp(reason, "do-not-disturb")) {
15195       ast_string_field_set(p, redircause, "UNKNOWN");
15196    } else if (!strcmp(reason, "deflection")) {
15197       ast_string_field_set(p, redircause, "UNKNOWN");
15198    } else if (!strcmp(reason, "follow-me")) {
15199       ast_string_field_set(p, redircause, "UNKNOWN");
15200    } else if (!strcmp(reason, "out-of-service")) {
15201       ast_string_field_set(p, redircause, "UNREACHABLE");
15202    } else if (!strcmp(reason, "away")) {
15203       ast_string_field_set(p, redircause, "UNREACHABLE");
15204    } else {
15205       ast_string_field_set(p, redircause, "UNKNOWN");
15206    }
15207 }
15208 
15209 /*! \brief Parse the parts of the P-Asserted-Identity header
15210  * on an incoming packet. Returns 1 if a valid header is found
15211  * and it is different from the current caller id.
15212  */
15213 static int get_pai(struct sip_pvt *p, struct sip_request *req)
15214 {
15215    char pai[256];
15216    char privacy[64];
15217    char *cid_num = NULL;
15218    char *cid_name = NULL;
15219    char emptyname[1] = "";
15220    int callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
15221    char *uri = NULL;
15222    int is_anonymous = 0, do_update = 1, no_name = 0;
15223 
15224    ast_copy_string(pai, get_header(req, "P-Asserted-Identity"), sizeof(pai));
15225 
15226    if (ast_strlen_zero(pai)) {
15227       return 0;
15228    }
15229 
15230    /* use the reqresp_parser function get_name_and_number*/
15231    if (get_name_and_number(pai, &cid_name, &cid_num)) {
15232       return 0;
15233    }
15234 
15235    if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(cid_num)) {
15236       ast_shrink_phone_number(cid_num);
15237    }
15238 
15239    uri = get_in_brackets(pai);
15240    if (!strncasecmp(uri, "sip:anonymous@anonymous.invalid", 31)) {
15241       callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
15242       /*XXX Assume no change in cid_num. Perhaps it should be
15243        * blanked?
15244        */
15245       ast_free(cid_num);
15246       is_anonymous = 1;
15247       cid_num = (char *)p->cid_num;
15248    }
15249 
15250    ast_copy_string(privacy, get_header(req, "Privacy"), sizeof(privacy));
15251    if (!ast_strlen_zero(privacy) && !strncmp(privacy, "id", 2)) {
15252       callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
15253    }
15254    if (!cid_name) {
15255       no_name = 1;
15256       cid_name = (char *)emptyname;
15257    }  
15258    /* Only return true if the supplied caller id is different */
15259    if (!strcasecmp(p->cid_num, cid_num) && !strcasecmp(p->cid_name, cid_name) && p->callingpres == callingpres) {
15260       do_update = 0;
15261    } else {
15262 
15263       ast_string_field_set(p, cid_num, cid_num);
15264       ast_string_field_set(p, cid_name, cid_name);
15265       p->callingpres = callingpres;
15266 
15267       if (p->owner) {
15268          ast_set_callerid(p->owner, cid_num, cid_name, NULL);
15269          p->owner->caller.id.name.presentation = callingpres;
15270          p->owner->caller.id.number.presentation = callingpres;
15271       }
15272    }
15273 
15274    /* get_name_and_number allocates memory for cid_num and cid_name so we have to free it */
15275    if (!is_anonymous) {
15276       ast_free(cid_num);
15277    }
15278    if (!no_name) {
15279       ast_free(cid_name);
15280    }
15281 
15282    return do_update;
15283 }
15284 
15285 /*! \brief Get name, number and presentation from remote party id header,
15286  *  returns true if a valid header was found and it was different from the
15287  *  current caller id.
15288  */
15289 static int get_rpid(struct sip_pvt *p, struct sip_request *oreq)
15290 {
15291    char tmp[256];
15292    struct sip_request *req;
15293    char *cid_num = "";
15294    char *cid_name = "";
15295    int callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
15296    char *privacy = "";
15297    char *screen = "";
15298    char *start, *end;
15299 
15300    if (!ast_test_flag(&p->flags[0], SIP_TRUSTRPID))
15301       return 0;
15302    req = oreq;
15303    if (!req)
15304       req = &p->initreq;
15305    ast_copy_string(tmp, get_header(req, "Remote-Party-ID"), sizeof(tmp));
15306    if (ast_strlen_zero(tmp)) {
15307       return get_pai(p, req);
15308    }
15309 
15310    start = tmp;
15311    if (*start == '"') {
15312       *start++ = '\0';
15313       end = strchr(start, '"');
15314       if (!end)
15315          return 0;
15316       *end++ = '\0';
15317       cid_name = start;
15318       start = ast_skip_blanks(end);
15319    }
15320 
15321    if (*start != '<')
15322       return 0;
15323    *start++ = '\0';
15324    end = strchr(start, '@');
15325    if (!end)
15326       return 0;
15327    *end++ = '\0';
15328    if (strncasecmp(start, "sip:", 4))
15329       return 0;
15330    cid_num = start + 4;
15331    if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(cid_num))
15332       ast_shrink_phone_number(cid_num);
15333    start = end;
15334 
15335    end = strchr(start, '>');
15336    if (!end)
15337       return 0;
15338    *end++ = '\0';
15339    if (*end) {
15340       start = end;
15341       if (*start != ';')
15342          return 0;
15343       *start++ = '\0';
15344       while (!ast_strlen_zero(start)) {
15345          end = strchr(start, ';');
15346          if (end)
15347             *end++ = '\0';
15348          if (!strncasecmp(start, "privacy=", 8))
15349             privacy = start + 8;
15350          else if (!strncasecmp(start, "screen=", 7))
15351             screen = start + 7;
15352          start = end;
15353       }
15354 
15355       if (!strcasecmp(privacy, "full")) {
15356          if (!strcasecmp(screen, "yes"))
15357             callingpres = AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN;
15358          else if (!strcasecmp(screen, "no"))
15359             callingpres = AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
15360       } else {
15361          if (!strcasecmp(screen, "yes"))
15362             callingpres = AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
15363          else if (!strcasecmp(screen, "no"))
15364             callingpres = AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED;
15365       }
15366    }
15367 
15368    /* Only return true if the supplied caller id is different */
15369    if (!strcasecmp(p->cid_num, cid_num) && !strcasecmp(p->cid_name, cid_name) && p->callingpres == callingpres)
15370       return 0;
15371 
15372    ast_string_field_set(p, cid_num, cid_num);
15373    ast_string_field_set(p, cid_name, cid_name);
15374    p->callingpres = callingpres;
15375 
15376    if (p->owner) {
15377       ast_set_callerid(p->owner, cid_num, cid_name, NULL);
15378       p->owner->caller.id.name.presentation = callingpres;
15379       p->owner->caller.id.number.presentation = callingpres;
15380    }
15381 
15382    return 1;
15383 }
15384 
15385 /*! \brief Get referring dnis */
15386 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason)
15387 {
15388    char tmp[256], *exten, *rexten, *rdomain, *rname = NULL;
15389    char *params, *reason_param = NULL;
15390    struct sip_request *req;
15391 
15392    req = oreq ? oreq : &p->initreq;
15393 
15394    ast_copy_string(tmp, get_header(req, "Diversion"), sizeof(tmp));
15395    if (ast_strlen_zero(tmp))
15396       return -1;
15397 
15398    if ((params = strchr(tmp, '>'))) {
15399       params = strchr(params, ';');
15400    }
15401 
15402    exten = get_in_brackets(tmp);
15403    if (!strncasecmp(exten, "sip:", 4)) {
15404       exten += 4;
15405    } else if (!strncasecmp(exten, "sips:", 5)) {
15406       exten += 5;
15407    } else {
15408       ast_log(LOG_WARNING, "Huh?  Not an RDNIS SIP header (%s)?\n", exten);
15409       return -1;
15410    }
15411 
15412    /* Get diversion-reason param if present */
15413    if (params) {
15414       *params = '\0';   /* Cut off parameters  */
15415       params++;
15416       while (*params == ';' || *params == ' ')
15417          params++;
15418       /* Check if we have a reason parameter */
15419       if ((reason_param = strcasestr(params, "reason="))) {
15420          char *end;
15421          reason_param+=7;
15422          if ((end = strchr(reason_param, ';'))) {
15423             *end = '\0';
15424          }
15425          /* Remove enclosing double-quotes */
15426          if (*reason_param == '"')
15427             reason_param = ast_strip_quoted(reason_param, "\"", "\"");
15428          if (!ast_strlen_zero(reason_param)) {
15429             sip_set_redirstr(p, reason_param);
15430             if (p->owner) {
15431                pbx_builtin_setvar_helper(p->owner, "__PRIREDIRECTREASON", p->redircause);
15432                pbx_builtin_setvar_helper(p->owner, "__SIPREDIRECTREASON", reason_param);
15433             }
15434          }
15435       }
15436    }
15437 
15438    rdomain = exten;
15439    rexten = strsep(&rdomain, "@");  /* trim anything after @ */
15440    if (p->owner)
15441       pbx_builtin_setvar_helper(p->owner, "__SIPRDNISDOMAIN", rdomain);
15442 
15443    if (sip_debug_test_pvt(p))
15444       ast_verbose("RDNIS for this call is %s (reason %s)\n", exten, S_OR(reason_param, ""));
15445 
15446    /*ast_string_field_set(p, rdnis, rexten);*/
15447 
15448    if (*tmp == '\"') {
15449       char *end_quote;
15450       rname = tmp + 1;
15451       end_quote = strchr(rname, '\"');
15452       if (end_quote) {
15453          *end_quote = '\0';
15454       }
15455    }
15456 
15457    if (number) {
15458       *number = ast_strdup(rexten);
15459    }
15460 
15461    if (name && rname) {
15462       *name = ast_strdup(rname);
15463    }
15464 
15465    if (reason && !ast_strlen_zero(reason_param)) {
15466       *reason = sip_reason_str_to_code(reason_param);
15467    }
15468 
15469    return 0;
15470 }
15471 
15472 /*!
15473  * \brief Find out who the call is for.
15474  *
15475  * \details
15476  * We use the request uri as a destination.
15477  * This code assumes authentication has been done, so that the
15478  * device (peer/user) context is already set.
15479  *
15480  * \return 0 on success (found a matching extension), non-zero on failure
15481  *
15482  * \note If the incoming uri is a SIPS: uri, we are required to carry this across
15483  * the dialplan, so that the outbound call also is a sips: call or encrypted
15484  * IAX2 call. If that's not available, the call should FAIL.
15485  */
15486 static enum sip_get_dest_result get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id)
15487 {
15488    char tmp[256] = "", *uri, *unused_password, *domain;
15489    char tmpf[256] = "", *from = NULL;
15490    struct sip_request *req;
15491    char *decoded_uri;
15492 
15493    req = oreq;
15494    if (!req) {
15495       req = &p->initreq;
15496    }
15497 
15498    /* Find the request URI */
15499    if (req->rlPart2)
15500       ast_copy_string(tmp, REQ_OFFSET_TO_STR(req, rlPart2), sizeof(tmp));
15501    
15502    uri = ast_strdupa(get_in_brackets(tmp));
15503 
15504    if (parse_uri_legacy_check(uri, "sip:,sips:", &uri, &unused_password, &domain, NULL)) {
15505       ast_log(LOG_WARNING, "Not a SIP header (%s)?\n", uri);
15506       return SIP_GET_DEST_INVALID_URI;
15507    }
15508 
15509    SIP_PEDANTIC_DECODE(domain);
15510    SIP_PEDANTIC_DECODE(uri);
15511 
15512    extract_host_from_hostport(&domain);
15513 
15514    if (ast_strlen_zero(uri)) {
15515       /*
15516        * Either there really was no extension found or the request
15517        * URI had encoded nulls that made the string "empty".  Use "s"
15518        * as the extension.
15519        */
15520       uri = "s";
15521    }
15522 
15523    ast_string_field_set(p, domain, domain);
15524 
15525    /* Now find the From: caller ID and name */
15526    /* XXX Why is this done in get_destination? Isn't it already done?
15527       Needs to be checked
15528         */
15529    ast_copy_string(tmpf, get_header(req, "From"), sizeof(tmpf));
15530    if (!ast_strlen_zero(tmpf)) {
15531       from = get_in_brackets(tmpf);
15532       if (parse_uri_legacy_check(from, "sip:,sips:", &from, NULL, &domain, NULL)) {
15533          ast_log(LOG_WARNING, "Not a SIP header (%s)?\n", from);
15534          return SIP_GET_DEST_INVALID_URI;
15535       }
15536 
15537       SIP_PEDANTIC_DECODE(from);
15538       SIP_PEDANTIC_DECODE(domain);
15539 
15540       extract_host_from_hostport(&domain);
15541 
15542       ast_string_field_set(p, fromdomain, domain);
15543    }
15544 
15545    if (!AST_LIST_EMPTY(&domain_list)) {
15546       char domain_context[AST_MAX_EXTENSION];
15547 
15548       domain_context[0] = '\0';
15549       if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
15550          if (!sip_cfg.allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
15551             ast_debug(1, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
15552             return SIP_GET_DEST_REFUSED;
15553          }
15554       }
15555       /* If we don't have a peer (i.e. we're a guest call),
15556        * overwrite the original context */
15557       if (!ast_test_flag(&p->flags[1], SIP_PAGE2_HAVEPEERCONTEXT) && !ast_strlen_zero(domain_context)) {
15558          ast_string_field_set(p, context, domain_context);
15559       }
15560    }
15561 
15562    /* If the request coming in is a subscription and subscribecontext has been specified use it */
15563    if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext)) {
15564       ast_string_field_set(p, context, p->subscribecontext);
15565    }
15566 
15567    if (sip_debug_test_pvt(p)) {
15568       ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
15569    }
15570 
15571    /* Since extensions.conf can have unescaped characters, try matching a
15572     * decoded uri in addition to the non-decoded uri. */
15573    decoded_uri = ast_strdupa(uri);
15574    ast_uri_decode(decoded_uri);
15575 
15576    /* If this is a subscription we actually just need to see if a hint exists for the extension */
15577    if (req->method == SIP_SUBSCRIBE) {
15578       char hint[AST_MAX_EXTENSION];
15579       int which = 0;
15580       if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, uri) ||
15581           (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, decoded_uri) && (which = 1))) {
15582          if (!oreq) {
15583             ast_string_field_set(p, exten, which ? decoded_uri : uri);
15584          }
15585          return SIP_GET_DEST_EXTEN_FOUND;
15586       } else {
15587          return SIP_GET_DEST_EXTEN_NOT_FOUND;
15588       }
15589    } else {
15590       struct ast_cc_agent *agent;
15591       /* Check the dialplan for the username part of the request URI,
15592          the domain will be stored in the SIPDOMAIN variable
15593          Return 0 if we have a matching extension */
15594       if (ast_exists_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from))) {
15595          if (!oreq) {
15596             ast_string_field_set(p, exten, uri);
15597          }
15598          return SIP_GET_DEST_EXTEN_FOUND;
15599       }
15600       if (ast_exists_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))
15601          || !strcmp(decoded_uri, ast_pickup_ext())) {
15602          if (!oreq) {
15603             ast_string_field_set(p, exten, decoded_uri);
15604          }
15605          return SIP_GET_DEST_EXTEN_FOUND;
15606       }
15607       if ((agent = find_sip_cc_agent_by_notify_uri(tmp))) {
15608          struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
15609          /* This is a CC recall. We can set p's extension to the exten from
15610           * the original INVITE
15611           */
15612          ast_string_field_set(p, exten, agent_pvt->original_exten);
15613          /* And we need to let the CC core know that the caller is attempting
15614           * his recall
15615           */
15616          ast_cc_agent_recalling(agent->core_id, "SIP caller %s is attempting recall",
15617                agent->device_name);
15618          if (cc_recall_core_id) {
15619             *cc_recall_core_id = agent->core_id;
15620          }
15621          ao2_ref(agent, -1);
15622          return SIP_GET_DEST_EXTEN_FOUND;
15623       }
15624    }
15625 
15626    if (ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)
15627       && (ast_canmatch_extension(NULL, p->context, uri, 1, S_OR(p->cid_num, from))
15628          || ast_canmatch_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))
15629          || !strncmp(decoded_uri, ast_pickup_ext(), strlen(decoded_uri)))) {
15630       /* Overlap dialing is enabled and we need more digits to match an extension. */
15631       return SIP_GET_DEST_EXTEN_MATCHMORE;
15632    }
15633 
15634    return SIP_GET_DEST_EXTEN_NOT_FOUND;
15635 }
15636 
15637 /*! \brief Lock dialog lock and find matching pvt lock
15638    \return a reference, remember to release it when done
15639 */
15640 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag)
15641 {
15642    struct sip_pvt *sip_pvt_ptr;
15643    struct sip_pvt tmp_dialog = {
15644       .callid = callid,
15645    };
15646 
15647    if (totag) {
15648       ast_debug(4, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
15649    }
15650 
15651    /* Search dialogs and find the match */
15652    
15653    sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find of dialog in dialogs table");
15654    if (sip_pvt_ptr) {
15655       /* Go ahead and lock it (and its owner) before returning */
15656       sip_pvt_lock(sip_pvt_ptr);
15657       if (sip_cfg.pedanticsipchecking) {
15658          unsigned char frommismatch = 0, tomismatch = 0;
15659 
15660          if (ast_strlen_zero(fromtag)) {
15661             sip_pvt_unlock(sip_pvt_ptr);
15662             ast_debug(4, "Matched %s call for callid=%s - no from tag specified, pedantic check fails\n",
15663                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
15664             return NULL;
15665          }
15666 
15667          if (ast_strlen_zero(totag)) {
15668             sip_pvt_unlock(sip_pvt_ptr);
15669             ast_debug(4, "Matched %s call for callid=%s - no to tag specified, pedantic check fails\n",
15670                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
15671             return NULL;
15672          }
15673          /* RFC 3891
15674           * > 3.  User Agent Server Behavior: Receiving a Replaces Header
15675           * > The Replaces header contains information used to match an existing
15676           * > SIP dialog (call-id, to-tag, and from-tag).  Upon receiving an INVITE
15677           * > with a Replaces header, the User Agent (UA) attempts to match this
15678           * > information with a confirmed or early dialog.  The User Agent Server
15679           * > (UAS) matches the to-tag and from-tag parameters as if they were tags
15680           * > present in an incoming request.  In other words, the to-tag parameter
15681           * > is compared to the local tag, and the from-tag parameter is compared
15682           * > to the remote tag.
15683           *
15684           * Thus, the totag is always compared to the local tag, regardless if
15685           * this our call is an incoming or outgoing call.
15686           */
15687          frommismatch = !!strcmp(fromtag, sip_pvt_ptr->theirtag);
15688          tomismatch = !!strcmp(totag, sip_pvt_ptr->tag);
15689 
15690          if (frommismatch || tomismatch) {
15691             sip_pvt_unlock(sip_pvt_ptr);
15692             if (frommismatch) {
15693                ast_debug(4, "Matched %s call for callid=%s - pedantic from tag check fails; their tag is %s our tag is %s\n",
15694                     sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
15695                     fromtag, sip_pvt_ptr->theirtag);
15696             }
15697             if (tomismatch) {
15698                ast_debug(4, "Matched %s call for callid=%s - pedantic to tag check fails; their tag is %s our tag is %s\n",
15699                     sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid,
15700                     totag, sip_pvt_ptr->tag);
15701             }
15702             return NULL;
15703          }
15704       }
15705       
15706       if (totag)
15707          ast_debug(4, "Matched %s call - their tag is %s Our tag is %s\n",
15708                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING",
15709                  sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
15710 
15711       /* deadlock avoidance... */
15712       while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
15713          sip_pvt_unlock(sip_pvt_ptr);
15714          usleep(1);
15715          sip_pvt_lock(sip_pvt_ptr);
15716       }
15717    }
15718    
15719    return sip_pvt_ptr;
15720 }
15721 
15722 /*! \brief Call transfer support (the REFER method)
15723  *    Extracts Refer headers into pvt dialog structure
15724  *
15725  * \note If we get a SIPS uri in the refer-to header, we're required to set up a secure signalling path
15726  * to that extension. As a minimum, this needs to be added to a channel variable, if not a channel
15727  * flag.
15728  */
15729 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
15730 {
15731 
15732    const char *p_referred_by = NULL;
15733    char *h_refer_to = NULL;
15734    char *h_referred_by = NULL;
15735    char *refer_to;
15736    const char *p_refer_to;
15737    char *referred_by_uri = NULL;
15738    char *ptr;
15739    struct sip_request *req = NULL;
15740    const char *transfer_context = NULL;
15741    struct sip_refer *referdata;
15742 
15743 
15744    req = outgoing_req;
15745    referdata = transferer->refer;
15746 
15747    if (!req) {
15748       req = &transferer->initreq;
15749    }
15750 
15751    p_refer_to = get_header(req, "Refer-To");
15752    if (ast_strlen_zero(p_refer_to)) {
15753       ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
15754       return -2;  /* Syntax error */
15755    }
15756    h_refer_to = ast_strdupa(p_refer_to);
15757    refer_to = get_in_brackets(h_refer_to);
15758    if (!strncasecmp(refer_to, "sip:", 4)) {
15759       refer_to += 4;       /* Skip sip: */
15760    } else if (!strncasecmp(refer_to, "sips:", 5)) {
15761       refer_to += 5;
15762    } else {
15763       ast_log(LOG_WARNING, "Can't transfer to non-sip: URI.  (Refer-to: %s)?\n", refer_to);
15764       return -3;
15765    }
15766 
15767    /* Get referred by header if it exists */
15768    p_referred_by = get_header(req, "Referred-By");
15769 
15770    /* Give useful transfer information to the dialplan */
15771    if (transferer->owner) {
15772       struct ast_channel *peer = ast_bridged_channel(transferer->owner);
15773       if (peer) {
15774          pbx_builtin_setvar_helper(peer, "SIPREFERRINGCONTEXT", transferer->context);
15775          pbx_builtin_setvar_helper(peer, "SIPREFERREDBYHDR", p_referred_by);
15776       }
15777    }
15778 
15779    if (!ast_strlen_zero(p_referred_by)) {
15780       char *lessthan;
15781       h_referred_by = ast_strdupa(p_referred_by);
15782 
15783       /* Store referrer's caller ID name */
15784       ast_copy_string(referdata->referred_by_name, h_referred_by, sizeof(referdata->referred_by_name));
15785       if ((lessthan = strchr(referdata->referred_by_name, '<'))) {
15786          *(lessthan - 1) = '\0'; /* Space */
15787       }
15788 
15789       referred_by_uri = get_in_brackets(h_referred_by);
15790 
15791       if (!strncasecmp(referred_by_uri, "sip:", 4)) {
15792          referred_by_uri += 4;      /* Skip sip: */
15793       } else if (!strncasecmp(referred_by_uri, "sips:", 5)) {
15794          referred_by_uri += 5;      /* Skip sips: */
15795       } else {
15796          ast_log(LOG_WARNING, "Huh?  Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
15797          referred_by_uri = NULL;
15798       }
15799    }
15800 
15801    /* Check for arguments in the refer_to header */
15802    if ((ptr = strcasestr(refer_to, "replaces="))) {
15803       char *to = NULL, *from = NULL;
15804       
15805       /* This is an attended transfer */
15806       referdata->attendedtransfer = 1;
15807       ast_copy_string(referdata->replaces_callid, ptr+9, sizeof(referdata->replaces_callid));
15808       ast_uri_decode(referdata->replaces_callid);
15809       if ((ptr = strchr(referdata->replaces_callid, ';')))  /* Find options */ {
15810          *ptr++ = '\0';
15811       }
15812       
15813       if (ptr) {
15814          /* Find the different tags before we destroy the string */
15815          to = strcasestr(ptr, "to-tag=");
15816          from = strcasestr(ptr, "from-tag=");
15817       }
15818       
15819       /* Grab the to header */
15820       if (to) {
15821          ptr = to + 7;
15822          if ((to = strchr(ptr, '&'))) {
15823             *to = '\0';
15824          }
15825          if ((to = strchr(ptr, ';'))) {
15826             *to = '\0';
15827          }
15828          ast_copy_string(referdata->replaces_callid_totag, ptr, sizeof(referdata->replaces_callid_totag));
15829       }
15830       
15831       if (from) {
15832          ptr = from + 9;
15833          if ((to = strchr(ptr, '&'))) {
15834             *to = '\0';
15835          }
15836          if ((to = strchr(ptr, ';'))) {
15837             *to = '\0';
15838          }
15839          ast_copy_string(referdata->replaces_callid_fromtag, ptr, sizeof(referdata->replaces_callid_fromtag));
15840       }
15841 
15842       if (!strcmp(referdata->replaces_callid, transferer->callid) &&
15843          (!sip_cfg.pedanticsipchecking ||
15844          (!strcmp(referdata->replaces_callid_fromtag, transferer->theirtag) &&
15845          !strcmp(referdata->replaces_callid_totag, transferer->tag)))) {
15846             ast_log(LOG_WARNING, "Got an attempt to replace own Call-ID on %s\n", transferer->callid);
15847             return -4;
15848       }
15849 
15850       if (!sip_cfg.pedanticsipchecking) {
15851          ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata->replaces_callid );
15852       } else {
15853          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>" );
15854       }
15855    }
15856    
15857    if ((ptr = strchr(refer_to, '@'))) {   /* Separate domain */
15858       char *urioption = NULL, *domain;
15859       int bracket = 0;
15860       *ptr++ = '\0';
15861 
15862       if ((urioption = strchr(ptr, ';'))) { /* Separate urioptions */
15863          *urioption++ = '\0';
15864       }
15865 
15866       domain = ptr;
15867 
15868       /* Remove :port */
15869       for (; *ptr != '\0'; ++ptr) {
15870          if (*ptr == ':' && bracket == 0) {
15871             *ptr = '\0';
15872             break;
15873          } else if (*ptr == '[') {
15874             ++bracket;
15875          } else if (*ptr == ']') {
15876             --bracket;
15877          }
15878       }
15879 
15880       SIP_PEDANTIC_DECODE(domain);
15881       SIP_PEDANTIC_DECODE(urioption);
15882 
15883       /* Save the domain for the dial plan */
15884       ast_copy_string(referdata->refer_to_domain, domain, sizeof(referdata->refer_to_domain));
15885       if (urioption) {
15886          ast_copy_string(referdata->refer_to_urioption, urioption, sizeof(referdata->refer_to_urioption));
15887       }
15888    }
15889 
15890    if ((ptr = strchr(refer_to, ';')))  /* Remove options */
15891       *ptr = '\0';
15892 
15893    SIP_PEDANTIC_DECODE(refer_to);
15894    ast_copy_string(referdata->refer_to, refer_to, sizeof(referdata->refer_to));
15895    
15896    if (referred_by_uri) {
15897       if ((ptr = strchr(referred_by_uri, ';')))    /* Remove options */
15898          *ptr = '\0';
15899       SIP_PEDANTIC_DECODE(referred_by_uri);
15900       ast_copy_string(referdata->referred_by, referred_by_uri, sizeof(referdata->referred_by));
15901    } else {
15902       referdata->referred_by[0] = '\0';
15903    }
15904 
15905    /* Determine transfer context */
15906    if (transferer->owner)  /* Mimic behaviour in res_features.c */
15907       transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
15908 
15909    /* By default, use the context in the channel sending the REFER */
15910    if (ast_strlen_zero(transfer_context)) {
15911       transfer_context = S_OR(transferer->owner->macrocontext,
15912                S_OR(transferer->context, sip_cfg.default_context));
15913    }
15914 
15915    ast_copy_string(referdata->refer_to_context, transfer_context, sizeof(referdata->refer_to_context));
15916    
15917    /* Either an existing extension or the parking extension */
15918    if (referdata->attendedtransfer || ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL) ) {
15919       if (sip_debug_test_pvt(transferer)) {
15920          ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
15921       }
15922       /* We are ready to transfer to the extension */
15923       return 0;
15924    }
15925    if (sip_debug_test_pvt(transferer))
15926       ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
15927 
15928    /* Failure, we can't find this extension */
15929    return -1;
15930 }
15931 
15932 
15933 /*! \brief Call transfer support (old way, deprecated by the IETF)
15934  * \note does not account for SIPS: uri requirements, nor check transport
15935  */
15936 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
15937 {
15938    char tmp[256] = "", *c, *a;
15939    struct sip_request *req = oreq ? oreq : &p->initreq;
15940    struct sip_refer *referdata = NULL;
15941    const char *transfer_context = NULL;
15942    
15943    if (!p->refer && !sip_refer_allocate(p))
15944       return -1;
15945 
15946    referdata = p->refer;
15947 
15948    ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp));
15949    c = get_in_brackets(tmp);
15950 
15951    if (parse_uri_legacy_check(c, "sip:,sips:", &c, NULL, &a, NULL)) {
15952       ast_log(LOG_WARNING, "Huh?  Not a SIP header in Also: transfer (%s)?\n", c);
15953       return -1;
15954    }
15955    
15956    SIP_PEDANTIC_DECODE(c);
15957    SIP_PEDANTIC_DECODE(a);
15958 
15959    if (!ast_strlen_zero(a)) {
15960       ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain));
15961    }
15962 
15963    if (sip_debug_test_pvt(p))
15964       ast_verbose("Looking for %s in %s\n", c, p->context);
15965 
15966    if (p->owner)  /* Mimic behaviour in res_features.c */
15967       transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
15968 
15969    /* By default, use the context in the channel sending the REFER */
15970    if (ast_strlen_zero(transfer_context)) {
15971       transfer_context = S_OR(p->owner->macrocontext,
15972                S_OR(p->context, sip_cfg.default_context));
15973    }
15974    if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
15975       /* This is a blind transfer */
15976       ast_debug(1, "SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
15977       ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to));
15978       ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by));
15979       ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact));
15980       /* Set new context */
15981       ast_string_field_set(p, context, transfer_context);
15982       return 0;
15983    } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
15984       return 1;
15985    }
15986 
15987    return -1;
15988 }
15989 
15990 /*! \brief check received= and rport= in a SIP response.
15991  * If we get a response with received= and/or rport= in the Via:
15992  * line, use them as 'p->ourip' (see RFC 3581 for rport,
15993  * and RFC 3261 for received).
15994  * Using these two fields SIP can produce the correct
15995  * address and port in the SIP headers without the need for STUN.
15996  * The address part is also reused for the media sessions.
15997  * Note that ast_sip_ouraddrfor() still rewrites p->ourip
15998  * if you specify externaddr/seternaddr/.
15999  */
16000 static attribute_unused void check_via_response(struct sip_pvt *p, struct sip_request *req)
16001 {
16002    char via[256];
16003    char *cur, *opts;
16004 
16005    ast_copy_string(via, get_header(req, "Via"), sizeof(via));
16006 
16007    /* Work on the leftmost value of the topmost Via header */
16008    opts = strchr(via, ',');
16009    if (opts)
16010       *opts = '\0';
16011 
16012    /* parse all relevant options */
16013    opts = strchr(via, ';');
16014    if (!opts)
16015       return;  /* no options to parse */
16016    *opts++ = '\0';
16017    while ( (cur = strsep(&opts, ";")) ) {
16018       if (!strncmp(cur, "rport=", 6)) {
16019          int port = strtol(cur+6, NULL, 10);
16020          /* XXX add error checking */
16021          ast_sockaddr_set_port(&p->ourip, port);
16022       } else if (!strncmp(cur, "received=", 9)) {
16023          if (ast_parse_arg(cur + 9, PARSE_ADDR, &p->ourip))
16024             ;  /* XXX add error checking */
16025       }
16026    }
16027 }
16028 
16029 /*! \brief check Via: header for hostname, port and rport request/answer */
16030 static void check_via(struct sip_pvt *p, struct sip_request *req)
16031 {
16032    char via[512];
16033    char *c, *maddr;
16034    struct ast_sockaddr tmp = { { 0, } };
16035    uint16_t port;
16036 
16037    ast_copy_string(via, get_header(req, "Via"), sizeof(via));
16038 
16039    /* Work on the leftmost value of the topmost Via header */
16040    c = strchr(via, ',');
16041    if (c)
16042       *c = '\0';
16043 
16044    /* Check for rport */
16045    c = strstr(via, ";rport");
16046    if (c && (c[6] != '=')) { /* rport query, not answer */
16047       ast_set_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT);
16048       ast_set_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT);
16049    }
16050 
16051    /* Check for maddr */
16052    maddr = strstr(via, "maddr=");
16053    if (maddr) {
16054       maddr += 6;
16055       c = maddr + strspn(maddr, "abcdefghijklmnopqrstuvwxyz"
16056                       "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-.:[]");
16057       *c = '\0';
16058    }
16059 
16060    c = strchr(via, ';');
16061    if (c)
16062       *c = '\0';
16063 
16064    c = strchr(via, ' ');
16065    if (c) {
16066       *c = '\0';
16067       c = ast_skip_blanks(c+1);
16068       if (strcasecmp(via, "SIP/2.0/UDP") && strcasecmp(via, "SIP/2.0/TCP") && strcasecmp(via, "SIP/2.0/TLS")) {
16069          ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
16070          return;
16071       }
16072 
16073       if (maddr && ast_sockaddr_resolve_first(&p->sa, maddr, 0)) {
16074          p->sa = p->recv;
16075       }
16076 
16077       if (ast_sockaddr_resolve_first(&tmp, c, 0)) {
16078          ast_log(LOG_WARNING, "Could not resolve socket address for '%s'\n", c);
16079       }
16080       port = ast_sockaddr_port(&tmp);
16081       ast_sockaddr_set_port(&p->sa,
16082                   port != 0 ? port : STANDARD_SIP_PORT);
16083 
16084       if (sip_debug_test_pvt(p)) {
16085          ast_verbose("Sending to %s (%s)\n",
16086                 ast_sockaddr_stringify(sip_real_dst(p)),
16087                 sip_nat_mode(p));
16088       }
16089    }
16090 }
16091 
16092 /*! \brief Validate device authentication */
16093 static enum check_auth_result check_peer_ok(struct sip_pvt *p, char *of,
16094    struct sip_request *req, int sipmethod, struct ast_sockaddr *addr,
16095    struct sip_peer **authpeer,
16096    enum xmittype reliable, char *calleridname, char *uri2)
16097 {
16098    enum check_auth_result res;
16099    int debug = sip_debug_test_addr(addr);
16100    struct sip_peer *peer;
16101 
16102    if (sipmethod == SIP_SUBSCRIBE) {
16103       /* For subscribes, match on device name only; for other methods,
16104       * match on IP address-port of the incoming request.
16105       */
16106       peer = find_peer(of, NULL, TRUE, FINDALLDEVICES, FALSE, 0);
16107    } else {
16108       /* First find devices based on username (avoid all type=peer's) */
16109       peer = find_peer(of, NULL, TRUE, FINDUSERS, FALSE, 0);
16110 
16111       /* Then find devices based on IP */
16112       if (!peer) {
16113          peer = find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
16114       }
16115    }
16116 
16117    if (!peer) {
16118       if (debug) {
16119          ast_verbose("No matching peer for '%s' from '%s'\n",
16120             of, ast_sockaddr_stringify(&p->recv));
16121       }
16122       return AUTH_DONT_KNOW;
16123    }
16124 
16125    if (!ast_apply_ha(peer->ha, addr)) {
16126       ast_debug(2, "Found peer '%s' for '%s', but fails host access\n", peer->name, of);
16127       unref_peer(peer, "unref_peer: check_peer_ok: from find_peer call, early return of AUTH_ACL_FAILED");
16128       return AUTH_ACL_FAILED;
16129    }
16130    if (debug)
16131       ast_verbose("Found peer '%s' for '%s' from %s\n",
16132          peer->name, of, ast_sockaddr_stringify(&p->recv));
16133 
16134    /* XXX what about p->prefs = peer->prefs; ? */
16135    /* Set Frame packetization */
16136    if (p->rtp) {
16137       ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &peer->prefs);
16138       p->autoframing = peer->autoframing;
16139    }
16140 
16141    /* Take the peer */
16142    ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
16143    ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
16144    ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
16145 
16146    if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && p->udptl) {
16147       p->t38_maxdatagram = peer->t38_maxdatagram;
16148       set_t38_capabilities(p);
16149    }
16150 
16151    /* Copy SIP extensions profile to peer */
16152    /* XXX is this correct before a successful auth ? */
16153    if (p->sipoptions)
16154       peer->sipoptions = p->sipoptions;
16155 
16156    do_setnat(p);
16157 
16158    ast_string_field_set(p, peersecret, peer->secret);
16159    ast_string_field_set(p, peermd5secret, peer->md5secret);
16160    ast_string_field_set(p, subscribecontext, peer->subscribecontext);
16161    ast_string_field_set(p, mohinterpret, peer->mohinterpret);
16162    ast_string_field_set(p, mohsuggest, peer->mohsuggest);
16163    if (!ast_strlen_zero(peer->parkinglot)) {
16164       ast_string_field_set(p, parkinglot, peer->parkinglot);
16165    }
16166    ast_string_field_set(p, engine, peer->engine);
16167    p->disallowed_methods = peer->disallowed_methods;
16168    set_pvt_allowed_methods(p, req);
16169    ast_cc_copy_config_params(p->cc_params, peer->cc_params);
16170    if (peer->callingpres)  /* Peer calling pres setting will override RPID */
16171       p->callingpres = peer->callingpres;
16172    if (peer->maxms && peer->lastms)
16173       p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
16174    else
16175       p->timer_t1 = peer->timer_t1;
16176 
16177    /* Set timer B to control transaction timeouts */
16178    if (peer->timer_b)
16179       p->timer_b = peer->timer_b;
16180    else
16181       p->timer_b = 64 * p->timer_t1;
16182 
16183    p->allowtransfer = peer->allowtransfer;
16184 
16185    if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
16186       /* Pretend there is no required authentication */
16187       ast_string_field_set(p, peersecret, NULL);
16188       ast_string_field_set(p, peermd5secret, NULL);
16189    }
16190    if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, req->ignore))) {
16191       ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
16192       ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
16193       ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
16194       /* If we have a call limit, set flag */
16195       if (peer->call_limit)
16196          ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
16197       ast_string_field_set(p, peername, peer->name);
16198       ast_string_field_set(p, authname, peer->name);
16199 
16200       if (sipmethod == SIP_INVITE) {
16201          /* destroy old channel vars and copy in new ones. */
16202          ast_variables_destroy(p->chanvars);
16203          p->chanvars = copy_vars(peer->chanvars);
16204       }
16205 
16206       if (authpeer) {
16207          ao2_t_ref(peer, 1, "copy pointer into (*authpeer)");
16208          (*authpeer) = peer;  /* Add a ref to the object here, to keep it in memory a bit longer if it is realtime */
16209       }
16210 
16211       if (!ast_strlen_zero(peer->username)) {
16212          ast_string_field_set(p, username, peer->username);
16213          /* Use the default username for authentication on outbound calls */
16214          /* XXX this takes the name from the caller... can we override ? */
16215          ast_string_field_set(p, authname, peer->username);
16216       }
16217       if (!get_rpid(p, req)) {
16218          if (!ast_strlen_zero(peer->cid_num)) {
16219             char *tmp = ast_strdupa(peer->cid_num);
16220             if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
16221                ast_shrink_phone_number(tmp);
16222             ast_string_field_set(p, cid_num, tmp);
16223          }
16224          if (!ast_strlen_zero(peer->cid_name))
16225             ast_string_field_set(p, cid_name, peer->cid_name);
16226          if (peer->callingpres)
16227             p->callingpres = peer->callingpres;
16228       }
16229       if (!ast_strlen_zero(peer->cid_tag)) {
16230          ast_string_field_set(p, cid_tag, peer->cid_tag);
16231       }
16232       ast_string_field_set(p, fullcontact, peer->fullcontact);
16233 
16234       if (!ast_strlen_zero(peer->context)) {
16235          ast_string_field_set(p, context, peer->context);
16236       }
16237       if (!ast_strlen_zero(peer->mwi_from)) {
16238          ast_string_field_set(p, mwi_from, peer->mwi_from);
16239       }
16240 
16241       ast_string_field_set(p, peersecret, peer->secret);
16242       ast_string_field_set(p, peermd5secret, peer->md5secret);
16243       ast_string_field_set(p, language, peer->language);
16244       ast_string_field_set(p, accountcode, peer->accountcode);
16245       p->amaflags = peer->amaflags;
16246       p->callgroup = peer->callgroup;
16247       p->pickupgroup = peer->pickupgroup;
16248       p->capability = peer->capability;
16249       p->prefs = peer->prefs;
16250       p->jointcapability = peer->capability;
16251       if (peer->maxforwards > 0) {
16252          p->maxforwards = peer->maxforwards;
16253       }
16254       if (p->peercapability)
16255          p->jointcapability &= p->peercapability;
16256       p->maxcallbitrate = peer->maxcallbitrate;
16257       if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
16258           (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
16259          p->noncodeccapability |= AST_RTP_DTMF;
16260       else
16261          p->noncodeccapability &= ~AST_RTP_DTMF;
16262       p->jointnoncodeccapability = p->noncodeccapability;
16263       p->rtptimeout = peer->rtptimeout;
16264       p->rtpholdtimeout = peer->rtpholdtimeout;
16265       p->rtpkeepalive = peer->rtpkeepalive;
16266       if (!dialog_initialize_rtp(p)) {
16267          if (p->rtp) {
16268             ast_rtp_codecs_packetization_set(ast_rtp_instance_get_codecs(p->rtp), p->rtp, &peer->prefs);
16269             p->autoframing = peer->autoframing;
16270          }
16271       } else {
16272          res = AUTH_RTP_FAILED;
16273       }
16274    }
16275    unref_peer(peer, "check_peer_ok: unref_peer: tossing temp ptr to peer from find_peer");
16276    return res;
16277 }
16278 
16279 
16280 /*! \brief  Check if matching user or peer is defined
16281    Match user on From: user name and peer on IP/port
16282    This is used on first invite (not re-invites) and subscribe requests
16283     \return 0 on success, non-zero on failure
16284 */
16285 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
16286                      int sipmethod, const char *uri, enum xmittype reliable,
16287                      struct ast_sockaddr *addr, struct sip_peer **authpeer)
16288 {
16289    char from[256] = "", *of, *name, *unused_password, *domain;
16290    enum check_auth_result res = AUTH_DONT_KNOW;
16291    char calleridname[50];
16292    char *uri2 = ast_strdupa(uri);
16293 
16294    terminate_uri(uri2); /* trim extra stuff */
16295 
16296    ast_copy_string(from, get_header(req, "From"), sizeof(from));
16297    /* XXX here tries to map the username for invite things */
16298 
16299    /* strip the display-name portion off the beginning of the FROM header. */
16300    if (!(of = (char *) get_calleridname(from, calleridname, sizeof(calleridname)))) {
16301       ast_log(LOG_ERROR, "FROM header can not be parsed \n");
16302       return res;
16303    }
16304 
16305    if (calleridname[0]) {
16306       ast_string_field_set(p, cid_name, calleridname);
16307    }
16308 
16309    if (ast_strlen_zero(p->exten)) {
16310       char *t = uri2;
16311       if (!strncasecmp(t, "sip:", 4))
16312          t+= 4;
16313       else if (!strncasecmp(t, "sips:", 5))
16314          t += 5;
16315       ast_string_field_set(p, exten, t);
16316       t = strchr(p->exten, '@');
16317       if (t)
16318          *t = '\0';
16319 
16320       if (ast_strlen_zero(p->our_contact))
16321          build_contact(p);
16322    }
16323 
16324    of = get_in_brackets(of);
16325 
16326    /* save the URI part of the From header */
16327    ast_string_field_set(p, from, of);
16328 
16329    if (parse_uri_legacy_check(of, "sip:,sips:", &name, &unused_password, &domain, NULL)) {
16330       ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
16331    }
16332 
16333    SIP_PEDANTIC_DECODE(name);
16334    SIP_PEDANTIC_DECODE(domain);
16335 
16336    extract_host_from_hostport(&domain);
16337 
16338    if (ast_strlen_zero(domain)) {
16339       /* <sip:name@[EMPTY]>, never good */
16340       ast_log(LOG_ERROR, "Empty domain name in FROM header\n");
16341       return res;
16342    }
16343 
16344    if (ast_strlen_zero(name)) {
16345       /* <sip:[EMPTY][@]hostport>. Asterisk 1.4 and 1.6 have always
16346        * treated that as a username, so we continue the tradition:
16347        * uri is now <sip:host@hostport>. */
16348       name = domain;
16349    } else {
16350       /* Non-empty name, try to get caller id from it */
16351       char *tmp = ast_strdupa(name);
16352       /* We need to be able to handle from-headers looking like
16353          <sip:8164444422;phone-context=+1@1.2.3.4:5060;user=phone;tag=SDadkoa01-gK0c3bdb43>
16354       */
16355       tmp = strsep(&tmp, ";");
16356       if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp)) {
16357          ast_shrink_phone_number(tmp);
16358       }
16359       ast_string_field_set(p, cid_num, tmp);
16360    }
16361 
16362    if (global_match_auth_username) {
16363       /*
16364        * XXX This is experimental code to grab the search key from the
16365        * Auth header's username instead of the 'From' name, if available.
16366        * Do not enable this block unless you understand the side effects (if any!)
16367        * Note, the search for "username" should be done in a more robust way.
16368        * Note2, at the moment we check both fields, though maybe we should
16369        * pick one or another depending on the request ? XXX
16370        */
16371       const char *hdr = get_header(req, "Authorization");
16372       if (ast_strlen_zero(hdr)) {
16373          hdr = get_header(req, "Proxy-Authorization");
16374       }
16375 
16376       if (!ast_strlen_zero(hdr) && (hdr = strstr(hdr, "username=\""))) {
16377          ast_copy_string(from, hdr + strlen("username=\""), sizeof(from));
16378          name = from;
16379          name = strsep(&name, "\"");
16380       }
16381    }
16382 
16383    res = check_peer_ok(p, name, req, sipmethod, addr,
16384          authpeer, reliable, calleridname, uri2);
16385    if (res != AUTH_DONT_KNOW) {
16386       return res;
16387    }
16388 
16389    /* Finally, apply the guest policy */
16390    if (sip_cfg.allowguest) {
16391       /* Ignore check_return warning from Coverity for get_rpid below. */
16392       get_rpid(p, req);
16393       p->rtptimeout = global_rtptimeout;
16394       p->rtpholdtimeout = global_rtpholdtimeout;
16395       p->rtpkeepalive = global_rtpkeepalive;
16396       if (!dialog_initialize_rtp(p)) {
16397          res = AUTH_SUCCESSFUL;
16398       } else {
16399          res = AUTH_RTP_FAILED;
16400       }
16401    } else if (sip_cfg.alwaysauthreject) {
16402       res = AUTH_FAKE_AUTH; /* reject with fake authorization request */
16403    } else {
16404       res = AUTH_SECRET_FAILED; /* we don't want any guests, authentication will fail */
16405    }
16406 
16407    if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT)) {
16408       ast_set_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT);
16409    }
16410 
16411    return res;
16412 }
16413 
16414 /*! \brief  Find user
16415    If we get a match, this will add a reference pointer to the user object in ASTOBJ, that needs to be unreferenced
16416 */
16417 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct ast_sockaddr *addr)
16418 {
16419    return check_user_full(p, req, sipmethod, uri, reliable, addr, NULL);
16420 }
16421 
16422 /*! \brief Get message body from a SIP request
16423  * \param buf Destination buffer
16424  * \param len Destination buffer size
16425  * \param req The SIP request
16426  *
16427  * When parsing the request originally, the lines are split by LF or CRLF.
16428  * This function adds a single LF after every line.
16429  */
16430 static int get_msg_text(char *buf, int len, struct sip_request *req)
16431 {
16432    int x;
16433    int linelen;
16434 
16435    buf[0] = '\0';
16436    --len; /* reserve strncat null */
16437    for (x = 0; len && x < req->lines; ++x) {
16438       const char *line = REQ_OFFSET_TO_STR(req, line[x]);
16439       strncat(buf, line, len); /* safe */
16440       linelen = strlen(buf);
16441       buf += linelen;
16442       len -= linelen;
16443       if (len) {
16444          strcat(buf, "\n"); /* safe */
16445          ++buf;
16446          --len;
16447       }
16448    }
16449    return 0;
16450 }
16451 
16452 
16453 /*! \brief  Receive SIP MESSAGE method messages
16454 \note We only handle messages within current calls currently
16455    Reference: RFC 3428 */
16456 static void receive_message(struct sip_pvt *p, struct sip_request *req)
16457 {
16458    char buf[1400];   
16459    char *bufp;
16460    struct ast_frame f;
16461    const char *content_type = get_header(req, "Content-Type");
16462 
16463    if (strncmp(content_type, "text/plain", strlen("text/plain"))) { /* No text/plain attachment */
16464       transmit_response(p, "415 Unsupported Media Type", req); /* Good enough, or? */
16465       if (!p->owner)
16466          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16467       return;
16468    }
16469 
16470    if (get_msg_text(buf, sizeof(buf), req)) {
16471       ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
16472       transmit_response(p, "500 Internal Server Error", req);
16473       if (!p->owner) {
16474          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16475       }
16476       return;
16477    }
16478 
16479    /* Strip trailing line feeds from message body. (get_msg_text may add
16480     * a trailing linefeed and we don't need any at the end) */
16481    bufp = buf + strlen(buf);
16482    while (--bufp >= buf && *bufp == '\n') {
16483       *bufp = '\0';
16484    }
16485 
16486    if (p->owner) {
16487       if (sip_debug_test_pvt(p))
16488          ast_verbose("SIP Text message received: '%s'\n", buf);
16489       memset(&f, 0, sizeof(f));
16490       f.frametype = AST_FRAME_TEXT;
16491       f.subclass.integer = 0;
16492       f.offset = 0;
16493       f.data.ptr = buf;
16494       f.datalen = strlen(buf) + 1;
16495       ast_queue_frame(p->owner, &f);
16496       transmit_response(p, "202 Accepted", req); /* We respond 202 accepted, since we relay the message */
16497       return;
16498    }
16499 
16500    /* Message outside of a call, we do not support that */
16501    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);
16502    transmit_response(p, "405 Method Not Allowed", req);
16503    sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16504    return;
16505 }
16506 
16507 /*! \brief  CLI Command to show calls within limits set by call_limit */
16508 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16509 {
16510 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
16511 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
16512    char ilimits[40];
16513    char iused[40];
16514    int showall = FALSE;
16515    struct ao2_iterator i;
16516    struct sip_peer *peer;
16517    
16518    switch (cmd) {
16519    case CLI_INIT:
16520       e->command = "sip show inuse";
16521       e->usage =
16522          "Usage: sip show inuse [all]\n"
16523          "       List all SIP devices usage counters and limits.\n"
16524          "       Add option \"all\" to show all devices, not only those with a limit.\n";
16525       return NULL;
16526    case CLI_GENERATE:
16527       return NULL;
16528    }
16529 
16530    if (a->argc < 3)
16531       return CLI_SHOWUSAGE;
16532 
16533    if (a->argc == 4 && !strcmp(a->argv[3], "all"))
16534       showall = TRUE;
16535    
16536    ast_cli(a->fd, FORMAT, "* Peer name", "In use", "Limit");
16537 
16538    i = ao2_iterator_init(peers, 0);
16539    while ((peer = ao2_t_iterator_next(&i, "iterate thru peer table"))) {
16540       ao2_lock(peer);
16541       if (peer->call_limit)
16542          snprintf(ilimits, sizeof(ilimits), "%d", peer->call_limit);
16543       else
16544          ast_copy_string(ilimits, "N/A", sizeof(ilimits));
16545       snprintf(iused, sizeof(iused), "%d/%d/%d", peer->inUse, peer->inRinging, peer->onHold);
16546       if (showall || peer->call_limit)
16547          ast_cli(a->fd, FORMAT2, peer->name, iused, ilimits);
16548       ao2_unlock(peer);
16549       unref_peer(peer, "toss iterator pointer");
16550    }
16551    ao2_iterator_destroy(&i);
16552 
16553    return CLI_SUCCESS;
16554 #undef FORMAT
16555 #undef FORMAT2
16556 }
16557 
16558 
16559 /*! \brief Convert transfer mode to text string */
16560 static char *transfermode2str(enum transfermodes mode)
16561 {
16562    if (mode == TRANSFER_OPENFORALL)
16563       return "open";
16564    else if (mode == TRANSFER_CLOSED)
16565       return "closed";
16566    return "strict";
16567 }
16568 
16569 /*! \brief  Report Peer status in character string
16570  *  \return 0 if peer is unreachable, 1 if peer is online, -1 if unmonitored
16571  */
16572 
16573 
16574 /* Session-Timer Modes */
16575 static const struct _map_x_s stmodes[] = {
16576         { SESSION_TIMER_MODE_ACCEPT,    "Accept"},
16577         { SESSION_TIMER_MODE_ORIGINATE, "Originate"},
16578         { SESSION_TIMER_MODE_REFUSE,    "Refuse"},
16579         { -1,                           NULL},
16580 };
16581 
16582 static const char *stmode2str(enum st_mode m)
16583 {
16584    return map_x_s(stmodes, m, "Unknown");
16585 }
16586 
16587 static enum st_mode str2stmode(const char *s)
16588 {
16589    return map_s_x(stmodes, s, -1);
16590 }
16591 
16592 /* Session-Timer Refreshers */
16593 static const struct _map_x_s strefresher_params[] = {
16594         { SESSION_TIMER_REFRESHER_PARAM_UNKNOWN, "unknown" },
16595         { SESSION_TIMER_REFRESHER_PARAM_UAC,     "uac"     },
16596         { SESSION_TIMER_REFRESHER_PARAM_UAS,     "uas"     },
16597         { -1,                                NULL  },
16598 };
16599 
16600 static const struct _map_x_s strefreshers[] = {
16601         { SESSION_TIMER_REFRESHER_AUTO, "auto" },
16602         { SESSION_TIMER_REFRESHER_US,   "us"   },
16603         { SESSION_TIMER_REFRESHER_THEM, "them" },
16604         { -1,                           NULL   },
16605 };
16606 
16607 static const char *strefresherparam2str(enum st_refresher r)
16608 {
16609    return map_x_s(strefresher_params, r, "Unknown");
16610 }
16611 
16612 static enum st_refresher str2strefresherparam(const char *s)
16613 {
16614    return map_s_x(strefresher_params, s, -1);
16615 }
16616 
16617 static const char *strefresher2str(enum st_refresher r)
16618 {
16619    return map_x_s(strefreshers, r, "Unknown");
16620 }
16621 
16622 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
16623 {
16624    int res = 0;
16625    if (peer->maxms) {
16626       if (peer->lastms < 0) {
16627          ast_copy_string(status, "UNREACHABLE", statuslen);
16628       } else if (peer->lastms > peer->maxms) {
16629          snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
16630          res = 1;
16631       } else if (peer->lastms) {
16632          snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
16633          res = 1;
16634       } else {
16635          ast_copy_string(status, "UNKNOWN", statuslen);
16636       }
16637    } else {
16638       ast_copy_string(status, "Unmonitored", statuslen);
16639       /* Checking if port is 0 */
16640       res = -1;
16641    }
16642    return res;
16643 }
16644 
16645 /*! \brief  Show active TCP connections */
16646 static char *sip_show_tcp(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16647 {
16648    struct sip_threadinfo *th;
16649    struct ao2_iterator i;
16650 
16651 #define FORMAT2 "%-47.47s %9.9s %6.6s\n"
16652 #define FORMAT  "%-47.47s %-9.9s %-6.6s\n"
16653 
16654    switch (cmd) {
16655    case CLI_INIT:
16656       e->command = "sip show tcp";
16657       e->usage =
16658          "Usage: sip show tcp\n"
16659          "       Lists all active TCP/TLS sessions.\n";
16660       return NULL;
16661    case CLI_GENERATE:
16662       return NULL;
16663    }
16664 
16665    if (a->argc != 3)
16666       return CLI_SHOWUSAGE;
16667 
16668    ast_cli(a->fd, FORMAT2, "Address", "Transport", "Type");
16669 
16670    i = ao2_iterator_init(threadt, 0);
16671    while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
16672       ast_cli(a->fd, FORMAT,
16673          ast_sockaddr_stringify(&th->tcptls_session->remote_address),
16674          get_transport(th->type),
16675          (th->tcptls_session->client ? "Client" : "Server"));
16676       ao2_t_ref(th, -1, "decrement ref from iterator");
16677    }
16678    ao2_iterator_destroy(&i);
16679 
16680    return CLI_SUCCESS;
16681 #undef FORMAT
16682 #undef FORMAT2
16683 }
16684 
16685 /*! \brief  CLI Command 'SIP Show Users' */
16686 static char *sip_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16687 {
16688    regex_t regexbuf;
16689    int havepattern = FALSE;
16690    struct ao2_iterator user_iter;
16691    struct sip_peer *user;
16692 
16693 #define FORMAT  "%-25.25s  %-15.15s  %-15.15s  %-15.15s  %-5.5s%-10.10s\n"
16694 
16695    switch (cmd) {
16696    case CLI_INIT:
16697       e->command = "sip show users";
16698       e->usage =
16699          "Usage: sip show users [like <pattern>]\n"
16700          "       Lists all known SIP users.\n"
16701          "       Optional regular expression pattern is used to filter the user list.\n";
16702       return NULL;
16703    case CLI_GENERATE:
16704       return NULL;
16705    }
16706 
16707    switch (a->argc) {
16708    case 5:
16709       if (!strcasecmp(a->argv[3], "like")) {
16710          if (regcomp(&regexbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
16711             return CLI_SHOWUSAGE;
16712          havepattern = TRUE;
16713       } else
16714          return CLI_SHOWUSAGE;
16715    case 3:
16716       break;
16717    default:
16718       return CLI_SHOWUSAGE;
16719    }
16720 
16721    ast_cli(a->fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "ForcerPort");
16722 
16723    user_iter = ao2_iterator_init(peers, 0);
16724    while ((user = ao2_t_iterator_next(&user_iter, "iterate thru peers table"))) {
16725       ao2_lock(user);
16726       if (!(user->type & SIP_TYPE_USER)) {
16727          ao2_unlock(user);
16728          unref_peer(user, "sip show users");
16729          continue;
16730       }
16731 
16732       if (havepattern && regexec(&regexbuf, user->name, 0, NULL, 0)) {
16733          ao2_unlock(user);
16734          unref_peer(user, "sip show users");
16735          continue;
16736       }
16737 
16738       ast_cli(a->fd, FORMAT, user->name,
16739          user->secret,
16740          user->accountcode,
16741          user->context,
16742          AST_CLI_YESNO(user->ha != NULL),
16743          AST_CLI_YESNO(ast_test_flag(&user->flags[0], SIP_NAT_FORCE_RPORT)));
16744       ao2_unlock(user);
16745       unref_peer(user, "sip show users");
16746    }
16747    ao2_iterator_destroy(&user_iter);
16748 
16749    if (havepattern)
16750       regfree(&regexbuf);
16751 
16752    return CLI_SUCCESS;
16753 #undef FORMAT
16754 }
16755 
16756 /*! \brief Show SIP registrations in the manager API */
16757 static int manager_show_registry(struct mansession *s, const struct message *m)
16758 {
16759    const char *id = astman_get_header(m, "ActionID");
16760    char idtext[256] = "";
16761    int total = 0;
16762 
16763    if (!ast_strlen_zero(id))
16764       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
16765 
16766    astman_send_listack(s, m, "Registrations will follow", "start");
16767 
16768    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
16769       ASTOBJ_RDLOCK(iterator);
16770       astman_append(s,
16771          "Event: RegistryEntry\r\n"
16772          "%s"
16773          "Host: %s\r\n"
16774          "Port: %d\r\n"
16775          "Username: %s\r\n"
16776          "Domain: %s\r\n"
16777          "DomainPort: %d\r\n"
16778          "Refresh: %d\r\n"
16779          "State: %s\r\n"
16780          "RegistrationTime: %ld\r\n"
16781          "\r\n",
16782          idtext,
16783          iterator->hostname,
16784          iterator->portno ? iterator->portno : STANDARD_SIP_PORT,
16785          iterator->username,
16786          S_OR(iterator->regdomain,iterator->hostname),
16787          iterator->regdomainport ? iterator->regdomainport : STANDARD_SIP_PORT,
16788          iterator->refresh,
16789          regstate2str(iterator->regstate),
16790          (long) iterator->regtime.tv_sec);
16791       ASTOBJ_UNLOCK(iterator);
16792       total++;
16793    } while(0));
16794 
16795    astman_append(s,
16796       "Event: RegistrationsComplete\r\n"
16797       "EventList: Complete\r\n"
16798       "ListItems: %d\r\n"
16799       "%s"
16800       "\r\n", total, idtext);
16801    
16802    return 0;
16803 }
16804 
16805 /*! \brief  Show SIP peers in the manager API */
16806 /*    Inspired from chan_iax2 */
16807 static int manager_sip_show_peers(struct mansession *s, const struct message *m)
16808 {
16809    const char *id = astman_get_header(m, "ActionID");
16810    const char *a[] = {"sip", "show", "peers"};
16811    char idtext[256] = "";
16812    int total = 0;
16813 
16814    if (!ast_strlen_zero(id))
16815       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
16816 
16817    astman_send_listack(s, m, "Peer status list will follow", "start");
16818    /* List the peers in separate manager events */
16819    _sip_show_peers(-1, &total, s, m, 3, a);
16820    /* Send final confirmation */
16821    astman_append(s,
16822    "Event: PeerlistComplete\r\n"
16823    "EventList: Complete\r\n"
16824    "ListItems: %d\r\n"
16825    "%s"
16826    "\r\n", total, idtext);
16827    return 0;
16828 }
16829 
16830 /*! \brief  CLI Show Peers command */
16831 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16832 {
16833    switch (cmd) {
16834    case CLI_INIT:
16835       e->command = "sip show peers";
16836       e->usage =
16837          "Usage: sip show peers [like <pattern>]\n"
16838          "       Lists all known SIP peers.\n"
16839          "       Optional regular expression pattern is used to filter the peer list.\n";
16840       return NULL;
16841    case CLI_GENERATE:
16842       return NULL;
16843    }
16844 
16845    return _sip_show_peers(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
16846 }
16847 
16848 int peercomparefunc(const void *a, const void *b);
16849 
16850 int peercomparefunc(const void *a, const void *b)
16851 {
16852    struct sip_peer **ap = (struct sip_peer **)a;
16853    struct sip_peer **bp = (struct sip_peer **)b;
16854    return strcmp((*ap)->name, (*bp)->name);
16855 }
16856 
16857 
16858 /*! \brief Execute sip show peers command */
16859 static char *_sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
16860 {
16861    regex_t regexbuf;
16862    int havepattern = FALSE;
16863    struct sip_peer *peer;
16864    struct ao2_iterator* it_peers;
16865 
16866 /* the last argument is left-aligned, so we don't need a size anyways */
16867 #define FORMAT2 "%-25.25s  %-39.39s %-3.3s %-10.10s %-3.3s %-8s %-10s %s\n"
16868 
16869    char name[256];
16870    int total_peers = 0;
16871    int peers_mon_online = 0;
16872    int peers_mon_offline = 0;
16873    int peers_unmon_offline = 0;
16874    int peers_unmon_online = 0;
16875    const char *id;
16876    char idtext[256] = "";
16877    int realtimepeers;
16878    struct sip_peer **peerarray;
16879    int k;
16880 
16881    realtimepeers = ast_check_realtime("sippeers");
16882 
16883    if (s) { /* Manager - get ActionID */
16884       id = astman_get_header(m, "ActionID");
16885       if (!ast_strlen_zero(id))
16886          snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
16887    }
16888 
16889    switch (argc) {
16890    case 5:
16891       if (!strcasecmp(argv[3], "like")) {
16892          if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
16893             return CLI_SHOWUSAGE;
16894          havepattern = TRUE;
16895       } else
16896          return CLI_SHOWUSAGE;
16897    case 3:
16898       break;
16899    default:
16900       return CLI_SHOWUSAGE;
16901    }
16902 
16903    if (!s) {
16904       /* Normal list */
16905       ast_cli(fd, FORMAT2, "Name/username", "Host", "Dyn", "Forcerport", "ACL", "Port", "Status", (realtimepeers ? "Realtime" : ""));
16906    }
16907 
16908    ao2_lock(peers);
16909    if (!(it_peers = ao2_callback(peers, OBJ_MULTIPLE, NULL, NULL))) {
16910       ast_log(AST_LOG_ERROR, "Unable to create iterator for peers container for sip show peers\n");
16911       ao2_unlock(peers);
16912       return CLI_FAILURE;
16913    }
16914    if (!(peerarray = ast_calloc(sizeof(struct sip_peer *), ao2_container_count(peers)))) {
16915       ast_log(AST_LOG_ERROR, "Unable to allocate peer array for sip show peers\n");
16916       ao2_iterator_destroy(it_peers);
16917       ao2_unlock(peers);
16918       return CLI_FAILURE;
16919    }
16920    ao2_unlock(peers);
16921 
16922    while ((peer = ao2_t_iterator_next(it_peers, "iterate thru peers table"))) {
16923       ao2_lock(peer);
16924 
16925       if (!(peer->type & SIP_TYPE_PEER)) {
16926          ao2_unlock(peer);
16927          unref_peer(peer, "unref peer because it's actually a user");
16928          continue;
16929       }
16930 
16931       if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0)) {
16932          ao2_unlock(peer);
16933          unref_peer(peer, "toss iterator peer ptr before continue");
16934          continue;
16935       }
16936 
16937       peerarray[total_peers++] = peer;
16938       ao2_unlock(peer);
16939    }
16940    ao2_iterator_destroy(it_peers);
16941 
16942    qsort(peerarray, total_peers, sizeof(struct sip_peer *), peercomparefunc);
16943 
16944    for(k=0; k < total_peers; k++) {
16945       char status[20] = "";
16946       char srch[2000];
16947       char pstatus;
16948 
16949       /*
16950        * tmp_port and tmp_host store copies of ast_sockaddr_stringify strings since the
16951        * string pointers for that function aren't valid between subsequent calls to
16952        * ast_sockaddr_stringify functions
16953        */
16954       char *tmp_port;
16955       char *tmp_host;
16956 
16957       peer = peerarray[k];
16958 
16959       tmp_port = ast_sockaddr_isnull(&peer->addr) ?
16960          "0" : ast_strdupa(ast_sockaddr_stringify_port(&peer->addr));
16961 
16962       tmp_host = ast_sockaddr_isnull(&peer->addr) ?
16963          "(Unspecified)" : ast_strdupa(ast_sockaddr_stringify_addr(&peer->addr));
16964 
16965       ao2_lock(peer);
16966       if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0)) {
16967          ao2_unlock(peer);
16968          peer = peerarray[k] = unref_peer(peer, "toss iterator peer ptr before continue");
16969          continue;
16970       }
16971 
16972       if (!ast_strlen_zero(peer->username) && !s)
16973          snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
16974       else
16975          ast_copy_string(name, peer->name, sizeof(name));
16976 
16977       pstatus = peer_status(peer, status, sizeof(status));
16978       if (pstatus == 1)
16979          peers_mon_online++;
16980       else if (pstatus == 0)
16981          peers_mon_offline++;
16982       else {
16983          if (ast_sockaddr_isnull(&peer->addr) ||
16984              !ast_sockaddr_port(&peer->addr)) {
16985             peers_unmon_offline++;
16986          } else {
16987             peers_unmon_online++;
16988          }
16989       }
16990 
16991       snprintf(srch, sizeof(srch), FORMAT2, name,
16992          tmp_host,
16993          peer->host_dynamic ? " D " : "   ", /* Dynamic or not? */
16994          ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? " N " : "   ", /* NAT=yes? */
16995          peer->ha ? " A " : "   ",  /* permit/deny */
16996          tmp_port, status,
16997          realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
16998 
16999       if (!s)  {/* Normal CLI list */
17000          ast_cli(fd, FORMAT2, name,
17001          tmp_host,
17002          peer->host_dynamic ? " D " : "   ", /* Dynamic or not? */
17003          ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? " N " : "   ", /* NAT=yes? */
17004          peer->ha ? " A " : "   ",       /* permit/deny */
17005          tmp_port, status,
17006          realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
17007       } else { /* Manager format */
17008          /* The names here need to be the same as other channels */
17009          astman_append(s,
17010          "Event: PeerEntry\r\n%s"
17011          "Channeltype: SIP\r\n"
17012          "ObjectName: %s\r\n"
17013          "ChanObjectType: peer\r\n" /* "peer" or "user" */
17014          "IPaddress: %s\r\n"
17015          "IPport: %s\r\n"
17016          "Dynamic: %s\r\n"
17017          "Forcerport: %s\r\n"
17018          "VideoSupport: %s\r\n"
17019          "TextSupport: %s\r\n"
17020          "ACL: %s\r\n"
17021          "Status: %s\r\n"
17022          "RealtimeDevice: %s\r\n\r\n",
17023          idtext,
17024          peer->name,
17025          ast_sockaddr_isnull(&peer->addr) ? "-none-" : tmp_host,
17026          ast_sockaddr_isnull(&peer->addr) ? "0" : tmp_port,
17027          peer->host_dynamic ? "yes" : "no",  /* Dynamic or not? */
17028          ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) ? "yes" : "no",  /* NAT=yes? */
17029          ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no",  /* VIDEOSUPPORT=yes? */
17030          ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "yes" : "no",   /* TEXTSUPPORT=yes? */
17031          peer->ha ? "yes" : "no",       /* permit/deny */
17032          status,
17033          realtimepeers ? (peer->is_realtime ? "yes":"no") : "no");
17034       }
17035       ao2_unlock(peer);
17036       peer = peerarray[k] = unref_peer(peer, "toss iterator peer ptr");
17037    }
17038 
17039    if (!s)
17040       ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
17041               total_peers, peers_mon_online, peers_mon_offline, peers_unmon_online, peers_unmon_offline);
17042 
17043    if (havepattern)
17044       regfree(&regexbuf);
17045 
17046    if (total)
17047       *total = total_peers;
17048 
17049    ast_free(peerarray);
17050 
17051    return CLI_SUCCESS;
17052 #undef FORMAT2
17053 }
17054 
17055 static int peer_dump_func(void *userobj, void *arg, int flags)
17056 {
17057    struct sip_peer *peer = userobj;
17058    int refc = ao2_t_ref(userobj, 0, "");
17059    struct ast_cli_args *a = (struct ast_cli_args *) arg;
17060    
17061    ast_cli(a->fd, "name: %s\ntype: peer\nobjflags: %d\nrefcount: %d\n\n",
17062       peer->name, 0, refc);
17063    return 0;
17064 }
17065 
17066 static int dialog_dump_func(void *userobj, void *arg, int flags)
17067 {
17068    struct sip_pvt *pvt = userobj;
17069    int refc = ao2_t_ref(userobj, 0, "");
17070    struct ast_cli_args *a = (struct ast_cli_args *) arg;
17071    
17072    ast_cli(a->fd, "name: %s\ntype: dialog\nobjflags: %d\nrefcount: %d\n\n",
17073       pvt->callid, 0, refc);
17074    return 0;
17075 }
17076 
17077 
17078 /*! \brief List all allocated SIP Objects (realtime or static) */
17079 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17080 {
17081    char tmp[256];
17082    
17083    switch (cmd) {
17084    case CLI_INIT:
17085       e->command = "sip show objects";
17086       e->usage =
17087          "Usage: sip show objects\n"
17088          "       Lists status of known SIP objects\n";
17089       return NULL;
17090    case CLI_GENERATE:
17091       return NULL;
17092    }  
17093 
17094    if (a->argc != 3)
17095       return CLI_SHOWUSAGE;
17096    ast_cli(a->fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
17097    ao2_t_callback(peers, OBJ_NODATA, peer_dump_func, a, "initiate ao2_callback to dump peers");
17098    ast_cli(a->fd, "-= Peer objects by IP =-\n\n"); 
17099    ao2_t_callback(peers_by_ip, OBJ_NODATA, peer_dump_func, a, "initiate ao2_callback to dump peers_by_ip");
17100    ast_cli(a->fd, "-= Registry objects: %d =-\n\n", regobjs);
17101    ASTOBJ_CONTAINER_DUMP(a->fd, tmp, sizeof(tmp), &regl);
17102    ast_cli(a->fd, "-= Dialog objects:\n\n");
17103    ao2_t_callback(dialogs, OBJ_NODATA, dialog_dump_func, a, "initiate ao2_callback to dump dialogs");
17104    return CLI_SUCCESS;
17105 }
17106 /*! \brief Print call group and pickup group */
17107 static void print_group(int fd, ast_group_t group, int crlf)
17108 {
17109    char buf[256];
17110    ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
17111 }
17112 
17113 /*! \brief mapping between dtmf flags and strings */
17114 static const struct _map_x_s dtmfstr[] = {
17115    { SIP_DTMF_RFC2833,     "rfc2833" },
17116    { SIP_DTMF_INFO,        "info" },
17117    { SIP_DTMF_SHORTINFO,   "shortinfo" },
17118    { SIP_DTMF_INBAND,      "inband" },
17119    { SIP_DTMF_AUTO,        "auto" },
17120    { -1,                   NULL }, /* terminator */
17121 };
17122 
17123 /*! \brief Convert DTMF mode to printable string */
17124 static const char *dtmfmode2str(int mode)
17125 {
17126    return map_x_s(dtmfstr, mode, "<error>");
17127 }
17128 
17129 /*! \brief maps a string to dtmfmode, returns -1 on error */
17130 static int str2dtmfmode(const char *str)
17131 {
17132    return map_s_x(dtmfstr, str, -1);
17133 }
17134 
17135 static const struct _map_x_s insecurestr[] = {
17136    { SIP_INSECURE_PORT,    "port" },
17137    { SIP_INSECURE_INVITE,  "invite" },
17138    { SIP_INSECURE_PORT | SIP_INSECURE_INVITE, "port,invite" },
17139    { 0,                    "no" },
17140    { -1,                   NULL }, /* terminator */
17141 };
17142 
17143 /*! \brief Convert Insecure setting to printable string */
17144 static const char *insecure2str(int mode)
17145 {
17146    return map_x_s(insecurestr, mode, "<error>");
17147 }
17148 
17149 static const struct _map_x_s allowoverlapstr[] = {
17150    { SIP_PAGE2_ALLOWOVERLAP_YES,   "Yes" },
17151    { SIP_PAGE2_ALLOWOVERLAP_DTMF,  "DTMF" },
17152    { SIP_PAGE2_ALLOWOVERLAP_NO,    "No" },
17153    { -1,                           NULL }, /* terminator */
17154 };
17155 
17156 /*! \brief Convert AllowOverlap setting to printable string */
17157 static const char *allowoverlap2str(int mode)
17158 {
17159    return map_x_s(allowoverlapstr, mode, "<error>");
17160 }
17161 
17162 /*! \brief Destroy disused contexts between reloads
17163    Only used in reload_config so the code for regcontext doesn't get ugly
17164 */
17165 static void cleanup_stale_contexts(char *new, char *old)
17166 {
17167    char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
17168 
17169    while ((oldcontext = strsep(&old, "&"))) {
17170       stalecontext = '\0';
17171       ast_copy_string(newlist, new, sizeof(newlist));
17172       stringp = newlist;
17173       while ((newcontext = strsep(&stringp, "&"))) {
17174          if (!strcmp(newcontext, oldcontext)) {
17175             /* This is not the context you're looking for */
17176             stalecontext = '\0';
17177             break;
17178          } else if (strcmp(newcontext, oldcontext)) {
17179             stalecontext = oldcontext;
17180          }
17181          
17182       }
17183       if (stalecontext)
17184          ast_context_destroy(ast_context_find(stalecontext), "SIP");
17185    }
17186 }
17187 
17188 /*!
17189  * \brief Match dialogs that need to be destroyed
17190  *
17191  * \details This is used with ao2_callback to unlink/delete all dialogs that
17192  * are marked needdestroy.
17193  *
17194  * \todo Re-work this to improve efficiency.  Currently, this function is called
17195  * on _every_ dialog after processing _every_ incoming SIP/UDP packet, or
17196  * potentially even more often when the scheduler has entries to run.
17197  */
17198 static int dialog_needdestroy(void *dialogobj, void *arg, int flags)
17199 {
17200    struct sip_pvt *dialog = dialogobj;
17201    time_t *t = arg;
17202 
17203    if (sip_pvt_trylock(dialog)) {
17204       /* Don't block the monitor thread.  This function is called often enough
17205        * that we can wait for the next time around. */
17206       return 0;
17207    }
17208 
17209    /* Check RTP timeouts and kill calls if we have a timeout set and do not get RTP */
17210    check_rtp_timeout(dialog, *t);
17211 
17212    /* We absolutely cannot destroy the rtp struct while a bridge is active or we WILL crash */
17213    if (dialog->rtp && ast_rtp_instance_get_bridged(dialog->rtp)) {
17214       ast_debug(2, "Bridge still active.  Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
17215       sip_pvt_unlock(dialog);
17216       return 0;
17217    }
17218 
17219    if (dialog->vrtp && ast_rtp_instance_get_bridged(dialog->vrtp)) {
17220       ast_debug(2, "Bridge still active.  Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
17221       sip_pvt_unlock(dialog);
17222       return 0;
17223    }
17224 
17225    /* If we have sessions that needs to be destroyed, do it now */
17226    /* Check if we have outstanding requests not responsed to or an active call
17227       - if that's the case, wait with destruction */
17228    if (dialog->needdestroy && !dialog->packets && !dialog->owner) {
17229       /* We absolutely cannot destroy the rtp struct while a bridge is active or we WILL crash */
17230       if (dialog->rtp && ast_rtp_instance_get_bridged(dialog->rtp)) {
17231          ast_debug(2, "Bridge still active.  Delaying destruction of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
17232          sip_pvt_unlock(dialog);
17233          return 0;
17234       }
17235       
17236       if (dialog->vrtp && ast_rtp_instance_get_bridged(dialog->vrtp)) {
17237          ast_debug(2, "Bridge still active.  Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
17238          sip_pvt_unlock(dialog);
17239          return 0;
17240       }
17241 
17242       sip_pvt_unlock(dialog);
17243 
17244       /* This dialog needs to be destroyed. */
17245       ao2_t_link(dialogs_to_destroy, dialog, "Link dialog for destruction");
17246       return 0;
17247    }
17248 
17249    sip_pvt_unlock(dialog);
17250 
17251    return 0;
17252 }
17253 
17254 /*!
17255  * \internal
17256  * \brief ao2_callback to unlink the specified dialog object.
17257  *
17258  * \param obj Ptr to dialog to unlink.
17259  * \param arg Don't care.
17260  * \param flags Don't care.
17261  *
17262  * \retval CMP_MATCH
17263  */
17264 static int dialog_unlink_callback(void *obj, void *arg, int flags)
17265 {
17266    struct sip_pvt *dialog = obj;
17267 
17268    dialog_unlink_all(dialog);
17269 
17270    return CMP_MATCH;
17271 }
17272 
17273 /*! \brief Remove temporary realtime objects from memory (CLI) */
17274 /*! \todo XXXX Propably needs an overhaul after removal of the devices */
17275 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17276 {
17277    struct sip_peer *peer, *pi;
17278    int prunepeer = FALSE;
17279    int multi = FALSE;
17280    const char *name = NULL;
17281    regex_t regexbuf;
17282    int havepattern = 0;
17283    struct ao2_iterator i;
17284    static const char * const choices[] = { "all", "like", NULL };
17285    char *cmplt;
17286    
17287    if (cmd == CLI_INIT) {
17288       e->command = "sip prune realtime [peer|all]";
17289       e->usage =
17290          "Usage: sip prune realtime [peer [<name>|all|like <pattern>]|all]\n"
17291          "       Prunes object(s) from the cache.\n"
17292          "       Optional regular expression pattern is used to filter the objects.\n";
17293       return NULL;
17294    } else if (cmd == CLI_GENERATE) {
17295       if (a->pos == 4 && !strcasecmp(a->argv[3], "peer")) {
17296          cmplt = ast_cli_complete(a->word, choices, a->n);
17297          if (!cmplt)
17298             cmplt = complete_sip_peer(a->word, a->n - sizeof(choices), SIP_PAGE2_RTCACHEFRIENDS);
17299          return cmplt;
17300       }
17301       if (a->pos == 5 && !strcasecmp(a->argv[4], "like"))
17302          return complete_sip_peer(a->word, a->n, SIP_PAGE2_RTCACHEFRIENDS);
17303       return NULL;
17304    }
17305    switch (a->argc) {
17306    case 4:
17307       name = a->argv[3];
17308       /* we accept a name in position 3, but keywords are not good. */
17309       if (!strcasecmp(name, "peer") || !strcasecmp(name, "like"))
17310          return CLI_SHOWUSAGE;
17311       prunepeer = TRUE;
17312       if (!strcasecmp(name, "all")) {
17313          multi = TRUE;
17314          name = NULL;
17315       }
17316       /* else a single name, already set */
17317       break;
17318    case 5:
17319       /* sip prune realtime {peer|like} name */
17320       name = a->argv[4];
17321       if (!strcasecmp(a->argv[3], "peer"))
17322          prunepeer = TRUE;
17323       else if (!strcasecmp(a->argv[3], "like")) {
17324          prunepeer = TRUE;
17325          multi = TRUE;
17326       } else
17327          return CLI_SHOWUSAGE;
17328       if (!strcasecmp(name, "like"))
17329          return CLI_SHOWUSAGE;
17330       if (!multi && !strcasecmp(name, "all")) {
17331          multi = TRUE;
17332          name = NULL;
17333       }
17334       break;
17335    case 6:
17336       name = a->argv[5];
17337       multi = TRUE;
17338       /* sip prune realtime {peer} like name */
17339       if (strcasecmp(a->argv[4], "like"))
17340          return CLI_SHOWUSAGE;
17341       if (!strcasecmp(a->argv[3], "peer")) {
17342          prunepeer = TRUE;
17343       } else
17344          return CLI_SHOWUSAGE;
17345       break;
17346    default:
17347       return CLI_SHOWUSAGE;
17348    }
17349 
17350    if (multi && name) {
17351       if (regcomp(&regexbuf, name, REG_EXTENDED | REG_NOSUB)) {
17352          return CLI_SHOWUSAGE;
17353       }
17354       havepattern = 1;
17355    }
17356 
17357    if (multi) {
17358       if (prunepeer) {
17359          int pruned = 0;
17360          
17361          i = ao2_iterator_init(peers, 0);
17362          while ((pi = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
17363             ao2_lock(pi);
17364             if (name && regexec(&regexbuf, pi->name, 0, NULL, 0)) {
17365                ao2_unlock(pi);
17366                unref_peer(pi, "toss iterator peer ptr before continue");
17367                continue;
17368             };
17369             if (ast_test_flag(&pi->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
17370                pi->the_mark = 1;
17371                pruned++;
17372             }
17373             ao2_unlock(pi);
17374             unref_peer(pi, "toss iterator peer ptr");
17375          }
17376          ao2_iterator_destroy(&i);
17377          if (pruned) {
17378             unlink_marked_peers_from_tables();
17379             ast_cli(a->fd, "%d peers pruned.\n", pruned);
17380          } else
17381             ast_cli(a->fd, "No peers found to prune.\n");
17382       }
17383    } else {
17384       if (prunepeer) {
17385          struct sip_peer tmp;
17386          ast_copy_string(tmp.name, name, sizeof(tmp.name));
17387          if ((peer = ao2_t_find(peers, &tmp, OBJ_POINTER | OBJ_UNLINK, "finding to unlink from peers"))) {
17388             if (!ast_sockaddr_isnull(&peer->addr)) {
17389                ao2_t_unlink(peers_by_ip, peer, "unlinking peer from peers_by_ip also");
17390             }
17391             if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
17392                ast_cli(a->fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
17393                /* put it back! */
17394                ao2_t_link(peers, peer, "link peer into peer table");
17395                if (!ast_sockaddr_isnull(&peer->addr)) {
17396                   ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
17397                }
17398             } else
17399                ast_cli(a->fd, "Peer '%s' pruned.\n", name);
17400             unref_peer(peer, "sip_prune_realtime: unref_peer: tossing temp peer ptr");
17401          } else
17402             ast_cli(a->fd, "Peer '%s' not found.\n", name);
17403       }
17404    }
17405 
17406    if (havepattern) {
17407       regfree(&regexbuf);
17408    }
17409 
17410    return CLI_SUCCESS;
17411 }
17412 
17413 /*! \brief Print codec list from preference to CLI/manager */
17414 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
17415 {
17416    int x;
17417    format_t codec;
17418 
17419    for(x = 0; x < 64 ; x++) {
17420       codec = ast_codec_pref_index(pref, x);
17421       if (!codec)
17422          break;
17423       ast_cli(fd, "%s", ast_getformatname(codec));
17424       ast_cli(fd, ":%d", pref->framing[x]);
17425       if (x < 31 && ast_codec_pref_index(pref, x + 1))
17426          ast_cli(fd, ",");
17427    }
17428    if (!x)
17429       ast_cli(fd, "none");
17430 }
17431 
17432 /*! \brief Print domain mode to cli */
17433 static const char *domain_mode_to_text(const enum domain_mode mode)
17434 {
17435    switch (mode) {
17436    case SIP_DOMAIN_AUTO:
17437       return "[Automatic]";
17438    case SIP_DOMAIN_CONFIG:
17439       return "[Configured]";
17440    }
17441 
17442    return "";
17443 }
17444 
17445 /*! \brief CLI command to list local domains */
17446 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17447 {
17448    struct domain *d;
17449 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
17450 
17451    switch (cmd) {
17452    case CLI_INIT:
17453       e->command = "sip show domains";
17454       e->usage =
17455          "Usage: sip show domains\n"
17456          "       Lists all configured SIP local domains.\n"
17457          "       Asterisk only responds to SIP messages to local domains.\n";
17458       return NULL;
17459    case CLI_GENERATE:
17460       return NULL;
17461    }
17462 
17463    if (AST_LIST_EMPTY(&domain_list)) {
17464       ast_cli(a->fd, "SIP Domain support not enabled.\n\n");
17465       return CLI_SUCCESS;
17466    } else {
17467       ast_cli(a->fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
17468       AST_LIST_LOCK(&domain_list);
17469       AST_LIST_TRAVERSE(&domain_list, d, list)
17470          ast_cli(a->fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
17471             domain_mode_to_text(d->mode));
17472       AST_LIST_UNLOCK(&domain_list);
17473       ast_cli(a->fd, "\n");
17474       return CLI_SUCCESS;
17475    }
17476 }
17477 #undef FORMAT
17478 
17479 /*! \brief Show SIP peers in the manager API  */
17480 static int manager_sip_show_peer(struct mansession *s, const struct message *m)
17481 {
17482    const char *a[4];
17483    const char *peer;
17484 
17485    peer = astman_get_header(m, "Peer");
17486    if (ast_strlen_zero(peer)) {
17487       astman_send_error(s, m, "Peer: <name> missing.");
17488       return 0;
17489    }
17490    a[0] = "sip";
17491    a[1] = "show";
17492    a[2] = "peer";
17493    a[3] = peer;
17494 
17495    _sip_show_peer(1, -1, s, m, 4, a);
17496    astman_append(s, "\r\n" );
17497    return 0;
17498 }
17499 
17500 /*! \brief Show one peer in detail */
17501 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17502 {
17503    switch (cmd) {
17504    case CLI_INIT:
17505       e->command = "sip show peer";
17506       e->usage =
17507          "Usage: sip show peer <name> [load]\n"
17508          "       Shows all details on one SIP peer and the current status.\n"
17509          "       Option \"load\" forces lookup of peer in realtime storage.\n";
17510       return NULL;
17511    case CLI_GENERATE:
17512       return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
17513    }
17514    return _sip_show_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
17515 }
17516 
17517 /*! \brief Send qualify message to peer from cli or manager. Mostly for debugging. */
17518 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
17519 {
17520    struct sip_peer *peer;
17521    int load_realtime;
17522 
17523    if (argc < 4)
17524       return CLI_SHOWUSAGE;
17525 
17526    load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
17527    if ((peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0))) {
17528       sip_poke_peer(peer, 1);
17529       unref_peer(peer, "qualify: done with peer");
17530    } else if (type == 0) {
17531       ast_cli(fd, "Peer '%s' not found\n", argv[3]);
17532    } else {
17533       astman_send_error(s, m, "Peer not found");
17534    }
17535    return CLI_SUCCESS;
17536 }
17537 
17538 /*! \brief Qualify SIP peers in the manager API  */
17539 static int manager_sip_qualify_peer(struct mansession *s, const struct message *m)
17540 {
17541    const char *a[4];
17542    const char *peer;
17543 
17544    peer = astman_get_header(m, "Peer");
17545    if (ast_strlen_zero(peer)) {
17546       astman_send_error(s, m, "Peer: <name> missing.");
17547       return 0;
17548    }
17549    a[0] = "sip";
17550    a[1] = "qualify";
17551    a[2] = "peer";
17552    a[3] = peer;
17553 
17554    _sip_qualify_peer(1, -1, s, m, 4, a);
17555    astman_append(s, "\r\n\r\n" );
17556    return 0;
17557 }
17558 
17559 /*! \brief Send an OPTIONS packet to a SIP peer */
17560 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17561 {
17562    switch (cmd) {
17563    case CLI_INIT:
17564       e->command = "sip qualify peer";
17565       e->usage =
17566          "Usage: sip qualify peer <name> [load]\n"
17567          "       Requests a response from one SIP peer and the current status.\n"
17568          "       Option \"load\" forces lookup of peer in realtime storage.\n";
17569       return NULL;
17570    case CLI_GENERATE:
17571       return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
17572    }
17573    return _sip_qualify_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
17574 }
17575 
17576 /*! \brief list peer mailboxes to CLI */
17577 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer)
17578 {
17579    struct sip_mailbox *mailbox;
17580 
17581    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
17582       ast_str_append(mailbox_str, 0, "%s%s%s%s",
17583          mailbox->mailbox,
17584          ast_strlen_zero(mailbox->context) ? "" : "@",
17585          S_OR(mailbox->context, ""),
17586          AST_LIST_NEXT(mailbox, entry) ? "," : "");
17587    }
17588 }
17589 
17590 static struct _map_x_s faxecmodes[] = {
17591    { SIP_PAGE2_T38SUPPORT_UDPTL,       "None"},
17592    { SIP_PAGE2_T38SUPPORT_UDPTL_FEC,      "FEC"},
17593    { SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY,  "Redundancy"},
17594    { -1,                NULL},
17595 };
17596 
17597 static const char *faxec2str(int faxec)
17598 {
17599    return map_x_s(faxecmodes, faxec, "Unknown");
17600 }
17601 
17602 /*! \brief Show one peer in detail (main function) */
17603 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
17604 {
17605    char status[30] = "";
17606    char cbuf[256];
17607    struct sip_peer *peer;
17608    char codec_buf[512];
17609    struct ast_codec_pref *pref;
17610    struct ast_variable *v;
17611    int x = 0, load_realtime;
17612    format_t codec = 0;
17613    int realtimepeers;
17614 
17615    realtimepeers = ast_check_realtime("sippeers");
17616 
17617    if (argc < 4)
17618       return CLI_SHOWUSAGE;
17619 
17620    load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
17621    peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0);
17622 
17623    if (s) {    /* Manager */
17624       if (peer) {
17625          const char *id = astman_get_header(m, "ActionID");
17626 
17627          astman_append(s, "Response: Success\r\n");
17628          if (!ast_strlen_zero(id))
17629             astman_append(s, "ActionID: %s\r\n", id);
17630       } else {
17631          snprintf (cbuf, sizeof(cbuf), "Peer %s not found.", argv[3]);
17632          astman_send_error(s, m, cbuf);
17633          return CLI_SUCCESS;
17634       }
17635    }
17636    if (peer && type==0 ) { /* Normal listing */
17637       struct ast_str *mailbox_str = ast_str_alloca(512);
17638       struct sip_auth_container *credentials;
17639 
17640       ao2_lock(peer);
17641       credentials = peer->auth;
17642       if (credentials) {
17643          ao2_t_ref(credentials, +1, "Ref peer auth for show");
17644       }
17645       ao2_unlock(peer);
17646 
17647       ast_cli(fd, "\n\n");
17648       ast_cli(fd, "  * Name       : %s\n", peer->name);
17649       if (realtimepeers) { /* Realtime is enabled */
17650          ast_cli(fd, "  Realtime peer: %s\n", peer->is_realtime ? "Yes, cached" : "No");
17651       }
17652       ast_cli(fd, "  Secret       : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
17653       ast_cli(fd, "  MD5Secret    : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
17654       ast_cli(fd, "  Remote Secret: %s\n", ast_strlen_zero(peer->remotesecret)?"<Not set>":"<Set>");
17655       if (credentials) {
17656          struct sip_auth *auth;
17657 
17658          AST_LIST_TRAVERSE(&credentials->list, auth, node) {
17659             ast_cli(fd, "  Realm-auth   : Realm %-15.15s User %-10.20s %s\n",
17660                auth->realm,
17661                auth->username,
17662                !ast_strlen_zero(auth->secret)
17663                   ? "<Secret set>"
17664                   : (!ast_strlen_zero(auth->md5secret)
17665                      ? "<MD5secret set>" : "<Not set>"));
17666          }
17667          ao2_t_ref(credentials, -1, "Unref peer auth for show");
17668       }
17669       ast_cli(fd, "  Context      : %s\n", peer->context);
17670       ast_cli(fd, "  Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
17671       ast_cli(fd, "  Language     : %s\n", peer->language);
17672       if (!ast_strlen_zero(peer->accountcode))
17673          ast_cli(fd, "  Accountcode  : %s\n", peer->accountcode);
17674       ast_cli(fd, "  AMA flags    : %s\n", ast_cdr_flags2str(peer->amaflags));
17675       ast_cli(fd, "  Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
17676       ast_cli(fd, "  CallingPres  : %s\n", ast_describe_caller_presentation(peer->callingpres));
17677       if (!ast_strlen_zero(peer->fromuser))
17678          ast_cli(fd, "  FromUser     : %s\n", peer->fromuser);
17679       if (!ast_strlen_zero(peer->fromdomain))
17680          ast_cli(fd, "  FromDomain   : %s Port %d\n", peer->fromdomain, (peer->fromdomainport) ? peer->fromdomainport : STANDARD_SIP_PORT);
17681       ast_cli(fd, "  Callgroup    : ");
17682       print_group(fd, peer->callgroup, 0);
17683       ast_cli(fd, "  Pickupgroup  : ");
17684       print_group(fd, peer->pickupgroup, 0);
17685       peer_mailboxes_to_str(&mailbox_str, peer);
17686       ast_cli(fd, "  MOH Suggest  : %s\n", peer->mohsuggest);
17687       ast_cli(fd, "  Mailbox      : %s\n", mailbox_str->str);
17688       ast_cli(fd, "  VM Extension : %s\n", peer->vmexten);
17689       ast_cli(fd, "  LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
17690       ast_cli(fd, "  Call limit   : %d\n", peer->call_limit);
17691       ast_cli(fd, "  Max forwards : %d\n", peer->maxforwards);
17692       if (peer->busy_level)
17693          ast_cli(fd, "  Busy level   : %d\n", peer->busy_level);
17694       ast_cli(fd, "  Dynamic      : %s\n", AST_CLI_YESNO(peer->host_dynamic));
17695       ast_cli(fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
17696       ast_cli(fd, "  MaxCallBR    : %d kbps\n", peer->maxcallbitrate);
17697       ast_cli(fd, "  Expire       : %ld\n", ast_sched_when(sched, peer->expire));
17698       ast_cli(fd, "  Insecure     : %s\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
17699       ast_cli(fd, "  Force rport  : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT)));
17700       ast_cli(fd, "  ACL          : %s\n", AST_CLI_YESNO(peer->ha != NULL));
17701       ast_cli(fd, "  DirectMedACL : %s\n", AST_CLI_YESNO(peer->directmediaha != NULL));
17702       ast_cli(fd, "  T.38 support : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
17703       ast_cli(fd, "  T.38 EC mode : %s\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
17704       ast_cli(fd, "  T.38 MaxDtgrm: %d\n", peer->t38_maxdatagram);
17705       ast_cli(fd, "  DirectMedia  : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)));
17706       ast_cli(fd, "  PromiscRedir : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)));
17707       ast_cli(fd, "  User=Phone   : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)));
17708       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)));
17709       ast_cli(fd, "  Text Support : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)));
17710       ast_cli(fd, "  Ign SDP ver  : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_IGNORESDPVERSION)));
17711       ast_cli(fd, "  Trust RPID   : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_TRUSTRPID)));
17712       ast_cli(fd, "  Send RPID    : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[0], SIP_SENDRPID)));
17713       ast_cli(fd, "  Subscriptions: %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
17714       ast_cli(fd, "  Overlap dial : %s\n", allowoverlap2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP)));
17715       if (peer->outboundproxy)
17716          ast_cli(fd, "  Outb. proxy  : %s %s\n", ast_strlen_zero(peer->outboundproxy->name) ? "<not set>" : peer->outboundproxy->name,
17717                      peer->outboundproxy->force ? "(forced)" : "");
17718 
17719       /* - is enumerated */
17720       ast_cli(fd, "  DTMFmode     : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
17721       ast_cli(fd, "  Timer T1     : %d\n", peer->timer_t1);
17722       ast_cli(fd, "  Timer B      : %d\n", peer->timer_b);
17723       ast_cli(fd, "  ToHost       : %s\n", peer->tohost);
17724       ast_cli(fd, "  Addr->IP     : %s\n", ast_sockaddr_stringify(&peer->addr));
17725       ast_cli(fd, "  Defaddr->IP  : %s\n", ast_sockaddr_stringify(&peer->defaddr));
17726       ast_cli(fd, "  Prim.Transp. : %s\n", get_transport(peer->socket.type));
17727       ast_cli(fd, "  Allowed.Trsp : %s\n", get_transport_list(peer->transports));
17728       if (!ast_strlen_zero(sip_cfg.regcontext))
17729          ast_cli(fd, "  Reg. exten   : %s\n", peer->regexten);
17730       ast_cli(fd, "  Def. Username: %s\n", peer->username);
17731       ast_cli(fd, "  SIP Options  : ");
17732       if (peer->sipoptions) {
17733          int lastoption = -1;
17734          for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
17735             if (sip_options[x].id != lastoption) {
17736                if (peer->sipoptions & sip_options[x].id)
17737                   ast_cli(fd, "%s ", sip_options[x].text);
17738                lastoption = x;
17739             }
17740          }
17741       } else
17742          ast_cli(fd, "(none)");
17743 
17744       ast_cli(fd, "\n");
17745       ast_cli(fd, "  Codecs       : ");
17746       ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
17747       ast_cli(fd, "%s\n", codec_buf);
17748       ast_cli(fd, "  Codec Order  : (");
17749       print_codec_to_cli(fd, &peer->prefs);
17750       ast_cli(fd, ")\n");
17751 
17752       ast_cli(fd, "  Auto-Framing :  %s \n", AST_CLI_YESNO(peer->autoframing));
17753       ast_cli(fd, "  Status       : ");
17754       peer_status(peer, status, sizeof(status));
17755       ast_cli(fd, "%s\n", status);
17756       ast_cli(fd, "  Useragent    : %s\n", peer->useragent);
17757       ast_cli(fd, "  Reg. Contact : %s\n", peer->fullcontact);
17758       ast_cli(fd, "  Qualify Freq : %d ms\n", peer->qualifyfreq);
17759       if (peer->chanvars) {
17760          ast_cli(fd, "  Variables    :\n");
17761          for (v = peer->chanvars ; v ; v = v->next)
17762             ast_cli(fd, "                 %s = %s\n", v->name, v->value);
17763       }
17764 
17765       ast_cli(fd, "  Sess-Timers  : %s\n", stmode2str(peer->stimer.st_mode_oper));
17766       ast_cli(fd, "  Sess-Refresh : %s\n", strefresherparam2str(peer->stimer.st_ref));
17767       ast_cli(fd, "  Sess-Expires : %d secs\n", peer->stimer.st_max_se);
17768       ast_cli(fd, "  Min-Sess     : %d secs\n", peer->stimer.st_min_se);
17769       ast_cli(fd, "  RTP Engine   : %s\n", peer->engine);
17770       ast_cli(fd, "  Parkinglot   : %s\n", peer->parkinglot);
17771       ast_cli(fd, "  Use Reason   : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_Q850_REASON)));
17772       ast_cli(fd, "  Encryption   : %s\n", AST_CLI_YESNO(ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP)));
17773       ast_cli(fd, "\n");
17774       peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer ptr");
17775    } else  if (peer && type == 1) { /* manager listing */
17776       char buffer[256];
17777       struct ast_str *mailbox_str = ast_str_alloca(512);
17778       astman_append(s, "Channeltype: SIP\r\n");
17779       astman_append(s, "ObjectName: %s\r\n", peer->name);
17780       astman_append(s, "ChanObjectType: peer\r\n");
17781       astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
17782       astman_append(s, "RemoteSecretExist: %s\r\n", ast_strlen_zero(peer->remotesecret)?"N":"Y");
17783       astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
17784       astman_append(s, "Context: %s\r\n", peer->context);
17785       astman_append(s, "Language: %s\r\n", peer->language);
17786       if (!ast_strlen_zero(peer->accountcode))
17787          astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
17788       astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
17789       astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
17790       if (!ast_strlen_zero(peer->fromuser))
17791          astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
17792       if (!ast_strlen_zero(peer->fromdomain))
17793          astman_append(s, "SIP-FromDomain: %s\r\nSip-FromDomain-Port: %d\r\n", peer->fromdomain, (peer->fromdomainport) ? peer->fromdomainport : STANDARD_SIP_PORT);
17794       astman_append(s, "Callgroup: ");
17795       astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->callgroup));
17796       astman_append(s, "Pickupgroup: ");
17797       astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->pickupgroup));
17798       astman_append(s, "MOHSuggest: %s\r\n", peer->mohsuggest);
17799       peer_mailboxes_to_str(&mailbox_str, peer);
17800       astman_append(s, "VoiceMailbox: %s\r\n", mailbox_str->str);
17801       astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
17802       astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
17803       astman_append(s, "Maxforwards: %d\r\n", peer->maxforwards);
17804       astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
17805       astman_append(s, "Busy-level: %d\r\n", peer->busy_level);
17806       astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
17807       astman_append(s, "Dynamic: %s\r\n", peer->host_dynamic?"Y":"N");
17808       astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
17809       astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched, peer->expire));
17810       astman_append(s, "SIP-AuthInsecure: %s\r\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
17811       astman_append(s, "SIP-Forcerport: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT)?"Y":"N"));
17812       astman_append(s, "ACL: %s\r\n", (peer->ha?"Y":"N"));
17813       astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
17814       astman_append(s, "SIP-DirectMedia: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_DIRECT_MEDIA)?"Y":"N"));
17815       astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
17816       astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
17817       astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
17818       astman_append(s, "SIP-TextSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)?"Y":"N"));
17819       astman_append(s, "SIP-T.38Support: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)?"Y":"N"));
17820       astman_append(s, "SIP-T.38EC: %s\r\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
17821       astman_append(s, "SIP-T.38MaxDtgrm: %d\r\n", peer->t38_maxdatagram);
17822       astman_append(s, "SIP-Sess-Timers: %s\r\n", stmode2str(peer->stimer.st_mode_oper));
17823       astman_append(s, "SIP-Sess-Refresh: %s\r\n", strefresherparam2str(peer->stimer.st_ref));
17824       astman_append(s, "SIP-Sess-Expires: %d\r\n", peer->stimer.st_max_se);
17825       astman_append(s, "SIP-Sess-Min: %d\r\n", peer->stimer.st_min_se);
17826       astman_append(s, "SIP-RTP-Engine: %s\r\n", peer->engine);
17827       astman_append(s, "SIP-Encryption: %s\r\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP) ? "Y" : "N");
17828 
17829       /* - is enumerated */
17830       astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
17831       astman_append(s, "ToHost: %s\r\n", peer->tohost);
17832       astman_append(s, "Address-IP: %s\r\nAddress-Port: %d\r\n", ast_sockaddr_stringify_addr(&peer->addr), ast_sockaddr_port(&peer->addr));
17833       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));
17834       astman_append(s, "Default-Username: %s\r\n", peer->username);
17835       if (!ast_strlen_zero(sip_cfg.regcontext))
17836          astman_append(s, "RegExtension: %s\r\n", peer->regexten);
17837       astman_append(s, "Codecs: ");
17838       ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
17839       astman_append(s, "%s\r\n", codec_buf);
17840       astman_append(s, "CodecOrder: ");
17841       pref = &peer->prefs;
17842       for(x = 0; x < 64 ; x++) {
17843          codec = ast_codec_pref_index(pref, x);
17844          if (!codec)
17845             break;
17846          astman_append(s, "%s", ast_getformatname(codec));
17847          if (x < 63 && ast_codec_pref_index(pref, x+1))
17848             astman_append(s, ",");
17849       }
17850 
17851       astman_append(s, "\r\n");
17852       astman_append(s, "Status: ");
17853       peer_status(peer, status, sizeof(status));
17854       astman_append(s, "%s\r\n", status);
17855       astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
17856       astman_append(s, "Reg-Contact: %s\r\n", peer->fullcontact);
17857       astman_append(s, "QualifyFreq: %d ms\r\n", peer->qualifyfreq);
17858       astman_append(s, "Parkinglot: %s\r\n", peer->parkinglot);
17859       if (peer->chanvars) {
17860          for (v = peer->chanvars ; v ; v = v->next) {
17861             astman_append(s, "ChanVariable: %s=%s\r\n", v->name, v->value);
17862          }
17863       }
17864       astman_append(s, "SIP-Use-Reason-Header: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_Q850_REASON)) ? "Y" : "N");
17865 
17866       peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer");
17867 
17868    } else {
17869       ast_cli(fd, "Peer %s not found.\n", argv[3]);
17870       ast_cli(fd, "\n");
17871    }
17872 
17873    return CLI_SUCCESS;
17874 }
17875 
17876 /*! \brief Do completion on user name */
17877 static char *complete_sip_user(const char *word, int state)
17878 {
17879    char *result = NULL;
17880    int wordlen = strlen(word);
17881    int which = 0;
17882    struct ao2_iterator user_iter;
17883    struct sip_peer *user;
17884 
17885    user_iter = ao2_iterator_init(peers, 0);
17886    while ((user = ao2_t_iterator_next(&user_iter, "iterate thru peers table"))) {
17887       ao2_lock(user);
17888       if (!(user->type & SIP_TYPE_USER)) {
17889          ao2_unlock(user);
17890          unref_peer(user, "complete sip user");
17891          continue;
17892       }
17893       /* locking of the object is not required because only the name and flags are being compared */
17894       if (!strncasecmp(word, user->name, wordlen) && ++which > state) {
17895          result = ast_strdup(user->name);
17896       }
17897       ao2_unlock(user);
17898       unref_peer(user, "complete sip user");
17899       if (result) {
17900          break;
17901       }
17902    }
17903    ao2_iterator_destroy(&user_iter);
17904    return result;
17905 }
17906 /*! \brief Support routine for 'sip show user' CLI */
17907 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
17908 {
17909    if (pos == 3)
17910       return complete_sip_user(word, state);
17911 
17912    return NULL;
17913 }
17914 
17915 /*! \brief Show one user in detail */
17916 static char *sip_show_user(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17917 {
17918    char cbuf[256];
17919    struct sip_peer *user;
17920    struct ast_variable *v;
17921    int load_realtime;
17922 
17923    switch (cmd) {
17924    case CLI_INIT:
17925       e->command = "sip show user";
17926       e->usage =
17927          "Usage: sip show user <name> [load]\n"
17928          "       Shows all details on one SIP user and the current status.\n"
17929          "       Option \"load\" forces lookup of peer in realtime storage.\n";
17930       return NULL;
17931    case CLI_GENERATE:
17932       return complete_sip_show_user(a->line, a->word, a->pos, a->n);
17933    }
17934 
17935    if (a->argc < 4)
17936       return CLI_SHOWUSAGE;
17937 
17938    /* Load from realtime storage? */
17939    load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? TRUE : FALSE;
17940 
17941    if ((user = find_peer(a->argv[3], NULL, load_realtime, FINDUSERS, FALSE, 0))) {
17942       ao2_lock(user);
17943       ast_cli(a->fd, "\n\n");
17944       ast_cli(a->fd, "  * Name       : %s\n", user->name);
17945       ast_cli(a->fd, "  Secret       : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
17946       ast_cli(a->fd, "  MD5Secret    : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
17947       ast_cli(a->fd, "  Context      : %s\n", user->context);
17948       ast_cli(a->fd, "  Language     : %s\n", user->language);
17949       if (!ast_strlen_zero(user->accountcode))
17950          ast_cli(a->fd, "  Accountcode  : %s\n", user->accountcode);
17951       ast_cli(a->fd, "  AMA flags    : %s\n", ast_cdr_flags2str(user->amaflags));
17952       ast_cli(a->fd, "  Transfer mode: %s\n", transfermode2str(user->allowtransfer));
17953       ast_cli(a->fd, "  MaxCallBR    : %d kbps\n", user->maxcallbitrate);
17954       ast_cli(a->fd, "  CallingPres  : %s\n", ast_describe_caller_presentation(user->callingpres));
17955       ast_cli(a->fd, "  Call limit   : %d\n", user->call_limit);
17956       ast_cli(a->fd, "  Callgroup    : ");
17957       print_group(a->fd, user->callgroup, 0);
17958       ast_cli(a->fd, "  Pickupgroup  : ");
17959       print_group(a->fd, user->pickupgroup, 0);
17960       ast_cli(a->fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
17961       ast_cli(a->fd, "  ACL          : %s\n", AST_CLI_YESNO(user->ha != NULL));
17962       ast_cli(a->fd, "  Sess-Timers  : %s\n", stmode2str(user->stimer.st_mode_oper));
17963       ast_cli(a->fd, "  Sess-Refresh : %s\n", strefresherparam2str(user->stimer.st_ref));
17964       ast_cli(a->fd, "  Sess-Expires : %d secs\n", user->stimer.st_max_se);
17965       ast_cli(a->fd, "  Sess-Min-SE  : %d secs\n", user->stimer.st_min_se);
17966       ast_cli(a->fd, "  RTP Engine   : %s\n", user->engine);
17967 
17968       ast_cli(a->fd, "  Codec Order  : (");
17969       print_codec_to_cli(a->fd, &user->prefs);
17970       ast_cli(a->fd, ")\n");
17971 
17972       ast_cli(a->fd, "  Auto-Framing:  %s \n", AST_CLI_YESNO(user->autoframing));
17973       if (user->chanvars) {
17974          ast_cli(a->fd, "  Variables    :\n");
17975          for (v = user->chanvars ; v ; v = v->next)
17976             ast_cli(a->fd, "                 %s = %s\n", v->name, v->value);
17977       }
17978 
17979       ast_cli(a->fd, "\n");
17980 
17981       ao2_unlock(user);
17982       unref_peer(user, "sip show user");
17983    } else {
17984       ast_cli(a->fd, "User %s not found.\n", a->argv[3]);
17985       ast_cli(a->fd, "\n");
17986    }
17987 
17988    return CLI_SUCCESS;
17989 }
17990 
17991 
17992 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
17993 {
17994    struct ast_str *cbuf;
17995    struct ast_cb_names cbnames = {9, { "retrans_pkt",
17996                                         "__sip_autodestruct",
17997                                         "expire_register",
17998                                         "auto_congest",
17999                                         "sip_reg_timeout",
18000                                         "sip_poke_peer_s",
18001                                         "sip_poke_noanswer",
18002                                         "sip_reregister",
18003                                         "sip_reinvite_retry"},
18004                            { retrans_pkt,
18005                                      __sip_autodestruct,
18006                                      expire_register,
18007                                      auto_congest,
18008                                      sip_reg_timeout,
18009                                      sip_poke_peer_s,
18010                                      sip_poke_noanswer,
18011                                      sip_reregister,
18012                                      sip_reinvite_retry}};
18013    
18014    switch (cmd) {
18015    case CLI_INIT:
18016       e->command = "sip show sched";
18017       e->usage =
18018          "Usage: sip show sched\n"
18019          "       Shows stats on what's in the sched queue at the moment\n";
18020       return NULL;
18021    case CLI_GENERATE:
18022       return NULL;
18023    }
18024 
18025    cbuf = ast_str_alloca(2048);
18026 
18027    ast_cli(a->fd, "\n");
18028    ast_sched_report(sched, &cbuf, &cbnames);
18029    ast_cli(a->fd, "%s", cbuf->str);
18030 
18031    return CLI_SUCCESS;
18032 }
18033 
18034 /*! \brief  Show SIP Registry (registrations with other SIP proxies */
18035 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18036 {
18037 #define FORMAT2 "%-39.39s %-6.6s %-12.12s  %8.8s %-20.20s %-25.25s\n"
18038 #define FORMAT  "%-39.39s %-6.6s %-12.12s  %8d %-20.20s %-25.25s\n"
18039    char host[80];
18040    char user[80];
18041    char tmpdat[256];
18042    struct ast_tm tm;
18043    int counter = 0;
18044 
18045    switch (cmd) {
18046    case CLI_INIT:
18047       e->command = "sip show registry";
18048       e->usage =
18049          "Usage: sip show registry\n"
18050          "       Lists all registration requests and status.\n";
18051       return NULL;
18052    case CLI_GENERATE:
18053       return NULL;
18054    }
18055 
18056    if (a->argc != 3)
18057       return CLI_SHOWUSAGE;
18058    ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Refresh", "State", "Reg.Time");
18059    
18060    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
18061       ASTOBJ_RDLOCK(iterator);
18062       snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
18063       snprintf(user, sizeof(user), "%s", iterator->username);
18064       if (!ast_strlen_zero(iterator->regdomain)) {
18065          snprintf(tmpdat, sizeof(tmpdat), "%s", user);
18066          snprintf(user, sizeof(user), "%s@%s", tmpdat, iterator->regdomain);}
18067       if (iterator->regdomainport) {
18068          snprintf(tmpdat, sizeof(tmpdat), "%s", user);
18069          snprintf(user, sizeof(user), "%s:%d", tmpdat, iterator->regdomainport);}
18070       if (iterator->regtime.tv_sec) {
18071          ast_localtime(&iterator->regtime, &tm, NULL);
18072          ast_strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
18073       } else
18074          tmpdat[0] = '\0';
18075       ast_cli(a->fd, FORMAT, host, (iterator->dnsmgr) ? "Y" : "N", user, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
18076       ASTOBJ_UNLOCK(iterator);
18077       counter++;
18078    } while(0));
18079    ast_cli(a->fd, "%d SIP registrations.\n", counter);
18080    return CLI_SUCCESS;
18081 #undef FORMAT
18082 #undef FORMAT2
18083 }
18084 
18085 /*! \brief Unregister (force expiration) a SIP peer in the registry via CLI
18086    \note This function does not tell the SIP device what's going on,
18087    so use it with great care.
18088 */
18089 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18090 {
18091    struct sip_peer *peer;
18092    int load_realtime = 0;
18093 
18094    switch (cmd) {
18095    case CLI_INIT:
18096       e->command = "sip unregister";
18097       e->usage =
18098          "Usage: sip unregister <peer>\n"
18099          "       Unregister (force expiration) a SIP peer from the registry\n";
18100       return NULL;
18101    case CLI_GENERATE:
18102       return complete_sip_unregister(a->line, a->word, a->pos, a->n);
18103    }
18104    
18105    if (a->argc != 3)
18106       return CLI_SHOWUSAGE;
18107    
18108    if ((peer = find_peer(a->argv[2], NULL, load_realtime, FINDPEERS, TRUE, 0))) {
18109       if (peer->expire > 0) {
18110          AST_SCHED_DEL_UNREF(sched, peer->expire,
18111             unref_peer(peer, "remove register expire ref"));
18112          expire_register(ref_peer(peer, "ref for expire_register"));
18113          ast_cli(a->fd, "Unregistered peer \'%s\'\n\n", a->argv[2]);
18114       } else {
18115          ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
18116       }
18117       unref_peer(peer, "sip_unregister: unref_peer via sip_unregister: done with peer from find_peer call");
18118    } else {
18119       ast_cli(a->fd, "Peer unknown: \'%s\'. Not unregistered.\n", a->argv[2]);
18120    }
18121    
18122    return CLI_SUCCESS;
18123 }
18124 
18125 /*! \brief Callback for show_chanstats */
18126 static int show_chanstats_cb(void *__cur, void *__arg, int flags)
18127 {
18128 #define FORMAT2 "%-15.15s  %-11.11s  %-8.8s %-10.10s  %-10.10s (     %%) %-6.6s %-10.10s  %-10.10s (     %%) %-6.6s\n"
18129 #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"
18130    struct sip_pvt *cur = __cur;
18131    struct ast_rtp_instance_stats stats;
18132    char durbuf[10];
18133    int duration;
18134    int durh, durm, durs;
18135    struct ast_channel *c;
18136    struct __show_chan_arg *arg = __arg;
18137    int fd = arg->fd;
18138 
18139    sip_pvt_lock(cur);
18140    c = cur->owner;
18141 
18142    if (cur->subscribed != NONE) {
18143       /* Subscriptions */
18144       sip_pvt_unlock(cur);
18145       return 0;   /* don't care, we scan all channels */
18146    }
18147 
18148    if (!cur->rtp) {
18149       if (sipdebug) {
18150          ast_cli(fd, "%-15.15s  %-11.11s (inv state: %s) -- %s\n",
18151             ast_sockaddr_stringify_addr(&cur->sa), cur->callid,
18152             invitestate2string[cur->invitestate].desc,
18153             "-- No RTP active");
18154       }
18155       sip_pvt_unlock(cur);
18156       return 0;   /* don't care, we scan all channels */
18157    }
18158 
18159    if (ast_rtp_instance_get_stats(cur->rtp, &stats, AST_RTP_INSTANCE_STAT_ALL)) {
18160       sip_pvt_unlock(cur);
18161       ast_log(LOG_WARNING, "Could not get RTP stats.\n");
18162       return 0;
18163    }
18164 
18165    if (c && c->cdr && !ast_tvzero(c->cdr->start)) {
18166       duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
18167       durh = duration / 3600;
18168       durm = (duration % 3600) / 60;
18169       durs = duration % 60;
18170       snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
18171    } else {
18172       durbuf[0] = '\0';
18173    }
18174 
18175    ast_cli(fd, FORMAT,
18176       ast_sockaddr_stringify_addr(&cur->sa),
18177       cur->callid,
18178       durbuf,
18179       stats.rxcount > (unsigned int) 100000 ? (unsigned int) (stats.rxcount)/(unsigned int) 1000 : stats.rxcount,
18180       stats.rxcount > (unsigned int) 100000 ? "K":" ",
18181       stats.rxploss,
18182       (stats.rxcount + stats.rxploss) > 0 ? (double) stats.rxploss / (stats.rxcount + stats.rxploss) * 100 : 0,
18183       stats.rxjitter,
18184       stats.txcount > (unsigned int) 100000 ? (unsigned int) (stats.txcount)/(unsigned int) 1000 : stats.txcount,
18185       stats.txcount > (unsigned int) 100000 ? "K":" ",
18186       stats.txploss,
18187       stats.txcount > 0 ? (double) stats.txploss / stats.txcount * 100 : 0,
18188       stats.txjitter
18189    );
18190    arg->numchans++;
18191    sip_pvt_unlock(cur);
18192 
18193    return 0;   /* don't care, we scan all channels */
18194 }
18195 
18196 /*! \brief SIP show channelstats CLI (main function) */
18197 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18198 {
18199    struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
18200 
18201    switch (cmd) {
18202    case CLI_INIT:
18203       e->command = "sip show channelstats";
18204       e->usage =
18205          "Usage: sip show channelstats\n"
18206          "       Lists all currently active SIP channel's RTCP statistics.\n"
18207          "       Note that calls in the much optimized RTP P2P bridge mode will not show any packets here.";
18208       return NULL;
18209    case CLI_GENERATE:
18210       return NULL;
18211    }
18212 
18213    if (a->argc != 3)
18214       return CLI_SHOWUSAGE;
18215 
18216    ast_cli(a->fd, FORMAT2, "Peer", "Call ID", "Duration", "Recv: Pack", "Lost", "Jitter", "Send: Pack", "Lost", "Jitter");
18217    /* iterate on the container and invoke the callback on each item */
18218    ao2_t_callback(dialogs, OBJ_NODATA, show_chanstats_cb, &arg, "callback to sip show chanstats");
18219    ast_cli(a->fd, "%d active SIP channel%s\n", arg.numchans, (arg.numchans != 1) ? "s" : "");
18220    return CLI_SUCCESS;
18221 }
18222 #undef FORMAT
18223 #undef FORMAT2
18224 
18225 /*! \brief List global settings for the SIP channel */
18226 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18227 {
18228    int realtimepeers;
18229    int realtimeregs;
18230    char codec_buf[SIPBUFSIZE];
18231    const char *msg;  /* temporary msg pointer */
18232    struct sip_auth_container *credentials;
18233 
18234    switch (cmd) {
18235    case CLI_INIT:
18236       e->command = "sip show settings";
18237       e->usage =
18238          "Usage: sip show settings\n"
18239          "       Provides detailed list of the configuration of the SIP channel.\n";
18240       return NULL;
18241    case CLI_GENERATE:
18242       return NULL;
18243    }
18244 
18245    if (a->argc != 3)
18246       return CLI_SHOWUSAGE;
18247 
18248    realtimepeers = ast_check_realtime("sippeers");
18249    realtimeregs = ast_check_realtime("sipregs");
18250 
18251    ast_mutex_lock(&authl_lock);
18252    credentials = authl;
18253    if (credentials) {
18254       ao2_t_ref(credentials, +1, "Ref global auth for show");
18255    }
18256    ast_mutex_unlock(&authl_lock);
18257 
18258    ast_cli(a->fd, "\n\nGlobal Settings:\n");
18259    ast_cli(a->fd, "----------------\n");
18260    ast_cli(a->fd, "  UDP Bindaddress:        %s\n", ast_sockaddr_stringify(&bindaddr));
18261    if (ast_sockaddr_is_ipv6(&bindaddr) && ast_sockaddr_is_any(&bindaddr)) {
18262       ast_cli(a->fd, "  ** Additional Info:\n");
18263       ast_cli(a->fd, "     [::] may include IPv4 in addition to IPv6, if such a feature is enabled in the OS.\n");
18264    }
18265    ast_cli(a->fd, "  TCP SIP Bindaddress:    %s\n",
18266       sip_cfg.tcp_enabled != FALSE ?
18267             ast_sockaddr_stringify(&sip_tcp_desc.local_address) :
18268             "Disabled");
18269    ast_cli(a->fd, "  TLS SIP Bindaddress:    %s\n",
18270       default_tls_cfg.enabled != FALSE ?
18271             ast_sockaddr_stringify(&sip_tls_desc.local_address) :
18272             "Disabled");
18273    ast_cli(a->fd, "  Videosupport:           %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT)));
18274    ast_cli(a->fd, "  Textsupport:            %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT)));
18275    ast_cli(a->fd, "  Ignore SDP sess. ver.:  %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION)));
18276    ast_cli(a->fd, "  AutoCreate Peer:        %s\n", AST_CLI_YESNO(sip_cfg.autocreatepeer));
18277    ast_cli(a->fd, "  Match Auth Username:    %s\n", AST_CLI_YESNO(global_match_auth_username));
18278    ast_cli(a->fd, "  Allow unknown access:   %s\n", AST_CLI_YESNO(sip_cfg.allowguest));
18279    ast_cli(a->fd, "  Allow subscriptions:    %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
18280    ast_cli(a->fd, "  Allow overlap dialing:  %s\n", allowoverlap2str(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)));
18281    ast_cli(a->fd, "  Allow promisc. redir:   %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_PROMISCREDIR)));
18282    ast_cli(a->fd, "  Enable call counters:   %s\n", AST_CLI_YESNO(global_callcounter));
18283    ast_cli(a->fd, "  SIP domain support:     %s\n", AST_CLI_YESNO(!AST_LIST_EMPTY(&domain_list)));
18284    ast_cli(a->fd, "  Realm. auth:            %s\n", AST_CLI_YESNO(credentials != NULL));
18285    if (credentials) {
18286       struct sip_auth *auth;
18287 
18288       AST_LIST_TRAVERSE(&credentials->list, auth, node) {
18289          ast_cli(a->fd, "  Realm. auth entry:      Realm %-15.15s User %-10.20s %s\n",
18290             auth->realm,
18291             auth->username,
18292             !ast_strlen_zero(auth->secret)
18293                ? "<Secret set>"
18294                : (!ast_strlen_zero(auth->md5secret)
18295                   ? "<MD5secret set>" : "<Not set>"));
18296       }
18297       ao2_t_ref(credentials, -1, "Unref global auth for show");
18298    }
18299    ast_cli(a->fd, "  Our auth realm          %s\n", sip_cfg.realm);
18300    ast_cli(a->fd, "  Use domains as realms:  %s\n", AST_CLI_YESNO(sip_cfg.domainsasrealm));
18301    ast_cli(a->fd, "  Call to non-local dom.: %s\n", AST_CLI_YESNO(sip_cfg.allow_external_domains));
18302    ast_cli(a->fd, "  URI user is phone no:   %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_USEREQPHONE)));
18303    ast_cli(a->fd, "  Always auth rejects:    %s\n", AST_CLI_YESNO(sip_cfg.alwaysauthreject));
18304    ast_cli(a->fd, "  Direct RTP setup:       %s\n", AST_CLI_YESNO(sip_cfg.directrtpsetup));
18305    ast_cli(a->fd, "  User Agent:             %s\n", global_useragent);
18306    ast_cli(a->fd, "  SDP Session Name:       %s\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
18307    ast_cli(a->fd, "  SDP Owner Name:         %s\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner);
18308    ast_cli(a->fd, "  Reg. context:           %s\n", S_OR(sip_cfg.regcontext, "(not set)"));
18309    ast_cli(a->fd, "  Regexten on Qualify:    %s\n", AST_CLI_YESNO(sip_cfg.regextenonqualify));
18310    ast_cli(a->fd, "  Legacy userfield parse: %s\n", AST_CLI_YESNO(sip_cfg.legacy_useroption_parsing));
18311    ast_cli(a->fd, "  Caller ID:              %s\n", default_callerid);
18312    if ((default_fromdomainport) && (default_fromdomainport != STANDARD_SIP_PORT)) {
18313       ast_cli(a->fd, "  From: Domain:           %s:%d\n", default_fromdomain, default_fromdomainport);
18314    } else {
18315       ast_cli(a->fd, "  From: Domain:           %s\n", default_fromdomain);
18316    }
18317    ast_cli(a->fd, "  Record SIP history:     %s\n", AST_CLI_ONOFF(recordhistory));
18318    ast_cli(a->fd, "  Call Events:            %s\n", AST_CLI_ONOFF(sip_cfg.callevents));
18319    ast_cli(a->fd, "  Auth. Failure Events:   %s\n", AST_CLI_ONOFF(global_authfailureevents));
18320 
18321    ast_cli(a->fd, "  T.38 support:           %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
18322    ast_cli(a->fd, "  T.38 EC mode:           %s\n", faxec2str(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
18323    ast_cli(a->fd, "  T.38 MaxDtgrm:          %d\n", global_t38_maxdatagram);
18324    if (!realtimepeers && !realtimeregs)
18325       ast_cli(a->fd, "  SIP realtime:           Disabled\n" );
18326    else
18327       ast_cli(a->fd, "  SIP realtime:           Enabled\n" );
18328    ast_cli(a->fd, "  Qualify Freq :          %d ms\n", global_qualifyfreq);
18329    ast_cli(a->fd, "  Q.850 Reason header:    %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_Q850_REASON)));
18330    ast_cli(a->fd, "  Store SIP_CAUSE:        %s\n", AST_CLI_YESNO(global_store_sip_cause));
18331    ast_cli(a->fd, "\nNetwork QoS Settings:\n");
18332    ast_cli(a->fd, "---------------------------\n");
18333    ast_cli(a->fd, "  IP ToS SIP:             %s\n", ast_tos2str(global_tos_sip));
18334    ast_cli(a->fd, "  IP ToS RTP audio:       %s\n", ast_tos2str(global_tos_audio));
18335    ast_cli(a->fd, "  IP ToS RTP video:       %s\n", ast_tos2str(global_tos_video));
18336    ast_cli(a->fd, "  IP ToS RTP text:        %s\n", ast_tos2str(global_tos_text));
18337    ast_cli(a->fd, "  802.1p CoS SIP:         %d\n", global_cos_sip);
18338    ast_cli(a->fd, "  802.1p CoS RTP audio:   %d\n", global_cos_audio);
18339    ast_cli(a->fd, "  802.1p CoS RTP video:   %d\n", global_cos_video);
18340    ast_cli(a->fd, "  802.1p CoS RTP text:    %d\n", global_cos_text);
18341    ast_cli(a->fd, "  Jitterbuffer enabled:   %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_ENABLED)));
18342    if (ast_test_flag(&global_jbconf, AST_JB_ENABLED)) {
18343       ast_cli(a->fd, "  Jitterbuffer forced:    %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_FORCED)));
18344       ast_cli(a->fd, "  Jitterbuffer max size:  %ld\n", global_jbconf.max_size);
18345       ast_cli(a->fd, "  Jitterbuffer resync:    %ld\n", global_jbconf.resync_threshold);
18346       ast_cli(a->fd, "  Jitterbuffer impl:      %s\n", global_jbconf.impl);
18347       if (!strcasecmp(global_jbconf.impl, "adaptive")) {
18348          ast_cli(a->fd, "  Jitterbuffer tgt extra: %ld\n", global_jbconf.target_extra);
18349       }
18350       ast_cli(a->fd, "  Jitterbuffer log:       %s\n", AST_CLI_YESNO(ast_test_flag(&global_jbconf, AST_JB_LOG)));
18351    }
18352 
18353    ast_cli(a->fd, "\nNetwork Settings:\n");
18354    ast_cli(a->fd, "---------------------------\n");
18355    /* determine if/how SIP address can be remapped */
18356    if (localaddr == NULL)
18357       msg = "Disabled, no localnet list";
18358    else if (ast_sockaddr_isnull(&externaddr))
18359       msg = "Disabled";
18360    else if (!ast_strlen_zero(externhost))
18361       msg = "Enabled using externhost";
18362    else
18363       msg = "Enabled using externaddr";
18364    ast_cli(a->fd, "  SIP address remapping:  %s\n", msg);
18365    ast_cli(a->fd, "  Externhost:             %s\n", S_OR(externhost, "<none>"));
18366    ast_cli(a->fd, "  Externaddr:             %s\n", ast_sockaddr_stringify(&externaddr));
18367    ast_cli(a->fd, "  Externrefresh:          %d\n", externrefresh);
18368    {
18369       struct ast_ha *d;
18370       const char *prefix = "Localnet:";
18371 
18372       for (d = localaddr; d ; prefix = "", d = d->next) {
18373          const char *addr = ast_strdupa(ast_sockaddr_stringify_addr(&d->addr));
18374          const char *mask = ast_strdupa(ast_sockaddr_stringify_addr(&d->netmask));
18375          ast_cli(a->fd, "  %-24s%s/%s\n", prefix, addr, mask);
18376       }
18377    }
18378    ast_cli(a->fd, "\nGlobal Signalling Settings:\n");
18379    ast_cli(a->fd, "---------------------------\n");
18380    ast_cli(a->fd, "  Codecs:                 ");
18381    ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, sip_cfg.capability);
18382    ast_cli(a->fd, "%s\n", codec_buf);
18383    ast_cli(a->fd, "  Codec Order:            ");
18384    print_codec_to_cli(a->fd, &default_prefs);
18385    ast_cli(a->fd, "\n");
18386    ast_cli(a->fd, "  Relax DTMF:             %s\n", AST_CLI_YESNO(global_relaxdtmf));
18387    ast_cli(a->fd, "  RFC2833 Compensation:   %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE)));
18388    ast_cli(a->fd, "  Symmetric RTP:          %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_SYMMETRICRTP)));
18389    ast_cli(a->fd, "  Compact SIP headers:    %s\n", AST_CLI_YESNO(sip_cfg.compactheaders));
18390    ast_cli(a->fd, "  RTP Keepalive:          %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
18391    ast_cli(a->fd, "  RTP Timeout:            %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
18392    ast_cli(a->fd, "  RTP Hold Timeout:       %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
18393    ast_cli(a->fd, "  MWI NOTIFY mime type:   %s\n", default_notifymime);
18394    ast_cli(a->fd, "  DNS SRV lookup:         %s\n", AST_CLI_YESNO(sip_cfg.srvlookup));
18395    ast_cli(a->fd, "  Pedantic SIP support:   %s\n", AST_CLI_YESNO(sip_cfg.pedanticsipchecking));
18396    ast_cli(a->fd, "  Reg. min duration       %d secs\n", min_expiry);
18397    ast_cli(a->fd, "  Reg. max duration:      %d secs\n", max_expiry);
18398    ast_cli(a->fd, "  Reg. default duration:  %d secs\n", default_expiry);
18399    ast_cli(a->fd, "  Outbound reg. timeout:  %d secs\n", global_reg_timeout);
18400    ast_cli(a->fd, "  Outbound reg. attempts: %d\n", global_regattempts_max);
18401    ast_cli(a->fd, "  Notify ringing state:   %s\n", AST_CLI_YESNO(sip_cfg.notifyringing));
18402    if (sip_cfg.notifyringing) {
18403       ast_cli(a->fd, "    Include CID:          %s%s\n",
18404             AST_CLI_YESNO(sip_cfg.notifycid),
18405             sip_cfg.notifycid == IGNORE_CONTEXT ? " (Ignoring context)" : "");
18406    }
18407    ast_cli(a->fd, "  Notify hold state:      %s\n", AST_CLI_YESNO(sip_cfg.notifyhold));
18408    ast_cli(a->fd, "  SIP Transfer mode:      %s\n", transfermode2str(sip_cfg.allowtransfer));
18409    ast_cli(a->fd, "  Max Call Bitrate:       %d kbps\n", default_maxcallbitrate);
18410    ast_cli(a->fd, "  Auto-Framing:           %s\n", AST_CLI_YESNO(global_autoframing));
18411    ast_cli(a->fd, "  Outb. proxy:            %s %s\n", ast_strlen_zero(sip_cfg.outboundproxy.name) ? "<not set>" : sip_cfg.outboundproxy.name,
18412                      sip_cfg.outboundproxy.force ? "(forced)" : "");
18413    ast_cli(a->fd, "  Session Timers:         %s\n", stmode2str(global_st_mode));
18414    ast_cli(a->fd, "  Session Refresher:      %s\n", strefresherparam2str(global_st_refresher));
18415    ast_cli(a->fd, "  Session Expires:        %d secs\n", global_max_se);
18416    ast_cli(a->fd, "  Session Min-SE:         %d secs\n", global_min_se);
18417    ast_cli(a->fd, "  Timer T1:               %d\n", global_t1);
18418    ast_cli(a->fd, "  Timer T1 minimum:       %d\n", global_t1min);
18419    ast_cli(a->fd, "  Timer B:                %d\n", global_timer_b);
18420    ast_cli(a->fd, "  No premature media:     %s\n", AST_CLI_YESNO(global_prematuremediafilter));
18421    ast_cli(a->fd, "  Max forwards:           %d\n", sip_cfg.default_max_forwards);
18422 
18423    ast_cli(a->fd, "\nDefault Settings:\n");
18424    ast_cli(a->fd, "-----------------\n");
18425    ast_cli(a->fd, "  Allowed transports:     %s\n", get_transport_list(default_transports));
18426    ast_cli(a->fd, "  Outbound transport:    %s\n", get_transport(default_primary_transport));
18427    ast_cli(a->fd, "  Context:                %s\n", sip_cfg.default_context);
18428    ast_cli(a->fd, "  Force rport:            %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_NAT_FORCE_RPORT)));
18429    ast_cli(a->fd, "  DTMF:                   %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
18430    ast_cli(a->fd, "  Qualify:                %d\n", default_qualify);
18431    ast_cli(a->fd, "  Use ClientCode:         %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[0], SIP_USECLIENTCODE)));
18432    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)));
18433    ast_cli(a->fd, "  Language:               %s\n", default_language);
18434    ast_cli(a->fd, "  MOH Interpret:          %s\n", default_mohinterpret);
18435    ast_cli(a->fd, "  MOH Suggest:            %s\n", default_mohsuggest);
18436    ast_cli(a->fd, "  Voice Mail Extension:   %s\n", default_vmexten);
18437 
18438    
18439    if (realtimepeers || realtimeregs) {
18440       ast_cli(a->fd, "\nRealtime SIP Settings:\n");
18441       ast_cli(a->fd, "----------------------\n");
18442       ast_cli(a->fd, "  Realtime Peers:         %s\n", AST_CLI_YESNO(realtimepeers));
18443       ast_cli(a->fd, "  Realtime Regs:          %s\n", AST_CLI_YESNO(realtimeregs));
18444       ast_cli(a->fd, "  Cache Friends:          %s\n", AST_CLI_YESNO(ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)));
18445       ast_cli(a->fd, "  Update:                 %s\n", AST_CLI_YESNO(sip_cfg.peer_rtupdate));
18446       ast_cli(a->fd, "  Ignore Reg. Expire:     %s\n", AST_CLI_YESNO(sip_cfg.ignore_regexpire));
18447       ast_cli(a->fd, "  Save sys. name:         %s\n", AST_CLI_YESNO(sip_cfg.rtsave_sysname));
18448       ast_cli(a->fd, "  Auto Clear:             %d (%s)\n", sip_cfg.rtautoclear, ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR) ? "Enabled" : "Disabled");
18449    }
18450    ast_cli(a->fd, "\n----\n");
18451    return CLI_SUCCESS;
18452 }
18453 
18454 static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18455 {
18456 #define FORMAT  "%-30.30s  %-12.12s  %-10.10s  %-10.10s\n"
18457    char host[80];
18458    
18459    switch (cmd) {
18460    case CLI_INIT:
18461       e->command = "sip show mwi";
18462       e->usage =
18463          "Usage: sip show mwi\n"
18464          "       Provides a list of MWI subscriptions and status.\n";
18465       return NULL;
18466    case CLI_GENERATE:
18467       return NULL;
18468    }
18469    
18470    ast_cli(a->fd, FORMAT, "Host", "Username", "Mailbox", "Subscribed");
18471    
18472    ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
18473       ASTOBJ_RDLOCK(iterator);
18474       snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
18475       ast_cli(a->fd, FORMAT, host, iterator->username, iterator->mailbox, AST_CLI_YESNO(iterator->subscribed));
18476       ASTOBJ_UNLOCK(iterator);
18477    } while(0));
18478 
18479    return CLI_SUCCESS;
18480 #undef FORMAT
18481 }
18482 
18483 
18484 /*! \brief Show subscription type in string format */
18485 static const char *subscription_type2str(enum subscriptiontype subtype)
18486 {
18487    int i;
18488 
18489    for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
18490       if (subscription_types[i].type == subtype) {
18491          return subscription_types[i].text;
18492       }
18493    }
18494    return subscription_types[0].text;
18495 }
18496 
18497 /*! \brief Find subscription type in array */
18498 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
18499 {
18500    int i;
18501 
18502    for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
18503       if (subscription_types[i].type == subtype) {
18504          return &subscription_types[i];
18505       }
18506    }
18507    return &subscription_types[0];
18508 }
18509 
18510 /*
18511  * We try to structure all functions that loop on data structures as
18512  * a handler for individual entries, and a mainloop that iterates
18513  * on the main data structure. This way, moving the code to containers
18514  * that support iteration through callbacks will be a lot easier.
18515  */
18516 
18517 #define FORMAT4 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-13.13s  %-15.15s %-10.10s %-6.6d\n"
18518 #define FORMAT3 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-13.13s  %-15.15s %-10.10s %-6.6s\n"
18519 #define FORMAT2 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-7.7s  %-15.15s %-10.10s %-10.10s\n"
18520 #define FORMAT  "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-3.3s %-3.3s  %-15.15s %-10.10s %-10.10s\n"
18521 
18522 /*! \brief callback for show channel|subscription */
18523 static int show_channels_cb(void *__cur, void *__arg, int flags)
18524 {
18525    struct sip_pvt *cur = __cur;
18526    struct __show_chan_arg *arg = __arg;
18527    const struct ast_sockaddr *dst;
18528 
18529    sip_pvt_lock(cur);
18530    dst = sip_real_dst(cur);
18531 
18532    /* XXX indentation preserved to reduce diff. Will be fixed later */
18533    if (cur->subscribed == NONE && !arg->subscriptions) {
18534       /* set if SIP transfer in progress */
18535       const char *referstatus = cur->refer ? referstatus2str(cur->refer->status) : "";
18536       char formatbuf[SIPBUFSIZE/2];
18537       
18538       ast_cli(arg->fd, FORMAT, ast_sockaddr_stringify_addr(dst),
18539             S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
18540             cur->callid,
18541             ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0),
18542             AST_CLI_YESNO(ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD)),
18543             cur->needdestroy ? "(d)" : "",
18544             cur->lastmsg ,
18545             referstatus,
18546             cur->relatedpeer ? cur->relatedpeer->name : "<guest>"
18547          );
18548       arg->numchans++;
18549    }
18550    if (cur->subscribed != NONE && arg->subscriptions) {
18551       struct ast_str *mailbox_str = ast_str_alloca(512);
18552       if (cur->subscribed == MWI_NOTIFICATION && cur->relatedpeer)
18553          peer_mailboxes_to_str(&mailbox_str, cur->relatedpeer);
18554       ast_cli(arg->fd, FORMAT4, ast_sockaddr_stringify_addr(dst),
18555             S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
18556                cur->callid,
18557             /* the 'complete' exten/context is hidden in the refer_to field for subscriptions */
18558             cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
18559             cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate),
18560             subscription_type2str(cur->subscribed),
18561             cur->subscribed == MWI_NOTIFICATION ? S_OR(mailbox_str->str, "<none>") : "<none>",
18562             cur->expiry
18563          );
18564       arg->numchans++;
18565    }
18566    sip_pvt_unlock(cur);
18567    return 0;   /* don't care, we scan all channels */
18568 }
18569 
18570 /*! \brief CLI for show channels or subscriptions.
18571  * This is a new-style CLI handler so a single function contains
18572  * the prototype for the function, the 'generator' to produce multiple
18573  * entries in case it is required, and the actual handler for the command.
18574  */
18575 static char *sip_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18576 {
18577    struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
18578 
18579 
18580    if (cmd == CLI_INIT) {
18581       e->command = "sip show {channels|subscriptions}";
18582       e->usage =
18583          "Usage: sip show channels\n"
18584          "       Lists all currently active SIP calls (dialogs).\n"
18585          "Usage: sip show subscriptions\n"
18586          "       Lists active SIP subscriptions.\n";
18587       return NULL;
18588    } else if (cmd == CLI_GENERATE)
18589       return NULL;
18590 
18591    if (a->argc != e->args)
18592       return CLI_SHOWUSAGE;
18593    arg.subscriptions = !strcasecmp(a->argv[e->args - 1], "subscriptions");
18594    if (!arg.subscriptions)
18595       ast_cli(arg.fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Format", "Hold", "Last Message", "Expiry", "Peer");
18596    else
18597       ast_cli(arg.fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox", "Expiry");
18598 
18599    /* iterate on the container and invoke the callback on each item */
18600    ao2_t_callback(dialogs, OBJ_NODATA, show_channels_cb, &arg, "callback to show channels");
18601    
18602    /* print summary information */
18603    ast_cli(arg.fd, "%d active SIP %s%s\n", arg.numchans,
18604       (arg.subscriptions ? "subscription" : "dialog"),
18605       ESS(arg.numchans));  /* ESS(n) returns an "s" if n>1 */
18606    return CLI_SUCCESS;
18607 #undef FORMAT
18608 #undef FORMAT2
18609 #undef FORMAT3
18610 }
18611 
18612 /*! \brief Support routine for 'sip show channel' and 'sip show history' CLI
18613  * This is in charge of generating all strings that match a prefix in the
18614  * given position. As many functions of this kind, each invokation has
18615  * O(state) time complexity so be careful in using it.
18616  */
18617 static char *complete_sipch(const char *line, const char *word, int pos, int state)
18618 {
18619    int which=0;
18620    struct sip_pvt *cur;
18621    char *c = NULL;
18622    int wordlen = strlen(word);
18623    struct ao2_iterator i;
18624 
18625    if (pos != 3) {
18626       return NULL;
18627    }
18628 
18629    i = ao2_iterator_init(dialogs, 0);
18630    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
18631       sip_pvt_lock(cur);
18632       if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
18633          c = ast_strdup(cur->callid);
18634          sip_pvt_unlock(cur);
18635          dialog_unref(cur, "drop ref in iterator loop break");
18636          break;
18637       }
18638       sip_pvt_unlock(cur);
18639       dialog_unref(cur, "drop ref in iterator loop");
18640    }
18641    ao2_iterator_destroy(&i);
18642    return c;
18643 }
18644 
18645 
18646 /*! \brief Do completion on peer name */
18647 static char *complete_sip_peer(const char *word, int state, int flags2)
18648 {
18649    char *result = NULL;
18650    int wordlen = strlen(word);
18651    int which = 0;
18652    struct ao2_iterator i = ao2_iterator_init(peers, 0);
18653    struct sip_peer *peer;
18654 
18655    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
18656       /* locking of the object is not required because only the name and flags are being compared */
18657       if (!strncasecmp(word, peer->name, wordlen) &&
18658             (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
18659             ++which > state)
18660          result = ast_strdup(peer->name);
18661       unref_peer(peer, "toss iterator peer ptr before break");
18662       if (result) {
18663          break;
18664       }
18665    }
18666    ao2_iterator_destroy(&i);
18667    return result;
18668 }
18669 
18670 /*! \brief Do completion on registered peer name */
18671 static char *complete_sip_registered_peer(const char *word, int state, int flags2)
18672 {
18673        char *result = NULL;
18674        int wordlen = strlen(word);
18675        int which = 0;
18676        struct ao2_iterator i;
18677        struct sip_peer *peer;
18678        
18679        i = ao2_iterator_init(peers, 0);
18680        while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
18681           if (!strncasecmp(word, peer->name, wordlen) &&
18682          (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
18683          ++which > state && peer->expire > 0)
18684              result = ast_strdup(peer->name);
18685           if (result) {
18686              unref_peer(peer, "toss iterator peer ptr before break");
18687              break;
18688           }
18689           unref_peer(peer, "toss iterator peer ptr");
18690        }
18691        ao2_iterator_destroy(&i);
18692        return result;
18693 }
18694 
18695 /*! \brief Support routine for 'sip show history' CLI */
18696 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state)
18697 {
18698    if (pos == 3)
18699       return complete_sipch(line, word, pos, state);
18700 
18701    return NULL;
18702 }
18703 
18704 /*! \brief Support routine for 'sip show peer' CLI */
18705 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
18706 {
18707    if (pos == 3) {
18708       return complete_sip_peer(word, state, 0);
18709    }
18710 
18711    return NULL;
18712 }
18713 
18714 /*! \brief Support routine for 'sip unregister' CLI */
18715 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state)
18716 {
18717        if (pos == 2)
18718                return complete_sip_registered_peer(word, state, 0);
18719 
18720        return NULL;
18721 }
18722 
18723 /*! \brief Support routine for 'sip notify' CLI */
18724 static char *complete_sipnotify(const char *line, const char *word, int pos, int state)
18725 {
18726    char *c = NULL;
18727 
18728    if (pos == 2) {
18729       int which = 0;
18730       char *cat = NULL;
18731       int wordlen = strlen(word);
18732 
18733       /* do completion for notify type */
18734 
18735       if (!notify_types)
18736          return NULL;
18737       
18738       while ( (cat = ast_category_browse(notify_types, cat)) ) {
18739          if (!strncasecmp(word, cat, wordlen) && ++which > state) {
18740             c = ast_strdup(cat);
18741             break;
18742          }
18743       }
18744       return c;
18745    }
18746 
18747    if (pos > 2)
18748       return complete_sip_peer(word, state, 0);
18749 
18750    return NULL;
18751 }
18752 
18753 /*! \brief Show details of one active dialog */
18754 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18755 {
18756    struct sip_pvt *cur;
18757    size_t len;
18758    int found = 0;
18759    struct ao2_iterator i;
18760 
18761    switch (cmd) {
18762    case CLI_INIT:
18763       e->command = "sip show channel";
18764       e->usage =
18765          "Usage: sip show channel <call-id>\n"
18766          "       Provides detailed status on a given SIP dialog (identified by SIP call-id).\n";
18767       return NULL;
18768    case CLI_GENERATE:
18769       return complete_sipch(a->line, a->word, a->pos, a->n);
18770    }
18771 
18772    if (a->argc != 4)
18773       return CLI_SHOWUSAGE;
18774    len = strlen(a->argv[3]);
18775    
18776    i = ao2_iterator_init(dialogs, 0);
18777    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
18778       sip_pvt_lock(cur);
18779 
18780       if (!strncasecmp(cur->callid, a->argv[3], len)) {
18781          char formatbuf[SIPBUFSIZE/2];
18782          ast_cli(a->fd, "\n");
18783          if (cur->subscribed != NONE)
18784             ast_cli(a->fd, "  * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
18785          else
18786             ast_cli(a->fd, "  * SIP Call\n");
18787          ast_cli(a->fd, "  Curr. trans. direction:  %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
18788          ast_cli(a->fd, "  Call-ID:                %s\n", cur->callid);
18789          ast_cli(a->fd, "  Owner channel ID:       %s\n", cur->owner ? cur->owner->name : "<none>");
18790          ast_cli(a->fd, "  Our Codec Capability:   %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->capability));
18791          ast_cli(a->fd, "  Non-Codec Capability (DTMF):   %d\n", cur->noncodeccapability);
18792          ast_cli(a->fd, "  Their Codec Capability:   %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->peercapability));
18793          ast_cli(a->fd, "  Joint Codec Capability:   %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->jointcapability));
18794          ast_cli(a->fd, "  Format:                 %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0) );
18795          ast_cli(a->fd, "  T.38 support            %s\n", AST_CLI_YESNO(cur->udptl != NULL));
18796          ast_cli(a->fd, "  Video support           %s\n", AST_CLI_YESNO(cur->vrtp != NULL));
18797          ast_cli(a->fd, "  MaxCallBR:              %d kbps\n", cur->maxcallbitrate);
18798          ast_cli(a->fd, "  Theoretical Address:    %s\n", ast_sockaddr_stringify(&cur->sa));
18799          ast_cli(a->fd, "  Received Address:       %s\n", ast_sockaddr_stringify(&cur->recv));
18800          ast_cli(a->fd, "  SIP Transfer mode:      %s\n", transfermode2str(cur->allowtransfer));
18801          ast_cli(a->fd, "  Force rport:            %s\n", AST_CLI_YESNO(ast_test_flag(&cur->flags[0], SIP_NAT_FORCE_RPORT)));
18802          if (ast_sockaddr_isnull(&cur->redirip)) {
18803             ast_cli(a->fd,
18804                "  Audio IP:               %s (local)\n",
18805                ast_sockaddr_stringify_addr(&cur->ourip));
18806          } else {
18807             ast_cli(a->fd,
18808                "  Audio IP:               %s (Outside bridge)\n",
18809                ast_sockaddr_stringify_addr(&cur->redirip));
18810          }
18811          ast_cli(a->fd, "  Our Tag:                %s\n", cur->tag);
18812          ast_cli(a->fd, "  Their Tag:              %s\n", cur->theirtag);
18813          ast_cli(a->fd, "  SIP User agent:         %s\n", cur->useragent);
18814          if (!ast_strlen_zero(cur->username))
18815             ast_cli(a->fd, "  Username:               %s\n", cur->username);
18816          if (!ast_strlen_zero(cur->peername))
18817             ast_cli(a->fd, "  Peername:               %s\n", cur->peername);
18818          if (!ast_strlen_zero(cur->uri))
18819             ast_cli(a->fd, "  Original uri:           %s\n", cur->uri);
18820          if (!ast_strlen_zero(cur->cid_num))
18821             ast_cli(a->fd, "  Caller-ID:              %s\n", cur->cid_num);
18822          ast_cli(a->fd, "  Need Destroy:           %s\n", AST_CLI_YESNO(cur->needdestroy));
18823          ast_cli(a->fd, "  Last Message:           %s\n", cur->lastmsg);
18824          ast_cli(a->fd, "  Promiscuous Redir:      %s\n", AST_CLI_YESNO(ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR)));
18825          ast_cli(a->fd, "  Route:                  %s\n", cur->route ? cur->route->hop : "N/A");
18826          ast_cli(a->fd, "  DTMF Mode:              %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
18827          ast_cli(a->fd, "  SIP Options:            ");
18828          if (cur->sipoptions) {
18829             int x;
18830             for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
18831                if (cur->sipoptions & sip_options[x].id)
18832                   ast_cli(a->fd, "%s ", sip_options[x].text);
18833             }
18834             ast_cli(a->fd, "\n");
18835          } else
18836             ast_cli(a->fd, "(none)\n");
18837 
18838          if (!cur->stimer)
18839             ast_cli(a->fd, "  Session-Timer:          Uninitiallized\n");
18840          else {
18841             ast_cli(a->fd, "  Session-Timer:          %s\n", cur->stimer->st_active ? "Active" : "Inactive");
18842             if (cur->stimer->st_active == TRUE) {
18843                ast_cli(a->fd, "  S-Timer Interval:       %d\n", cur->stimer->st_interval);
18844                ast_cli(a->fd, "  S-Timer Refresher:      %s\n", strefresher2str(cur->stimer->st_ref));
18845                ast_cli(a->fd, "  S-Timer Expirys:        %d\n", cur->stimer->st_expirys);
18846                ast_cli(a->fd, "  S-Timer Sched Id:       %d\n", cur->stimer->st_schedid);
18847                ast_cli(a->fd, "  S-Timer Peer Sts:       %s\n", cur->stimer->st_active_peer_ua ? "Active" : "Inactive");
18848                ast_cli(a->fd, "  S-Timer Cached Min-SE:  %d\n", cur->stimer->st_cached_min_se);
18849                ast_cli(a->fd, "  S-Timer Cached SE:      %d\n", cur->stimer->st_cached_max_se);
18850                ast_cli(a->fd, "  S-Timer Cached Ref:     %s\n", strefresherparam2str(cur->stimer->st_cached_ref));
18851                ast_cli(a->fd, "  S-Timer Cached Mode:    %s\n", stmode2str(cur->stimer->st_cached_mode));
18852             }
18853          }
18854 
18855          ast_cli(a->fd, "\n\n");
18856 
18857          found++;
18858       }
18859 
18860       sip_pvt_unlock(cur);
18861 
18862       ao2_t_ref(cur, -1, "toss dialog ptr set by iterator_next");
18863    }
18864    ao2_iterator_destroy(&i);
18865 
18866    if (!found)
18867       ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
18868 
18869    return CLI_SUCCESS;
18870 }
18871 
18872 /*! \brief Show history details of one dialog */
18873 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
18874 {
18875    struct sip_pvt *cur;
18876    size_t len;
18877    int found = 0;
18878    struct ao2_iterator i;
18879 
18880    switch (cmd) {
18881    case CLI_INIT:
18882       e->command = "sip show history";
18883       e->usage =
18884          "Usage: sip show history <call-id>\n"
18885          "       Provides detailed dialog history on a given SIP call (specified by call-id).\n";
18886       return NULL;
18887    case CLI_GENERATE:
18888       return complete_sip_show_history(a->line, a->word, a->pos, a->n);
18889    }
18890 
18891    if (a->argc != 4)
18892       return CLI_SHOWUSAGE;
18893 
18894    if (!recordhistory)
18895       ast_cli(a->fd, "\n***Note: History recording is currently DISABLED.  Use 'sip set history on' to ENABLE.\n");
18896 
18897    len = strlen(a->argv[3]);
18898 
18899    i = ao2_iterator_init(dialogs, 0);
18900    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
18901       sip_pvt_lock(cur);
18902       if (!strncasecmp(cur->callid, a->argv[3], len)) {
18903          struct sip_history *hist;
18904          int x = 0;
18905 
18906          ast_cli(a->fd, "\n");
18907          if (cur->subscribed != NONE)
18908             ast_cli(a->fd, "  * Subscription\n");
18909          else
18910             ast_cli(a->fd, "  * SIP Call\n");
18911          if (cur->history)
18912             AST_LIST_TRAVERSE(cur->history, hist, list)
18913                ast_cli(a->fd, "%d. %s\n", ++x, hist->event);
18914          if (x == 0)
18915             ast_cli(a->fd, "Call '%s' has no history\n", cur->callid);
18916          found++;
18917       }
18918       sip_pvt_unlock(cur);
18919       ao2_t_ref(cur, -1, "toss dialog ptr from iterator_next");
18920    }
18921    ao2_iterator_destroy(&i);
18922 
18923    if (!found)
18924       ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
18925 
18926    return CLI_SUCCESS;
18927 }
18928 
18929 /*! \brief Dump SIP history to debug log file at end of lifespan for SIP dialog */
18930 static void sip_dump_history(struct sip_pvt *dialog)
18931 {
18932    int x = 0;
18933    struct sip_history *hist;
18934    static int errmsg = 0;
18935 
18936    if (!dialog)
18937       return;
18938 
18939    if (!option_debug && !sipdebug) {
18940       if (!errmsg) {
18941          ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
18942          errmsg = 1;
18943       }
18944       return;
18945    }
18946 
18947    ast_debug(1, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
18948    if (dialog->subscribed)
18949       ast_debug(1, "  * Subscription\n");
18950    else
18951       ast_debug(1, "  * SIP Call\n");
18952    if (dialog->history)
18953       AST_LIST_TRAVERSE(dialog->history, hist, list)
18954          ast_debug(1, "  %-3.3d. %s\n", ++x, hist->event);
18955    if (!x)
18956       ast_debug(1, "Call '%s' has no history\n", dialog->callid);
18957    ast_debug(1, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
18958 }
18959 
18960 
18961 /*! \brief  Receive SIP INFO Message */
18962 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
18963 {
18964    char buf[1024] = "";
18965    unsigned int event;
18966    const char *c = get_header(req, "Content-Type");
18967 
18968    /* Need to check the media/type */
18969    if (!strcasecmp(c, "application/dtmf-relay") ||
18970        !strcasecmp(c, "application/vnd.nortelnetworks.digits") ||
18971        !strcasecmp(c, "application/dtmf")) {
18972       unsigned int duration = 0;
18973 
18974       if (!p->owner) {  /* not a PBX call */
18975          transmit_response(p, "481 Call leg/transaction does not exist", req);
18976          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18977          return;
18978       }
18979 
18980       /* If dtmf-relay or vnd.nortelnetworks.digits, parse the signal and duration;
18981        * otherwise use the body as the signal */
18982       if (strcasecmp(c, "application/dtmf")) {
18983          const char *msg_body;
18984 
18985          if (   ast_strlen_zero(msg_body = get_body(req, "Signal", '='))
18986             && ast_strlen_zero(msg_body = get_body(req, "d", '='))) {
18987             ast_log(LOG_WARNING, "Unable to retrieve DTMF signal for INFO message on "
18988                   "call %s\n", p->callid);
18989             transmit_response(p, "200 OK", req);
18990             return;
18991          }
18992          ast_copy_string(buf, msg_body, sizeof(buf));
18993 
18994          if (!ast_strlen_zero((msg_body = get_body(req, "Duration", '=')))) {
18995             sscanf(msg_body, "%30u", &duration);
18996          }
18997       } else {
18998          /* Type is application/dtmf, simply use what's in the message body */
18999          get_msg_text(buf, sizeof(buf), req);
19000       }
19001 
19002       /* An empty message body requires us to send a 200 OK */
19003       if (ast_strlen_zero(buf)) {
19004          transmit_response(p, "200 OK", req);
19005          return;
19006       }
19007 
19008       if (!duration) {
19009          duration = 100; /* 100 ms */
19010       }
19011 
19012       if (buf[0] == '*') {
19013          event = 10;
19014       } else if (buf[0] == '#') {
19015          event = 11;
19016       } else if (buf[0] == '!') {
19017          event = 16;
19018       } else if ('A' <= buf[0] && buf[0] <= 'D') {
19019          event = 12 + buf[0] - 'A';
19020       } else if ('a' <= buf[0] && buf[0] <= 'd') {
19021          event = 12 + buf[0] - 'a';
19022       } else if ((sscanf(buf, "%30u", &event) != 1) || event > 16) {
19023          ast_log(AST_LOG_WARNING, "Unable to convert DTMF event signal code to a valid "
19024                "value for INFO message on call %s\n", p->callid);
19025          transmit_response(p, "200 OK", req);
19026          return;
19027       }
19028 
19029       if (event == 16) {
19030          /* send a FLASH event */
19031          struct ast_frame f = { AST_FRAME_CONTROL, { AST_CONTROL_FLASH, } };
19032          ast_queue_frame(p->owner, &f);
19033          if (sipdebug) {
19034             ast_verbose("* DTMF-relay event received: FLASH\n");
19035          }
19036       } else {
19037          /* send a DTMF event */
19038          struct ast_frame f = { AST_FRAME_DTMF, };
19039          if (event < 10) {
19040             f.subclass.integer = '0' + event;
19041          } else if (event == 10) {
19042             f.subclass.integer = '*';
19043          } else if (event == 11) {
19044             f.subclass.integer = '#';
19045          } else {
19046             f.subclass.integer = 'A' + (event - 12);
19047          }
19048          f.len = duration;
19049          ast_queue_frame(p->owner, &f);
19050          if (sipdebug) {
19051             ast_verbose("* DTMF-relay event received: %c\n", (int) f.subclass.integer);
19052          }
19053       }
19054       transmit_response(p, "200 OK", req);
19055       return;
19056    } else if (!strcasecmp(c, "application/media_control+xml")) {
19057       /* Eh, we'll just assume it's a fast picture update for now */
19058       if (p->owner)
19059          ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
19060       transmit_response(p, "200 OK", req);
19061       return;
19062    } else if (!ast_strlen_zero(c = get_header(req, "X-ClientCode"))) {
19063       /* Client code (from SNOM phone) */
19064       if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
19065          if (p->owner && p->owner->cdr)
19066             ast_cdr_setuserfield(p->owner, c);
19067          if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr)
19068             ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
19069          transmit_response(p, "200 OK", req);
19070       } else {
19071          transmit_response(p, "403 Forbidden", req);
19072       }
19073       return;
19074    } else if (!ast_strlen_zero(c = get_header(req, "Record"))) {
19075       /* INFO messages generated by some phones to start/stop recording
19076          on phone calls.
19077          OEJ: I think this should be something that is enabled/disabled
19078          per device. I don't want incoming callers to record calls in my
19079          pbx.
19080       */
19081       
19082       struct ast_call_feature *feat;
19083       int j;
19084       struct ast_frame f = { AST_FRAME_DTMF, };
19085 
19086       if (!p->owner) {        /* not a PBX call */
19087          transmit_response(p, "481 Call leg/transaction does not exist", req);
19088          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19089          return;
19090       }
19091 
19092       /* first, get the feature string, if it exists */
19093       ast_rdlock_call_features();
19094       feat = ast_find_call_feature("automon");
19095       if (!feat || ast_strlen_zero(feat->exten)) {
19096          ast_log(LOG_WARNING, "Recording requested, but no One Touch Monitor registered. (See features.conf)\n");
19097          /* 403 means that we don't support this feature, so don't request it again */
19098          transmit_response(p, "403 Forbidden", req);
19099          ast_unlock_call_features();
19100          return;
19101       }
19102       /* Send the feature code to the PBX as DTMF, just like the handset had sent it */
19103       f.len = 100;
19104       for (j=0; j < strlen(feat->exten); j++) {
19105          f.subclass.integer = feat->exten[j];
19106          ast_queue_frame(p->owner, &f);
19107          if (sipdebug)
19108             ast_verbose("* DTMF-relay event faked: %c\n", f.subclass.integer);
19109       }
19110       ast_unlock_call_features();
19111 
19112       ast_debug(1, "Got a Request to Record the channel, state %s\n", c);
19113       transmit_response(p, "200 OK", req);
19114       return;
19115    } else if (ast_strlen_zero(c = get_header(req, "Content-Length")) || !strcasecmp(c, "0")) {
19116       /* This is probably just a packet making sure the signalling is still up, just send back a 200 OK */
19117       transmit_response(p, "200 OK", req);
19118       return;
19119    }
19120 
19121    /* Other type of INFO message, not really understood by Asterisk */
19122    /* if (get_msg_text(buf, sizeof(buf), req)) { */
19123 
19124    ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
19125    transmit_response(p, "415 Unsupported media type", req);
19126    return;
19127 }
19128 
19129 /*! \brief Enable SIP Debugging for a single IP */
19130 static char *sip_do_debug_ip(int fd, const char *arg)
19131 {
19132    if (ast_sockaddr_resolve_first_af(&debugaddr, arg, 0, 0)) {
19133       return CLI_SHOWUSAGE;
19134    }
19135 
19136    ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_sockaddr_stringify_addr(&debugaddr));
19137    sipdebug |= sip_debug_console;
19138 
19139    return CLI_SUCCESS;
19140 }
19141 
19142 /*! \brief  Turn on SIP debugging for a given peer */
19143 static char *sip_do_debug_peer(int fd, const char *arg)
19144 {
19145    struct sip_peer *peer = find_peer(arg, NULL, TRUE, FINDPEERS, FALSE, 0);
19146    if (!peer)
19147       ast_cli(fd, "No such peer '%s'\n", arg);
19148    else if (ast_sockaddr_isnull(&peer->addr))
19149       ast_cli(fd, "Unable to get IP address of peer '%s'\n", arg);
19150    else {
19151       ast_sockaddr_copy(&debugaddr, &peer->addr);
19152       ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_sockaddr_stringify_addr(&debugaddr));
19153       sipdebug |= sip_debug_console;
19154    }
19155    if (peer)
19156       unref_peer(peer, "sip_do_debug_peer: unref_peer, from find_peer call");
19157    return CLI_SUCCESS;
19158 }
19159 
19160 /*! \brief Turn on SIP debugging (CLI command) */
19161 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19162 {
19163    int oldsipdebug = sipdebug & sip_debug_console;
19164    const char *what;
19165 
19166    if (cmd == CLI_INIT) {
19167       e->command = "sip set debug {on|off|ip|peer}";
19168       e->usage =
19169          "Usage: sip set debug {off|on|ip addr[:port]|peer peername}\n"
19170          "       Globally disables dumping of SIP packets,\n"
19171          "       or enables it either globally or for a (single)\n"
19172          "       IP address or registered peer.\n";
19173       return NULL;
19174    } else if (cmd == CLI_GENERATE) {
19175       if (a->pos == 4 && !strcasecmp(a->argv[3], "peer"))
19176          return complete_sip_peer(a->word, a->n, 0);
19177       return NULL;
19178         }
19179 
19180    what = a->argv[e->args-1];      /* guaranteed to exist */
19181    if (a->argc == e->args) {       /* on/off */
19182       if (!strcasecmp(what, "on")) {
19183          sipdebug |= sip_debug_console;
19184          sipdebug_text = 1;   /*! \note this can be a special debug command - "sip debug text" or something */
19185          memset(&debugaddr, 0, sizeof(debugaddr));
19186          ast_cli(a->fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
19187          return CLI_SUCCESS;
19188       } else if (!strcasecmp(what, "off")) {
19189          sipdebug &= ~sip_debug_console;
19190          sipdebug_text = 0;
19191          ast_cli(a->fd, "SIP Debugging Disabled\n");
19192          return CLI_SUCCESS;
19193       }
19194    } else if (a->argc == e->args +1) {/* ip/peer */
19195       if (!strcasecmp(what, "ip"))
19196          return sip_do_debug_ip(a->fd, a->argv[e->args]);
19197       else if (!strcasecmp(what, "peer"))
19198          return sip_do_debug_peer(a->fd, a->argv[e->args]);
19199    }
19200    return CLI_SHOWUSAGE;   /* default, failure */
19201 }
19202 
19203 /*! \brief Cli command to send SIP notify to peer */
19204 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19205 {
19206    struct ast_variable *varlist;
19207    int i;
19208 
19209    switch (cmd) {
19210    case CLI_INIT:
19211       e->command = "sip notify";
19212       e->usage =
19213          "Usage: sip notify <type> <peer> [<peer>...]\n"
19214          "       Send a NOTIFY message to a SIP peer or peers\n"
19215          "       Message types are defined in sip_notify.conf\n";
19216       return NULL;
19217    case CLI_GENERATE:
19218       return complete_sipnotify(a->line, a->word, a->pos, a->n);
19219    }
19220 
19221    if (a->argc < 4)
19222       return CLI_SHOWUSAGE;
19223 
19224    if (!notify_types) {
19225       ast_cli(a->fd, "No %s file found, or no types listed there\n", notify_config);
19226       return CLI_FAILURE;
19227    }
19228 
19229    varlist = ast_variable_browse(notify_types, a->argv[2]);
19230 
19231    if (!varlist) {
19232       ast_cli(a->fd, "Unable to find notify type '%s'\n", a->argv[2]);
19233       return CLI_FAILURE;
19234    }
19235 
19236    for (i = 3; i < a->argc; i++) {
19237       struct sip_pvt *p;
19238       char buf[512];
19239       struct ast_variable *header, *var;
19240 
19241       if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
19242          ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
19243          return CLI_FAILURE;
19244       }
19245 
19246       if (create_addr(p, a->argv[i], NULL, 1)) {
19247          /* Maybe they're not registered, etc. */
19248          dialog_unlink_all(p);
19249          dialog_unref(p, "unref dialog inside for loop" );
19250          /* sip_destroy(p); */
19251          ast_cli(a->fd, "Could not create address for '%s'\n", a->argv[i]);
19252          continue;
19253       }
19254 
19255       /* Notify is outgoing call */
19256       ast_set_flag(&p->flags[0], SIP_OUTGOING);
19257       sip_notify_allocate(p);
19258       p->notify->headers = header = ast_variable_new("Subscription-State", "terminated", "");
19259 
19260       for (var = varlist; var; var = var->next) {
19261          ast_copy_string(buf, var->value, sizeof(buf));
19262          ast_unescape_semicolon(buf);
19263 
19264          if (!strcasecmp(var->name, "Content")) {
19265             if (ast_str_strlen(p->notify->content))
19266                ast_str_append(&p->notify->content, 0, "\r\n");
19267             ast_str_append(&p->notify->content, 0, "%s", buf);
19268          } else if (!strcasecmp(var->name, "Content-Length")) {
19269             ast_log(LOG_WARNING, "it is not necessary to specify Content-Length in sip_notify.conf, ignoring\n");
19270          } else {
19271             header->next = ast_variable_new(var->name, buf, "");
19272             header = header->next;
19273          }
19274       }
19275 
19276       /* Recalculate our side, and recalculate Call ID */
19277       ast_cli(a->fd, "Sending NOTIFY of type '%s' to '%s'\n", a->argv[2], a->argv[i]);
19278       sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
19279       transmit_invite(p, SIP_NOTIFY, 0, 2, NULL);
19280       dialog_unref(p, "bump down the count of p since we're done with it.");
19281    }
19282 
19283    return CLI_SUCCESS;
19284 }
19285 
19286 /*! \brief Enable/Disable SIP History logging (CLI) */
19287 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
19288 {
19289    switch (cmd) {
19290    case CLI_INIT:
19291       e->command = "sip set history {on|off}";
19292       e->usage =
19293          "Usage: sip set history {on|off}\n"
19294          "       Enables/Disables recording of SIP dialog history for debugging purposes.\n"
19295          "       Use 'sip show history' to view the history of a call number.\n";
19296       return NULL;
19297    case CLI_GENERATE:
19298       return NULL;
19299    }
19300 
19301    if (a->argc != e->args)
19302       return CLI_SHOWUSAGE;
19303 
19304    if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
19305       recordhistory = TRUE;
19306       ast_cli(a->fd, "SIP History Recording Enabled (use 'sip show history')\n");
19307    } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
19308       recordhistory = FALSE;
19309       ast_cli(a->fd, "SIP History Recording Disabled\n");
19310    } else {
19311       return CLI_SHOWUSAGE;
19312    }
19313    return CLI_SUCCESS;
19314 }
19315 
19316 /*! \brief Authenticate for outbound registration */
19317 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code)
19318 {
19319    char *header, *respheader;
19320    char digest[1024];
19321 
19322    p->authtries++;
19323    auth_headers(code, &header, &respheader);
19324    memset(digest, 0, sizeof(digest));
19325    if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
19326       /* There's nothing to use for authentication */
19327       /* No digest challenge in request */
19328       if (sip_debug_test_pvt(p) && p->registry)
19329          ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
19330          /* No old challenge */
19331       return -1;
19332    }
19333    if (p->do_history)
19334       append_history(p, "RegistryAuth", "Try: %d", p->authtries);
19335    if (sip_debug_test_pvt(p) && p->registry)
19336       ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
19337    return transmit_register(p->registry, SIP_REGISTER, digest, respheader);
19338 }
19339 
19340 /*! \brief Add authentication on outbound SIP packet */
19341 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code, int sipmethod, int init)
19342 {
19343    char *header, *respheader;
19344    char digest[1024];
19345 
19346    if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
19347       return -2;
19348 
19349    p->authtries++;
19350    auth_headers(code, &header, &respheader);
19351    ast_debug(2, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
19352    memset(digest, 0, sizeof(digest));
19353    if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
19354       /* No way to authenticate */
19355       return -1;
19356    }
19357    /* Now we have a reply digest */
19358    p->options->auth = digest;
19359    p->options->authheader = respheader;
19360    return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init, NULL);
19361 }
19362 
19363 /*! \brief  reply to authentication for outbound registrations
19364 \return  Returns -1 if we have no auth
19365 \note This is used for register= servers in sip.conf, SIP proxies we register
19366    with  for receiving calls from.  */
19367 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod,  char *digest, int digest_len)
19368 {
19369    char tmp[512];
19370    char *c;
19371    char oldnonce[256];
19372 
19373    /* table of recognised keywords, and places where they should be copied */
19374    const struct x {
19375       const char *key;
19376       const ast_string_field *field;
19377    } *i, keys[] = {
19378       { "realm=", &p->realm },
19379       { "nonce=", &p->nonce },
19380       { "opaque=", &p->opaque },
19381       { "qop=", &p->qop },
19382       { "domain=", &p->domain },
19383       { NULL, 0 },
19384    };
19385 
19386    ast_copy_string(tmp, get_header(req, header), sizeof(tmp));
19387    if (ast_strlen_zero(tmp))
19388       return -1;
19389    if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
19390       ast_log(LOG_WARNING, "missing Digest.\n");
19391       return -1;
19392    }
19393    c = tmp + strlen("Digest ");
19394    ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
19395    while (c && *(c = ast_skip_blanks(c))) {  /* lookup for keys */
19396       for (i = keys; i->key != NULL; i++) {
19397          char *src, *separator;
19398          if (strncasecmp(c, i->key, strlen(i->key)) != 0)
19399             continue;
19400          /* Found. Skip keyword, take text in quotes or up to the separator. */
19401          c += strlen(i->key);
19402          if (*c == '"') {
19403             src = ++c;
19404             separator = "\"";
19405          } else {
19406             src = c;
19407             separator = ",";
19408          }
19409          strsep(&c, separator); /* clear separator and move ptr */
19410          ast_string_field_ptr_set(p, i->field, src);
19411          break;
19412       }
19413       if (i->key == NULL) /* not found, try ',' */
19414          strsep(&c, ",");
19415    }
19416    /* Reset nonce count */
19417    if (strcmp(p->nonce, oldnonce))
19418       p->noncecount = 0;
19419 
19420    /* Save auth data for following registrations */
19421    if (p->registry) {
19422       struct sip_registry *r = p->registry;
19423 
19424       if (strcmp(r->nonce, p->nonce)) {
19425          ast_string_field_set(r, realm, p->realm);
19426          ast_string_field_set(r, nonce, p->nonce);
19427          ast_string_field_set(r, authdomain, p->domain);
19428          ast_string_field_set(r, opaque, p->opaque);
19429          ast_string_field_set(r, qop, p->qop);
19430          r->noncecount = 0;
19431       }
19432    }
19433    return build_reply_digest(p, sipmethod, digest, digest_len);
19434 }
19435 
19436 /*! \brief  Build reply digest
19437 \return  Returns -1 if we have no auth
19438 \note Build digest challenge for authentication of registrations and calls
19439    Also used for authentication of BYE
19440 */
19441 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
19442 {
19443    char a1[256];
19444    char a2[256];
19445    char a1_hash[256];
19446    char a2_hash[256];
19447    char resp[256];
19448    char resp_hash[256];
19449    char uri[256];
19450    char opaque[256] = "";
19451    char cnonce[80];
19452    const char *username;
19453    const char *secret;
19454    const char *md5secret;
19455    struct sip_auth *auth;  /* Realm authentication credential */
19456    struct sip_auth_container *credentials;
19457 
19458    if (!ast_strlen_zero(p->domain))
19459       snprintf(uri, sizeof(uri), "%s:%s", p->socket.type == SIP_TRANSPORT_TLS ? "sips" : "sip", p->domain);
19460    else if (!ast_strlen_zero(p->uri))
19461       ast_copy_string(uri, p->uri, sizeof(uri));
19462    else
19463       snprintf(uri, sizeof(uri), "%s:%s@%s", p->socket.type == SIP_TRANSPORT_TLS ? "sips" : "sip", p->username, ast_sockaddr_stringify_host_remote(&p->sa));
19464 
19465    snprintf(cnonce, sizeof(cnonce), "%08lx", ast_random());
19466 
19467    /* Check if we have peer credentials */
19468    ao2_lock(p);
19469    credentials = p->peerauth;
19470    if (credentials) {
19471       ao2_t_ref(credentials, +1, "Ref peer auth for digest");
19472    }
19473    ao2_unlock(p);
19474    auth = find_realm_authentication(credentials, p->realm);
19475    if (!auth) {
19476       /* If not, check global credentials */
19477       if (credentials) {
19478          ao2_t_ref(credentials, -1, "Unref peer auth for digest");
19479       }
19480       ast_mutex_lock(&authl_lock);
19481       credentials = authl;
19482       if (credentials) {
19483          ao2_t_ref(credentials, +1, "Ref global auth for digest");
19484       }
19485       ast_mutex_unlock(&authl_lock);
19486       auth = find_realm_authentication(credentials, p->realm);
19487    }
19488 
19489    if (auth) {
19490       ast_debug(3, "use realm [%s] from peer [%s][%s]\n", auth->username, p->peername, p->username);
19491       username = auth->username;
19492       secret = auth->secret;
19493       md5secret = auth->md5secret;
19494       if (sipdebug)
19495          ast_debug(1, "Using realm %s authentication for call %s\n", p->realm, p->callid);
19496    } else {
19497       /* No authentication, use peer or register= config */
19498       username = p->authname;
19499       secret = p->relatedpeer 
19500          && !ast_strlen_zero(p->relatedpeer->remotesecret)
19501             ? p->relatedpeer->remotesecret : p->peersecret;
19502       md5secret = p->peermd5secret;
19503    }
19504    if (ast_strlen_zero(username)) {
19505       /* We have no authentication */
19506       if (credentials) {
19507          ao2_t_ref(credentials, -1, "Unref auth for digest");
19508       }
19509       return -1;
19510    }
19511 
19512    /* Calculate SIP digest response */
19513    snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
19514    snprintf(a2, sizeof(a2), "%s:%s", sip_methods[method].text, uri);
19515    if (!ast_strlen_zero(md5secret))
19516       ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
19517    else
19518       ast_md5_hash(a1_hash, a1);
19519    ast_md5_hash(a2_hash, a2);
19520 
19521    p->noncecount++;
19522    if (!ast_strlen_zero(p->qop))
19523       snprintf(resp, sizeof(resp), "%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, p->noncecount, cnonce, "auth", a2_hash);
19524    else
19525       snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, p->nonce, a2_hash);
19526    ast_md5_hash(resp_hash, resp);
19527 
19528    /* only include the opaque string if it's set */
19529    if (!ast_strlen_zero(p->opaque)) {
19530       snprintf(opaque, sizeof(opaque), ", opaque=\"%s\"", p->opaque);
19531    }
19532 
19533    /* XXX We hard code our qop to "auth" for now.  XXX */
19534    if (!ast_strlen_zero(p->qop))
19535       snprintf(digest, digest_len, "Digest username=\"%s\", realm=\"%s\", algorithm=MD5, uri=\"%s\", nonce=\"%s\", response=\"%s\"%s, qop=auth, cnonce=\"%s\", nc=%08x", username, p->realm, uri, p->nonce, resp_hash, opaque, cnonce, p->noncecount);
19536    else
19537       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);
19538 
19539    append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);
19540 
19541    if (credentials) {
19542       ao2_t_ref(credentials, -1, "Unref auth for digest");
19543    }
19544    return 0;
19545 }
19546    
19547 /*! \brief Read SIP header (dialplan function) */
19548 static int func_header_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len)
19549 {
19550    struct sip_pvt *p;
19551    const char *content = NULL;
19552    AST_DECLARE_APP_ARGS(args,
19553       AST_APP_ARG(header);
19554       AST_APP_ARG(number);
19555    );
19556    int i, number, start = 0;
19557 
19558    if (ast_strlen_zero(data)) {
19559       ast_log(LOG_WARNING, "This function requires a header name.\n");
19560       return -1;
19561    }
19562 
19563    ast_channel_lock(chan);
19564    if (!IS_SIP_TECH(chan->tech)) {
19565       ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
19566       ast_channel_unlock(chan);
19567       return -1;
19568    }
19569 
19570    AST_STANDARD_APP_ARGS(args, data);
19571    if (!args.number) {
19572       number = 1;
19573    } else {
19574       sscanf(args.number, "%30d", &number);
19575       if (number < 1)
19576          number = 1;
19577    }
19578 
19579    p = chan->tech_pvt;
19580 
19581    /* If there is no private structure, this channel is no longer alive */
19582    if (!p) {
19583       ast_channel_unlock(chan);
19584       return -1;
19585    }
19586 
19587    for (i = 0; i < number; i++)
19588       content = __get_header(&p->initreq, args.header, &start);
19589 
19590    if (ast_strlen_zero(content)) {
19591       ast_channel_unlock(chan);
19592       return -1;
19593    }
19594 
19595    ast_copy_string(buf, content, len);
19596    ast_channel_unlock(chan);
19597 
19598    return 0;
19599 }
19600 
19601 static struct ast_custom_function sip_header_function = {
19602    .name = "SIP_HEADER",
19603    .read = func_header_read,
19604 };
19605 
19606 /*! \brief  Dial plan function to check if domain is local */
19607 static int func_check_sipdomain(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
19608 {
19609    if (ast_strlen_zero(data)) {
19610       ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
19611       return -1;
19612    }
19613    if (check_sip_domain(data, NULL, 0))
19614       ast_copy_string(buf, data, len);
19615    else
19616       buf[0] = '\0';
19617    return 0;
19618 }
19619 
19620 static struct ast_custom_function checksipdomain_function = {
19621    .name = "CHECKSIPDOMAIN",
19622    .read = func_check_sipdomain,
19623 };
19624 
19625 /*! \brief  ${SIPPEER()} Dialplan function - reads peer data */
19626 static int function_sippeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
19627 {
19628    struct sip_peer *peer;
19629    char *colname;
19630 
19631    if ((colname = strchr(data, ':'))) {   /*! \todo Will be deprecated after 1.4 */
19632       static int deprecation_warning = 0;
19633       *colname++ = '\0';
19634       if (deprecation_warning++ % 10 == 0)
19635          ast_log(LOG_WARNING, "SIPPEER(): usage of ':' to separate arguments is deprecated.  Please use ',' instead.\n");
19636    } else if ((colname = strchr(data, ',')))
19637       *colname++ = '\0';
19638    else
19639       colname = "ip";
19640 
19641    if (!(peer = find_peer(data, NULL, TRUE, FINDPEERS, FALSE, 0)))
19642       return -1;
19643 
19644    if (!strcasecmp(colname, "ip")) {
19645       ast_copy_string(buf, ast_sockaddr_stringify_addr(&peer->addr), len);
19646    } else  if (!strcasecmp(colname, "port")) {
19647       snprintf(buf, len, "%d", ast_sockaddr_port(&peer->addr));
19648    } else  if (!strcasecmp(colname, "status")) {
19649       peer_status(peer, buf, len);
19650    } else  if (!strcasecmp(colname, "language")) {
19651       ast_copy_string(buf, peer->language, len);
19652    } else  if (!strcasecmp(colname, "regexten")) {
19653       ast_copy_string(buf, peer->regexten, len);
19654    } else  if (!strcasecmp(colname, "limit")) {
19655       snprintf(buf, len, "%d", peer->call_limit);
19656    } else  if (!strcasecmp(colname, "busylevel")) {
19657       snprintf(buf, len, "%d", peer->busy_level);
19658    } else  if (!strcasecmp(colname, "curcalls")) {
19659       snprintf(buf, len, "%d", peer->inUse);
19660    } else if (!strcasecmp(colname, "maxforwards")) {
19661       snprintf(buf, len, "%d", peer->maxforwards);
19662    } else  if (!strcasecmp(colname, "accountcode")) {
19663       ast_copy_string(buf, peer->accountcode, len);
19664    } else  if (!strcasecmp(colname, "callgroup")) {
19665       ast_print_group(buf, len, peer->callgroup);
19666    } else  if (!strcasecmp(colname, "pickupgroup")) {
19667       ast_print_group(buf, len, peer->pickupgroup);
19668    } else  if (!strcasecmp(colname, "useragent")) {
19669       ast_copy_string(buf, peer->useragent, len);
19670    } else  if (!strcasecmp(colname, "mailbox")) {
19671       struct ast_str *mailbox_str = ast_str_alloca(512);
19672       peer_mailboxes_to_str(&mailbox_str, peer);
19673       ast_copy_string(buf, mailbox_str->str, len);
19674    } else  if (!strcasecmp(colname, "context")) {
19675       ast_copy_string(buf, peer->context, len);
19676    } else  if (!strcasecmp(colname, "expire")) {
19677       snprintf(buf, len, "%d", peer->expire);
19678    } else  if (!strcasecmp(colname, "dynamic")) {
19679       ast_copy_string(buf, peer->host_dynamic ? "yes" : "no", len);
19680    } else  if (!strcasecmp(colname, "callerid_name")) {
19681       ast_copy_string(buf, peer->cid_name, len);
19682    } else  if (!strcasecmp(colname, "callerid_num")) {
19683       ast_copy_string(buf, peer->cid_num, len);
19684    } else  if (!strcasecmp(colname, "codecs")) {
19685       ast_getformatname_multiple(buf, len -1, peer->capability);
19686    } else if (!strcasecmp(colname, "encryption")) {
19687       snprintf(buf, len, "%d", ast_test_flag(&peer->flags[1], SIP_PAGE2_USE_SRTP));
19688    } else  if (!strncasecmp(colname, "chanvar[", 8)) {
19689       char *chanvar=colname + 8;
19690       struct ast_variable *v;
19691    
19692       chanvar = strsep(&chanvar, "]");
19693       for (v = peer->chanvars ; v ; v = v->next) {
19694          if (!strcasecmp(v->name, chanvar)) {
19695             ast_copy_string(buf, v->value, len);
19696          }
19697       }
19698    } else  if (!strncasecmp(colname, "codec[", 6)) {
19699       char *codecnum;
19700       format_t codec = 0;
19701       
19702       codecnum = colname + 6; /* move past the '[' */
19703       codecnum = strsep(&codecnum, "]"); /* trim trailing ']' if any */
19704       if((codec = ast_codec_pref_index(&peer->prefs, atoi(codecnum)))) {
19705          ast_copy_string(buf, ast_getformatname(codec), len);
19706       } else {
19707          buf[0] = '\0';
19708       }
19709    } else {
19710       buf[0] = '\0';
19711    }
19712 
19713    unref_peer(peer, "unref_peer from function_sippeer, just before return");
19714 
19715    return 0;
19716 }
19717 
19718 /*! \brief Structure to declare a dialplan function: SIPPEER */
19719 static struct ast_custom_function sippeer_function = {
19720    .name = "SIPPEER",
19721    .read = function_sippeer,
19722 };
19723 
19724 /*! \brief ${SIPCHANINFO()} Dialplan function - reads sip channel data */
19725 static int function_sipchaninfo_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
19726 {
19727    struct sip_pvt *p;
19728    static int deprecated = 0;
19729 
19730    *buf = 0;
19731    
19732    if (!data) {
19733       ast_log(LOG_WARNING, "This function requires a parameter name.\n");
19734       return -1;
19735    }
19736 
19737    ast_channel_lock(chan);
19738    if (!IS_SIP_TECH(chan->tech)) {
19739       ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
19740       ast_channel_unlock(chan);
19741       return -1;
19742    }
19743 
19744    if (deprecated++ % 20 == 0) {
19745       /* Deprecated in 1.6.1 */
19746       ast_log(LOG_WARNING, "SIPCHANINFO() is deprecated.  Please transition to using CHANNEL().\n");
19747    }
19748 
19749    p = chan->tech_pvt;
19750 
19751    /* If there is no private structure, this channel is no longer alive */
19752    if (!p) {
19753       ast_channel_unlock(chan);
19754       return -1;
19755    }
19756 
19757    if (!strcasecmp(data, "peerip")) {
19758       ast_copy_string(buf, ast_sockaddr_stringify_addr(&p->sa), len);
19759    } else  if (!strcasecmp(data, "recvip")) {
19760       ast_copy_string(buf, ast_sockaddr_stringify_addr(&p->recv), len);
19761    } else  if (!strcasecmp(data, "from")) {
19762       ast_copy_string(buf, p->from, len);
19763    } else  if (!strcasecmp(data, "uri")) {
19764       ast_copy_string(buf, p->uri, len);
19765    } else  if (!strcasecmp(data, "useragent")) {
19766       ast_copy_string(buf, p->useragent, len);
19767    } else  if (!strcasecmp(data, "peername")) {
19768       ast_copy_string(buf, p->peername, len);
19769    } else if (!strcasecmp(data, "t38passthrough")) {
19770       if (p->t38.state == T38_DISABLED) {
19771          ast_copy_string(buf, "0", len);
19772       } else { /* T38 is offered or enabled in this call */
19773          ast_copy_string(buf, "1", len);
19774       }
19775    } else {
19776       ast_channel_unlock(chan);
19777       return -1;
19778    }
19779    ast_channel_unlock(chan);
19780 
19781    return 0;
19782 }
19783 
19784 /*! \brief Structure to declare a dialplan function: SIPCHANINFO */
19785 static struct ast_custom_function sipchaninfo_function = {
19786    .name = "SIPCHANINFO",
19787    .read = function_sipchaninfo_read,
19788 };
19789 
19790 /*! \brief update redirecting information for a channel based on headers
19791  *
19792  */
19793 static void change_redirecting_information(struct sip_pvt *p, struct sip_request *req,
19794    struct ast_party_redirecting *redirecting,
19795    struct ast_set_party_redirecting *update_redirecting, int set_call_forward)
19796 {
19797    char *redirecting_from_name = NULL;
19798    char *redirecting_from_number = NULL;
19799    char *redirecting_to_name = NULL;
19800    char *redirecting_to_number = NULL;
19801    int reason = AST_REDIRECTING_REASON_UNCONDITIONAL;
19802    int is_response = req->method == SIP_RESPONSE;
19803    int res = 0;
19804 
19805    res = get_rdnis(p, req, &redirecting_from_name, &redirecting_from_number, &reason);
19806    if (res == -1) {
19807       if (is_response) {
19808          get_name_and_number(get_header(req, "TO"), &redirecting_from_name, &redirecting_from_number);
19809       } else {
19810          return;
19811       }
19812    }
19813 
19814    /* At this point, all redirecting "from" info should be filled in appropriately
19815     * on to the "to" info
19816     */
19817 
19818    if (is_response) {
19819       parse_moved_contact(p, req, &redirecting_to_name, &redirecting_to_number, set_call_forward);
19820    } else {
19821       get_name_and_number(get_header(req, "TO"), &redirecting_to_name, &redirecting_to_number);
19822    }
19823 
19824    if (!ast_strlen_zero(redirecting_from_number)) {
19825       ast_debug(3, "Got redirecting from number %s\n", redirecting_from_number);
19826       update_redirecting->from.number = 1;
19827       redirecting->from.number.valid = 1;
19828       ast_free(redirecting->from.number.str);
19829       redirecting->from.number.str = redirecting_from_number;
19830    }
19831    if (!ast_strlen_zero(redirecting_from_name)) {
19832       ast_debug(3, "Got redirecting from name %s\n", redirecting_from_name);
19833       update_redirecting->from.name = 1;
19834       redirecting->from.name.valid = 1;
19835       ast_free(redirecting->from.name.str);
19836       redirecting->from.name.str = redirecting_from_name;
19837    }
19838    if (!ast_strlen_zero(p->cid_tag)) {
19839       ast_free(redirecting->from.tag);
19840       redirecting->from.tag = ast_strdup(p->cid_tag);
19841       ast_free(redirecting->to.tag);
19842       redirecting->to.tag = ast_strdup(p->cid_tag);
19843    }
19844    if (!ast_strlen_zero(redirecting_to_number)) {
19845       ast_debug(3, "Got redirecting to number %s\n", redirecting_to_number);
19846       update_redirecting->to.number = 1;
19847       redirecting->to.number.valid = 1;
19848       ast_free(redirecting->to.number.str);
19849       redirecting->to.number.str = redirecting_to_number;
19850    }
19851    if (!ast_strlen_zero(redirecting_to_name)) {
19852       ast_debug(3, "Got redirecting to name %s\n", redirecting_from_number);
19853       update_redirecting->to.name = 1;
19854       redirecting->to.name.valid = 1;
19855       ast_free(redirecting->to.name.str);
19856       redirecting->to.name.str = redirecting_to_name;
19857    }
19858    redirecting->reason = reason;
19859 }
19860 
19861 /*! \brief Parse 302 Moved temporalily response
19862    \todo XXX Doesn't redirect over TLS on sips: uri's.
19863       If we get a redirect to a SIPS: uri, this needs to be going back to the
19864       dialplan (this is a request for a secure signalling path).
19865       Note that transport=tls is deprecated, but we need to support it on incoming requests.
19866 */
19867 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward)
19868 {
19869    char contact[SIPBUFSIZE];
19870    char *contact_name = NULL;
19871    char *contact_number = NULL;
19872    char *separator, *trans;
19873    char *domain;
19874    enum sip_transport transport = SIP_TRANSPORT_UDP;
19875 
19876    ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
19877    if ((separator = strchr(contact, ',')))
19878       *separator = '\0';
19879 
19880    contact_number = get_in_brackets(contact);
19881    if ((trans = strcasestr(contact_number, ";transport="))) {
19882       trans += 11;
19883 
19884       if ((separator = strchr(trans, ';')))
19885          *separator = '\0';
19886 
19887       if (!strncasecmp(trans, "tcp", 3))
19888          transport = SIP_TRANSPORT_TCP;
19889       else if (!strncasecmp(trans, "tls", 3))
19890          transport = SIP_TRANSPORT_TLS;
19891       else {
19892          if (strncasecmp(trans, "udp", 3))
19893             ast_debug(1, "received contact with an invalid transport, '%s'\n", contact_number);
19894          /* This will assume UDP for all unknown transports */
19895          transport = SIP_TRANSPORT_UDP;
19896       }
19897    }
19898    contact_number = remove_uri_parameters(contact_number);
19899 
19900    if (p->socket.tcptls_session) {
19901       ao2_ref(p->socket.tcptls_session, -1);
19902       p->socket.tcptls_session = NULL;
19903    }
19904 
19905    set_socket_transport(&p->socket, transport);
19906 
19907    if (set_call_forward && ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
19908       char *host = NULL;
19909       if (!strncasecmp(contact_number, "sip:", 4))
19910          contact_number += 4;
19911       else if (!strncasecmp(contact_number, "sips:", 5))
19912          contact_number += 5;
19913       separator = strchr(contact_number, '/');
19914       if (separator)
19915          *separator = '\0';
19916       if ((host = strchr(contact_number, '@'))) {
19917          *host++ = '\0';
19918          ast_debug(2, "Found promiscuous redirection to 'SIP/%s::::%s@%s'\n", contact_number, get_transport(transport), host);
19919          if (p->owner)
19920             ast_string_field_build(p->owner, call_forward, "SIP/%s::::%s@%s", contact_number, get_transport(transport), host);
19921       } else {
19922          ast_debug(2, "Found promiscuous redirection to 'SIP/::::%s@%s'\n", get_transport(transport), contact_number);
19923          if (p->owner)
19924             ast_string_field_build(p->owner, call_forward, "SIP/::::%s@%s", get_transport(transport), contact_number);
19925       }
19926    } else {
19927       separator = strchr(contact, '@');
19928       if (separator) {
19929          *separator++ = '\0';
19930          domain = separator;
19931       } else {
19932          /* No username part */
19933          domain = contact;
19934       }
19935       separator = strchr(contact, '/');   /* WHEN do we hae a forward slash in the URI? */
19936       if (separator)
19937          *separator = '\0';
19938 
19939       if (!strncasecmp(contact_number, "sip:", 4))
19940          contact_number += 4;
19941       else if (!strncasecmp(contact_number, "sips:", 5))
19942          contact_number += 5;
19943       separator = strchr(contact_number, ';');  /* And username ; parameters? */
19944       if (separator)
19945          *separator = '\0';
19946       ast_uri_decode(contact_number);
19947       if (set_call_forward) {
19948          ast_debug(2, "Received 302 Redirect to extension '%s' (domain %s)\n", contact_number, domain);
19949          if (p->owner) {
19950             pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
19951             ast_string_field_set(p->owner, call_forward, contact_number);
19952          }
19953       }
19954    }
19955 
19956    /* We've gotten the number for the contact, now get the name */
19957 
19958    if (*contact == '\"') {
19959       contact_name = contact + 1;
19960       if (!(separator = (char *)find_closing_quote(contact_name, NULL))) {
19961          ast_log(LOG_NOTICE, "No closing quote on name in Contact header? %s\n", contact);
19962       }
19963       *separator = '\0';
19964    }
19965 
19966    if (name && !ast_strlen_zero(contact_name)) {
19967       *name = ast_strdup(contact_name);
19968    }
19969    if (number) {
19970       *number = ast_strdup(contact_number);
19971    }
19972 }
19973 
19974 /*! \brief Check pending actions on SIP call 
19975  *
19976  * \note both sip_pvt and sip_pvt's owner channel (if present)
19977  *  must be locked for this function.
19978  */
19979 static void check_pendings(struct sip_pvt *p)
19980 {
19981    if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
19982       if (p->reinviteid > -1) {
19983          /* Outstanding p->reinviteid timeout, so wait... */
19984          return;
19985       } else if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA) {
19986          /* if we can't BYE, then this is really a pending CANCEL */
19987          p->invitestate = INV_CANCELLED;
19988          transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
19989          /* If the cancel occurred on an initial invite, cancel the pending BYE */
19990          if (!ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED)) {
19991             ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);
19992          }
19993          /* Actually don't destroy us yet, wait for the 487 on our original
19994             INVITE, but do set an autodestruct just in case we never get it. */
19995       } else {
19996          /* We have a pending outbound invite, don't send something
19997           * new in-transaction, unless it is a pending reinvite, then
19998           * by the time we are called here, we should probably just hang up. */
19999          if (p->pendinginvite && !p->ongoing_reinvite)
20000             return;
20001 
20002          if (p->owner) {
20003             ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
20004          }
20005          /* Perhaps there is an SD change INVITE outstanding */
20006          transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
20007          ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);
20008       }
20009       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20010    } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
20011       /* if we can't REINVITE, hold it for later */
20012       if (p->pendinginvite || p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA || p->waitid > 0) {
20013          ast_debug(2, "NOT Sending pending reinvite (yet) on '%s'\n", p->callid);
20014       } else {
20015          ast_debug(2, "Sending pending reinvite on '%s'\n", p->callid);
20016          /* Didn't get to reinvite yet, so do it now */
20017          transmit_reinvite_with_sdp(p, (p->t38.state == T38_LOCAL_REINVITE ? TRUE : FALSE), FALSE);
20018          ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE); 
20019       }
20020    }
20021 }
20022 
20023 /*! \brief Reset the NEEDREINVITE flag after waiting when we get 491 on a Re-invite
20024    to avoid race conditions between asterisk servers.
20025    Called from the scheduler.
20026 */
20027 static int sip_reinvite_retry(const void *data)
20028 {
20029    struct sip_pvt *p = (struct sip_pvt *) data;
20030    struct ast_channel *owner;
20031 
20032    sip_pvt_lock(p); /* called from schedule thread which requires a lock */
20033    while ((owner = p->owner) && ast_channel_trylock(owner)) {
20034       sip_pvt_unlock(p);
20035       usleep(1);
20036       sip_pvt_lock(p);
20037    }
20038    ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
20039    p->waitid = -1;
20040    check_pendings(p);
20041    sip_pvt_unlock(p);
20042    if (owner) {
20043       ast_channel_unlock(owner);
20044    }
20045    dialog_unref(p, "unref the dialog ptr from sip_reinvite_retry, because it held a dialog ptr");
20046    return 0;
20047 }
20048 
20049 /*!
20050  * \brief Handle authentication challenge for SIP UPDATE
20051  *
20052  * This function is only called upon the receipt of a 401/407 response to an UPDATE.
20053  */
20054 static void handle_response_update(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
20055 {
20056    if (p->options) {
20057       p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
20058    }
20059    if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, SIP_UPDATE, 1)) {
20060       ast_log(LOG_NOTICE, "Failed to authenticate on UPDATE to '%s'\n", get_header(&p->initreq, "From"));
20061    }
20062 }
20063 
20064 static void cc_handle_publish_error(struct sip_pvt *pvt, const int resp, struct sip_request *req, struct sip_epa_entry *epa_entry)
20065 {
20066    struct cc_epa_entry *cc_entry = epa_entry->instance_data;
20067    struct sip_monitor_instance *monitor_instance = ao2_callback(sip_monitor_instances, 0,
20068          find_sip_monitor_instance_by_suspension_entry, epa_entry);
20069    const char *min_expires;
20070 
20071    if (!monitor_instance) {
20072       ast_log(LOG_WARNING, "Can't find monitor_instance corresponding to epa_entry %p.\n", epa_entry);
20073       return;
20074    }
20075 
20076    if (resp != 423) {
20077       ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
20078             "Received error response to our PUBLISH");
20079       ao2_ref(monitor_instance, -1);
20080       return;
20081    }
20082 
20083    /* Allrighty, the other end doesn't like our Expires value. They think it's
20084     * too small, so let's see if they've provided a more sensible value. If they
20085     * haven't, then we'll just double our Expires value and see if they like that
20086     * instead.
20087     *
20088     * XXX Ideally this logic could be placed into its own function so that SUBSCRIBE,
20089     * PUBLISH, and REGISTER could all benefit from the same shared code.
20090     */
20091    min_expires = get_header(req, "Min-Expires");
20092    if (ast_strlen_zero(min_expires)) {
20093       pvt->expiry *= 2;
20094       if (pvt->expiry < 0) {
20095          /* You dork! You overflowed! */
20096          ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
20097                "PUBLISH expiry overflowed");
20098          ao2_ref(monitor_instance, -1);
20099          return;
20100       }
20101    } else if (sscanf(min_expires, "%d", &pvt->expiry) != 1) {
20102       ast_cc_monitor_failed(cc_entry->core_id, monitor_instance->device_name,
20103             "Min-Expires has non-numeric value");
20104       ao2_ref(monitor_instance, -1);
20105       return;
20106    }
20107    /* At this point, we have most certainly changed pvt->expiry, so try transmitting
20108     * again
20109     */
20110    transmit_invite(pvt, SIP_PUBLISH, FALSE, 0, NULL);
20111    ao2_ref(monitor_instance, -1);
20112 }
20113 
20114 static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
20115 {
20116    struct sip_epa_entry *epa_entry = p->epa_entry;
20117    const char *etag = get_header(req, "Sip-ETag");
20118 
20119    ast_assert(epa_entry != NULL);
20120 
20121    if (resp == 401 || resp == 407) {
20122       ast_string_field_set(p, theirtag, NULL);
20123       if (p->options) {
20124          p->options->auth_type = (resp == 401 ? WWW_AUTH : PROXY_AUTH);
20125       }
20126       if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp, SIP_PUBLISH, 0)) {
20127          ast_log(LOG_NOTICE, "Failed to authenticate on PUBLISH to '%s'\n", get_header(&p->initreq, "From"));
20128          pvt_set_needdestroy(p, "Failed to authenticate on PUBLISH");
20129          sip_alreadygone(p);
20130       }
20131       return;
20132    }
20133 
20134    if (resp == 501 || resp == 405) {
20135       mark_method_unallowed(&p->allowed_methods, SIP_PUBLISH);
20136    }
20137 
20138    if (resp == 200) {
20139       p->authtries = 0;
20140       /* If I've read section 6, item 6 of RFC 3903 correctly,
20141        * an ESC will only generate a new etag when it sends a 200 OK
20142        */
20143       if (!ast_strlen_zero(etag)) {
20144          ast_copy_string(epa_entry->entity_tag, etag, sizeof(epa_entry->entity_tag));
20145       }
20146       /* The nominal case. Everything went well. Everybody is happy.
20147        * Each EPA will have a specific action to take as a result of this
20148        * development, so ... callbacks!
20149        */
20150       if (epa_entry->static_data->handle_ok) {
20151          epa_entry->static_data->handle_ok(p, req, epa_entry);
20152       }
20153    } else {
20154       /* Rather than try to make individual callbacks for each error
20155        * type, there is just a single error callback. The callback
20156        * can distinguish between error messages and do what it needs to
20157        */
20158       if (epa_entry->static_data->handle_error) {
20159          epa_entry->static_data->handle_error(p, resp, req, epa_entry);
20160       }
20161    }
20162 }
20163 
20164 /*!
20165  * \internal
20166  * \brief Set hangup source and cause.
20167  *
20168  * \param p SIP private.
20169  * \param cause Hangup cause to queue.  Zero if no cause.
20170  *
20171  * \pre p and p->owner are locked.
20172  *
20173  * \return Nothing
20174  */
20175 static void sip_queue_hangup_cause(struct sip_pvt *p, int cause)
20176 {
20177    struct ast_channel *owner = p->owner;
20178    const char *name = ast_strdupa(owner->name);
20179 
20180    /* Cannot hold any channel/private locks when calling. */
20181    ast_channel_ref(owner);
20182    ast_channel_unlock(owner);
20183    sip_pvt_unlock(p);
20184    ast_set_hangupsource(owner, name, 0);
20185    if (cause) {
20186       ast_queue_hangup_with_cause(owner, cause);
20187    } else {
20188       ast_queue_hangup(owner);
20189    }
20190    ast_channel_unref(owner);
20191 
20192    /* Relock things. */
20193    owner = sip_pvt_lock_full(p);
20194    if (owner) {
20195       ast_channel_unref(owner);
20196    }
20197 }
20198 
20199 /*! \brief Handle SIP response to INVITE dialogue */
20200 static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
20201 {
20202    int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
20203    int res = 0;
20204    int xmitres = 0;
20205    int reinvite = ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
20206    char *p_hdrval;
20207    int rtn;
20208    struct ast_party_connected_line connected;
20209    struct ast_set_party_connected_line update_connected;
20210 
20211    if (reinvite)
20212       ast_debug(4, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
20213    else
20214       ast_debug(4, "SIP response %d to standard invite\n", resp);
20215 
20216    if (p->alreadygone) { /* This call is already gone */
20217       ast_debug(1, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
20218       return;
20219    }
20220 
20221    /* Acknowledge sequence number - This only happens on INVITE from SIP-call */
20222    /* Don't auto congest anymore since we've gotten something useful back */
20223    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"));
20224 
20225    /* RFC3261 says we must treat every 1xx response (but not 100)
20226       that we don't recognize as if it was 183.
20227    */
20228    if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 181 && resp != 182 && resp != 183)
20229       resp = 183;
20230 
20231    /* Any response between 100 and 199 is PROCEEDING */
20232    if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING)
20233       p->invitestate = INV_PROCEEDING;
20234 
20235    /* Final response, not 200 ? */
20236    if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA ))
20237       p->invitestate = INV_COMPLETED;
20238    
20239    if ((resp >= 200 && reinvite)) {
20240       p->ongoing_reinvite = 0;
20241       if (p->reinviteid > -1) {
20242          AST_SCHED_DEL_UNREF(sched, p->reinviteid, dialog_unref(p, "unref dialog for reinvite timeout because of a final response"));
20243       }
20244    }
20245 
20246    /* Final response, clear out pending invite */
20247    if ((resp == 200 || resp >= 300) && p->pendinginvite && seqno == p->pendinginvite) {
20248       p->pendinginvite = 0;
20249    }
20250 
20251    /* If this is a response to our initial INVITE, we need to set what we can use
20252     * for this peer.
20253     */
20254    if (!reinvite) {
20255       set_pvt_allowed_methods(p, req);
20256    }
20257 
20258    switch (resp) {
20259    case 100:   /* Trying */
20260    case 101:   /* Dialog establishment */
20261       if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
20262          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
20263       check_pendings(p);
20264       break;
20265 
20266    case 180:   /* 180 Ringing */
20267    case 182:       /* 182 Queued */
20268       if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
20269          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
20270       /* Store Route-set from provisional SIP responses so
20271        * early-dialog request can be routed properly
20272        * */
20273       parse_ok_contact(p, req);
20274       if (!reinvite) {
20275          build_route(p, req, 1, resp);
20276       }
20277       if (!req->ignore && p->owner) {
20278          if (get_rpid(p, req)) {
20279             /* Queue a connected line update */
20280             ast_party_connected_line_init(&connected);
20281             memset(&update_connected, 0, sizeof(update_connected));
20282 
20283             update_connected.id.number = 1;
20284             connected.id.number.valid = 1;
20285             connected.id.number.str = (char *) p->cid_num;
20286             connected.id.number.presentation = p->callingpres;
20287 
20288             update_connected.id.name = 1;
20289             connected.id.name.valid = 1;
20290             connected.id.name.str = (char *) p->cid_name;
20291             connected.id.name.presentation = p->callingpres;
20292 
20293             connected.id.tag = (char *) p->cid_tag;
20294             connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
20295             ast_channel_queue_connected_line_update(p->owner, &connected,
20296                &update_connected);
20297          }
20298          sip_handle_cc(p, req, AST_CC_CCNR);
20299          ast_queue_control(p->owner, AST_CONTROL_RINGING);
20300          if (p->owner->_state != AST_STATE_UP) {
20301             ast_setstate(p->owner, AST_STATE_RINGING);
20302          }
20303       }
20304       if (find_sdp(req)) {
20305          if (p->invitestate != INV_CANCELLED)
20306             p->invitestate = INV_EARLY_MEDIA;
20307          res = process_sdp(p, req, SDP_T38_NONE);
20308          if (!req->ignore && p->owner) {
20309             /* Queue a progress frame only if we have SDP in 180 or 182 */
20310             ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
20311          }
20312          ast_rtp_instance_activate(p->rtp);
20313       }
20314       check_pendings(p);
20315       break;
20316 
20317    case 181:   /* Call Is Being Forwarded */
20318       if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
20319          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
20320       /* Store Route-set from provisional SIP responses so
20321        * early-dialog request can be routed properly
20322        * */
20323       parse_ok_contact(p, req);
20324       if (!reinvite) {
20325          build_route(p, req, 1, resp);
20326       }
20327       if (!req->ignore && p->owner) {
20328          struct ast_party_redirecting redirecting;
20329          struct ast_set_party_redirecting update_redirecting;
20330 
20331          ast_party_redirecting_init(&redirecting);
20332          memset(&update_redirecting, 0, sizeof(update_redirecting));
20333          change_redirecting_information(p, req, &redirecting, &update_redirecting,
20334             FALSE);
20335          ast_channel_queue_redirecting_update(p->owner, &redirecting,
20336             &update_redirecting);
20337          ast_party_redirecting_free(&redirecting);
20338          sip_handle_cc(p, req, AST_CC_CCNR);
20339       }
20340       check_pendings(p);
20341       break;
20342 
20343    case 183:   /* Session progress */
20344       if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
20345          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
20346       /* Store Route-set from provisional SIP responses so
20347        * early-dialog request can be routed properly
20348        * */
20349       parse_ok_contact(p, req);
20350       if (!reinvite) {
20351          build_route(p, req, 1, resp);
20352       }
20353       if (!req->ignore && p->owner) {
20354          if (get_rpid(p, req)) {
20355             /* Queue a connected line update */
20356             ast_party_connected_line_init(&connected);
20357             memset(&update_connected, 0, sizeof(update_connected));
20358 
20359             update_connected.id.number = 1;
20360             connected.id.number.valid = 1;
20361             connected.id.number.str = (char *) p->cid_num;
20362             connected.id.number.presentation = p->callingpres;
20363 
20364             update_connected.id.name = 1;
20365             connected.id.name.valid = 1;
20366             connected.id.name.str = (char *) p->cid_name;
20367             connected.id.name.presentation = p->callingpres;
20368 
20369             connected.id.tag = (char *) p->cid_tag;
20370             connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
20371             ast_channel_queue_connected_line_update(p->owner, &connected,
20372                &update_connected);
20373          }
20374          sip_handle_cc(p, req, AST_CC_CCNR);
20375       }
20376       if (find_sdp(req)) {
20377          if (p->invitestate != INV_CANCELLED)
20378             p->invitestate = INV_EARLY_MEDIA;
20379          res = process_sdp(p, req, SDP_T38_NONE);
20380          if (!req->ignore && p->owner) {
20381             /* Queue a progress frame */
20382             ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
20383          }
20384          ast_rtp_instance_activate(p->rtp);
20385       } else {
20386          /* Alcatel PBXs are known to send 183s with no SDP after sending
20387           * a 100 Trying response. We're just going to treat this sort of thing
20388           * the same as we would treat a 180 Ringing
20389           */
20390          if (!req->ignore && p->owner) {
20391             ast_queue_control(p->owner, AST_CONTROL_RINGING);
20392          }
20393       }
20394       check_pendings(p);
20395       break;
20396 
20397    case 200:   /* 200 OK on invite - someone's answering our call */
20398       if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
20399          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
20400       p->authtries = 0;
20401       if (find_sdp(req)) {
20402          if ((res = process_sdp(p, req, SDP_T38_ACCEPT)) && !req->ignore)
20403             if (!reinvite) {
20404                /* This 200 OK's SDP is not acceptable, so we need to ack, then hangup */
20405                /* For re-invites, we try to recover */
20406                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
20407             }
20408          ast_rtp_instance_activate(p->rtp);
20409       }
20410 
20411       if (!req->ignore && p->owner) {
20412          int rpid_changed;
20413 
20414          rpid_changed = get_rpid(p, req);
20415          if (rpid_changed || !reinvite) {
20416             /* Queue a connected line update */
20417             ast_party_connected_line_init(&connected);
20418             memset(&update_connected, 0, sizeof(update_connected));
20419             if (rpid_changed
20420                || !ast_strlen_zero(p->cid_num)
20421                || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
20422                update_connected.id.number = 1;
20423                connected.id.number.valid = 1;
20424                connected.id.number.str = (char *) p->cid_num;
20425                connected.id.number.presentation = p->callingpres;
20426             }
20427             if (rpid_changed
20428                || !ast_strlen_zero(p->cid_name)
20429                || (p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED) {
20430                update_connected.id.name = 1;
20431                connected.id.name.valid = 1;
20432                connected.id.name.str = (char *) p->cid_name;
20433                connected.id.name.presentation = p->callingpres;
20434             }
20435             if (update_connected.id.number || update_connected.id.name) {
20436                connected.id.tag = (char *) p->cid_tag;
20437                connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
20438                ast_channel_queue_connected_line_update(p->owner, &connected,
20439                   &update_connected);
20440             }
20441          }
20442       }
20443 
20444       /* Parse contact header for continued conversation */
20445       /* When we get 200 OK, we know which device (and IP) to contact for this call */
20446       /* This is important when we have a SIP proxy between us and the phone */
20447       if (outgoing) {
20448          update_call_counter(p, DEC_CALL_RINGING);
20449          parse_ok_contact(p, req);
20450          /* Save Record-Route for any later requests we make on this dialogue */
20451          if (!reinvite) {
20452             build_route(p, req, 1, resp);
20453          }
20454          if(set_address_from_contact(p)) {
20455             /* Bad contact - we don't know how to reach this device */
20456             /* We need to ACK, but then send a bye */
20457             if (!p->route && !req->ignore)
20458                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
20459          }
20460 
20461       }
20462 
20463       if (!req->ignore && p->owner) {
20464          if (!reinvite) {
20465             ast_queue_control(p->owner, AST_CONTROL_ANSWER);
20466             if (sip_cfg.callevents)
20467                manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
20468                   "Channel: %s\r\nChanneltype: %s\r\nUniqueid: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
20469                   p->owner->name, "SIP", p->owner->uniqueid, p->callid, p->fullcontact, p->peername);
20470          } else { /* RE-invite */
20471             if (p->t38.state == T38_DISABLED) {
20472                ast_queue_control(p->owner, AST_CONTROL_UPDATE_RTP_PEER);
20473             } else {
20474                ast_queue_frame(p->owner, &ast_null_frame);
20475             }
20476          }
20477       } else {
20478           /* It's possible we're getting an 200 OK after we've tried to disconnect
20479               by sending CANCEL */
20480          /* First send ACK, then send bye */
20481          if (!req->ignore)
20482             ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
20483       }
20484 
20485       /* Check for Session-Timers related headers */
20486       if (st_get_mode(p, 0) != SESSION_TIMER_MODE_REFUSE && p->outgoing_call == TRUE && !reinvite) {
20487          p_hdrval = (char*)get_header(req, "Session-Expires");
20488          if (!ast_strlen_zero(p_hdrval)) {
20489             /* UAS supports Session-Timers */
20490             enum st_refresher_param st_ref_param;
20491             int tmp_st_interval = 0;
20492             rtn = parse_session_expires(p_hdrval, &tmp_st_interval, &st_ref_param);
20493             if (rtn != 0) {
20494                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
20495             }
20496             if (st_ref_param == SESSION_TIMER_REFRESHER_PARAM_UAC) {
20497                p->stimer->st_ref = SESSION_TIMER_REFRESHER_US;
20498             } else if (st_ref_param == SESSION_TIMER_REFRESHER_PARAM_UAS) {
20499                p->stimer->st_ref = SESSION_TIMER_REFRESHER_THEM;
20500             } else {
20501                ast_log(LOG_WARNING, "Unknown refresher on %s\n", p->callid);
20502             }
20503             if (tmp_st_interval) {
20504                p->stimer->st_interval = tmp_st_interval;
20505             }
20506             p->stimer->st_active = TRUE;
20507             p->stimer->st_active_peer_ua = TRUE;
20508             start_session_timer(p);
20509          } else {
20510             /* UAS doesn't support Session-Timers */
20511             if (st_get_mode(p, 0) == SESSION_TIMER_MODE_ORIGINATE) {
20512                p->stimer->st_ref = SESSION_TIMER_REFRESHER_US;
20513                p->stimer->st_active_peer_ua = FALSE;
20514                start_session_timer(p);
20515             }
20516          }
20517       }
20518 
20519 
20520       /* If I understand this right, the branch is different for a non-200 ACK only */
20521       p->invitestate = INV_TERMINATED;
20522       ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
20523       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
20524       check_pendings(p);
20525       break;
20526 
20527    case 407: /* Proxy authentication */
20528    case 401: /* Www auth */
20529       /* First we ACK */
20530       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20531       if (p->options)
20532          p->options->auth_type = resp;
20533 
20534       /* Then we AUTH */
20535       ast_string_field_set(p, theirtag, NULL);  /* forget their old tag, so we don't match tags when getting response */
20536       if (!req->ignore) {
20537          if (p->authtries < MAX_AUTHTRIES)
20538             p->invitestate = INV_CALLING;
20539          if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, SIP_INVITE, 1)) {
20540             ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
20541             pvt_set_needdestroy(p, "failed to authenticate on INVITE");
20542             sip_alreadygone(p);
20543             if (p->owner)
20544                ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
20545          }
20546       }
20547       break;
20548 
20549    case 403: /* Forbidden */
20550       /* First we ACK */
20551       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20552       ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", get_header(&p->initreq, "From"));
20553       if (!req->ignore && p->owner) {
20554          sip_queue_hangup_cause(p, hangup_sip2cause(resp));
20555       }
20556       break;
20557 
20558    case 404: /* Not found */
20559       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20560       if (p->owner && !req->ignore) {
20561          sip_queue_hangup_cause(p, hangup_sip2cause(resp));
20562       }
20563       break;
20564 
20565    case 481: /* Call leg does not exist */
20566       /* Could be REFER caused INVITE with replaces */
20567       ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
20568       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20569       if (p->owner) {
20570          ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
20571       }
20572       break;
20573 
20574    case 422: /* Session-Timers: Session interval too small */
20575       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20576       ast_string_field_set(p, theirtag, NULL);
20577       proc_422_rsp(p, req);
20578       break;
20579 
20580    case 428: /* Use identity header - rfc 4474 - not supported by Asterisk yet */
20581       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20582       append_history(p, "Identity", "SIP identity is required. Not supported by Asterisk.");
20583       ast_log(LOG_WARNING, "SIP identity required by proxy. SIP dialog '%s'. Giving up.\n", p->callid);
20584       if (p->owner && !req->ignore) {
20585          ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
20586       }
20587       break;
20588 
20589    case 487: /* Cancelled transaction */
20590       /* We have sent CANCEL on an outbound INVITE
20591          This transaction is already scheduled to be killed by sip_hangup().
20592       */
20593       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20594       if (p->owner && !req->ignore) {
20595          ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_CLEARING);
20596          append_history(p, "Hangup", "Got 487 on CANCEL request from us. Queued AST hangup request");
20597       } else if (!req->ignore) {
20598          update_call_counter(p, DEC_CALL_LIMIT);
20599          append_history(p, "Hangup", "Got 487 on CANCEL request from us on call without owner. Killing this dialog.");
20600       }
20601       check_pendings(p);
20602       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20603       break;
20604    case 415: /* Unsupported media type */
20605    case 488: /* Not acceptable here */
20606    case 606: /* Not Acceptable */
20607       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20608       if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
20609          change_t38_state(p, T38_DISABLED);
20610          /* Try to reset RTP timers */
20611          //ast_rtp_set_rtptimers_onhold(p->rtp);
20612 
20613          /* Trigger a reinvite back to audio */
20614          transmit_reinvite_with_sdp(p, FALSE, FALSE);
20615       } else {
20616          /* We can't set up this call, so give up */
20617          if (p->owner && !req->ignore) {
20618             ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
20619          }
20620       }
20621       break;
20622    case 491: /* Pending */
20623       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20624       if (p->owner && !req->ignore) {
20625          if (p->owner->_state != AST_STATE_UP) {
20626             ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
20627          } else {
20628             /* This is a re-invite that failed. */
20629             /* Reset the flag after a while
20630              */
20631             int wait;
20632             /* RFC 3261, if owner of call, wait between 2.1 to 4 seconds,
20633              * if not owner of call, wait 0 to 2 seconds */
20634             if (p->outgoing_call) {
20635                wait = 2100 + ast_random() % 2000;
20636             } else {
20637                wait = ast_random() % 2000;
20638             }
20639             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."));
20640             ast_log(LOG_WARNING, "just did sched_add waitid(%d) for sip_reinvite_retry for dialog %s in handle_response_invite\n", p->waitid, p->callid);
20641             ast_debug(2, "Reinvite race. Waiting %d secs before retry\n", wait);
20642          }
20643       }
20644       break;
20645 
20646    case 408: /* Request timeout */
20647    case 405: /* Not allowed */
20648    case 501: /* Not implemented */
20649       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
20650       if (p->owner) {
20651          ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
20652       }
20653       break;
20654    }
20655    if (xmitres == XMIT_ERROR)
20656       ast_log(LOG_WARNING, "Could not transmit message in dialog %s\n", p->callid);
20657 }
20658 
20659 /* \brief Handle SIP response in NOTIFY transaction
20660        We've sent a NOTIFY, now handle responses to it
20661   */
20662 static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
20663 {
20664    switch (resp) {
20665    case 200:   /* Notify accepted */
20666       /* They got the notify, this is the end */
20667       if (p->owner) {
20668          if (p->refer) {
20669             ast_log(LOG_NOTICE, "Got OK on REFER Notify message\n");
20670          } else {
20671             ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", p->owner->name);
20672          }
20673       } else {
20674          if (p->subscribed == NONE && !p->refer) {
20675             ast_debug(4, "Got 200 accepted on NOTIFY %s\n", p->callid);
20676             pvt_set_needdestroy(p, "received 200 response");
20677          }
20678          if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
20679             /* Ready to send the next state we have on queue */
20680             ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
20681             cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
20682          }
20683       }
20684       break;
20685    case 401:   /* Not www-authorized on SIP method */
20686    case 407:   /* Proxy auth */
20687       if (!p->notify) {
20688          break; /* Only device notify can use NOTIFY auth */
20689       }
20690       ast_string_field_set(p, theirtag, NULL);
20691       if (ast_strlen_zero(p->authname)) {
20692          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));
20693          pvt_set_needdestroy(p, "unable to authenticate NOTIFY");
20694       }
20695       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_NOTIFY, 0)) {
20696          ast_log(LOG_NOTICE, "Failed to authenticate on NOTIFY to '%s'\n", get_header(&p->initreq, "From"));
20697          pvt_set_needdestroy(p, "failed to authenticate NOTIFY");
20698       }
20699       break;
20700    case 481: /* Call leg does not exist */
20701       pvt_set_needdestroy(p, "Received 481 response for NOTIFY");
20702       break;
20703    }
20704 }
20705 
20706 /* \brief Handle SIP response in SUBSCRIBE transaction */
20707 static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
20708 {
20709    if (p->subscribed == CALL_COMPLETION) {
20710       struct sip_monitor_instance *monitor_instance;
20711 
20712       if (resp < 300) {
20713          return;
20714       }
20715 
20716       /* Final failure response received. */
20717       monitor_instance = ao2_callback(sip_monitor_instances, 0,
20718          find_sip_monitor_instance_by_subscription_pvt, p);
20719       if (monitor_instance) {
20720          ast_cc_monitor_failed(monitor_instance->core_id,
20721             monitor_instance->device_name,
20722             "Received error response to our SUBSCRIBE");
20723       }
20724       return;
20725    }
20726 
20727    if (p->subscribed != MWI_NOTIFICATION) {
20728       return;
20729    }
20730    if (!p->mwi) {
20731       return;
20732    }
20733 
20734    switch (resp) {
20735    case 200: /* Subscription accepted */
20736       ast_debug(3, "Got 200 OK on subscription for MWI\n");
20737       set_pvt_allowed_methods(p, req);
20738       if (p->options) {
20739          if (p->options->outboundproxy) {
20740             ao2_ref(p->options->outboundproxy, -1);
20741          }
20742          ast_free(p->options);
20743          p->options = NULL;
20744       }
20745       p->mwi->subscribed = 1;
20746       if ((p->mwi->resub = ast_sched_add(sched, mwi_expiry * 1000, sip_subscribe_mwi_do, ASTOBJ_REF(p->mwi))) < 0) {
20747          ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
20748       }
20749       break;
20750    case 401:
20751    case 407:
20752       ast_string_field_set(p, theirtag, NULL);
20753       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_SUBSCRIBE, 0)) {
20754          ast_log(LOG_NOTICE, "Failed to authenticate on SUBSCRIBE to '%s'\n", get_header(&p->initreq, "From"));
20755          p->mwi->call = NULL;
20756          ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
20757          pvt_set_needdestroy(p, "failed to authenticate SUBSCRIBE");
20758       }
20759       break;
20760    case 403:
20761       transmit_response_with_date(p, "200 OK", req);
20762       ast_log(LOG_WARNING, "Authentication failed while trying to subscribe for MWI.\n");
20763       p->mwi->call = NULL;
20764       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
20765       pvt_set_needdestroy(p, "received 403 response");
20766       sip_alreadygone(p);
20767       break;
20768    case 404:
20769       ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that a mailbox may not have been configured.\n");
20770       p->mwi->call = NULL;
20771       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
20772       pvt_set_needdestroy(p, "received 404 response");
20773       break;
20774    case 481:
20775       ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side said that our dialog did not exist.\n");
20776       p->mwi->call = NULL;
20777       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
20778       pvt_set_needdestroy(p, "received 481 response");
20779       break;
20780    case 500:
20781    case 501:
20782       ast_log(LOG_WARNING, "Subscription failed for MWI. The remote side may have suffered a heart attack.\n");
20783       p->mwi->call = NULL;
20784       ASTOBJ_UNREF(p->mwi, sip_subscribe_mwi_destroy);
20785       pvt_set_needdestroy(p, "received 500/501 response");
20786       break;
20787    }
20788 }
20789 
20790 /* \brief Handle SIP response in REFER transaction
20791    We've sent a REFER, now handle responses to it
20792   */
20793 static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
20794 {
20795    enum ast_control_transfer message = AST_TRANSFER_FAILED;
20796 
20797    /* If no refer structure exists, then do nothing */
20798    if (!p->refer)
20799       return;
20800 
20801    switch (resp) {
20802    case 202:   /* Transfer accepted */
20803       /* We need  to do something here */
20804       /* The transferee is now sending INVITE to target */
20805       p->refer->status = REFER_ACCEPTED;
20806       /* Now wait for next message */
20807       ast_debug(3, "Got 202 accepted on transfer\n");
20808       /* We should hang along, waiting for NOTIFY's here */
20809       break;
20810 
20811    case 401:   /* Not www-authorized on SIP method */
20812    case 407:   /* Proxy auth */
20813       if (ast_strlen_zero(p->authname)) {
20814          ast_log(LOG_WARNING, "Asked to authenticate REFER to %s but we have no matching peer or realm auth!\n",
20815             ast_sockaddr_stringify(&p->recv));
20816          if (p->owner) {
20817             ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
20818          }
20819          pvt_set_needdestroy(p, "unable to authenticate REFER");
20820       }
20821       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_REFER, 0)) {
20822          ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", get_header(&p->initreq, "From"));
20823          p->refer->status = REFER_NOAUTH;
20824          if (p->owner) {
20825             ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
20826          }
20827          pvt_set_needdestroy(p, "failed to authenticate REFER");
20828       }
20829       break;
20830    
20831    case 405:   /* Method not allowed */
20832       /* Return to the current call onhold */
20833       /* Status flag needed to be reset */
20834       ast_log(LOG_NOTICE, "SIP transfer to %s failed, REFER not allowed. \n", p->refer->refer_to);
20835       pvt_set_needdestroy(p, "received 405 response");
20836       p->refer->status = REFER_FAILED;
20837       if (p->owner) {
20838          ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
20839       }
20840       break;
20841 
20842    case 481: /* Call leg does not exist */
20843 
20844       /* A transfer with Replaces did not work */
20845       /* OEJ: We should Set flag, cancel the REFER, go back
20846       to original call - but right now we can't */
20847       ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
20848       if (p->owner)
20849          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
20850       pvt_set_needdestroy(p, "received 481 response");
20851       break;
20852 
20853    case 500:   /* Server error */
20854    case 501:   /* Method not implemented */
20855       /* Return to the current call onhold */
20856       /* Status flag needed to be reset */
20857       ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
20858       pvt_set_needdestroy(p, "received 500/501 response");
20859       p->refer->status = REFER_FAILED;
20860       if (p->owner) {
20861          ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
20862       }
20863       break;
20864    case 603:   /* Transfer declined */
20865       ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
20866       p->refer->status = REFER_FAILED;
20867       pvt_set_needdestroy(p, "received 603 response");
20868       if (p->owner) {
20869          ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
20870       }
20871       break;
20872    default:
20873       /* We should treat unrecognized 9xx as 900.  400 is actually
20874          specified as a possible response, but any 4-6xx is 
20875          theoretically possible. */
20876 
20877       if (resp < 299) { /* 1xx cases don't get here */
20878          ast_log(LOG_WARNING, "SIP transfer to %s had unxpected 2xx response (%d), confusion is possible. \n", p->refer->refer_to, resp);
20879       } else {
20880          ast_log(LOG_WARNING, "SIP transfer to %s with response (%d). \n", p->refer->refer_to, resp);
20881       }
20882 
20883       p->refer->status = REFER_FAILED;
20884       pvt_set_needdestroy(p, "received failure response");
20885       if (p->owner) {
20886          ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
20887       }
20888       break;
20889    }
20890 }
20891 
20892 /*! \brief Handle responses on REGISTER to services */
20893 static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
20894 {
20895    int expires, expires_ms;
20896    struct sip_registry *r;
20897    r=p->registry;
20898    
20899    switch (resp) {
20900    case 401:   /* Unauthorized */
20901       if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
20902          ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
20903          pvt_set_needdestroy(p, "failed to authenticate REGISTER");
20904       }
20905       break;
20906    case 403:   /* Forbidden */
20907       ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
20908       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 403"));
20909       r->regstate = REG_STATE_NOAUTH;
20910       pvt_set_needdestroy(p, "received 403 response");
20911       break;
20912    case 404:   /* Not found */
20913       ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username, p->registry->hostname);
20914       pvt_set_needdestroy(p, "received 404 response");
20915       if (r->call)
20916          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 404");
20917       r->regstate = REG_STATE_REJECTED;
20918       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 404"));
20919       break;
20920    case 407:   /* Proxy auth */
20921       if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
20922          ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
20923          pvt_set_needdestroy(p, "failed to authenticate REGISTER");
20924       }
20925       break;
20926    case 408:   /* Request timeout */
20927       /* Got a timeout response, so reset the counter of failed responses */
20928       if (r) {
20929          r->regattempts = 0;
20930       } else {
20931          ast_log(LOG_WARNING, "Got a 408 response to our REGISTER on call %s after we had destroyed the registry object\n", p->callid);
20932       }
20933       break;
20934    case 423:   /* Interval too brief */
20935       r->expiry = atoi(get_header(req, "Min-Expires"));
20936       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);
20937       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 423"));
20938       if (r->call) {
20939          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 423");
20940          pvt_set_needdestroy(p, "received 423 response");
20941       }
20942       if (r->expiry > max_expiry) {
20943          ast_log(LOG_WARNING, "Required expiration time from %s@%s is too high, giving up\n", p->registry->username, p->registry->hostname);
20944          r->expiry = r->configured_expiry;
20945          r->regstate = REG_STATE_REJECTED;
20946       } else {
20947          r->regstate = REG_STATE_UNREGISTERED;
20948          transmit_register(r, SIP_REGISTER, NULL, NULL);
20949       }
20950       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));
20951       break;
20952    case 479:   /* SER: Not able to process the URI - address is wrong in register*/
20953       ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username, p->registry->hostname);
20954       pvt_set_needdestroy(p, "received 479 response");
20955       if (r->call)
20956          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 479");
20957       r->regstate = REG_STATE_REJECTED;
20958       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 479"));
20959       break;
20960    case 200:   /* 200 OK */
20961       if (!r) {
20962          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));
20963          pvt_set_needdestroy(p, "received erroneous 200 response");
20964          return 0;
20965       }
20966       
20967       r->regstate = REG_STATE_REGISTERED;
20968       r->regtime = ast_tvnow();     /* Reset time of last successful registration */
20969       manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: SIP\r\nDomain: %s\r\nStatus: %s\r\n", r->hostname, regstate2str(r->regstate));
20970       r->regattempts = 0;
20971       ast_debug(1, "Registration successful\n");
20972       if (r->timeout > -1) {
20973          ast_debug(1, "Cancelling timeout %d\n", r->timeout);
20974       }
20975       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 200"));
20976       if (r->call)
20977          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 200");
20978       p->registry = registry_unref(p->registry, "unref registry entry p->registry");
20979       /* Let this one hang around until we have all the responses */
20980       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20981       /* p->needdestroy = 1; */
20982       
20983       /* set us up for re-registering
20984        * figure out how long we got registered for
20985        * according to section 6.13 of RFC, contact headers override
20986        * expires headers, so check those first */
20987       expires = 0;
20988 
20989       /* XXX todo: try to save the extra call */
20990       if (!ast_strlen_zero(get_header(req, "Contact"))) {
20991          const char *contact = NULL;
20992          const char *tmptmp = NULL;
20993          int start = 0;
20994          for(;;) {
20995             contact = __get_header(req, "Contact", &start);
20996             /* this loop ensures we get a contact header about our register request */
20997             if(!ast_strlen_zero(contact)) {
20998                if( (tmptmp=strstr(contact, p->our_contact))) {
20999                   contact=tmptmp;
21000                   break;
21001                }
21002             } else
21003                break;
21004          }
21005          tmptmp = strcasestr(contact, "expires=");
21006          if (tmptmp) {
21007             if (sscanf(tmptmp + 8, "%30d;", &expires) != 1)
21008                expires = 0;
21009          }
21010          
21011       }
21012       if (!expires)
21013          expires=atoi(get_header(req, "expires"));
21014       if (!expires)
21015          expires=default_expiry;
21016       
21017       expires_ms = expires * 1000;
21018       if (expires <= EXPIRY_GUARD_LIMIT)
21019          expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT), EXPIRY_GUARD_MIN);
21020       else
21021          expires_ms -= EXPIRY_GUARD_SECS * 1000;
21022       if (sipdebug)
21023          ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000);
21024       
21025       r->refresh= (int) expires_ms / 1000;
21026       
21027       /* Schedule re-registration before we expire */
21028       AST_SCHED_REPLACE_UNREF(r->expire, sched, expires_ms, sip_reregister, r,
21029                         registry_unref(_data,"unref in REPLACE del fail"),
21030                         registry_unref(r,"unref in REPLACE add fail"),
21031                         registry_addref(r,"The Addition side of REPLACE"));
21032    }
21033    return 1;
21034 }
21035 
21036 /*! \brief Handle qualification responses (OPTIONS) */
21037 static void handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
21038 {
21039    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! */
21040    int statechanged, is_reachable, was_reachable;
21041    int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);
21042 
21043    /*
21044     * Compute the response time to a ping (goes in peer->lastms.)
21045     * -1 means did not respond, 0 means unknown,
21046     * 1..maxms is a valid response, >maxms means late response.
21047     */
21048    if (pingtime < 1) {  /* zero = unknown, so round up to 1 */
21049       pingtime = 1;
21050    }
21051 
21052    if (!peer->maxms) { /* this should never happens */
21053       pvt_set_needdestroy(p, "got OPTIONS response but qualify is not enabled");
21054       return;
21055    }
21056 
21057    /* Now determine new state and whether it has changed.
21058     * Use some helper variables to simplify the writing
21059     * of the expressions.
21060     */
21061    was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
21062    is_reachable = pingtime <= peer->maxms;
21063    statechanged = peer->lastms == 0 /* yes, unknown before */
21064       || was_reachable != is_reachable;
21065 
21066    peer->lastms = pingtime;
21067    peer->call = dialog_unref(peer->call, "unref dialog peer->call");
21068    if (statechanged) {
21069       const char *s = is_reachable ? "Reachable" : "Lagged";
21070       char str_lastms[20];
21071       snprintf(str_lastms, sizeof(str_lastms), "%d", pingtime);
21072 
21073       ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
21074          peer->name, s, pingtime, peer->maxms);
21075       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
21076       if (sip_cfg.peer_rtupdate) {
21077          ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", str_lastms, SENTINEL);
21078       }
21079       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
21080          "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
21081          peer->name, s, pingtime);
21082       if (is_reachable && sip_cfg.regextenonqualify)
21083          register_peer_exten(peer, TRUE);
21084    }
21085 
21086    pvt_set_needdestroy(p, "got OPTIONS response");
21087 
21088    /* Try again eventually */
21089    AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
21090          is_reachable ? peer->qualifyfreq : DEFAULT_FREQ_NOTOK,
21091          sip_poke_peer_s, peer,
21092          unref_peer(_data, "removing poke peer ref"),
21093          unref_peer(peer, "removing poke peer ref"),
21094          ref_peer(peer, "adding poke peer ref"));
21095 }
21096 
21097 /*!
21098  * \internal
21099  * \brief Handle responses to INFO messages
21100  *
21101  * \note The INFO method MUST NOT change the state of calls or
21102  * related sessions (RFC 2976).
21103  */
21104 static void handle_response_info(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
21105 {
21106    int sipmethod = SIP_INFO;
21107 
21108    switch (resp) {
21109    case 401: /* Not www-authorized on SIP method */
21110    case 407: /* Proxy auth required */
21111       ast_log(LOG_WARNING, "Host '%s' requests authentication (%d) for '%s'\n",
21112          ast_sockaddr_stringify(&p->sa), resp, sip_methods[sipmethod].text);
21113       break;
21114    case 405: /* Method not allowed */
21115    case 501: /* Not Implemented */
21116       mark_method_unallowed(&p->allowed_methods, sipmethod);
21117       if (p->relatedpeer) {
21118          mark_method_allowed(&p->relatedpeer->disallowed_methods, sipmethod);
21119       }
21120       ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n",
21121          ast_sockaddr_stringify(&p->sa), sip_methods[sipmethod].text);
21122       break;
21123    default:
21124       if (300 <= resp && resp < 700) {
21125          ast_verb(3, "Got SIP %s response %d \"%s\" back from host '%s'\n",
21126             sip_methods[sipmethod].text, resp, rest, ast_sockaddr_stringify(&p->sa));
21127       }
21128       break;
21129    }
21130 }
21131 
21132 /*!
21133  * \internal
21134  * \brief Handle responses to MESSAGE messages
21135  *
21136  * \note The MESSAGE method should not change the state of calls
21137  * or related sessions if associated with a dialog. (Implied by
21138  * RFC 3428 Section 2).
21139  */
21140 static void handle_response_message(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
21141 {
21142    int sipmethod = SIP_MESSAGE;
21143    /* Out-of-dialog MESSAGE currently not supported. */
21144    //int in_dialog = ast_test_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21145 
21146    switch (resp) {
21147    case 401: /* Not www-authorized on SIP method */
21148    case 407: /* Proxy auth required */
21149       ast_log(LOG_WARNING, "Host '%s' requests authentication (%d) for '%s'\n",
21150          ast_sockaddr_stringify(&p->sa), resp, sip_methods[sipmethod].text);
21151       break;
21152    case 405: /* Method not allowed */
21153    case 501: /* Not Implemented */
21154       mark_method_unallowed(&p->allowed_methods, sipmethod);
21155       if (p->relatedpeer) {
21156          mark_method_allowed(&p->relatedpeer->disallowed_methods, sipmethod);
21157       }
21158       ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n",
21159          ast_sockaddr_stringify(&p->sa), sip_methods[sipmethod].text);
21160       break;
21161    default:
21162       if (100 <= resp && resp < 200) {
21163          /* Must allow provisional responses for out-of-dialog requests. */
21164       } else if (200 <= resp && resp < 300) {
21165          p->authtries = 0; /* Reset authentication counter */
21166       } else if (300 <= resp && resp < 700) {
21167          ast_verb(3, "Got SIP %s response %d \"%s\" back from host '%s'\n",
21168             sip_methods[sipmethod].text, resp, rest, ast_sockaddr_stringify(&p->sa));
21169       }
21170       break;
21171    }
21172 }
21173 
21174 /*! \brief Immediately stop RTP, VRTP and UDPTL as applicable */
21175 static void stop_media_flows(struct sip_pvt *p)
21176 {
21177    /* Immediately stop RTP, VRTP and UDPTL as applicable */
21178    if (p->rtp)
21179       ast_rtp_instance_stop(p->rtp);
21180    if (p->vrtp)
21181       ast_rtp_instance_stop(p->vrtp);
21182    if (p->trtp)
21183       ast_rtp_instance_stop(p->trtp);
21184    if (p->udptl)
21185       ast_udptl_stop(p->udptl);
21186 }
21187 
21188 /*! \brief Handle SIP response in dialogue
21189    \note only called by handle_incoming */
21190 static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, uint32_t seqno)
21191 {
21192    struct ast_channel *owner;
21193    int sipmethod;
21194    const char *c = get_header(req, "Cseq");
21195    /* 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 */
21196    char *c_copy = ast_strdupa(c);
21197    /* Skip the Cseq and its subsequent spaces */
21198    const char *msg = ast_skip_blanks(ast_skip_nonblanks(c_copy));
21199 
21200    if (!msg)
21201       msg = "";
21202 
21203    sipmethod = find_sip_method(msg);
21204 
21205    owner = p->owner;
21206    if (owner) {
21207       const char *rp = NULL, *rh = NULL;
21208 
21209       owner->hangupcause = 0;
21210       if (ast_test_flag(&p->flags[1], SIP_PAGE2_Q850_REASON) && (rh = get_header(req, "Reason"))) {
21211          rh = ast_skip_blanks(rh);
21212          if (!strncasecmp(rh, "Q.850", 5)) {
21213             rp = strstr(rh, "cause=");
21214             if (rp && sscanf(rp + 6, "%30d", &owner->hangupcause) == 1) {
21215                owner->hangupcause &= 0x7f;
21216                if (req->debug)
21217                   ast_verbose("Using Reason header for cause code: %d\n", owner->hangupcause);
21218             }
21219          }
21220       }
21221 
21222       if (!owner->hangupcause)
21223          owner->hangupcause = hangup_sip2cause(resp);
21224    }
21225 
21226    if (p->socket.type == SIP_TRANSPORT_UDP) {
21227       int ack_res = FALSE;
21228 
21229       /* Acknowledge whatever it is destined for */
21230       if ((resp >= 100) && (resp <= 199)) {
21231          /* NON-INVITE messages do not ack a 1XX response. RFC 3261 section 17.1.2.2 */
21232          if (sipmethod == SIP_INVITE) {
21233             ack_res = __sip_semi_ack(p, seqno, 0, sipmethod);
21234          }
21235       } else {
21236          ack_res = __sip_ack(p, seqno, 0, sipmethod);
21237       }
21238 
21239       if (ack_res == FALSE) {
21240          /* RFC 3261 13.2.2.4 and 17.1.1.2 - We must re-send ACKs to re-transmitted final responses */
21241          if (sipmethod == SIP_INVITE && resp >= 200) {
21242             transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, resp < 300 ? TRUE: FALSE);
21243          }
21244 
21245          append_history(p, "Ignore", "Ignoring this retransmit\n");
21246          return;
21247       }
21248    }
21249 
21250    /* If this is a NOTIFY for a subscription clear the flag that indicates that we have a NOTIFY pending */
21251    if (!p->owner && sipmethod == SIP_NOTIFY && p->pendinginvite) {
21252       p->pendinginvite = 0;
21253    }
21254 
21255    /* Get their tag if we haven't already */
21256    if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
21257       char tag[128];
21258 
21259       gettag(req, "To", tag, sizeof(tag));
21260       ast_string_field_set(p, theirtag, tag);
21261    }
21262    /* This needs to be configurable on a channel/peer level,
21263       not mandatory for all communication. Sadly enough, NAT implementations
21264       are not so stable so we can always rely on these headers.
21265       Temporarily disabled, while waiting for fix.
21266       Fix assigned to Rizzo :-)
21267    */
21268    /* check_via_response(p, req); */
21269 
21270    /* RFC 3261 Section 15 specifies that if we receive a 408 or 481
21271     * in response to a BYE, then we should end the current dialog
21272     * and session.  It is known that at least one phone manufacturer
21273     * potentially will send a 404 in response to a BYE, so we'll be
21274     * liberal in what we accept and end the dialog and session if we
21275     * receive any of those responses to a BYE.
21276     */
21277    if ((resp == 404 || resp == 408 || resp == 481) && sipmethod == SIP_BYE) {
21278       pvt_set_needdestroy(p, "received 4XX response to a BYE");
21279       return;
21280    }
21281 
21282    if (p->relatedpeer && sipmethod == SIP_OPTIONS) {
21283       /* We don't really care what the response is, just that it replied back.
21284          Well, as long as it's not a 100 response...  since we might
21285          need to hang around for something more "definitive" */
21286       if (resp != 100)
21287          handle_response_peerpoke(p, resp, req);
21288    } else if (sipmethod == SIP_REFER && resp >= 200) {
21289       handle_response_refer(p, resp, rest, req, seqno);
21290    } else if (sipmethod == SIP_PUBLISH) {
21291       /* SIP PUBLISH transcends this morass of doodoo and instead
21292        * we just always call the response handler. Good gravy!
21293        */
21294       handle_response_publish(p, resp, rest, req, seqno);
21295    } else if (sipmethod == SIP_INFO) {
21296       /* More good gravy! */
21297       handle_response_info(p, resp, rest, req, seqno);
21298    } else if (sipmethod == SIP_MESSAGE) {
21299       /* More good gravy! */
21300       handle_response_message(p, resp, rest, req, seqno);
21301    } else if (sipmethod == SIP_NOTIFY) {
21302       /* The gravy train continues to roll */
21303       handle_response_notify(p, resp, rest, req, seqno);
21304    } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
21305       switch(resp) {
21306       case 100:   /* 100 Trying */
21307       case 101:   /* 101 Dialog establishment */
21308       case 183:   /* 183 Session Progress */
21309       case 180:   /* 180 Ringing */
21310       case 182:   /* 182 Queued */
21311       case 181:   /* 181 Call Is Being Forwarded */
21312          if (sipmethod == SIP_INVITE)
21313             handle_response_invite(p, resp, rest, req, seqno);
21314          break;
21315       case 200:   /* 200 OK */
21316          p->authtries = 0; /* Reset authentication counter */
21317          if (sipmethod == SIP_INVITE) {
21318             handle_response_invite(p, resp, rest, req, seqno);
21319          } else if (sipmethod == SIP_REGISTER) {
21320             handle_response_register(p, resp, rest, req, seqno);
21321          } else if (sipmethod == SIP_SUBSCRIBE) {
21322             ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21323             handle_response_subscribe(p, resp, rest, req, seqno);
21324          } else if (sipmethod == SIP_BYE) {     /* Ok, we're ready to go */
21325             pvt_set_needdestroy(p, "received 200 response");
21326             ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
21327          }
21328          break;
21329       case 401: /* Not www-authorized on SIP method */
21330       case 407: /* Proxy auth required */
21331          if (sipmethod == SIP_INVITE)
21332             handle_response_invite(p, resp, rest, req, seqno);
21333          else if (sipmethod == SIP_SUBSCRIBE)
21334             handle_response_subscribe(p, resp, rest, req, seqno);
21335          else if (p->registry && sipmethod == SIP_REGISTER)
21336             handle_response_register(p, resp, rest, req, seqno);
21337          else if (sipmethod == SIP_UPDATE) {
21338             handle_response_update(p, resp, rest, req, seqno);
21339          } else if (sipmethod == SIP_BYE) {
21340             if (p->options)
21341                p->options->auth_type = resp;
21342             if (ast_strlen_zero(p->authname)) {
21343                ast_log(LOG_WARNING, "Asked to authenticate %s, to %s but we have no matching peer!\n",
21344                      msg, ast_sockaddr_stringify(&p->recv));
21345                pvt_set_needdestroy(p, "unable to authenticate BYE");
21346             } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp,  sipmethod, 0)) {
21347                ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
21348                pvt_set_needdestroy(p, "failed to authenticate BYE");
21349             }
21350          } else {
21351             ast_log(LOG_WARNING, "Got authentication request (%d) on %s to '%s'\n", resp, sip_methods[sipmethod].text, get_header(req, "To"));
21352             pvt_set_needdestroy(p, "received 407 response");
21353          }
21354          break;
21355       case 403: /* Forbidden - we failed authentication */
21356          if (sipmethod == SIP_INVITE)
21357             handle_response_invite(p, resp, rest, req, seqno);
21358          else if (sipmethod == SIP_SUBSCRIBE)
21359             handle_response_subscribe(p, resp, rest, req, seqno);
21360          else if (p->registry && sipmethod == SIP_REGISTER)
21361             handle_response_register(p, resp, rest, req, seqno);
21362          else {
21363             ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
21364             pvt_set_needdestroy(p, "received 403 response");
21365          }
21366          break;
21367       case 404: /* Not found */
21368          if (p->registry && sipmethod == SIP_REGISTER)
21369             handle_response_register(p, resp, rest, req, seqno);
21370          else if (sipmethod == SIP_INVITE)
21371             handle_response_invite(p, resp, rest, req, seqno);
21372          else if (sipmethod == SIP_SUBSCRIBE)
21373             handle_response_subscribe(p, resp, rest, req, seqno);
21374          else if (owner)
21375             ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
21376          break;
21377       case 423: /* Interval too brief */
21378          if (sipmethod == SIP_REGISTER)
21379             handle_response_register(p, resp, rest, req, seqno);
21380          break;
21381       case 408: /* Request timeout - terminate dialog */
21382          if (sipmethod == SIP_INVITE)
21383             handle_response_invite(p, resp, rest, req, seqno);
21384          else if (sipmethod == SIP_REGISTER)
21385             handle_response_register(p, resp, rest, req, seqno);
21386          else if (sipmethod == SIP_BYE) {
21387             pvt_set_needdestroy(p, "received 408 response");
21388             ast_debug(4, "Got timeout on bye. Thanks for the answer. Now, kill this call\n");
21389          } else {
21390             if (owner)
21391                ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
21392             pvt_set_needdestroy(p, "received 408 response");
21393          }
21394          break;
21395 
21396       case 428:
21397       case 422: /* Session-Timers: Session Interval Too Small */
21398          if (sipmethod == SIP_INVITE) {
21399             handle_response_invite(p, resp, rest, req, seqno);
21400          }
21401          break;
21402 
21403       case 481: /* Call leg does not exist */
21404          if (sipmethod == SIP_INVITE) {
21405             handle_response_invite(p, resp, rest, req, seqno);
21406          } else if (sipmethod == SIP_SUBSCRIBE) {
21407             handle_response_subscribe(p, resp, rest, req, seqno);
21408          } else if (sipmethod == SIP_BYE) {
21409             /* The other side has no transaction to bye,
21410             just assume it's all right then */
21411             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
21412          } else if (sipmethod == SIP_CANCEL) {
21413             /* The other side has no transaction to cancel,
21414             just assume it's all right then */
21415             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
21416          } else {
21417             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
21418             /* Guessing that this is not an important request */
21419          }
21420          break;
21421       case 487:
21422          if (sipmethod == SIP_INVITE)
21423             handle_response_invite(p, resp, rest, req, seqno);
21424          break;
21425       case 415: /* Unsupported media type */
21426       case 488: /* Not acceptable here - codec error */
21427       case 606: /* Not Acceptable */
21428          if (sipmethod == SIP_INVITE)
21429             handle_response_invite(p, resp, rest, req, seqno);
21430          break;
21431       case 491: /* Pending */
21432          if (sipmethod == SIP_INVITE)
21433             handle_response_invite(p, resp, rest, req, seqno);
21434          else {
21435             ast_debug(1, "Got 491 on %s, unsupported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
21436             pvt_set_needdestroy(p, "received 491 response");
21437          }
21438          break;
21439       case 405: /* Method not allowed */
21440       case 501: /* Not Implemented */
21441          mark_method_unallowed(&p->allowed_methods, sipmethod);
21442          if (p->relatedpeer) {
21443             mark_method_allowed(&p->relatedpeer->disallowed_methods, sipmethod);
21444          }
21445          if (sipmethod == SIP_INVITE)
21446             handle_response_invite(p, resp, rest, req, seqno);
21447          else
21448             ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_sockaddr_stringify(&p->sa), msg);
21449          break;
21450       default:
21451          if ((resp >= 300) && (resp < 700)) {
21452             /* Fatal response */
21453             if ((resp != 487))
21454                ast_verb(3, "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_sockaddr_stringify(&p->sa));
21455    
21456             if (sipmethod == SIP_INVITE)
21457                stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
21458 
21459             /* XXX Locking issues?? XXX */
21460             switch(resp) {
21461             case 300: /* Multiple Choices */
21462             case 301: /* Moved permanently */
21463             case 302: /* Moved temporarily */
21464             case 305: /* Use Proxy */
21465                if (p->owner) {
21466                   struct ast_party_redirecting redirecting;
21467                   struct ast_set_party_redirecting update_redirecting;
21468 
21469                   ast_party_redirecting_init(&redirecting);
21470                   memset(&update_redirecting, 0, sizeof(update_redirecting));
21471                   change_redirecting_information(p, req, &redirecting,
21472                      &update_redirecting, TRUE);
21473                   ast_channel_set_redirecting(p->owner, &redirecting,
21474                      &update_redirecting);
21475                   ast_party_redirecting_free(&redirecting);
21476                }
21477                /* Fall through */
21478             case 486: /* Busy here */
21479             case 600: /* Busy everywhere */
21480             case 603: /* Decline */
21481                if (p->owner) {
21482                   sip_handle_cc(p, req, AST_CC_CCBS);
21483                   ast_queue_control(p->owner, AST_CONTROL_BUSY);
21484                }
21485                break;
21486             case 482: /* Loop Detected */
21487             case 480: /* Temporarily Unavailable */
21488             case 404: /* Not Found */
21489             case 410: /* Gone */
21490             case 400: /* Bad Request */
21491             case 500: /* Server error */
21492                if (sipmethod == SIP_SUBSCRIBE) {
21493                   handle_response_subscribe(p, resp, rest, req, seqno);
21494                   break;
21495                }
21496                /* Fall through */
21497             case 502: /* Bad gateway */
21498             case 503: /* Service Unavailable */
21499             case 504: /* Server Timeout */
21500                if (owner)
21501                   ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
21502                break;
21503             case 484: /* Address Incomplete */
21504                if (owner && sipmethod != SIP_BYE) {
21505                   switch (ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)) {
21506                   case SIP_PAGE2_ALLOWOVERLAP_YES:
21507                      ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
21508                      break;
21509                   default:
21510                      ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(404));
21511                      break;
21512                   }
21513                }
21514                break;
21515             default:
21516                /* Send hangup */ 
21517                if (owner && sipmethod != SIP_BYE)
21518                   ast_queue_hangup_with_cause(p->owner, hangup_sip2cause(resp));
21519                break;
21520             }
21521             /* ACK on invite */
21522             if (sipmethod == SIP_INVITE)
21523                transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
21524             sip_alreadygone(p);
21525             if (!p->owner) {
21526                pvt_set_needdestroy(p, "transaction completed");
21527             }
21528          } else if ((resp >= 100) && (resp < 200)) {
21529             if (sipmethod == SIP_INVITE) {
21530                if (!req->ignore && sip_cancel_destroy(p))
21531                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
21532                if (find_sdp(req))
21533                   process_sdp(p, req, SDP_T38_NONE);
21534                if (p->owner) {
21535                   /* Queue a progress frame */
21536                   ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
21537                }
21538             }
21539          } else
21540             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));
21541       }
21542    } else { 
21543       /* Responses to OUTGOING SIP requests on INCOMING calls
21544          get handled here. As well as out-of-call message responses */
21545       if (req->debug)
21546          ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
21547 
21548       if (sipmethod == SIP_INVITE && resp == 200) {
21549          /* Tags in early session is replaced by the tag in 200 OK, which is
21550          the final reply to our INVITE */
21551          char tag[128];
21552 
21553          gettag(req, "To", tag, sizeof(tag));
21554          ast_string_field_set(p, theirtag, tag);
21555       }
21556 
21557       switch(resp) {
21558       case 200:
21559          if (sipmethod == SIP_INVITE) {
21560             handle_response_invite(p, resp, rest, req, seqno);
21561          } else if (sipmethod == SIP_CANCEL) {
21562             ast_debug(1, "Got 200 OK on CANCEL\n");
21563 
21564             /* Wait for 487, then destroy */
21565          } else if (sipmethod == SIP_BYE) {
21566             pvt_set_needdestroy(p, "transaction completed");
21567          }
21568          break;
21569       case 401:   /* www-auth */
21570       case 407:
21571          if (sipmethod == SIP_INVITE)
21572             handle_response_invite(p, resp, rest, req, seqno);
21573          else if (sipmethod == SIP_BYE) {
21574             if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, sipmethod, 0)) {
21575                ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
21576                pvt_set_needdestroy(p, "failed to authenticate BYE");
21577             }
21578          }
21579          break;
21580       case 481:   /* Call leg does not exist */
21581          if (sipmethod == SIP_INVITE) {
21582             /* Re-invite failed */
21583             handle_response_invite(p, resp, rest, req, seqno);
21584          } else if (sipmethod == SIP_BYE) {
21585             pvt_set_needdestroy(p, "received 481 response");
21586          } else if (sipdebug) {
21587             ast_debug(1, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
21588          }
21589          break;
21590       case 501: /* Not Implemented */
21591          if (sipmethod == SIP_INVITE)
21592             handle_response_invite(p, resp, rest, req, seqno);
21593          break;
21594       default: /* Errors without handlers */
21595          if ((resp >= 100) && (resp < 200)) {
21596             if (sipmethod == SIP_INVITE) {   /* re-invite */
21597                if (!req->ignore && sip_cancel_destroy(p))
21598                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
21599             }
21600          }
21601          if ((resp >= 300) && (resp < 700)) {
21602             if ((resp != 487))
21603                ast_verb(3, "Incoming call: Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_sockaddr_stringify(&p->sa));
21604             switch(resp) {
21605             case 415: /* Unsupported media type */
21606             case 488: /* Not acceptable here - codec error */
21607             case 603: /* Decline */
21608             case 500: /* Server error */
21609             case 502: /* Bad gateway */
21610             case 503: /* Service Unavailable */
21611             case 504: /* Server timeout */
21612 
21613                /* re-invite failed */
21614                if (sipmethod == SIP_INVITE && sip_cancel_destroy(p))
21615                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
21616                break;
21617             }
21618          }
21619          break;
21620       }
21621    }
21622 }
21623 
21624 
21625 /*! \brief Park SIP call support function
21626    Starts in a new thread, then parks the call
21627    XXX Should we add a wait period after streaming audio and before hangup?? Sometimes the
21628       audio can't be heard before hangup
21629 */
21630 static void *sip_park_thread(void *stuff)
21631 {
21632    struct ast_channel *transferee, *transferer; /* Chan1: The transferee, Chan2: The transferer */
21633    struct sip_dual *d;
21634    int ext;
21635    int res;
21636 
21637    d = stuff;
21638    transferee = d->chan1;
21639    transferer = d->chan2;
21640 
21641    ast_debug(4, "SIP Park: Transferer channel %s, Transferee %s\n", transferer->name, transferee->name);
21642 
21643    res = ast_park_call_exten(transferee, transferer, d->park_exten, d->park_context, 0, &ext);
21644 
21645 #ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
21646    if (res) {
21647       transmit_message_with_text(transferer->tech_pvt, "Unable to park call.\n");
21648    } else {
21649       /* Then tell the transferer what happened */
21650       sprintf(buf, "Call parked on extension '%d'", ext);
21651       transmit_message_with_text(transferer->tech_pvt, buf);
21652    }
21653 #endif
21654 
21655    /* Any way back to the current call??? */
21656    /* Transmit response to the REFER request */
21657    if (!res)   {
21658       /* Transfer succeeded */
21659       append_history(transferer->tech_pvt, "SIPpark", "Parked call on %d", ext);
21660       transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "200 OK", TRUE);
21661       transferer->hangupcause = AST_CAUSE_NORMAL_CLEARING;
21662       ast_hangup(transferer); /* This will cause a BYE */
21663       ast_debug(1, "SIP Call parked on extension '%d'\n", ext);
21664    } else {
21665       transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "503 Service Unavailable", TRUE);
21666       append_history(transferer->tech_pvt, "SIPpark", "Parking failed\n");
21667       ast_debug(1, "SIP Call parked failed \n");
21668       /* Do not hangup call */
21669    }
21670    deinit_req(&d->req);
21671    ast_free(d->park_exten);
21672    ast_free(d->park_context);
21673    ast_free(d);
21674    return NULL;
21675 }
21676 
21677 /*! DO NOT hold any locks while calling sip_park */
21678 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)
21679 {
21680    struct sip_dual *d;
21681    struct ast_channel *transferee, *transferer;
21682    pthread_t th;
21683 
21684    transferee = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan1->accountcode, chan1->exten, chan1->context, chan1->linkedid, chan1->amaflags, "Parking/%s", chan1->name);
21685    transferer = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->linkedid, chan2->amaflags, "SIPPeer/%s", chan2->name);
21686    d = ast_calloc(1, sizeof(*d));
21687    if (!transferee || !transferer || !d) {
21688       if (transferee) {
21689          ast_hangup(transferee);
21690       }
21691       if (transferer) {
21692          ast_hangup(transferer);
21693       }
21694       ast_free(d);
21695       return -1;
21696    }
21697    d->park_exten = ast_strdup(park_exten);
21698    d->park_context = ast_strdup(park_context);
21699    if (!d->park_exten || !d->park_context) {
21700       ast_hangup(transferee);
21701       ast_hangup(transferer);
21702       ast_free(d->park_exten);
21703       ast_free(d->park_context);
21704       ast_free(d);
21705       return -1;
21706    }
21707 
21708    /* Make formats okay */
21709    transferee->readformat = chan1->readformat;
21710    transferee->writeformat = chan1->writeformat;
21711 
21712    /* Prepare for taking over the channel */
21713    if (ast_channel_masquerade(transferee, chan1)) {
21714       ast_hangup(transferee);
21715       ast_hangup(transferer);
21716       ast_free(d->park_exten);
21717       ast_free(d->park_context);
21718       ast_free(d);
21719       return -1;
21720    }
21721 
21722    /* Setup the extensions and such */
21723    ast_copy_string(transferee->context, chan1->context, sizeof(transferee->context));
21724    ast_copy_string(transferee->exten, chan1->exten, sizeof(transferee->exten));
21725    transferee->priority = chan1->priority;
21726 
21727    ast_do_masquerade(transferee);
21728 
21729    /* We make a clone of the peer channel too, so we can play
21730       back the announcement */
21731 
21732    /* Make formats okay */
21733    transferer->readformat = chan2->readformat;
21734    transferer->writeformat = chan2->writeformat;
21735    ast_string_field_set(transferer, parkinglot, chan2->parkinglot);
21736 
21737    /* Prepare for taking over the channel */
21738    if (ast_channel_masquerade(transferer, chan2)) {
21739       ast_hangup(transferer);
21740       ast_free(d->park_exten);
21741       ast_free(d->park_context);
21742       ast_free(d);
21743       return -1;
21744    }
21745 
21746    /* Setup the extensions and such */
21747    ast_copy_string(transferer->context, chan2->context, sizeof(transferer->context));
21748    ast_copy_string(transferer->exten, chan2->exten, sizeof(transferer->exten));
21749    transferer->priority = chan2->priority;
21750 
21751    ast_do_masquerade(transferer);
21752 
21753    /* Save original request for followup */
21754    copy_request(&d->req, req);
21755    d->chan1 = transferee;  /* Transferee */
21756    d->chan2 = transferer;  /* Transferer */
21757    d->seqno = seqno;
21758    if (ast_pthread_create_detached_background(&th, NULL, sip_park_thread, d) < 0) {
21759       /* Could not start thread */
21760       deinit_req(&d->req);
21761       ast_free(d->park_exten);
21762       ast_free(d->park_context);
21763       ast_free(d);   /* We don't need it anymore. If thread is created, d will be free'd
21764                by sip_park_thread() */
21765       return -1;
21766    }
21767    return 0;
21768 }
21769 
21770 
21771 /*! \brief SIP pickup support function
21772  * Starts in a new thread, then pickup the call
21773  */
21774 static void *sip_pickup_thread(void *stuff)
21775 {
21776    struct ast_channel *chan;
21777    chan = stuff;
21778 
21779    if (ast_pickup_call(chan)) {
21780       chan->hangupcause = AST_CAUSE_CALL_REJECTED;
21781    } else {
21782       chan->hangupcause = AST_CAUSE_NORMAL_CLEARING;
21783    }
21784    ast_hangup(chan);
21785    ast_channel_unref(chan);
21786    chan = NULL;
21787    return NULL;
21788 }
21789 
21790 /*! \brief Pickup a call using the subsystem in features.c
21791  * This is executed in a separate thread
21792  */
21793 static int sip_pickup(struct ast_channel *chan)
21794 {
21795    pthread_t threadid;
21796 
21797    ast_channel_ref(chan);
21798 
21799    if (ast_pthread_create_detached_background(&threadid, NULL, sip_pickup_thread, chan)) {
21800       ast_debug(1, "Unable to start Group pickup thread on channel %s\n", chan->name);
21801       ast_channel_unref(chan);
21802       return -1;
21803    }
21804    ast_debug(1, "Started Group pickup thread on channel %s\n", chan->name);
21805    return 0;
21806 }
21807 
21808 
21809 /*! \brief Turn off generator data
21810    XXX Does this function belong in the SIP channel?
21811 */
21812 static void ast_quiet_chan(struct ast_channel *chan)
21813 {
21814    if (chan && chan->_state == AST_STATE_UP) {
21815       if (ast_test_flag(chan, AST_FLAG_MOH))
21816          ast_moh_stop(chan);
21817       else if (chan->generatordata)
21818          ast_deactivate_generator(chan);
21819    }
21820 }
21821 
21822 /*! \brief Attempt transfer of SIP call
21823    This fix for attended transfers on a local PBX */
21824 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target)
21825 {
21826    int res = 0;
21827    struct ast_channel *peera = NULL,   
21828       *peerb = NULL,
21829       *peerc = NULL,
21830       *peerd = NULL;
21831 
21832 
21833    /* We will try to connect the transferee with the target and hangup
21834       all channels to the transferer */   
21835    ast_debug(4, "Sip transfer:--------------------\n");
21836    if (transferer->chan1)
21837       ast_debug(4, "-- Transferer to PBX channel: %s State %s\n", transferer->chan1->name, ast_state2str(transferer->chan1->_state));
21838    else
21839       ast_debug(4, "-- No transferer first channel - odd??? \n");
21840    if (target->chan1)
21841       ast_debug(4, "-- Transferer to PBX second channel (target): %s State %s\n", target->chan1->name, ast_state2str(target->chan1->_state));
21842    else
21843       ast_debug(4, "-- No target first channel ---\n");
21844    if (transferer->chan2)
21845       ast_debug(4, "-- Bridged call to transferee: %s State %s\n", transferer->chan2->name, ast_state2str(transferer->chan2->_state));
21846    else
21847       ast_debug(4, "-- No bridged call to transferee\n");
21848    if (target->chan2)
21849       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)");
21850    else
21851       ast_debug(4, "-- No target second channel ---\n");
21852    ast_debug(4, "-- END Sip transfer:--------------------\n");
21853    if (transferer->chan2) { /* We have a bridge on the transferer's channel */
21854       peera = transferer->chan1; /* Transferer - PBX -> transferee channel * the one we hangup */
21855       peerb = target->chan1;     /* Transferer - PBX -> target channel - This will get lost in masq */
21856       peerc = transferer->chan2; /* Asterisk to Transferee */
21857       peerd = target->chan2;     /* Asterisk to Target */
21858       ast_debug(3, "SIP transfer: Four channels to handle\n");
21859    } else if (target->chan2) {   /* Transferer has no bridge (IVR), but transferee */
21860       peera = target->chan1;     /* Transferer to PBX -> target channel */
21861       peerb = transferer->chan1; /* Transferer to IVR*/
21862       peerc = target->chan2;     /* Asterisk to Target */
21863       peerd = transferer->chan2; /* Nothing */
21864       ast_debug(3, "SIP transfer: Three channels to handle\n");
21865    }
21866 
21867    if (peera && peerb && peerc && (peerb != peerc)) {
21868       ast_quiet_chan(peera);     /* Stop generators */
21869       ast_quiet_chan(peerb);  
21870       ast_quiet_chan(peerc);
21871       if (peerd)
21872          ast_quiet_chan(peerd);
21873 
21874       ast_debug(4, "SIP transfer: trying to masquerade %s into %s\n", peerc->name, peerb->name);
21875       if (ast_channel_masquerade(peerb, peerc)) {
21876          ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
21877          res = -1;
21878       } else
21879          ast_debug(4, "SIP transfer: Succeeded to masquerade channels.\n");
21880       return res;
21881    } else {
21882       ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
21883       if (transferer->chan1)
21884          ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
21885       if (target->chan1)
21886          ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
21887       return -1;
21888    }
21889    return 0;
21890 }
21891 
21892 /*! \brief Get tag from packet
21893  *
21894  * \return Returns the pointer to the provided tag buffer,
21895  *         or NULL if the tag was not found.
21896  */
21897 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
21898 {
21899    const char *thetag;
21900 
21901    if (!tagbuf)
21902       return NULL;
21903    tagbuf[0] = '\0';    /* reset the buffer */
21904    thetag = get_header(req, header);
21905    thetag = strcasestr(thetag, ";tag=");
21906    if (thetag) {
21907       thetag += 5;
21908       ast_copy_string(tagbuf, thetag, tagbufsize);
21909       return strsep(&tagbuf, ";");
21910    }
21911    return NULL;
21912 }
21913 
21914 static int handle_cc_notify(struct sip_pvt *pvt, struct sip_request *req)
21915 {
21916    struct sip_monitor_instance *monitor_instance = ao2_callback(sip_monitor_instances, 0,
21917          find_sip_monitor_instance_by_subscription_pvt, pvt);
21918    const char *status = get_body(req, "cc-state", ':');
21919    struct cc_epa_entry *cc_entry;
21920    char *uri;
21921 
21922    if (!monitor_instance) {
21923       transmit_response(pvt, "400 Bad Request", req);
21924       return -1;
21925    }
21926 
21927    if (ast_strlen_zero(status)) {
21928       ao2_ref(monitor_instance, -1);
21929       transmit_response(pvt, "400 Bad Request", req);
21930       return -1;
21931    }
21932 
21933    if (!strcmp(status, "queued")) {
21934       /* We've been told that we're queued. This is the endpoint's way of telling
21935        * us that it has accepted our CC request. We need to alert the core of this
21936        * development
21937        */
21938       ast_cc_monitor_request_acked(monitor_instance->core_id, "SIP endpoint %s accepted request", monitor_instance->device_name);
21939       transmit_response(pvt, "200 OK", req);
21940       ao2_ref(monitor_instance, -1);
21941       return 0;
21942    }
21943 
21944    /* It's open! Yay! */
21945    uri = get_body(req, "cc-URI", ':');
21946    if (ast_strlen_zero(uri)) {
21947       uri = get_in_brackets((char *)get_header(req, "From"));
21948    }
21949 
21950    ast_string_field_set(monitor_instance, notify_uri, uri);
21951    if (monitor_instance->suspension_entry) {
21952       cc_entry = monitor_instance->suspension_entry->instance_data;
21953       if (cc_entry->current_state == CC_CLOSED) {
21954          /* If we've created a suspension entry and the current state is closed, then that means
21955           * we got a notice from the CC core earlier to suspend monitoring, but because this particular
21956           * call leg had not yet notified us that it was ready for recall, it meant that we
21957           * could not yet send a PUBLISH. Now, however, we can.
21958           */
21959          construct_pidf_body(CC_CLOSED, monitor_instance->suspension_entry->body,
21960                sizeof(monitor_instance->suspension_entry->body), monitor_instance->peername);
21961          transmit_publish(monitor_instance->suspension_entry, SIP_PUBLISH_INITIAL, monitor_instance->notify_uri);
21962       } else {
21963          ast_cc_monitor_callee_available(monitor_instance->core_id, "SIP monitored callee has become available");
21964       }
21965    } else {
21966       ast_cc_monitor_callee_available(monitor_instance->core_id, "SIP monitored callee has become available");
21967    }
21968    ao2_ref(monitor_instance, -1);
21969    transmit_response(pvt, "200 OK", req);
21970 
21971    return 0;
21972 }
21973 
21974 /*! \brief Handle incoming notifications */
21975 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e)
21976 {
21977    /* This is mostly a skeleton for future improvements */
21978    /* Mostly created to return proper answers on notifications on outbound REFER's */
21979    int res = 0;
21980    const char *event = get_header(req, "Event");
21981    char *sep;
21982 
21983    if( (sep = strchr(event, ';')) ) {  /* XXX bug here - overwriting string ? */
21984       *sep++ = '\0';
21985    }
21986    
21987    if (sipdebug)
21988       ast_debug(2, "Got NOTIFY Event: %s\n", event);
21989 
21990    if (!strcmp(event, "refer")) {
21991       /* Save nesting depth for now, since there might be other events we will
21992          support in the future */
21993 
21994       /* Handle REFER notifications */
21995 
21996       char buf[1024];
21997       char *cmd, *code;
21998       int respcode;
21999       int success = TRUE;
22000 
22001       /* EventID for each transfer... EventID is basically the REFER cseq
22002 
22003        We are getting notifications on a call that we transfered
22004        We should hangup when we are getting a 200 OK in a sipfrag
22005        Check if we have an owner of this event */
22006       
22007       /* Check the content type */
22008       if (strncasecmp(get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
22009          /* We need a sipfrag */
22010          transmit_response(p, "400 Bad request", req);
22011          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22012          return -1;
22013       }
22014 
22015       /* Get the text of the attachment */
22016       if (get_msg_text(buf, sizeof(buf), req)) {
22017          ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
22018          transmit_response(p, "400 Bad request", req);
22019          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22020          return -1;
22021       }
22022 
22023       /*
22024       From the RFC...
22025       A minimal, but complete, implementation can respond with a single
22026       NOTIFY containing either the body:
22027          SIP/2.0 100 Trying
22028       
22029       if the subscription is pending, the body:
22030          SIP/2.0 200 OK
22031       if the reference was successful, the body:
22032          SIP/2.0 503 Service Unavailable
22033       if the reference failed, or the body:
22034          SIP/2.0 603 Declined
22035 
22036       if the REFER request was accepted before approval to follow the
22037       reference could be obtained and that approval was subsequently denied
22038       (see Section 2.4.7).
22039       
22040       If there are several REFERs in the same dialog, we need to
22041       match the ID of the event header...
22042       */
22043       ast_debug(3, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
22044       cmd = ast_skip_blanks(buf);
22045       code = cmd;
22046       /* We are at SIP/2.0 */
22047       while(*code && (*code > 32)) {   /* Search white space */
22048          code++;
22049       }
22050       *code++ = '\0';
22051       code = ast_skip_blanks(code);
22052       sep = code;
22053       sep++;
22054       while(*sep && (*sep > 32)) {  /* Search white space */
22055          sep++;
22056       }
22057       *sep++ = '\0';       /* Response string */
22058       respcode = atoi(code);
22059       switch (respcode) {
22060       case 200:   /* OK: The new call is up, hangup this call */
22061          /* Hangup the call that we are replacing */
22062          break;
22063       case 301: /* Moved permenantly */
22064       case 302: /* Moved temporarily */
22065          /* Do we get the header in the packet in this case? */
22066          success = FALSE;
22067          break;
22068       case 503:   /* Service Unavailable: The new call failed */
22069       case 603:   /* Declined: Not accepted */
22070             /* Cancel transfer, continue the current call */
22071          success = FALSE;
22072          break;
22073       case 0:     /* Parse error */
22074             /* Cancel transfer, continue the current call */
22075          ast_log(LOG_NOTICE, "Error parsing sipfrag in NOTIFY in response to REFER.\n");
22076          success = FALSE;
22077          break;
22078       default:
22079          if (respcode < 200) {
22080             /* ignore provisional responses */
22081             success = -1;
22082          } else {
22083             ast_log(LOG_NOTICE, "Got unknown code '%d' in NOTIFY in response to REFER.\n", respcode);
22084             success = FALSE;
22085          }
22086          break;
22087       }
22088       if (success == FALSE) {
22089          ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
22090       }
22091 
22092       if (p->owner && success != -1) {
22093          enum ast_control_transfer message = success ? AST_TRANSFER_SUCCESS : AST_TRANSFER_FAILED;
22094          ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
22095       }
22096       /* Confirm that we received this packet */
22097       transmit_response(p, "200 OK", req);
22098    } else if (!strcmp(event, "message-summary")) {
22099       const char *mailbox = NULL;
22100       char *c = ast_strdupa(get_body(req, "Voice-Message", ':'));
22101 
22102       if (!p->mwi) {
22103          struct sip_peer *peer = find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
22104 
22105          if (peer) {
22106             mailbox = ast_strdupa(peer->unsolicited_mailbox);
22107             unref_peer(peer, "removing unsolicited mwi ref");
22108          }
22109       } else {
22110          mailbox = p->mwi->mailbox;
22111       }
22112 
22113       if (!ast_strlen_zero(mailbox) && !ast_strlen_zero(c)) {
22114          char *old = strsep(&c, " ");
22115          char *new = strsep(&old, "/");
22116          struct ast_event *event;
22117 
22118          if ((event = ast_event_new(AST_EVENT_MWI,
22119                      AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
22120                      AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, "SIP_Remote",
22121                      AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(new),
22122                      AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_UINT, atoi(old),
22123                      AST_EVENT_IE_END))) {
22124             ast_event_queue_and_cache(event);
22125          }
22126          transmit_response(p, "200 OK", req);
22127       } else {
22128          transmit_response(p, "489 Bad event", req);
22129          res = -1;
22130       }
22131    } else if (!strcmp(event, "keep-alive")) {
22132        /* Used by Sipura/Linksys for NAT pinhole,
22133         * just confirm that we received the packet. */
22134       transmit_response(p, "200 OK", req);
22135    } else if (!strcmp(event, "call-completion")) {
22136       res = handle_cc_notify(p, req);
22137    } else {
22138       /* We don't understand this event. */
22139       transmit_response(p, "489 Bad event", req);
22140       res = -1;
22141    }
22142 
22143    if (!p->lastinvite)
22144       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22145 
22146    return res;
22147 }
22148 
22149 /*! \brief Handle incoming OPTIONS request
22150    An OPTIONS request should be answered like an INVITE from the same UA, including SDP
22151 */
22152 static int handle_request_options(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e)
22153 {
22154    const char *msg;
22155    enum sip_get_dest_result gotdest;
22156    int res;
22157 
22158    if (p->lastinvite) {
22159       /* if this is a request in an active dialog, just confirm that the dialog exists. */
22160       transmit_response_with_allow(p, "200 OK", req, 0);
22161       return 0;
22162    }
22163 
22164    if (sip_cfg.auth_options_requests) {
22165       /* Do authentication if this OPTIONS request began the dialog */
22166       copy_request(&p->initreq, req);
22167       set_pvt_allowed_methods(p, req);
22168       res = check_user(p, req, SIP_OPTIONS, e, XMIT_UNRELIABLE, addr);
22169       if (res == AUTH_CHALLENGE_SENT) {
22170          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22171          return 0;
22172       }
22173       if (res < 0) { /* Something failed in authentication */
22174          if (res == AUTH_FAKE_AUTH) {
22175             ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
22176             transmit_fake_auth_response(p, SIP_OPTIONS, req, XMIT_UNRELIABLE);
22177          } else {
22178             ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
22179             transmit_response(p, "403 Forbidden", req);
22180          }
22181          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22182          return 0;
22183       }
22184    }
22185 
22186    /* must go through authentication before getting here */
22187    gotdest = get_destination(p, req, NULL);
22188    build_contact(p);
22189 
22190    if (ast_strlen_zero(p->context))
22191       ast_string_field_set(p, context, sip_cfg.default_context);
22192 
22193    if (ast_shutting_down()) {
22194       msg = "503 Unavailable";
22195    } else {
22196       msg = "404 Not Found";
22197       switch (gotdest) {
22198       case SIP_GET_DEST_INVALID_URI:
22199          msg = "416 Unsupported URI scheme";
22200          break;
22201       case SIP_GET_DEST_EXTEN_MATCHMORE:
22202       case SIP_GET_DEST_REFUSED:
22203       case SIP_GET_DEST_EXTEN_NOT_FOUND:
22204          //msg = "404 Not Found";
22205          break;
22206       case SIP_GET_DEST_EXTEN_FOUND:
22207          msg = "200 OK";
22208          break;
22209       }
22210    }
22211    transmit_response_with_allow(p, msg, req, 0);
22212 
22213    /* Destroy if this OPTIONS was the opening request, but not if
22214       it's in the middle of a normal call flow. */
22215    sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22216 
22217    return 0;
22218 }
22219 
22220 /*! \brief Handle the transfer part of INVITE with a replaces: header,
22221     meaning a target pickup or an attended transfer.
22222     Used only once.
22223    XXX 'ignore' is unused.
22224 
22225    \note this function is called by handle_request_invite(). Four locks
22226    held at the beginning of this function, p, p->owner, p->refer->refer_call and
22227    p->refere->refer_call->owner.  only p's lock should remain at the end of this
22228    function.  p's lock as well as the channel p->owner's lock are held by
22229    handle_request_do(), we unlock p->owner before the masq.  By setting nounlock
22230    we are indicating to handle_request_do() that we have already unlocked the owner.
22231  */
22232 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, struct ast_sockaddr *addr, int *nounlock)
22233 {
22234    int earlyreplace = 0;
22235    int oneleggedreplace = 0;     /* Call with no bridge, propably IVR or voice message */
22236    struct ast_channel *c = p->owner;   /* Our incoming call */
22237    struct ast_channel *replacecall = p->refer->refer_call->owner; /* The channel we're about to take over */
22238    struct ast_channel *targetcall;     /* The bridge to the take-over target */
22239 
22240    /* Check if we're in ring state */
22241    if (replacecall->_state == AST_STATE_RING)
22242       earlyreplace = 1;
22243 
22244    /* Check if we have a bridge */
22245    if (!(targetcall = ast_bridged_channel(replacecall))) {
22246       /* We have no bridge */
22247       if (!earlyreplace) {
22248          ast_debug(2, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", replacecall->name);
22249          oneleggedreplace = 1;
22250       }
22251    }
22252    if (targetcall && targetcall->_state == AST_STATE_RINGING)
22253       ast_debug(4, "SIP transfer: Target channel is in ringing state\n");
22254 
22255    if (targetcall)
22256       ast_debug(4, "SIP transfer: Invite Replace incoming channel should bridge to channel %s while hanging up channel %s\n", targetcall->name, replacecall->name);
22257    else
22258       ast_debug(4, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", replacecall->name);
22259 
22260    if (req->ignore) {
22261       ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
22262       /* We should answer something here. If we are here, the
22263          call we are replacing exists, so an accepted
22264          can't harm */
22265       transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE, FALSE);
22266       /* Do something more clever here */
22267       if (c) {
22268          *nounlock = 1;
22269          ast_channel_unlock(c);
22270       }
22271       ast_channel_unlock(replacecall);
22272       sip_pvt_unlock(p->refer->refer_call);
22273       return 1;
22274    }
22275    if (!c) {
22276       /* What to do if no channel ??? */
22277       ast_log(LOG_ERROR, "Unable to create new channel.  Invite/replace failed.\n");
22278       transmit_response_reliable(p, "503 Service Unavailable", req);
22279       append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
22280       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22281       ast_channel_unlock(replacecall);
22282       sip_pvt_unlock(p->refer->refer_call);
22283       return 1;
22284    }
22285    append_history(p, "Xfer", "INVITE/Replace received");
22286    /* We have three channels to play with
22287       channel c: New incoming call
22288       targetcall: Call from PBX to target
22289       p->refer->refer_call: SIP pvt dialog from transferer to pbx.
22290       replacecall: The owner of the previous
22291       We need to masq C into refer_call to connect to
22292       targetcall;
22293       If we are talking to internal audio stream, target call is null.
22294    */
22295 
22296    /* Fake call progress */
22297    transmit_response(p, "100 Trying", req);
22298    ast_setstate(c, AST_STATE_RING);
22299 
22300    /* Masquerade the new call into the referred call to connect to target call
22301       Targetcall is not touched by the masq */
22302 
22303    /* Answer the incoming call and set channel to UP state */
22304    transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE, FALSE);
22305 
22306    ast_setstate(c, AST_STATE_UP);
22307 
22308    /* Stop music on hold and other generators */
22309    ast_quiet_chan(replacecall);
22310    ast_quiet_chan(targetcall);
22311    ast_debug(4, "Invite/Replaces: preparing to masquerade %s into %s\n", c->name, replacecall->name);
22312 
22313    /* Make sure that the masq does not free our PVT for the old call */
22314    if (! earlyreplace && ! oneleggedreplace )
22315       ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER);  /* Delay hangup */
22316 
22317    /* Prepare the masquerade - if this does not happen, we will be gone */
22318    if(ast_channel_masquerade(replacecall, c))
22319       ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
22320    else
22321       ast_debug(4, "Invite/Replaces: Going to masquerade %s into %s\n", c->name, replacecall->name);
22322 
22323    /* C should now be in place of replacecall. all channel locks and pvt locks should be removed
22324     * before issuing the masq.  Since we are unlocking both the pvt (p) and its owner channel (c)
22325     * it is possible for channel c to be destroyed on us.  To prevent this, we must give c a reference
22326     * before any unlocking takes place and remove it only once we are completely done with it */
22327    ast_channel_ref(c);
22328    ast_channel_unlock(replacecall);
22329    ast_channel_unlock(c);
22330    sip_pvt_unlock(p->refer->refer_call);
22331    sip_pvt_unlock(p);
22332    if (ast_do_masquerade(replacecall)) {
22333       ast_log(LOG_WARNING, "Failed to perform masquerade with INVITE replaces\n");
22334    }
22335    ast_channel_lock(c);
22336    if (earlyreplace || oneleggedreplace ) {
22337       c->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
22338    }
22339    ast_setstate(c, AST_STATE_DOWN);
22340    ast_channel_unlock(c);
22341 
22342    /* The call should be down with no ast_channel, so hang it up */
22343    c->tech_pvt = dialog_unref(c->tech_pvt, "unref dialog c->tech_pvt");
22344 
22345    /* c and c's tech pvt must be unlocked at this point for ast_hangup */
22346    ast_hangup(c);
22347    /* this indicates to handle_request_do that the owner channel has already been unlocked */
22348    *nounlock = 1;
22349    /* lock PVT structure again after hangup */
22350    sip_pvt_lock(p);
22351    ast_channel_unref(c);
22352    return 0;
22353 }
22354 
22355 /*! \note No channel or pvt locks should be held while calling this function. */
22356 static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context)
22357 {
22358    struct ast_str *str = ast_str_alloca(AST_MAX_EXTENSION + AST_MAX_CONTEXT + 2);
22359    struct ast_app *pickup = pbx_findapp("Pickup");
22360 
22361    if (!pickup) {
22362       ast_log(LOG_ERROR, "Unable to perform pickup: Application 'Pickup' not loaded (app_directed_pickup.so).\n");
22363       return -1;
22364    }
22365 
22366    ast_str_set(&str, 0, "%s@%s", extension, sip_cfg.notifycid == IGNORE_CONTEXT ? "PICKUPMARK" : context);
22367 
22368    ast_debug(2, "About to call Pickup(%s)\n", str->str);
22369 
22370    /* There is no point in capturing the return value since pickup_exec
22371       doesn't return anything meaningful unless the passed data is an empty
22372       string (which in our case it will not be) */
22373    pbx_exec(channel, pickup, str->str);
22374 
22375    return 0;
22376 }
22377 
22378 /*! \brief Called to deny a T38 reinvite if the core does not respond to our request */
22379 static int sip_t38_abort(const void *data)
22380 {
22381    struct sip_pvt *p = (struct sip_pvt *) data;
22382 
22383    sip_pvt_lock(p);
22384    /* an application may have taken ownership of the T.38 negotiation on this
22385     * channel while we were waiting to grab the lock... if it did, the scheduler
22386     * id will have been reset to -1, which is our indication that we do *not*
22387     * want to abort the negotiation process
22388     */
22389    if (p->t38id != -1) {
22390       change_t38_state(p, T38_DISABLED);
22391       transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
22392       p->t38id = -1;
22393       dialog_unref(p, "unref the dialog ptr from sip_t38_abort, because it held a dialog ptr");
22394    }
22395    sip_pvt_unlock(p);
22396    return 0;
22397 }
22398 
22399 /*!
22400  * \brief bare-bones support for SIP UPDATE
22401  *
22402  * XXX This is not even close to being RFC 3311-compliant. We don't advertise
22403  * that we support the UPDATE method, so no one should ever try sending us
22404  * an UPDATE anyway. However, Asterisk can send an UPDATE to change connected
22405  * line information, so we need to be prepared to handle this. The way we distinguish
22406  * such an UPDATE is through the X-Asterisk-rpid-update header.
22407  *
22408  * Actually updating the media session may be some future work.
22409  */
22410 static int handle_request_update(struct sip_pvt *p, struct sip_request *req)
22411 {
22412    if (ast_strlen_zero(get_header(req, "X-Asterisk-rpid-update"))) {
22413       transmit_response(p, "501 Method Not Implemented", req);
22414       return 0;
22415    }
22416    if (!p->owner) {
22417       transmit_response(p, "481 Call/Transaction Does Not Exist", req);
22418       return 0;
22419    }
22420    if (get_rpid(p, req)) {
22421       struct ast_party_connected_line connected;
22422       struct ast_set_party_connected_line update_connected;
22423 
22424       ast_party_connected_line_init(&connected);
22425       memset(&update_connected, 0, sizeof(update_connected));
22426 
22427       update_connected.id.number = 1;
22428       connected.id.number.valid = 1;
22429       connected.id.number.str = (char *) p->cid_num;
22430       connected.id.number.presentation = p->callingpres;
22431 
22432       update_connected.id.name = 1;
22433       connected.id.name.valid = 1;
22434       connected.id.name.str = (char *) p->cid_name;
22435       connected.id.name.presentation = p->callingpres;
22436 
22437       connected.id.tag = (char *) p->cid_tag;
22438       connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
22439       ast_channel_queue_connected_line_update(p->owner, &connected, &update_connected);
22440    }
22441    transmit_response(p, "200 OK", req);
22442    return 0;
22443 }
22444 
22445 /*!
22446  * \brief Handle incoming INVITE request
22447  * \note If the INVITE has a Replaces header, it is part of an
22448  * attended transfer. If so, we do not go through the dial
22449  * plan but try to find the active call and masquerade
22450  * into it
22451  */
22452 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)
22453 {
22454    int res = 1;
22455    int gotdest;
22456    const char *p_replaces;
22457    char *replace_id = NULL;
22458    int refer_locked = 0;
22459    const char *required;
22460    unsigned int required_profile = 0;
22461    struct ast_channel *c = NULL;    /* New channel */
22462    struct sip_peer *authpeer = NULL;   /* Matching Peer */
22463    int reinvite = 0;
22464    int rtn;
22465    struct ast_party_redirecting redirecting;
22466    struct ast_set_party_redirecting update_redirecting;
22467 
22468    const char *p_uac_se_hdr;       /* UAC's Session-Expires header string                      */
22469    const char *p_uac_min_se;       /* UAC's requested Min-SE interval (char string)            */
22470    int uac_max_se = -1;            /* UAC's Session-Expires in integer format                  */
22471    int uac_min_se = -1;            /* UAC's Min-SE in integer format                           */
22472    int st_active = FALSE;          /* Session-Timer on/off boolean                             */
22473    int st_interval = 0;            /* Session-Timer negotiated refresh interval                */
22474    enum st_refresher tmp_st_ref = SESSION_TIMER_REFRESHER_AUTO; /* Session-Timer refresher     */
22475    int dlg_min_se = -1;
22476    struct {
22477       char exten[AST_MAX_EXTENSION];
22478       char context[AST_MAX_CONTEXT];
22479    } pickup = {
22480          .exten = "",
22481    };
22482 
22483    /* Find out what they support */
22484    if (!p->sipoptions) {
22485       const char *supported = get_header(req, "Supported");
22486       if (!ast_strlen_zero(supported)) {
22487          p->sipoptions = parse_sip_options(supported, NULL, 0);
22488       }
22489    }
22490 
22491    /* Find out what they require */
22492    required = get_header(req, "Require");
22493    if (!ast_strlen_zero(required)) {
22494       char unsupported[256] = { 0, };
22495       required_profile = parse_sip_options(required, unsupported, ARRAY_LEN(unsupported));
22496 
22497       /* If there are any options required that we do not support,
22498        * then send a 420 with only those unsupported options listed */
22499       if (!ast_strlen_zero(unsupported)) {
22500          transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, unsupported);
22501          ast_log(LOG_WARNING, "Received SIP INVITE with unsupported required extension: required:%s unsupported:%s\n", required, unsupported);
22502          p->invitestate = INV_COMPLETED;
22503          if (!p->lastinvite)
22504             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22505          res = -1;
22506          goto request_invite_cleanup;
22507       }
22508    }
22509 
22510    /* The option tags may be present in Supported: or Require: headers.
22511    Include the Require: option tags for further processing as well */
22512    p->sipoptions |= required_profile;
22513    p->reqsipoptions = required_profile;
22514 
22515    /* Check if this is a loop */
22516    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) {
22517       /* This is a call to ourself.  Send ourselves an error code and stop
22518          processing immediately, as SIP really has no good mechanism for
22519          being able to call yourself */
22520       /* If pedantic is on, we need to check the tags. If they're different, this is
22521          in fact a forked call through a SIP proxy somewhere. */
22522       int different;
22523       const char *initial_rlPart2 = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
22524       const char *this_rlPart2 = REQ_OFFSET_TO_STR(req, rlPart2);
22525       if (sip_cfg.pedanticsipchecking)
22526          different = sip_uri_cmp(initial_rlPart2, this_rlPart2);
22527       else
22528          different = strcmp(initial_rlPart2, this_rlPart2);
22529       if (!different) {
22530          transmit_response(p, "482 Loop Detected", req);
22531          p->invitestate = INV_COMPLETED;
22532          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22533          res = 0;
22534          goto request_invite_cleanup;
22535       } else {
22536          /*! This is a spiral. What we need to do is to just change the outgoing INVITE
22537           * so that it now routes to the new Request URI. Since we created the INVITE ourselves
22538           * that should be all we need to do.
22539           *
22540           * \todo XXX This needs to be reviewed.  YOu don't change the request URI really, you route the packet
22541           * correctly instead...
22542           */
22543          char *uri = ast_strdupa(this_rlPart2);
22544          char *at = strchr(uri, '@');
22545          char *peerorhost;
22546          ast_debug(2, "Potential spiral detected. Original RURI was %s, new RURI is %s\n", initial_rlPart2, this_rlPart2);
22547          transmit_response(p, "100 Trying", req);
22548          if (at) {
22549             *at = '\0';
22550          }
22551          /* Parse out "sip:" */
22552          if ((peerorhost = strchr(uri, ':'))) {
22553             *peerorhost++ = '\0';
22554          }
22555          ast_string_field_set(p, theirtag, NULL);
22556          /* Treat this as if there were a call forward instead...
22557           */
22558          ast_string_field_set(p->owner, call_forward, peerorhost);
22559          ast_queue_control(p->owner, AST_CONTROL_BUSY);
22560          res = 0;
22561          goto request_invite_cleanup;
22562       }
22563    }
22564 
22565    if (!req->ignore && p->pendinginvite) {
22566       if (!ast_test_flag(&p->flags[0], SIP_OUTGOING) && (p->invitestate == INV_COMPLETED || p->invitestate == INV_TERMINATED)) {
22567          /* What do these circumstances mean? We have received an INVITE for an "incoming" dialog for which we
22568           * have sent a final response. We have not yet received an ACK, though (which is why p->pendinginvite is non-zero).
22569           * We also know that the INVITE is not a retransmission, because otherwise the "ignore" flag would be set.
22570           * This means that either we are receiving a reinvite for a terminated dialog, or we are receiving an INVITE with
22571           * credentials based on one we challenged earlier.
22572           *
22573           * The action to take in either case is to treat the INVITE as though it contains an implicit ACK for the previous
22574           * transaction. Calling __sip_ack will take care of this by clearing the p->pendinginvite and removing the response
22575           * from the previous transaction from the list of outstanding packets.
22576           */
22577          __sip_ack(p, p->pendinginvite, 1, 0);
22578       } else {
22579          /* We already have a pending invite. Sorry. You are on hold. */
22580          p->glareinvite = seqno;
22581          if (p->rtp && find_sdp(req)) {
22582             struct ast_sockaddr addr;
22583             if (get_ip_and_port_from_sdp(req, SDP_AUDIO, &addr)) {
22584                ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Audio may not work properly on this call.\n");
22585             } else {
22586                ast_rtp_instance_set_alt_remote_address(p->rtp, &addr);
22587             }
22588             if (p->vrtp) {
22589                if (get_ip_and_port_from_sdp(req, SDP_VIDEO, &addr)) {
22590                   ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Video may not work properly on this call.\n");
22591                } else {
22592                   ast_rtp_instance_set_alt_remote_address(p->vrtp, &addr);
22593                }
22594             }
22595          }
22596          transmit_response_reliable(p, "491 Request Pending", req);
22597          check_via(p, req);
22598          ast_debug(1, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
22599          /* Don't destroy dialog here */
22600          res = 0;
22601          goto request_invite_cleanup;
22602       }
22603    }
22604 
22605    p_replaces = get_header(req, "Replaces");
22606    if (!ast_strlen_zero(p_replaces)) {
22607       /* We have a replaces header */
22608       char *ptr;
22609       char *fromtag = NULL;
22610       char *totag = NULL;
22611       char *start, *to;
22612       int error = 0;
22613 
22614       if (p->owner) {
22615          ast_debug(3, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
22616          transmit_response_reliable(p, "400 Bad request", req);   /* The best way to not not accept the transfer */
22617          check_via(p, req);
22618          copy_request(&p->initreq, req);
22619          /* Do not destroy existing call */
22620          res = -1;
22621          goto request_invite_cleanup;
22622       }
22623 
22624       if (sipdebug)
22625          ast_debug(3, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
22626       /* Create a buffer we can manipulate */
22627       replace_id = ast_strdupa(p_replaces);
22628       ast_uri_decode(replace_id);
22629 
22630       if (!p->refer && !sip_refer_allocate(p)) {
22631          transmit_response_reliable(p, "500 Server Internal Error", req);
22632          append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
22633          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22634          p->invitestate = INV_COMPLETED;
22635          check_via(p, req);
22636          copy_request(&p->initreq, req);
22637          res = -1;
22638          goto request_invite_cleanup;
22639       }
22640 
22641       /*  Todo: (When we find phones that support this)
22642          if the replaces header contains ";early-only"
22643          we can only replace the call in early
22644          stage, not after it's up.
22645 
22646          If it's not in early mode, 486 Busy.
22647       */
22648 
22649       /* Skip leading whitespace */
22650       replace_id = ast_skip_blanks(replace_id);
22651 
22652       start = replace_id;
22653       while ( (ptr = strsep(&start, ";")) ) {
22654          ptr = ast_skip_blanks(ptr); /* XXX maybe unnecessary ? */
22655          if ( (to = strcasestr(ptr, "to-tag=") ) )
22656             totag = to + 7;   /* skip the keyword */
22657          else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
22658             fromtag = to + 9; /* skip the keyword */
22659             fromtag = strsep(&fromtag, "&"); /* trim what ? */
22660          }
22661       }
22662 
22663       if (sipdebug)
22664          ast_debug(4, "Invite/replaces: Will use Replace-Call-ID : %s Fromtag: %s Totag: %s\n",
22665                  replace_id,
22666                  fromtag ? fromtag : "<no from tag>",
22667                  totag ? totag : "<no to tag>");
22668 
22669       /* Try to find call that we are replacing.
22670          If we have a Replaces header, we need to cancel that call if we succeed with this call.
22671          First we cheat a little and look for a magic call-id from phones that support
22672          dialog-info+xml so we can do technology independent pickup... */
22673       if (strncmp(replace_id, "pickup-", 7) == 0) {
22674          struct sip_pvt *subscription = NULL;
22675          replace_id += 7; /* Worst case we are looking at \0 */
22676 
22677          if ((subscription = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
22678             ast_log(LOG_NOTICE, "Unable to find subscription with call-id: %s\n", replace_id);
22679             transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
22680             error = 1;
22681          } else {
22682             ast_log(LOG_NOTICE, "Trying to pick up %s@%s\n", subscription->exten, subscription->context);
22683             ast_copy_string(pickup.exten, subscription->exten, sizeof(pickup.exten));
22684             ast_copy_string(pickup.context, subscription->context, sizeof(pickup.context));
22685             sip_pvt_unlock(subscription);
22686             if (subscription->owner) {
22687                ast_channel_unlock(subscription->owner);
22688             }
22689             subscription = dialog_unref(subscription, "unref dialog subscription");
22690          }
22691       }
22692 
22693       /* This locks both refer_call pvt and refer_call pvt's owner!!!*/
22694       if (!error && ast_strlen_zero(pickup.exten) && (p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
22695          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
22696          transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
22697          error = 1;
22698       } else {
22699          refer_locked = 1;
22700       }
22701 
22702       /* The matched call is the call from the transferer to Asterisk .
22703          We want to bridge the bridged part of the call to the
22704          incoming invite, thus taking over the refered call */
22705 
22706       if (p->refer->refer_call == p) {
22707          ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
22708          transmit_response_reliable(p, "400 Bad request", req);   /* The best way to not not accept the transfer */
22709          error = 1;
22710       }
22711 
22712       if (!error && ast_strlen_zero(pickup.exten) && !p->refer->refer_call->owner) {
22713          /* Oops, someting wrong anyway, no owner, no call */
22714          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
22715          /* Check for better return code */
22716          transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replace)", req);
22717          error = 1;
22718       }
22719 
22720       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) {
22721          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
22722          transmit_response_reliable(p, "603 Declined (Replaces)", req);
22723          error = 1;
22724       }
22725 
22726       if (error) {   /* Give up this dialog */
22727          append_history(p, "Xfer", "INVITE/Replace Failed.");
22728          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22729          sip_pvt_unlock(p);
22730          if (p->refer->refer_call) {
22731             sip_pvt_unlock(p->refer->refer_call);
22732             if (p->refer->refer_call->owner) {
22733                ast_channel_unlock(p->refer->refer_call->owner);
22734             }
22735             p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
22736          }
22737          refer_locked = 0;
22738          p->invitestate = INV_COMPLETED;
22739          check_via(p, req);
22740          copy_request(&p->initreq, req);
22741          res = -1;
22742          goto request_invite_cleanup;
22743       }
22744    }
22745 
22746    /* Check if this is an INVITE that sets up a new dialog or
22747       a re-invite in an existing dialog */
22748 
22749    if (!req->ignore) {
22750       int newcall = (p->initreq.headers ? TRUE : FALSE);
22751 
22752       if (sip_cancel_destroy(p))
22753          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
22754       /* This also counts as a pending invite */
22755       p->pendinginvite = seqno;
22756       check_via(p, req);
22757 
22758       copy_request(&p->initreq, req);     /* Save this INVITE as the transaction basis */
22759       if (sipdebug)
22760          ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
22761       if (!p->owner) {  /* Not a re-invite */
22762          if (debug)
22763             ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
22764          if (newcall)
22765             append_history(p, "Invite", "New call: %s", p->callid);
22766          parse_ok_contact(p, req);
22767       } else { /* Re-invite on existing call */
22768          ast_clear_flag(&p->flags[0], SIP_OUTGOING);  /* This is now an inbound dialog */
22769          if (get_rpid(p, req)) {
22770             struct ast_party_connected_line connected;
22771             struct ast_set_party_connected_line update_connected;
22772 
22773             ast_party_connected_line_init(&connected);
22774             memset(&update_connected, 0, sizeof(update_connected));
22775 
22776             update_connected.id.number = 1;
22777             connected.id.number.valid = 1;
22778             connected.id.number.str = (char *) p->cid_num;
22779             connected.id.number.presentation = p->callingpres;
22780 
22781             update_connected.id.name = 1;
22782             connected.id.name.valid = 1;
22783             connected.id.name.str = (char *) p->cid_name;
22784             connected.id.name.presentation = p->callingpres;
22785 
22786             connected.id.tag = (char *) p->cid_tag;
22787             connected.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
22788             ast_channel_queue_connected_line_update(p->owner, &connected,
22789                &update_connected);
22790          }
22791          /* Handle SDP here if we already have an owner */
22792          if (find_sdp(req)) {
22793             if (process_sdp(p, req, SDP_T38_INITIATE)) {
22794                if (!ast_strlen_zero(get_header(req, "Content-Encoding"))) {
22795                   /* Asterisk does not yet support any Content-Encoding methods.  Always
22796                    * attempt to process the sdp, but return a 415 if a Content-Encoding header
22797                    * was present after processing failed.  */
22798                   transmit_response_reliable(p, "415 Unsupported Media type", req);
22799                } else {
22800                   transmit_response_reliable(p, "488 Not acceptable here", req);
22801                }
22802                if (!p->lastinvite)
22803                   sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22804                res = -1;
22805                goto request_invite_cleanup;
22806             }
22807             ast_queue_control(p->owner, AST_CONTROL_SRCUPDATE);
22808          } else {
22809             p->jointcapability = p->capability;
22810             ast_debug(1, "Hm....  No sdp for the moment\n");
22811             /* Some devices signal they want to be put off hold by sending a re-invite
22812                *without* an SDP, which is supposed to mean "Go back to your state"
22813                and since they put os on remote hold, we go back to off hold */
22814             if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
22815                ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
22816                /* Activate a re-invite */
22817                ast_queue_frame(p->owner, &ast_null_frame);
22818                change_hold_state(p, req, FALSE, 0);
22819             }
22820          }
22821          if (p->do_history) /* This is a response, note what it was for */
22822             append_history(p, "ReInv", "Re-invite received");
22823       }
22824    } else if (debug)
22825       ast_verbose("Ignoring this INVITE request\n");
22826 
22827    if (!p->lastinvite && !req->ignore && !p->owner) {
22828       /* This is a new invite */
22829       /* Handle authentication if this is our first invite */
22830       int cc_recall_core_id = -1;
22831       set_pvt_allowed_methods(p, req);
22832       res = check_user_full(p, req, SIP_INVITE, e, XMIT_RELIABLE, addr, &authpeer);
22833       if (res == AUTH_CHALLENGE_SENT) {
22834          p->invitestate = INV_COMPLETED;     /* Needs to restart in another INVITE transaction */
22835          res = 0;
22836          goto request_invite_cleanup;
22837       }
22838       if (res < 0) { /* Something failed in authentication */
22839          if (res == AUTH_FAKE_AUTH) {
22840             ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
22841             transmit_fake_auth_response(p, SIP_INVITE, req, XMIT_RELIABLE);
22842          } else {
22843             ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
22844             transmit_response_reliable(p, "403 Forbidden", req);
22845          }
22846          p->invitestate = INV_COMPLETED;
22847          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22848          res = 0;
22849          goto request_invite_cleanup;
22850       }
22851 
22852       /* Successful authentication and peer matching so record the peer related to this pvt (for easy access to peer settings) */
22853       if (p->relatedpeer) {
22854          p->relatedpeer = unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
22855       }
22856       if (authpeer) {
22857          p->relatedpeer = ref_peer(authpeer, "setting dialog's relatedpeer pointer");
22858       }
22859 
22860       req->authenticated = 1;
22861 
22862       /* We have a successful authentication, process the SDP portion if there is one */
22863       if (find_sdp(req)) {
22864          if (process_sdp(p, req, SDP_T38_INITIATE)) {
22865             /* Asterisk does not yet support any Content-Encoding methods.  Always
22866              * attempt to process the sdp, but return a 415 if a Content-Encoding header
22867              * was present after processing fails. */
22868             if (!ast_strlen_zero(get_header(req, "Content-Encoding"))) {
22869                transmit_response_reliable(p, "415 Unsupported Media type", req);
22870             } else {
22871                /* Unacceptable codecs */
22872                transmit_response_reliable(p, "488 Not acceptable here", req);
22873             }
22874             p->invitestate = INV_COMPLETED;
22875             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22876             ast_debug(1, "No compatible codecs for this SIP call.\n");
22877             res = -1;
22878             goto request_invite_cleanup;
22879          }
22880       } else { /* No SDP in invite, call control session */
22881          p->jointcapability = p->capability;
22882          ast_debug(2, "No SDP in Invite, third party call control\n");
22883       }
22884 
22885       /* Queue NULL frame to prod ast_rtp_bridge if appropriate */
22886       /* This seems redundant ... see !p-owner above */
22887       if (p->owner)
22888          ast_queue_frame(p->owner, &ast_null_frame);
22889 
22890 
22891       /* Initialize the context if it hasn't been already */
22892       if (ast_strlen_zero(p->context))
22893          ast_string_field_set(p, context, sip_cfg.default_context);
22894 
22895 
22896       /* Check number of concurrent calls -vs- incoming limit HERE */
22897       ast_debug(1, "Checking SIP call limits for device %s\n", p->username);
22898       if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
22899          if (res < 0) {
22900             ast_log(LOG_NOTICE, "Failed to place call for device %s, too many calls\n", p->username);
22901             transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
22902             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22903             p->invitestate = INV_COMPLETED;
22904          }
22905          res = 0;
22906          goto request_invite_cleanup;
22907       }
22908       gotdest = get_destination(p, NULL, &cc_recall_core_id);  /* Get destination right away */
22909       extract_uri(p, req);       /* Get the Contact URI */
22910       build_contact(p);       /* Build our contact header */
22911 
22912       if (p->rtp) {
22913          ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
22914          ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF_COMPENSATE, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
22915       }
22916 
22917       if (!replace_id && (gotdest != SIP_GET_DEST_EXTEN_FOUND)) { /* No matching extension found */
22918          switch(gotdest) {
22919          case SIP_GET_DEST_INVALID_URI:
22920             transmit_response_reliable(p, "416 Unsupported URI scheme", req);
22921             break;
22922          case SIP_GET_DEST_EXTEN_MATCHMORE:
22923             if (ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP)
22924                == SIP_PAGE2_ALLOWOVERLAP_YES) {
22925                transmit_response_reliable(p, "484 Address Incomplete", req);
22926                break;
22927             }
22928             /*
22929              * XXX We would have to implement collecting more digits in
22930              * chan_sip for any other schemes of overlap dialing.
22931              *
22932              * For SIP_PAGE2_ALLOWOVERLAP_DTMF it is better to do this in
22933              * the dialplan using the Incomplete application rather than
22934              * having the channel driver do it.
22935              */
22936             /* Fall through */
22937          case SIP_GET_DEST_EXTEN_NOT_FOUND:
22938             {
22939                char *decoded_exten = ast_strdupa(p->exten);
22940                transmit_response_reliable(p, "404 Not Found", req);
22941                ast_uri_decode(decoded_exten);
22942                ast_log(LOG_NOTICE, "Call from '%s' (%s) to extension"
22943                   " '%s' rejected because extension not found in context '%s'.\n",
22944                   S_OR(p->username, p->peername), ast_sockaddr_stringify(&p->recv), decoded_exten, p->context);
22945             }
22946             break;
22947          case SIP_GET_DEST_REFUSED:
22948          default:
22949             transmit_response_reliable(p, "403 Forbidden", req);
22950          } /* end switch */
22951 
22952          p->invitestate = INV_COMPLETED;
22953          update_call_counter(p, DEC_CALL_LIMIT);
22954          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
22955          res = 0;
22956          goto request_invite_cleanup;
22957       } else {
22958 
22959          /* If no extension was specified, use the s one */
22960          /* Basically for calling to IP/Host name only */
22961          if (ast_strlen_zero(p->exten))
22962             ast_string_field_set(p, exten, "s");
22963          /* Initialize our tag */
22964 
22965          make_our_tag(p);
22966          /* First invitation - create the channel.  Allocation
22967           * failures are handled below. */
22968          c = sip_new(p, AST_STATE_DOWN, S_OR(p->peername, NULL), NULL);
22969          if (cc_recall_core_id != -1) {
22970             ast_setup_cc_recall_datastore(c, cc_recall_core_id);
22971             ast_cc_agent_set_interfaces_chanvar(c);
22972          }
22973          *recount = 1;
22974 
22975          /* Save Record-Route for any later requests we make on this dialogue */
22976          build_route(p, req, 0, 0);
22977 
22978          if (c) {
22979             ast_party_redirecting_init(&redirecting);
22980             memset(&update_redirecting, 0, sizeof(update_redirecting));
22981             change_redirecting_information(p, req, &redirecting, &update_redirecting,
22982                FALSE); /*Will return immediately if no Diversion header is present */
22983             ast_channel_set_redirecting(c, &redirecting, &update_redirecting);
22984             ast_party_redirecting_free(&redirecting);
22985          }
22986       }
22987    } else {
22988       ast_party_redirecting_init(&redirecting);
22989       memset(&update_redirecting, 0, sizeof(update_redirecting));
22990       if (sipdebug) {
22991          if (!req->ignore)
22992             ast_debug(2, "Got a SIP re-invite for call %s\n", p->callid);
22993          else
22994             ast_debug(2, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
22995       }
22996       if (!req->ignore)
22997          reinvite = 1;
22998       c = p->owner;
22999       change_redirecting_information(p, req, &redirecting, &update_redirecting, FALSE); /*Will return immediately if no Diversion header is present */
23000       if (c) {
23001          ast_channel_set_redirecting(c, &redirecting, &update_redirecting);
23002       }
23003       ast_party_redirecting_free(&redirecting);
23004    }
23005 
23006    /* Session-Timers */
23007    if ((p->sipoptions & SIP_OPT_TIMER) && !ast_strlen_zero(get_header(req, "Session-Expires"))) {
23008       enum st_refresher_param st_ref_param;
23009 
23010       /* The UAC has requested session-timers for this session. Negotiate
23011       the session refresh interval and who will be the refresher */
23012       ast_debug(2, "Incoming INVITE with 'timer' option supported and \"Session-Expires\" header.\n");
23013 
23014       /* Allocate Session-Timers struct w/in the dialog */
23015       if (!p->stimer)
23016          sip_st_alloc(p);
23017 
23018       /* Parse the Session-Expires header */
23019       p_uac_se_hdr = get_header(req, "Session-Expires");
23020       rtn = parse_session_expires(p_uac_se_hdr, &uac_max_se, &st_ref_param);
23021       tmp_st_ref = (st_ref_param == SESSION_TIMER_REFRESHER_PARAM_UAC) ? SESSION_TIMER_REFRESHER_THEM : SESSION_TIMER_REFRESHER_US;
23022       if (rtn != 0) {
23023          transmit_response_reliable(p, "400 Session-Expires Invalid Syntax", req);
23024          p->invitestate = INV_COMPLETED;
23025          if (!p->lastinvite) {
23026             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23027          }
23028          res = -1;
23029          goto request_invite_cleanup;
23030       }
23031 
23032       /* Parse the Min-SE header */
23033       p_uac_min_se = get_header(req, "Min-SE");
23034       if (!ast_strlen_zero(p_uac_min_se)) {
23035          rtn = parse_minse(p_uac_min_se, &uac_min_se);
23036          if (rtn != 0) {
23037             transmit_response_reliable(p, "400 Min-SE Invalid Syntax", req);
23038             p->invitestate = INV_COMPLETED;
23039             if (!p->lastinvite) {
23040                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23041             }
23042             res = -1;
23043             goto request_invite_cleanup;
23044          }
23045       }
23046 
23047       dlg_min_se = st_get_se(p, FALSE);
23048       switch (st_get_mode(p, 1)) {
23049       case SESSION_TIMER_MODE_ACCEPT:
23050       case SESSION_TIMER_MODE_ORIGINATE:
23051          if (uac_max_se > 0 && uac_max_se < dlg_min_se) {
23052             transmit_response_with_minse(p, "422 Session Interval Too Small", req, dlg_min_se);
23053             p->invitestate = INV_COMPLETED;
23054             if (!p->lastinvite) {
23055                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23056             }
23057             res = -1;
23058             goto request_invite_cleanup;
23059          }
23060 
23061          p->stimer->st_active_peer_ua = TRUE;
23062          st_active = TRUE;
23063          if (st_ref_param == SESSION_TIMER_REFRESHER_PARAM_UNKNOWN) {
23064             tmp_st_ref = st_get_refresher(p);
23065          }
23066 
23067          if (uac_max_se > 0) {
23068             int dlg_max_se = st_get_se(p, TRUE);
23069             if (dlg_max_se >= uac_min_se) {
23070                st_interval = (uac_max_se < dlg_max_se) ? uac_max_se : dlg_max_se;
23071             } else {
23072                st_interval = uac_max_se;
23073             }
23074          } else {
23075             /* Set to default max value */
23076             st_interval = global_max_se;
23077          }
23078          break;
23079 
23080       case SESSION_TIMER_MODE_REFUSE:
23081          if (p->reqsipoptions & SIP_OPT_TIMER) {
23082             transmit_response_with_unsupported(p, "420 Option Disabled", req, required);
23083             ast_log(LOG_WARNING, "Received SIP INVITE with supported but disabled option: %s\n", required);
23084             p->invitestate = INV_COMPLETED;
23085             if (!p->lastinvite) {
23086                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23087             }
23088             res = -1;
23089             goto request_invite_cleanup;
23090          }
23091          break;
23092 
23093       default:
23094          ast_log(LOG_ERROR, "Internal Error %d at %s:%d\n", st_get_mode(p, 1), __FILE__, __LINE__);
23095          break;
23096       }
23097    } else {
23098       /* The UAC did not request session-timers.  Asterisk (UAS), will now decide
23099       (based on session-timer-mode in sip.conf) whether to run session-timers for
23100       this session or not. */
23101       switch (st_get_mode(p, 1)) {
23102       case SESSION_TIMER_MODE_ORIGINATE:
23103          st_active = TRUE;
23104          st_interval = st_get_se(p, TRUE);
23105          tmp_st_ref = SESSION_TIMER_REFRESHER_US;
23106          p->stimer->st_active_peer_ua = FALSE;
23107          break;
23108 
23109       default:
23110          break;
23111       }
23112    }
23113 
23114    if (reinvite == 0) {
23115       /* Session-Timers: Start session refresh timer based on negotiation/config */
23116       if (st_active == TRUE) {
23117          p->stimer->st_active = TRUE;
23118          p->stimer->st_interval = st_interval;
23119          p->stimer->st_ref = tmp_st_ref;
23120          start_session_timer(p);
23121       }
23122    } else {
23123       if (p->stimer->st_active == TRUE) {
23124          /* Session-Timers:  A re-invite request sent within a dialog will serve as
23125          a refresh request, no matter whether the re-invite was sent for refreshing
23126          the session or modifying it.*/
23127          ast_debug (2, "Restarting session-timers on a refresh - %s\n", p->callid);
23128 
23129          /* The UAC may be adjusting the session-timers mid-session */
23130          if (st_interval > 0) {
23131             p->stimer->st_interval = st_interval;
23132             p->stimer->st_ref      = tmp_st_ref;
23133          }
23134 
23135          restart_session_timer(p);
23136          if (p->stimer->st_expirys > 0) {
23137             p->stimer->st_expirys--;
23138          }
23139       }
23140    }
23141 
23142    if (!req->ignore && p)
23143       p->lastinvite = seqno;
23144 
23145    if (c && replace_id) {  /* Attended transfer or call pickup - we're the target */
23146       if (!ast_strlen_zero(pickup.exten)) {
23147          append_history(p, "Xfer", "INVITE/Replace received");
23148 
23149          /* Let the caller know we're giving it a shot */
23150          transmit_response(p, "100 Trying", req);
23151          p->invitestate = INV_PROCEEDING;
23152          ast_setstate(c, AST_STATE_RING);
23153 
23154          /* Do the pickup itself */
23155          ast_channel_unlock(c);
23156          *nounlock = 1;
23157 
23158          /* since p->owner (c) is unlocked, we need to go ahead and unlock pvt for both
23159           * magic pickup and ast_hangup.  Both of these functions will attempt to lock
23160           * p->owner again, which can cause a deadlock if we already hold a lock on p.
23161           * Locking order is, channel then pvt.  Dead lock avoidance must be used if
23162           * called the other way around. */
23163          sip_pvt_unlock(p);
23164          do_magic_pickup(c, pickup.exten, pickup.context);
23165          /* Now we're either masqueraded or we failed to pickup, in either case we... */
23166          ast_hangup(c);
23167          sip_pvt_lock(p); /* pvt is expected to remain locked on return, so re-lock it */
23168 
23169          res = 0;
23170          goto request_invite_cleanup;
23171       } else {
23172          /* Go and take over the target call */
23173          if (sipdebug)
23174             ast_debug(4, "Sending this call to the invite/replcaes handler %s\n", p->callid);
23175          res = handle_invite_replaces(p, req, debug, seqno, addr, nounlock);
23176          refer_locked = 0;
23177          goto request_invite_cleanup;
23178       }
23179    }
23180 
23181 
23182    if (c) { /* We have a call  -either a new call or an old one (RE-INVITE) */
23183       enum ast_channel_state c_state = c->_state;
23184 
23185       if (c_state != AST_STATE_UP && reinvite &&
23186          (p->invitestate == INV_TERMINATED || p->invitestate == INV_CONFIRMED)) {
23187          /* If these conditions are true, and the channel is still in the 'ringing'
23188           * state, then this likely means that we have a situation where the initial
23189           * INVITE transaction has completed *but* the channel's state has not yet been
23190           * changed to UP. The reason this could happen is if the reinvite is received
23191           * on the SIP socket prior to an application calling ast_read on this channel
23192           * to read the answer frame we earlier queued on it. In this case, the reinvite
23193           * is completely legitimate so we need to handle this the same as if the channel
23194           * were already UP. Thus we are purposely falling through to the AST_STATE_UP case.
23195           */
23196          c_state = AST_STATE_UP;
23197       }
23198 
23199       switch(c_state) {
23200       case AST_STATE_DOWN:
23201          ast_debug(2, "%s: New call is still down.... Trying... \n", c->name);
23202          transmit_provisional_response(p, "100 Trying", req, 0);
23203          p->invitestate = INV_PROCEEDING;
23204          ast_setstate(c, AST_STATE_RING);
23205          if (strcmp(p->exten, ast_pickup_ext())) { /* Call to extension -start pbx on this call */
23206             enum ast_pbx_result result;
23207 
23208             result = ast_pbx_start(c);
23209 
23210             switch(result) {
23211             case AST_PBX_FAILED:
23212                ast_log(LOG_WARNING, "Failed to start PBX :(\n");
23213                p->invitestate = INV_COMPLETED;
23214                transmit_response_reliable(p, "503 Unavailable", req);
23215                break;
23216             case AST_PBX_CALL_LIMIT:
23217                ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
23218                p->invitestate = INV_COMPLETED;
23219                transmit_response_reliable(p, "480 Temporarily Unavailable", req);
23220                break;
23221             case AST_PBX_SUCCESS:
23222                /* nothing to do */
23223                break;
23224             }
23225 
23226             if (result) {
23227 
23228                /* Unlock locks so ast_hangup can do its magic */
23229                ast_channel_unlock(c);
23230                *nounlock = 1;
23231                sip_pvt_unlock(p);
23232                ast_hangup(c);
23233                sip_pvt_lock(p);
23234                c = NULL;
23235             }
23236          } else { /* Pickup call in call group */
23237             if (sip_pickup(c)) {
23238                ast_log(LOG_WARNING, "Failed to start Group pickup by %s\n", c->name);
23239                transmit_response_reliable(p, "480 Temporarily Unavailable", req);
23240                sip_alreadygone(p);
23241                c->hangupcause = AST_CAUSE_FAILURE;
23242 
23243                /* Unlock locks so ast_hangup can do its magic */
23244                ast_channel_unlock(c);
23245                *nounlock = 1;
23246 
23247                p->invitestate = INV_COMPLETED;
23248                sip_pvt_unlock(p);
23249                ast_hangup(c);
23250                sip_pvt_lock(p);
23251                c = NULL;
23252             }
23253          }
23254          break;
23255       case AST_STATE_RING:
23256          transmit_provisional_response(p, "100 Trying", req, 0);
23257          p->invitestate = INV_PROCEEDING;
23258          break;
23259       case AST_STATE_RINGING:
23260          transmit_provisional_response(p, "180 Ringing", req, 0);
23261          p->invitestate = INV_PROCEEDING;
23262          break;
23263       case AST_STATE_UP:
23264          ast_debug(2, "%s: This call is UP.... \n", c->name);
23265 
23266          transmit_response(p, "100 Trying", req);
23267 
23268          if (p->t38.state == T38_PEER_REINVITE) {
23269             if (p->t38id > -1) {
23270                /* reset t38 abort timer */
23271                AST_SCHED_DEL_UNREF(sched, p->t38id, dialog_unref(p, "remove ref for t38id"));
23272             }
23273             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."));
23274          } else if (p->t38.state == T38_ENABLED) {
23275             ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
23276             transmit_response_with_t38_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ?  XMIT_UNRELIABLE : XMIT_CRITICAL)));
23277          } else if (p->t38.state == T38_DISABLED) {
23278             /* If this is not a re-invite or something to ignore - it's critical */
23279             if (p->srtp && !ast_test_flag(p->srtp, SRTP_CRYPTO_OFFER_OK)) {
23280                ast_log(LOG_WARNING, "Target does not support required crypto\n");
23281                transmit_response_reliable(p, "488 Not Acceptable Here (crypto)", req);
23282             } else {
23283                ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
23284                transmit_response_with_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ?  XMIT_UNRELIABLE : XMIT_CRITICAL)), p->session_modify == TRUE ? FALSE : TRUE, FALSE);
23285                ast_queue_control(p->owner, AST_CONTROL_UPDATE_RTP_PEER);
23286             }
23287          }
23288 
23289          p->invitestate = INV_TERMINATED;
23290          break;
23291       default:
23292          ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
23293          transmit_response(p, "100 Trying", req);
23294          break;
23295       }
23296    } else {
23297       if (p && (p->autokillid == -1)) {
23298          const char *msg;
23299 
23300          if (!p->jointcapability)
23301             msg = "488 Not Acceptable Here (codec error)";
23302          else {
23303             ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
23304             msg = "503 Unavailable";
23305          }
23306          transmit_response_reliable(p, msg, req);
23307          p->invitestate = INV_COMPLETED;
23308          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
23309       }
23310    }
23311 
23312 request_invite_cleanup:
23313 
23314    if (refer_locked && p->refer && p->refer->refer_call) {
23315       sip_pvt_unlock(p->refer->refer_call);
23316       if (p->refer->refer_call->owner) {
23317          ast_channel_unlock(p->refer->refer_call->owner);
23318       }
23319       p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
23320    }
23321    if (authpeer) {
23322       authpeer = unref_peer(authpeer, "unref_peer, from handle_request_invite authpeer");
23323    }
23324 
23325    return res;
23326 }
23327 
23328 /*! \brief  Find all call legs and bridge transferee with target
23329  * called from handle_request_refer
23330  *
23331  * \note this function assumes two locks to begin with, sip_pvt transferer and current.chan1 (the pvt's owner)... 
23332  * 2 additional locks are held at the beginning of the function, targetcall_pvt, and targetcall_pvt's owner
23333  * channel (which is stored in target.chan1).  These 2 locks _MUST_ be let go by the end of the function.  Do
23334  * not be confused into thinking a pvt's owner is the same thing as the channels locked at the beginning of
23335  * this function, after the masquerade this may not be true.  Be consistent and unlock only the exact same
23336  * pointers that were locked to begin with.
23337  *
23338  * If this function is successful, only the transferer pvt lock will remain on return.  Setting nounlock indicates
23339  * to handle_request_do() that the pvt's owner it locked does not require an unlock.
23340  */
23341 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, uint32_t seqno, int *nounlock)
23342 {
23343    struct sip_dual target;    /* Chan 1: Call from tranferer to Asterisk */
23344                /* Chan 2: Call from Asterisk to target */
23345    int res = 0;
23346    struct sip_pvt *targetcall_pvt;
23347    struct ast_party_connected_line connected_to_transferee;
23348    struct ast_party_connected_line connected_to_target;
23349    char transferer_linkedid[32];
23350    struct ast_channel *chans[2];
23351 
23352    /* Check if the call ID of the replaces header does exist locally */
23353    if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag,
23354       transferer->refer->replaces_callid_fromtag))) {
23355       if (transferer->refer->localtransfer) {
23356          /* We did not find the refered call. Sorry, can't accept then */
23357          /* Let's fake a response from someone else in order
23358             to follow the standard */
23359          transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
23360          append_history(transferer, "Xfer", "Refer failed");
23361          ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
23362          transferer->refer->status = REFER_FAILED;
23363          return -1;
23364       }
23365       /* Fall through for remote transfers that we did not find locally */
23366       ast_debug(3, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
23367       return 0;
23368    }
23369 
23370    /* Ok, we can accept this transfer */
23371    append_history(transferer, "Xfer", "Refer accepted");
23372    if (!targetcall_pvt->owner) { /* No active channel */
23373       ast_debug(4, "SIP attended transfer: Error: No owner of target call\n");
23374       /* Cancel transfer */
23375       transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
23376       append_history(transferer, "Xfer", "Refer failed");
23377       ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
23378       transferer->refer->status = REFER_FAILED;
23379       sip_pvt_unlock(targetcall_pvt);
23380       if (targetcall_pvt)
23381          ao2_t_ref(targetcall_pvt, -1, "Drop targetcall_pvt pointer");
23382       return -1;
23383    }
23384 
23385    /* We have a channel, find the bridge */
23386    target.chan1 = targetcall_pvt->owner;           /* Transferer to Asterisk */
23387    target.chan2 = ast_bridged_channel(targetcall_pvt->owner);  /* Asterisk to target */
23388 
23389    if (!target.chan2 || !(target.chan2->_state == AST_STATE_UP || target.chan2->_state == AST_STATE_RINGING) ) {
23390       /* Wrong state of new channel */
23391       if (target.chan2)
23392          ast_debug(4, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(target.chan2->_state));
23393       else if (target.chan1->_state != AST_STATE_RING)
23394          ast_debug(4, "SIP attended transfer: Error: No target channel\n");
23395       else
23396          ast_debug(4, "SIP attended transfer: Attempting transfer in ringing state\n");
23397    }
23398 
23399    /* Transfer */
23400    if (sipdebug) {
23401       if (current->chan2)  /* We have two bridges */
23402          ast_debug(4, "SIP attended transfer: trying to bridge %s and %s\n", target.chan1->name, current->chan2->name);
23403       else        /* One bridge, propably transfer of IVR/voicemail etc */
23404          ast_debug(4, "SIP attended transfer: trying to make %s take over (masq) %s\n", target.chan1->name, current->chan1->name);
23405    }
23406 
23407    ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);   /* Delay hangup */
23408 
23409    ast_copy_string(transferer_linkedid, transferer->owner->linkedid, sizeof(transferer_linkedid));
23410 
23411    /* Perform the transfer */
23412    chans[0] = transferer->owner;
23413    chans[1] = target.chan1;
23414    ast_manager_event_multichan(EVENT_FLAG_CALL, "Transfer", 2, chans,
23415       "TransferMethod: SIP\r\n"
23416       "TransferType: Attended\r\n"
23417       "Channel: %s\r\n"
23418       "Uniqueid: %s\r\n"
23419       "SIP-Callid: %s\r\n"
23420       "TargetChannel: %s\r\n"
23421       "TargetUniqueid: %s\r\n",
23422       transferer->owner->name,
23423       transferer->owner->uniqueid,
23424       transferer->callid,
23425       target.chan1->name,
23426       target.chan1->uniqueid);
23427    ast_party_connected_line_init(&connected_to_transferee);
23428    ast_party_connected_line_init(&connected_to_target);
23429    /* No need to lock current->chan1 here since it was locked in sipsock_read */
23430    ast_party_connected_line_copy(&connected_to_transferee, &current->chan1->connected);
23431    /* No need to lock target.chan1 here since it was locked in get_sip_pvt_byid_locked */
23432    ast_party_connected_line_copy(&connected_to_target, &target.chan1->connected);
23433    connected_to_target.source = connected_to_transferee.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
23434    res = attempt_transfer(current, &target);
23435    if (res) {
23436       /* Failed transfer */
23437       transmit_notify_with_sipfrag(transferer, seqno, "486 Busy Here", TRUE);
23438       append_history(transferer, "Xfer", "Refer failed");
23439       ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
23440       /* if transfer failed, go ahead and unlock targetcall_pvt and it's owner channel */
23441       sip_pvt_unlock(targetcall_pvt);
23442       ast_channel_unlock(target.chan1);
23443    } else {
23444       /* Transfer succeeded! */
23445       const char *xfersound = pbx_builtin_getvar_helper(target.chan1, "ATTENDED_TRANSFER_COMPLETE_SOUND");
23446 
23447       /* target.chan1 was locked in get_sip_pvt_byid_locked, do not unlock target.chan1 before this */
23448       ast_cel_report_event(target.chan1, AST_CEL_ATTENDEDTRANSFER, NULL, transferer_linkedid, target.chan2);
23449 
23450       /* Tell transferer that we're done. */
23451       transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
23452       append_history(transferer, "Xfer", "Refer succeeded");
23453       transferer->refer->status = REFER_200OK;
23454       if (target.chan2 && !ast_strlen_zero(xfersound) && ast_streamfile(target.chan2, xfersound, target.chan2->language) >= 0) {
23455          ast_waitstream(target.chan2, "");
23456       }
23457 
23458       /* By forcing the masquerade, we know that target.chan1 and target.chan2 are bridged. We then
23459        * can queue connected line updates where they need to go.
23460        *
23461        * before a masquerade, all channel and pvt locks must be unlocked.  Any recursive
23462        * channel locks held before this function invalidates channel container locking order.
23463        * Since we are unlocking both the pvt (transferer) and its owner channel (current.chan1)
23464        * it is possible for current.chan1 to be destroyed in the pbx thread.  To prevent this
23465        * we must give c a reference before any unlocking takes place.
23466        */
23467 
23468       ast_channel_ref(current->chan1);
23469       ast_channel_unlock(current->chan1); /* current.chan1 is p->owner before the masq, it was locked by socket_read()*/
23470       ast_channel_unlock(target.chan1);
23471       *nounlock = 1;  /* we just unlocked the dialog's channel and have no plans of locking it again. */
23472       sip_pvt_unlock(targetcall_pvt);
23473       sip_pvt_unlock(transferer);
23474 
23475       ast_do_masquerade(target.chan1);
23476 
23477       ast_indicate(target.chan1, AST_CONTROL_UNHOLD);
23478       if (target.chan2) {
23479          ast_indicate(target.chan2, AST_CONTROL_UNHOLD);
23480       }
23481 
23482       if (current->chan2 && current->chan2->_state == AST_STATE_RING) {
23483          ast_indicate(target.chan1, AST_CONTROL_RINGING);
23484       }
23485 
23486       if (target.chan2) {
23487          ast_channel_queue_connected_line_update(target.chan1, &connected_to_transferee, NULL);
23488          ast_channel_queue_connected_line_update(target.chan2, &connected_to_target, NULL);
23489       } else {
23490          /* Since target.chan1 isn't actually connected to another channel, there is no way for us
23491           * to queue a frame so that its connected line status will be updated.
23492           *
23493           * Instead, we use the somewhat hackish approach of using a special control frame type that
23494           * instructs ast_read to perform a specific action. In this case, the frame we queue tells
23495           * ast_read to call the connected line interception macro configured for target.chan1.
23496           */
23497          struct ast_control_read_action_payload *frame_payload;
23498          int payload_size;
23499          int frame_size;
23500          unsigned char connected_line_data[1024];
23501          payload_size = ast_connected_line_build_data(connected_line_data,
23502             sizeof(connected_line_data), &connected_to_target, NULL);
23503          frame_size = payload_size + sizeof(*frame_payload);
23504          if (payload_size != -1) {
23505             frame_payload = ast_alloca(frame_size);
23506             frame_payload->payload_size = payload_size;
23507             memcpy(frame_payload->payload, connected_line_data, payload_size);
23508             frame_payload->action = AST_FRAME_READ_ACTION_CONNECTED_LINE_MACRO;
23509             ast_queue_control_data(target.chan1, AST_CONTROL_READ_ACTION, frame_payload, frame_size);
23510          }
23511          /* In addition to queueing the read action frame so that target.chan1's connected line info
23512           * will be updated, we also are going to queue a plain old connected line update on target.chan1. This
23513           * way, either Dial or Queue can apply this connected line update to the outgoing ringing channel.
23514           */
23515          ast_channel_queue_connected_line_update(target.chan1, &connected_to_transferee, NULL);
23516 
23517       }
23518       sip_pvt_lock(transferer); /* the transferer pvt is expected to remain locked on return */
23519 
23520       ast_channel_unref(current->chan1);
23521    }
23522 
23523    /* at this point if the transfer is successful only the transferer pvt should be locked. */
23524    ast_party_connected_line_free(&connected_to_target);
23525    ast_party_connected_line_free(&connected_to_transferee);
23526    if (targetcall_pvt)
23527       ao2_t_ref(targetcall_pvt, -1, "drop targetcall_pvt");
23528    return 1;
23529 }
23530 
23531 
23532 /*! \brief Handle incoming REFER request */
23533 /*! \page SIP_REFER SIP transfer Support (REFER)
23534 
23535    REFER is used for call transfer in SIP. We get a REFER
23536    to place a new call with an INVITE somwhere and then
23537    keep the transferor up-to-date of the transfer. If the
23538    transfer fails, get back on line with the orginal call.
23539 
23540    - REFER can be sent outside or inside of a dialog.
23541      Asterisk only accepts REFER inside of a dialog.
23542 
23543    - If we get a replaces header, it is an attended transfer
23544 
23545    \par Blind transfers
23546    The transferor provides the transferee
23547    with the transfer targets contact. The signalling between
23548    transferer or transferee should not be cancelled, so the
23549    call is recoverable if the transfer target can not be reached
23550    by the transferee.
23551 
23552    In this case, Asterisk receives a TRANSFER from
23553    the transferor, thus is the transferee. We should
23554    try to set up a call to the contact provided
23555    and if that fails, re-connect the current session.
23556    If the new call is set up, we issue a hangup.
23557    In this scenario, we are following section 5.2
23558    in the SIP CC Transfer draft. (Transfer without
23559    a GRUU)
23560 
23561    \par Transfer with consultation hold
23562    In this case, the transferor
23563    talks to the transfer target before the transfer takes place.
23564    This is implemented with SIP hold and transfer.
23565    Note: The invite From: string could indicate a transfer.
23566    (Section 6. Transfer with consultation hold)
23567    The transferor places the transferee on hold, starts a call
23568    with the transfer target to alert them to the impending
23569    transfer, terminates the connection with the target, then
23570    proceeds with the transfer (as in Blind transfer above)
23571 
23572    \par Attended transfer
23573    The transferor places the transferee
23574    on hold, calls the transfer target to alert them,
23575    places the target on hold, then proceeds with the transfer
23576    using a Replaces header field in the Refer-to header. This
23577    will force the transfee to send an Invite to the target,
23578    with a replaces header that instructs the target to
23579    hangup the call between the transferor and the target.
23580    In this case, the Refer/to: uses the AOR address. (The same
23581    URI that the transferee used to establish the session with
23582    the transfer target (To: ). The Require: replaces header should
23583    be in the INVITE to avoid the wrong UA in a forked SIP proxy
23584    scenario to answer and have no call to replace with.
23585 
23586    The referred-by header is *NOT* required, but if we get it,
23587    can be copied into the INVITE to the transfer target to
23588    inform the target about the transferor
23589 
23590    "Any REFER request has to be appropriately authenticated.".
23591    
23592    We can't destroy dialogs, since we want the call to continue.
23593    
23594    */
23595 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, uint32_t seqno, int *nounlock)
23596 {
23597    /*!
23598     * Chan1: Call between asterisk and transferer
23599     * Chan2: Call between asterisk and transferee
23600     */
23601    struct sip_dual current = { 0, };
23602    struct ast_channel *chans[2] = { 0, };
23603    char *refer_to = NULL;
23604    char *refer_to_domain = NULL;
23605    char *refer_to_context = NULL;
23606    char *referred_by = NULL;
23607    char *callid = NULL;
23608    int localtransfer = 0;
23609    int attendedtransfer = 0;
23610    int res = 0;
23611 
23612    if (req->debug) {
23613       ast_verbose("Call %s got a SIP call transfer from %s: (REFER)!\n",
23614          p->callid,
23615          ast_test_flag(&p->flags[0], SIP_OUTGOING) ? "callee" : "caller");
23616    }
23617 
23618    if (!p->owner) {
23619       /* This is a REFER outside of an existing SIP dialog */
23620       /* We can't handle that, so decline it */
23621       ast_debug(3, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
23622       transmit_response(p, "603 Declined (No dialog)", req);
23623       if (!req->ignore) {
23624          append_history(p, "Xfer", "Refer failed. Outside of dialog.");
23625          sip_alreadygone(p);
23626          pvt_set_needdestroy(p, "outside of dialog");
23627       }
23628       res = 0;
23629       goto handle_refer_cleanup;
23630    }
23631 
23632    /* Check if transfer is allowed from this device */
23633    if (p->allowtransfer == TRANSFER_CLOSED ) {
23634       /* Transfer not allowed, decline */
23635       transmit_response(p, "603 Declined (policy)", req);
23636       append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
23637       /* Do not destroy SIP session */
23638       res = 0;
23639       goto handle_refer_cleanup;
23640    }
23641 
23642    if (!req->ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
23643       /* Already have a pending REFER */
23644       transmit_response(p, "491 Request pending", req);
23645       append_history(p, "Xfer", "Refer failed. Request pending.");
23646       res = 0;
23647       goto handle_refer_cleanup;
23648    }
23649 
23650    /* Allocate memory for call transfer data */
23651    if (!p->refer && !sip_refer_allocate(p)) {
23652       transmit_response(p, "500 Internal Server Error", req);
23653       append_history(p, "Xfer", "Refer failed. Memory allocation error.");
23654       res = -3;
23655       goto handle_refer_cleanup;
23656    }
23657 
23658    res = get_refer_info(p, req); /* Extract headers */
23659 
23660    p->refer->status = REFER_SENT;
23661 
23662    if (res != 0) {
23663       switch (res) {
23664       case -2: /* Syntax error */
23665          transmit_response(p, "400 Bad Request (Refer-to missing)", req);
23666          append_history(p, "Xfer", "Refer failed. Refer-to missing.");
23667          if (req->debug) {
23668             ast_debug(1, "SIP transfer to black hole can't be handled (no refer-to: )\n");
23669          }
23670          break;
23671       case -3:
23672          transmit_response(p, "603 Declined (Non sip: uri)", req);
23673          append_history(p, "Xfer", "Refer failed. Non SIP uri");
23674          if (req->debug) {
23675             ast_debug(1, "SIP transfer to non-SIP uri denied\n");
23676          }
23677          break;
23678       default:
23679          /* Refer-to extension not found, fake a failed transfer */
23680          transmit_response(p, "202 Accepted", req);
23681          append_history(p, "Xfer", "Refer failed. Bad extension.");
23682          transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
23683          ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
23684          if (req->debug) {
23685             ast_debug(1, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
23686          }
23687          break;
23688       }
23689       res = 0;
23690       goto handle_refer_cleanup;
23691    }
23692    if (ast_strlen_zero(p->context)) {
23693       ast_string_field_set(p, context, sip_cfg.default_context);
23694    }
23695 
23696    /* If we do not support SIP domains, all transfers are local */
23697    if (sip_cfg.allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
23698       p->refer->localtransfer = 1;
23699       if (sipdebug) {
23700          ast_debug(3, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
23701       }
23702    } else if (AST_LIST_EMPTY(&domain_list) || check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
23703       /* This PBX doesn't bother with SIP domains or domain is local, so this transfer is local */
23704       p->refer->localtransfer = 1;
23705    } else if (sipdebug) {
23706       ast_debug(3, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
23707    }
23708 
23709    /* Is this a repeat of a current request? Ignore it */
23710    /* Don't know what else to do right now. */
23711    if (req->ignore) {
23712       goto handle_refer_cleanup;
23713    }
23714 
23715    /* If this is a blind transfer, we have the following
23716    channels to work with:
23717    - chan1, chan2: The current call between transferer and transferee (2 channels)
23718    - target_channel: A new call from the transferee to the target (1 channel)
23719    We need to stay tuned to what happens in order to be able
23720    to bring back the call to the transferer */
23721 
23722    /* If this is a attended transfer, we should have all call legs within reach:
23723    - chan1, chan2: The call between the transferer and transferee (2 channels)
23724    - target_channel, targetcall_pvt: The call between the transferer and the target (2 channels)
23725    We want to bridge chan2 with targetcall_pvt!
23726    
23727    The replaces call id in the refer message points
23728    to the call leg between Asterisk and the transferer.
23729    So we need to connect the target and the transferee channel
23730    and hangup the two other channels silently
23731    
23732    If the target is non-local, the call ID could be on a remote
23733    machine and we need to send an INVITE with replaces to the
23734    target. We basically handle this as a blind transfer
23735    and let the sip_call function catch that we need replaces
23736    header in the INVITE.
23737    */
23738 
23739    /* Get the transferer's channel */
23740    chans[0] = current.chan1 = p->owner;
23741 
23742    /* Find the other part of the bridge (2) - transferee */
23743    chans[1] = current.chan2 = ast_bridged_channel(current.chan1);
23744 
23745    ast_channel_ref(current.chan1);
23746    if (current.chan2) {
23747       ast_channel_ref(current.chan2);
23748    }
23749 
23750    if (sipdebug) {
23751       ast_debug(3, "SIP %s transfer: Transferer channel %s, transferee channel %s\n",
23752          p->refer->attendedtransfer ? "attended" : "blind",
23753          current.chan1->name,
23754          current.chan2 ? current.chan2->name : "<none>");
23755    }
23756 
23757    if (!current.chan2 && !p->refer->attendedtransfer) {
23758       /* No bridged channel, propably IVR or echo or similar... */
23759       /* Guess we should masquerade or something here */
23760       /* Until we figure it out, refuse transfer of such calls */
23761       if (sipdebug) {
23762          ast_debug(3, "Refused SIP transfer on non-bridged channel.\n");
23763       }
23764       p->refer->status = REFER_FAILED;
23765       append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
23766       transmit_response(p, "603 Declined", req);
23767       res = -1;
23768       goto handle_refer_cleanup;
23769    }
23770 
23771    if (current.chan2) {
23772       if (sipdebug) {
23773          ast_debug(4, "Got SIP transfer, applying to bridged peer '%s'\n", current.chan2->name);
23774       }
23775       ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
23776    }
23777 
23778    ast_set_flag(&p->flags[0], SIP_GOTREFER);
23779 
23780    /* From here on failures will be indicated with NOTIFY requests */
23781    transmit_response(p, "202 Accepted", req);
23782 
23783    /* Attended transfer: Find all call legs and bridge transferee with target*/
23784    if (p->refer->attendedtransfer) {
23785       /* both p and p->owner _MUST_ be locked while calling local_attended_transfer */
23786       if ((res = local_attended_transfer(p, &current, req, seqno, nounlock))) {
23787          goto handle_refer_cleanup; /* We're done with the transfer */
23788       }
23789       /* Fall through for remote transfers that we did not find locally */
23790       if (sipdebug) {
23791          ast_debug(4, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
23792       }
23793       /* Fallthrough if we can't find the call leg internally */
23794    }
23795 
23796    /* Copy data we can not safely access after letting the pvt lock go. */
23797    refer_to = ast_strdupa(p->refer->refer_to);
23798    refer_to_domain = ast_strdupa(p->refer->refer_to_domain);
23799    refer_to_context = ast_strdupa(p->refer->refer_to_context);
23800    referred_by = ast_strdupa(p->refer->referred_by);
23801    callid = ast_strdupa(p->callid);
23802    localtransfer = p->refer->localtransfer;
23803    attendedtransfer = p->refer->attendedtransfer;
23804 
23805    if (!*nounlock) {
23806       ast_channel_unlock(p->owner);
23807       *nounlock = 1;
23808    }
23809    sip_pvt_unlock(p);
23810 
23811    /* Parking a call.  DO NOT hold any locks while calling ast_parking_ext_valid() */
23812    if (localtransfer && ast_parking_ext_valid(refer_to, current.chan1, refer_to_context)) {
23813       sip_pvt_lock(p);
23814       ast_clear_flag(&p->flags[0], SIP_GOTREFER);
23815       p->refer->status = REFER_200OK;
23816       append_history(p, "Xfer", "REFER to call parking.");
23817       sip_pvt_unlock(p);
23818 
23819       ast_manager_event_multichan(EVENT_FLAG_CALL, "Transfer", 2, chans,
23820          "TransferMethod: SIP\r\n"
23821          "TransferType: Blind\r\n"
23822          "Channel: %s\r\n"
23823          "Uniqueid: %s\r\n"
23824          "SIP-Callid: %s\r\n"
23825          "TargetChannel: %s\r\n"
23826          "TargetUniqueid: %s\r\n"
23827          "TransferExten: %s\r\n"
23828          "Transfer2Parking: Yes\r\n",
23829          current.chan1->name,
23830          current.chan1->uniqueid,
23831          callid,
23832          current.chan2->name,
23833          current.chan2->uniqueid,
23834          refer_to);
23835 
23836       if (sipdebug) {
23837          ast_debug(4, "SIP transfer to parking: trying to park %s. Parked by %s\n", current.chan2->name, current.chan1->name);
23838       }
23839 
23840       /* DO NOT hold any locks while calling sip_park */
23841       if (sip_park(current.chan2, current.chan1, req, seqno, refer_to, refer_to_context)) {
23842          sip_pvt_lock(p);
23843          transmit_notify_with_sipfrag(p, seqno, "500 Internal Server Error", TRUE);
23844       } else {
23845          sip_pvt_lock(p);
23846       }
23847       goto handle_refer_cleanup;
23848    }
23849 
23850    /* Blind transfers and remote attended xfers.
23851     * Locks should not be held while calling pbx_builtin_setvar_helper. This function
23852     * locks the channel being passed into it.*/
23853    if (current.chan1 && current.chan2) {
23854       ast_debug(3, "chan1->name: %s\n", current.chan1->name);
23855       pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", current.chan2->name);
23856    }
23857 
23858    if (current.chan2) {
23859       pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", current.chan1->name);
23860       pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", refer_to_domain);
23861       pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
23862       /* One for the new channel */
23863       pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
23864       /* Attended transfer to remote host, prepare headers for the INVITE */
23865       if (!ast_strlen_zero(referred_by)) {
23866          pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", referred_by);
23867       }
23868    }
23869 
23870    sip_pvt_lock(p);
23871    /* Generate a Replaces string to be used in the INVITE during attended transfer */
23872    if (!ast_strlen_zero(p->refer->replaces_callid)) {
23873       char tempheader[SIPBUFSIZE];
23874       snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid,
23875          p->refer->replaces_callid_totag ? ";to-tag=" : "",
23876          p->refer->replaces_callid_totag,
23877          p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
23878          p->refer->replaces_callid_fromtag);
23879 
23880       if (current.chan2) {
23881          sip_pvt_unlock(p);
23882          pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader);
23883          sip_pvt_lock(p);
23884       }
23885    }
23886 
23887    /* Connect the call */
23888 
23889    /* FAKE ringing if not attended transfer */
23890    if (!p->refer->attendedtransfer) {
23891       transmit_notify_with_sipfrag(p, seqno, "180 Ringing", FALSE);
23892    }
23893 
23894    /* For blind transfer, this will lead to a new call */
23895    /* For attended transfer to remote host, this will lead to
23896       a new SIP call with a replaces header, if the dial plan allows it
23897    */
23898    if (!current.chan2) {
23899       /* We have no bridge, so we're talking with Asterisk somehow */
23900       /* We need to masquerade this call */
23901       /* What to do to fix this situation:
23902          * Set up the new call in a new channel
23903          * Let the new channel masq into this channel
23904          Please add that code here :-)
23905       */
23906       p->refer->status = REFER_FAILED;
23907       transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
23908       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
23909       append_history(p, "Xfer", "Refer failed (only bridged calls).");
23910       res = -1;
23911       goto handle_refer_cleanup;
23912    }
23913    ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);   /* Delay hangup */
23914 
23915    /* Do not hold the pvt lock during the indicate and async_goto. Those functions
23916     * lock channels which will invalidate locking order if the pvt lock is held.*/
23917    /* For blind transfers, move the call to the new extensions. For attended transfers on multiple
23918     * servers - generate an INVITE with Replaces. Either way, let the dial plan decided
23919     * indicate before masquerade so the indication actually makes it to the real channel
23920     * when using local channels with MOH passthru */
23921    sip_pvt_unlock(p);
23922    ast_indicate(current.chan2, AST_CONTROL_UNHOLD);
23923    res = ast_async_goto(current.chan2, refer_to_context, refer_to, 1);
23924 
23925    if (!res) {
23926       ast_manager_event_multichan(EVENT_FLAG_CALL, "Transfer", 2, chans,
23927          "TransferMethod: SIP\r\n"
23928          "TransferType: Blind\r\n"
23929          "Channel: %s\r\n"
23930          "Uniqueid: %s\r\n"
23931          "SIP-Callid: %s\r\n"
23932          "TargetChannel: %s\r\n"
23933          "TargetUniqueid: %s\r\n"
23934          "TransferExten: %s\r\n"
23935          "TransferContext: %s\r\n",
23936          current.chan1->name,
23937          current.chan1->uniqueid,
23938          callid,
23939          current.chan2->name,
23940          current.chan2->uniqueid,
23941          refer_to,
23942          refer_to_context);
23943       /* Success  - we have a new channel */
23944       ast_debug(3, "%s transfer succeeded. Telling transferer.\n", attendedtransfer? "Attended" : "Blind");
23945 
23946       /* XXX - what to we put in CEL 'extra' for attended transfers to external systems? NULL for now */
23947       ast_channel_lock(current.chan1);
23948       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);
23949       ast_channel_unlock(current.chan1);
23950 
23951       sip_pvt_lock(p);
23952       transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
23953       if (p->refer->localtransfer) {
23954          p->refer->status = REFER_200OK;
23955       }
23956       if (p->owner) {
23957          p->owner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
23958       }
23959       append_history(p, "Xfer", "Refer succeeded.");
23960       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
23961       /* Do not hangup call, the other side do that when we say 200 OK */
23962       /* We could possibly implement a timer here, auto congestion */
23963       res = 0;
23964    } else {
23965       sip_pvt_lock(p);
23966       ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Don't delay hangup */
23967       ast_debug(3, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
23968       append_history(p, "Xfer", "Refer failed.");
23969       /* Failure of some kind */
23970       p->refer->status = REFER_FAILED;
23971       transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
23972       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
23973       res = -1;
23974    }
23975 
23976 handle_refer_cleanup:
23977    if (current.chan1) {
23978       ast_channel_unref(current.chan1);
23979    }
23980    if (current.chan2) {
23981       ast_channel_unref(current.chan2);
23982    }
23983 
23984    /* Make sure we exit with the pvt locked */
23985    return res;
23986 }
23987 
23988 /*! \brief Handle incoming CANCEL request */
23989 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
23990 {
23991 
23992    check_via(p, req);
23993    sip_alreadygone(p);
23994 
23995    if (p->owner && p->owner->_state == AST_STATE_UP) {
23996       /* This call is up, cancel is ignored, we need a bye */
23997       transmit_response(p, "200 OK", req);
23998       ast_debug(1, "Got CANCEL on an answered call. Ignoring... \n");
23999       return 0;
24000    }
24001 
24002    /* At this point, we could have cancelled the invite at the same time
24003       as the other side sends a CANCEL. Our final reply with error code
24004       might not have been received by the other side before the CANCEL
24005       was sent, so let's just give up retransmissions and waiting for
24006       ACK on our error code. The call is hanging up any way. */
24007    if (p->invitestate == INV_TERMINATED || p->invitestate == INV_COMPLETED) {
24008       __sip_pretend_ack(p);
24009    }
24010    if (p->invitestate != INV_TERMINATED)
24011       p->invitestate = INV_CANCELLED;
24012 
24013    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD))
24014       update_call_counter(p, DEC_CALL_LIMIT);
24015 
24016    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
24017    if (p->owner) {
24018       sip_queue_hangup_cause(p, 0);
24019    } else {
24020       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
24021    }
24022    if (ast_str_strlen(p->initreq.data) > 0) {
24023       struct sip_pkt *pkt, *prev_pkt;
24024       /* If the CANCEL we are receiving is a retransmission, and we already have scheduled
24025        * a reliable 487, then we don't want to schedule another one on top of the previous
24026        * one.
24027        *
24028        * As odd as this may sound, we can't rely on the previously-transmitted "reliable"
24029        * response in this situation. What if we've sent all of our reliable responses
24030        * already and now all of a sudden, we get this second CANCEL?
24031        *
24032        * The only way to do this correctly is to cancel our previously-scheduled reliably-
24033        * transmitted response and send a new one in its place.
24034        */
24035       for (pkt = p->packets, prev_pkt = NULL; pkt; prev_pkt = pkt, pkt = pkt->next) {
24036          if (pkt->seqno == p->lastinvite && pkt->response_code == 487) {
24037             AST_SCHED_DEL(sched, pkt->retransid);
24038             UNLINK(pkt, p->packets, prev_pkt);
24039             dialog_unref(pkt->owner, "unref packet->owner from dialog");
24040             if (pkt->data) {
24041                ast_free(pkt->data);
24042             }
24043             ast_free(pkt);
24044             break;
24045          }
24046       }
24047       transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
24048       transmit_response(p, "200 OK", req);
24049       return 1;
24050    } else {
24051       transmit_response(p, "481 Call Leg Does Not Exist", req);
24052       return 0;
24053    }
24054 }
24055 
24056 /*! \brief Handle incoming BYE request */
24057 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
24058 {
24059    struct ast_channel *c=NULL;
24060    int res;
24061    struct ast_channel *bridged_to;
24062    const char *required;
24063 
24064    /* If we have an INCOMING invite that we haven't answered, terminate that transaction */
24065    if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !req->ignore) {
24066       transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
24067    }
24068 
24069    __sip_pretend_ack(p);
24070 
24071    p->invitestate = INV_TERMINATED;
24072 
24073    copy_request(&p->initreq, req);
24074    if (sipdebug)
24075       ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
24076    check_via(p, req);
24077    sip_alreadygone(p);
24078 
24079    /* Get RTCP quality before end of call */
24080    if (p->do_history || p->owner) {
24081       char quality_buf[AST_MAX_USER_FIELD], *quality;
24082       struct ast_channel *bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
24083 
24084       /* We need to get the lock on bridge because ast_rtp_instance_set_stats_vars will attempt
24085        * to lock the bridge. This may get hairy...
24086        */
24087       while (bridge && ast_channel_trylock(bridge)) {
24088          ast_channel_unlock(p->owner);
24089          do {
24090             /* Can't use DEADLOCK_AVOIDANCE since p is an ao2 object */
24091             sip_pvt_unlock(p);
24092             usleep(1);
24093             sip_pvt_lock(p);
24094          } while (p->owner && ast_channel_trylock(p->owner));
24095          bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
24096       }
24097 
24098 
24099       if (p->rtp && (quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
24100          if (p->do_history) {
24101             append_history(p, "RTCPaudio", "Quality:%s", quality);
24102 
24103             if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_JITTER, quality_buf, sizeof(quality_buf)))) {
24104                append_history(p, "RTCPaudioJitter", "Quality:%s", quality);
24105             }
24106             if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_LOSS, quality_buf, sizeof(quality_buf)))) {
24107                append_history(p, "RTCPaudioLoss", "Quality:%s", quality);
24108             }
24109             if ((quality = ast_rtp_instance_get_quality(p->rtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY_RTT, quality_buf, sizeof(quality_buf)))) {
24110                append_history(p, "RTCPaudioRTT", "Quality:%s", quality);
24111             }
24112          }
24113 
24114          if (p->owner) {
24115             ast_rtp_instance_set_stats_vars(p->owner, p->rtp);
24116          }
24117 
24118       }
24119 
24120       if (bridge) {
24121          struct sip_pvt *q = bridge->tech_pvt;
24122 
24123          if (IS_SIP_TECH(bridge->tech) && q && q->rtp) {
24124             ast_rtp_instance_set_stats_vars(bridge, q->rtp);
24125          }
24126          ast_channel_unlock(bridge);
24127       }
24128 
24129       if (p->vrtp && (quality = ast_rtp_instance_get_quality(p->vrtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
24130          if (p->do_history) {
24131             append_history(p, "RTCPvideo", "Quality:%s", quality);
24132          }
24133          if (p->owner) {
24134             pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", quality);
24135          }
24136       }
24137       if (p->trtp && (quality = ast_rtp_instance_get_quality(p->trtp, AST_RTP_INSTANCE_STAT_FIELD_QUALITY, quality_buf, sizeof(quality_buf)))) {
24138          if (p->do_history) {
24139             append_history(p, "RTCPtext", "Quality:%s", quality);
24140          }
24141          if (p->owner) {
24142             pbx_builtin_setvar_helper(p->owner, "RTPTEXTQOS", quality);
24143          }
24144       }
24145    }
24146 
24147    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
24148    stop_session_timer(p); /* Stop Session-Timer */
24149 
24150    if (!ast_strlen_zero(get_header(req, "Also"))) {
24151       ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method.  Ask vendor to support REFER instead\n",
24152          ast_sockaddr_stringify(&p->recv));
24153       if (ast_strlen_zero(p->context))
24154          ast_string_field_set(p, context, sip_cfg.default_context);
24155       res = get_also_info(p, req);
24156       if (!res) {
24157          c = p->owner;
24158          if (c) {
24159             bridged_to = ast_bridged_channel(c);
24160             if (bridged_to) {
24161                /* Don't actually hangup here... */
24162                ast_queue_control(c, AST_CONTROL_UNHOLD);
24163                ast_channel_unlock(c);  /* async_goto can do a masquerade, no locks can be held during a masq */
24164                ast_async_goto(bridged_to, p->context, p->refer->refer_to, 1);
24165                ast_channel_lock(c);
24166             } else
24167                ast_queue_hangup(p->owner);
24168          }
24169       } else {
24170          ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_sockaddr_stringify(&p->recv));
24171          if (p->owner)
24172             ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
24173       }
24174    } else if (p->owner) {
24175       sip_queue_hangup_cause(p, 0);
24176       sip_scheddestroy_final(p, DEFAULT_TRANS_TIMEOUT);
24177       ast_debug(3, "Received bye, issuing owner hangup\n");
24178    } else {
24179       sip_scheddestroy_final(p, DEFAULT_TRANS_TIMEOUT);
24180       ast_debug(3, "Received bye, no owner, selfdestruct soon.\n");
24181    }
24182    ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
24183 
24184    /* Find out what they require */
24185    required = get_header(req, "Require");
24186    if (!ast_strlen_zero(required)) {
24187       char unsupported[256] = { 0, };
24188       parse_sip_options(required, unsupported, ARRAY_LEN(unsupported));
24189       /* If there are any options required that we do not support,
24190        * then send a 420 with only those unsupported options listed */
24191       if (!ast_strlen_zero(unsupported)) {
24192          transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, unsupported);
24193          ast_log(LOG_WARNING, "Received SIP BYE with unsupported required extension: required:%s unsupported:%s\n", required, unsupported);
24194       } else {
24195          transmit_response(p, "200 OK", req);
24196       }
24197    } else {
24198       transmit_response(p, "200 OK", req);
24199    }
24200 
24201    return 1;
24202 }
24203 
24204 /*! \brief Handle incoming MESSAGE request */
24205 static int handle_request_message(struct sip_pvt *p, struct sip_request *req)
24206 {
24207    if (!req->ignore) {
24208       if (req->debug)
24209          ast_verbose("Receiving message!\n");
24210       receive_message(p, req);
24211    } else
24212       transmit_response(p, "202 Accepted", req);
24213    return 1;
24214 }
24215 
24216 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)
24217 {
24218    int etag_present = !ast_strlen_zero(etag);
24219    int body_present = req->lines > 0;
24220 
24221    ast_assert(expires_int != NULL);
24222 
24223    if (ast_strlen_zero(expires)) {
24224       /* Section 6, item 4, second bullet point of RFC 3903 says to
24225        * use a locally-configured default expiration if none is provided
24226        * in the request
24227        */
24228       *expires_int = DEFAULT_PUBLISH_EXPIRES;
24229    } else if (sscanf(expires, "%30d", expires_int) != 1) {
24230       return SIP_PUBLISH_UNKNOWN;
24231    }
24232 
24233    if (*expires_int == 0) {
24234       return SIP_PUBLISH_REMOVE;
24235    } else if (!etag_present && body_present) {
24236       return SIP_PUBLISH_INITIAL;
24237    } else if (etag_present && !body_present) {
24238       return SIP_PUBLISH_REFRESH;
24239    } else if (etag_present && body_present) {
24240       return SIP_PUBLISH_MODIFY;
24241    }
24242 
24243    return SIP_PUBLISH_UNKNOWN;
24244 }
24245 
24246 #ifdef HAVE_LIBXML2
24247 static void get_pidf_body(struct sip_request *req, char *pidf_body, size_t size)
24248 {
24249    int i;
24250    struct ast_str *str = ast_str_alloca(size);
24251    for (i = 0; i < req->lines; ++i) {
24252       ast_str_append(&str, 0, "%s", REQ_OFFSET_TO_STR(req, line[i]));
24253    }
24254    ast_copy_string(pidf_body, ast_str_buffer(str), size);
24255 }
24256 
24257 static int pidf_validate_tuple(struct ast_xml_node *tuple_node)
24258 {
24259    const char *id;
24260    int status_found = FALSE;
24261    struct ast_xml_node *tuple_children;
24262    struct ast_xml_node *tuple_children_iterator;
24263    /* Tuples have to have an id attribute or they're invalid */
24264    if (!(id = ast_xml_get_attribute(tuple_node, "id"))) {
24265       ast_log(LOG_WARNING, "Tuple XML element has no attribute 'id'\n");
24266       return FALSE;
24267    }
24268    /* We don't care what it actually is, just that it's there */
24269    ast_xml_free_attr(id);
24270    /* This is a tuple. It must have a status element */
24271    if (!(tuple_children = ast_xml_node_get_children(tuple_node))) {
24272       /* The tuple has no children. It sucks */
24273       ast_log(LOG_WARNING, "Tuple XML element has no child elements\n");
24274       return FALSE;
24275    }
24276    for (tuple_children_iterator = tuple_children; tuple_children_iterator;
24277          tuple_children_iterator = ast_xml_node_get_next(tuple_children_iterator)) {
24278       /* Similar to the wording used regarding tuples, the status element should appear
24279        * first. However, we will once again relax things and accept the status at any
24280        * position. We will enforce that only a single status element can be present.
24281        */
24282       if (strcmp(ast_xml_node_get_name(tuple_children_iterator), "status")) {
24283          /* Not the status, we don't care */
24284          continue;
24285       }
24286       if (status_found == TRUE) {
24287          /* THERE CAN BE ONLY ONE!!! */
24288          ast_log(LOG_WARNING, "Multiple status elements found in tuple. Only one allowed\n");
24289          return FALSE;
24290       }
24291       status_found = TRUE;
24292    }
24293    return status_found;
24294 }
24295 
24296 
24297 static int pidf_validate_presence(struct ast_xml_doc *doc)
24298 {
24299    struct ast_xml_node *presence_node = ast_xml_get_root(doc);
24300    struct ast_xml_node *child_nodes;
24301    struct ast_xml_node *node_iterator;
24302    struct ast_xml_ns *ns;
24303    const char *entity;
24304    const char *namespace;
24305    const char presence_namespace[] = "urn:ietf:params:xml:ns:pidf";
24306 
24307    if (!presence_node) {
24308       ast_log(LOG_WARNING, "Unable to retrieve root node of the XML document\n");
24309       return FALSE;
24310    }
24311    /* Okay, we managed to open the document! YAY! Now, let's start making sure it's all PIDF-ified
24312     * correctly.
24313     */
24314    if (strcmp(ast_xml_node_get_name(presence_node), "presence")) {
24315       ast_log(LOG_WARNING, "Root node of PIDF document is not 'presence'. Invalid\n");
24316       return FALSE;
24317    }
24318 
24319    /* The presence element must have an entity attribute and an xmlns attribute. Furthermore
24320     * the xmlns attribute must be "urn:ietf:params:xml:ns:pidf"
24321     */
24322    if (!(entity = ast_xml_get_attribute(presence_node, "entity"))) {
24323       ast_log(LOG_WARNING, "Presence element of PIDF document has no 'entity' attribute\n");
24324       return FALSE;
24325    }
24326    /* We're not interested in what the entity is, just that it exists */
24327    ast_xml_free_attr(entity);
24328 
24329    if (!(ns = ast_xml_find_namespace(doc, presence_node, NULL))) {
24330       ast_log(LOG_WARNING, "Couldn't find default namespace...\n");
24331       return FALSE;
24332    }
24333 
24334    namespace = ast_xml_get_ns_href(ns);
24335    if (ast_strlen_zero(namespace) || strcmp(namespace, presence_namespace)) {
24336       ast_log(LOG_WARNING, "PIDF document has invalid namespace value %s\n", namespace);
24337       return FALSE;
24338    }
24339 
24340    if (!(child_nodes = ast_xml_node_get_children(presence_node))) {
24341       ast_log(LOG_WARNING, "PIDF document has no elements as children of 'presence'. Invalid\n");
24342       return FALSE;
24343    }
24344 
24345    /* Check for tuple elements. RFC 3863 says that PIDF documents can have any number of
24346     * tuples, including 0. The big thing here is that if there are tuple elements present,
24347     * they have to have a single status element within.
24348     *
24349     * The RFC is worded such that tuples should appear as the first elements as children of
24350     * the presence element. However, we'll be accepting of documents which may place other elements
24351     * before the tuple(s).
24352     */
24353    for (node_iterator = child_nodes; node_iterator;
24354          node_iterator = ast_xml_node_get_next(node_iterator)) {
24355       if (strcmp(ast_xml_node_get_name(node_iterator), "tuple")) {
24356          /* Not a tuple. We don't give a rat's hind quarters */
24357          continue;
24358       }
24359       if (pidf_validate_tuple(node_iterator) == FALSE) {
24360          ast_log(LOG_WARNING, "Unable to validate tuple\n");
24361          return FALSE;
24362       }
24363    }
24364 
24365    return TRUE;
24366 }
24367 
24368 /*!
24369  * \brief Makes sure that body is properly formatted PIDF
24370  *
24371  * Specifically, we check that the document has a "presence" element
24372  * at the root and that within that, there is at least one "tuple" element
24373  * that contains a "status" element.
24374  *
24375  * XXX This function currently assumes a default namespace is used. Of course
24376  * if you're not using a default namespace, you're probably a stupid jerk anyway.
24377  *
24378  * \param req The SIP request to check
24379  * \param[out] pidf_doc The validated PIDF doc.
24380  * \retval FALSE The XML was malformed or the basic PIDF structure was marred
24381  * \retval TRUE The PIDF document is of a valid format
24382  */
24383 static int sip_pidf_validate(struct sip_request *req, struct ast_xml_doc **pidf_doc)
24384 {
24385    struct ast_xml_doc *doc;
24386    int content_length;
24387    const char *content_length_str = get_header(req, "Content-Length");
24388    const char *content_type = get_header(req, "Content-Type");
24389    char pidf_body[SIPBUFSIZE];
24390    int res;
24391 
24392    if (ast_strlen_zero(content_type) || strcmp(content_type, "application/pidf+xml")) {
24393       ast_log(LOG_WARNING, "Content type is not PIDF\n");
24394       return FALSE;
24395    }
24396 
24397    if (ast_strlen_zero(content_length_str)) {
24398       ast_log(LOG_WARNING, "No content length. Can't determine bounds of PIDF document\n");
24399       return FALSE;
24400    }
24401 
24402    if (sscanf(content_length_str, "%30d", &content_length) != 1) {
24403       ast_log(LOG_WARNING, "Invalid content length provided\n");
24404       return FALSE;
24405    }
24406 
24407    if (content_length > sizeof(pidf_body)) {
24408       ast_log(LOG_WARNING, "Content length of PIDF document truncated to %d bytes\n", (int) sizeof(pidf_body));
24409       content_length = sizeof(pidf_body);
24410    }
24411 
24412    get_pidf_body(req, pidf_body, content_length);
24413 
24414    if (!(doc = ast_xml_read_memory(pidf_body, content_length))) {
24415       ast_log(LOG_WARNING, "Unable to open XML PIDF document. Is it malformed?\n");
24416       return FALSE;
24417    }
24418 
24419    res = pidf_validate_presence(doc);
24420    if (res == TRUE) {
24421       *pidf_doc = doc;
24422    } else {
24423       ast_xml_close(doc);
24424    }
24425    return res;
24426 }
24427 
24428 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)
24429 {
24430    const char *uri = REQ_OFFSET_TO_STR(req, rlPart2);
24431    struct ast_cc_agent *agent;
24432    struct sip_cc_agent_pvt *agent_pvt;
24433    struct ast_xml_doc *pidf_doc = NULL;
24434    const char *basic_status = NULL;
24435    struct ast_xml_node *presence_node;
24436    struct ast_xml_node *presence_children;
24437    struct ast_xml_node *tuple_node;
24438    struct ast_xml_node *tuple_children;
24439    struct ast_xml_node *status_node;
24440    struct ast_xml_node *status_children;
24441    struct ast_xml_node *basic_node;
24442    int res = 0;
24443 
24444    if (!((agent = find_sip_cc_agent_by_notify_uri(uri)) || (agent = find_sip_cc_agent_by_subscribe_uri(uri)))) {
24445       ast_log(LOG_WARNING, "Could not find agent using uri '%s'\n", uri);
24446       transmit_response(pvt, "412 Conditional Request Failed", req);
24447       return -1;
24448    }
24449 
24450    agent_pvt = agent->private_data;
24451 
24452    if (sip_pidf_validate(req, &pidf_doc) == FALSE) {
24453       res = -1;
24454       goto cc_publish_cleanup;
24455    }
24456 
24457    /* It's important to note that the PIDF validation routine has no knowledge
24458     * of what we specifically want in this instance. A valid PIDF document could
24459     * have no tuples, or it could have tuples whose status element has no basic
24460     * element contained within. While not violating the PIDF spec, these are
24461     * insufficient for our needs in this situation
24462     */
24463    presence_node = ast_xml_get_root(pidf_doc);
24464    if (!(presence_children = ast_xml_node_get_children(presence_node))) {
24465       ast_log(LOG_WARNING, "No tuples within presence element.\n");
24466       res = -1;
24467       goto cc_publish_cleanup;
24468    }
24469 
24470    if (!(tuple_node = ast_xml_find_element(presence_children, "tuple", NULL, NULL))) {
24471       ast_log(LOG_NOTICE, "Couldn't find tuple node?\n");
24472       res = -1;
24473       goto cc_publish_cleanup;
24474    }
24475 
24476    /* We already made sure that the tuple has a status node when we validated the PIDF
24477     * document earlier. So there's no need to enclose this operation in an if statement.
24478     */
24479    tuple_children = ast_xml_node_get_children(tuple_node);
24480    /* coverity[null_returns: FALSE] */
24481    status_node = ast_xml_find_element(tuple_children, "status", NULL, NULL);
24482 
24483    if (!(status_children = ast_xml_node_get_children(status_node))) {
24484       ast_log(LOG_WARNING, "No basic elements within status element.\n");
24485       res = -1;
24486       goto cc_publish_cleanup;
24487    }
24488 
24489    if (!(basic_node = ast_xml_find_element(status_children, "basic", NULL, NULL))) {
24490       ast_log(LOG_WARNING, "Couldn't find basic node?\n");
24491       res = -1;
24492       goto cc_publish_cleanup;
24493    }
24494 
24495    basic_status = ast_xml_get_text(basic_node);
24496 
24497    if (ast_strlen_zero(basic_status)) {
24498       ast_log(LOG_NOTICE, "NOthing in basic node?\n");
24499       res = -1;
24500       goto cc_publish_cleanup;
24501    }
24502 
24503    if (!strcmp(basic_status, "open")) {
24504       agent_pvt->is_available = TRUE;
24505       ast_cc_agent_caller_available(agent->core_id, "Received PUBLISH stating SIP caller %s is available",
24506             agent->device_name);
24507    } else if (!strcmp(basic_status, "closed")) {
24508       agent_pvt->is_available = FALSE;
24509       ast_cc_agent_caller_busy(agent->core_id, "Received PUBLISH stating SIP caller %s is busy",
24510             agent->device_name);
24511    } else {
24512       ast_log(LOG_NOTICE, "Invalid content in basic element: %s\n", basic_status);
24513    }
24514 
24515 cc_publish_cleanup:
24516    if (basic_status) {
24517       ast_xml_free_text(basic_status);
24518    }
24519    if (pidf_doc) {
24520       ast_xml_close(pidf_doc);
24521    }
24522    ao2_ref(agent, -1);
24523    if (res) {
24524       transmit_response(pvt, "400 Bad Request", req);
24525    }
24526    return res;
24527 }
24528 
24529 #endif /* HAVE_LIBXML2 */
24530 
24531 static int handle_sip_publish_initial(struct sip_pvt *p, struct sip_request *req, struct event_state_compositor *esc, const int expires)
24532 {
24533    struct sip_esc_entry *esc_entry = create_esc_entry(esc, req, expires);
24534    int res = 0;
24535 
24536    if (!esc_entry) {
24537       transmit_response(p, "503 Internal Server Failure", req);
24538       return -1;
24539    }
24540 
24541    if (esc->callbacks->initial_handler) {
24542       res = esc->callbacks->initial_handler(p, req, esc, esc_entry);
24543    }
24544 
24545    if (!res) {
24546       transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 0);
24547    }
24548 
24549    ao2_ref(esc_entry, -1);
24550    return res;
24551 }
24552 
24553 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)
24554 {
24555    struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
24556    int expires_ms = expires * 1000;
24557    int res = 0;
24558 
24559    if (!esc_entry) {
24560       transmit_response(p, "412 Conditional Request Failed", req);
24561       return -1;
24562    }
24563 
24564    AST_SCHED_REPLACE_UNREF(esc_entry->sched_id, sched, expires_ms, publish_expire, esc_entry,
24565          ao2_ref(_data, -1),
24566          ao2_ref(esc_entry, -1),
24567          ao2_ref(esc_entry, +1));
24568 
24569    if (esc->callbacks->refresh_handler) {
24570       res = esc->callbacks->refresh_handler(p, req, esc, esc_entry);
24571    }
24572 
24573    if (!res) {
24574       transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
24575    }
24576 
24577    ao2_ref(esc_entry, -1);
24578    return res;
24579 }
24580 
24581 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)
24582 {
24583    struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
24584    int expires_ms = expires * 1000;
24585    int res = 0;
24586 
24587    if (!esc_entry) {
24588       transmit_response(p, "412 Conditional Request Failed", req);
24589       return -1;
24590    }
24591 
24592    AST_SCHED_REPLACE_UNREF(esc_entry->sched_id, sched, expires_ms, publish_expire, esc_entry,
24593          ao2_ref(_data, -1),
24594          ao2_ref(esc_entry, -1),
24595          ao2_ref(esc_entry, +1));
24596 
24597    if (esc->callbacks->modify_handler) {
24598       res = esc->callbacks->modify_handler(p, req, esc, esc_entry);
24599    }
24600 
24601    if (!res) {
24602       transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
24603    }
24604 
24605    ao2_ref(esc_entry, -1);
24606    return res;
24607 }
24608 
24609 static int handle_sip_publish_remove(struct sip_pvt *p, struct sip_request *req, struct event_state_compositor *esc, const char * const etag)
24610 {
24611    struct sip_esc_entry *esc_entry = get_esc_entry(etag, esc);
24612    int res = 0;
24613 
24614    if (!esc_entry) {
24615       transmit_response(p, "412 Conditional Request Failed", req);
24616       return -1;
24617    }
24618 
24619    AST_SCHED_DEL(sched, esc_entry->sched_id);
24620    /* Scheduler's ref of the esc_entry */
24621    ao2_ref(esc_entry, -1);
24622 
24623    if (esc->callbacks->remove_handler) {
24624       res = esc->callbacks->remove_handler(p, req, esc, esc_entry);
24625    }
24626 
24627    if (!res) {
24628       transmit_response_with_sip_etag(p, "200 OK", req, esc_entry, 1);
24629    }
24630 
24631    /* Ref from finding the esc_entry earlier in function */
24632    ao2_unlink(esc->compositor, esc_entry);
24633    ao2_ref(esc_entry, -1);
24634    return res;
24635 }
24636 
24637 static int handle_request_publish(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const uint32_t seqno, const char *uri)
24638 {
24639    const char *etag = get_header(req, "SIP-If-Match");
24640    const char *event = get_header(req, "Event");
24641    struct event_state_compositor *esc;
24642    enum sip_publish_type publish_type;
24643    const char *expires_str = get_header(req, "Expires");
24644    int expires_int;
24645    int auth_result;
24646    int handler_result = -1;
24647 
24648    if (ast_strlen_zero(event)) {
24649       transmit_response(p, "489 Bad Event", req);
24650       pvt_set_needdestroy(p, "missing Event: header");
24651       return -1;
24652    }
24653 
24654    if (!(esc = get_esc(event))) {
24655       transmit_response(p, "489 Bad Event", req);
24656       pvt_set_needdestroy(p, "unknown event package in publish");
24657       return -1;
24658    }
24659 
24660    auth_result = check_user(p, req, SIP_PUBLISH, uri, XMIT_RELIABLE, addr);
24661    if (auth_result == AUTH_CHALLENGE_SENT) {
24662       p->lastinvite = seqno;
24663       return 0;
24664    } else if (auth_result < 0) {
24665       if (auth_result == AUTH_FAKE_AUTH) {
24666          ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
24667          transmit_fake_auth_response(p, SIP_INVITE, req, XMIT_RELIABLE);
24668       } else {
24669          ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
24670          transmit_response_reliable(p, "403 Forbidden", req);
24671       }
24672       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
24673       ast_string_field_set(p, theirtag, NULL);
24674       return 0;
24675    } else if (auth_result == AUTH_SUCCESSFUL && p->lastinvite) {
24676       /* We need to stop retransmitting the 401 */
24677       __sip_ack(p, p->lastinvite, 1, 0);
24678    }
24679 
24680    publish_type = determine_sip_publish_type(req, event, etag, expires_str, &expires_int);
24681 
24682    if (expires_int > max_expiry) {
24683       expires_int = max_expiry;
24684    } else if (expires_int < min_expiry && expires_int > 0) {
24685       transmit_response_with_minexpires(p, "423 Interval too small", req);
24686       pvt_set_needdestroy(p, "Expires is less that the min expires allowed.");
24687       return 0;
24688    }
24689    p->expiry = expires_int;
24690 
24691    /* It is the responsibility of these handlers to formulate any response
24692     * sent for a PUBLISH
24693     */
24694    switch (publish_type) {
24695    case SIP_PUBLISH_UNKNOWN:
24696       transmit_response(p, "400 Bad Request", req);
24697       break;
24698    case SIP_PUBLISH_INITIAL:
24699       handler_result = handle_sip_publish_initial(p, req, esc, expires_int);
24700       break;
24701    case SIP_PUBLISH_REFRESH:
24702       handler_result = handle_sip_publish_refresh(p, req, esc, etag, expires_int);
24703       break;
24704    case SIP_PUBLISH_MODIFY:
24705       handler_result = handle_sip_publish_modify(p, req, esc, etag, expires_int);
24706       break;
24707    case SIP_PUBLISH_REMOVE:
24708       handler_result = handle_sip_publish_remove(p, req, esc, etag);
24709       break;
24710    default:
24711       transmit_response(p, "400 Impossible Condition", req);
24712       break;
24713    }
24714    if (!handler_result && p->expiry > 0) {
24715       sip_scheddestroy(p, (p->expiry + 10) * 1000);
24716    } else {
24717       pvt_set_needdestroy(p, "forcing expiration");
24718    }
24719 
24720    return handler_result;
24721 }
24722 
24723 /*! \internal \brief Subscribe to MWI events for the specified peer
24724  * \note The peer cannot be locked during this method.  sip_send_mwi_peer will
24725  * attempt to lock the peer after the event subscription lock is held; if the peer is locked during
24726  * this method then we will attempt to lock the event subscription lock but after the peer, creating
24727  * a locking inversion.
24728  */
24729 static void add_peer_mwi_subs(struct sip_peer *peer)
24730 {
24731    struct sip_mailbox *mailbox;
24732 
24733    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
24734       if (mailbox->event_sub) {
24735          ast_event_unsubscribe(mailbox->event_sub);
24736       }
24737 
24738       mailbox->event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, "SIP mbox event", peer,
24739          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
24740          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
24741          AST_EVENT_IE_END);
24742    }
24743 }
24744 
24745 static int handle_cc_subscribe(struct sip_pvt *p, struct sip_request *req)
24746 {
24747    const char *uri = REQ_OFFSET_TO_STR(req, rlPart2);
24748    char *param_separator;
24749    struct ast_cc_agent *agent;
24750    struct sip_cc_agent_pvt *agent_pvt;
24751    const char *expires_str = get_header(req, "Expires");
24752    int expires = -1; /* Just need it to be non-zero */
24753 
24754    if (!ast_strlen_zero(expires_str)) {
24755       sscanf(expires_str, "%d", &expires);
24756    }
24757 
24758    if ((param_separator = strchr(uri, ';'))) {
24759       *param_separator = '\0';
24760    }
24761 
24762    p->subscribed = CALL_COMPLETION;
24763 
24764    if (!(agent = find_sip_cc_agent_by_subscribe_uri(uri))) {
24765       if (!expires) {
24766          /* Typically, if a 0 Expires reaches us and we can't find
24767           * the corresponding agent, it means that the CC transaction
24768           * has completed and so the calling side is just trying to
24769           * clean up its subscription. We'll just respond with a
24770           * 200 OK and be done with it
24771           */
24772          transmit_response(p, "200 OK", req);
24773          return 0;
24774       }
24775       ast_log(LOG_WARNING, "Invalid URI '%s' in CC subscribe\n", uri);
24776       transmit_response(p, "404 Not Found", req);
24777       return -1;
24778    }
24779 
24780    agent_pvt = agent->private_data;
24781 
24782    if (!expires) {
24783       /* We got sent a SUBSCRIBE and found an agent. This means that CC
24784        * is being canceled.
24785        */
24786       ast_cc_failed(agent->core_id, "CC is being canceled by %s", agent->device_name);
24787       transmit_response(p, "200 OK", req);
24788       ao2_ref(agent, -1);
24789       return 0;
24790    }
24791 
24792    agent_pvt->subscribe_pvt = dialog_ref(p, "SIP CC agent gains reference to subscription dialog");
24793    ast_cc_agent_accept_request(agent->core_id, "SIP caller %s has requested CC via SUBSCRIBE",
24794          agent->device_name);
24795 
24796    /* We don't send a response here. That is done in the agent's ack callback or in the
24797     * agent destructor, should a failure occur before we have responded
24798     */
24799    ao2_ref(agent, -1);
24800    return 0;
24801 }
24802 
24803 /*! \brief  Handle incoming SUBSCRIBE request */
24804 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, uint32_t seqno, const char *e)
24805 {
24806    int gotdest = 0;
24807    int res = 0;
24808    int firststate;
24809    struct sip_peer *authpeer = NULL;
24810    const char *eventheader = get_header(req, "Event");   /* Get Event package name */
24811    int resubscribe = (p->subscribed != NONE) && !req->ignore;
24812    char *event_end;
24813    ptrdiff_t event_len = 0;
24814 
24815    if (p->initreq.headers) {  
24816       /* We already have a dialog */
24817       if (p->initreq.method != SIP_SUBSCRIBE) {
24818          /* This is a SUBSCRIBE within another SIP dialog, which we do not support */
24819          /* For transfers, this could happen, but since we haven't seen it happening, let us just refuse this */
24820          transmit_response(p, "403 Forbidden (within dialog)", req);
24821          /* Do not destroy session, since we will break the call if we do */
24822          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);
24823          return 0;
24824       } else if (req->debug) {
24825          if (resubscribe)
24826             ast_debug(1, "Got a re-subscribe on existing subscription %s\n", p->callid);
24827          else
24828             ast_debug(1, "Got a new subscription %s (possibly with auth) or retransmission\n", p->callid);
24829       }
24830    }
24831 
24832    /* Check if we have a global disallow setting on subscriptions.
24833       if so, we don't have to check peer settings after auth, which saves a lot of processing
24834    */
24835    if (!sip_cfg.allowsubscribe) {
24836       transmit_response(p, "403 Forbidden (policy)", req);
24837       pvt_set_needdestroy(p, "forbidden");
24838       return 0;
24839    }
24840 
24841    if (!req->ignore && !resubscribe) { /* Set up dialog, new subscription */
24842       const char *to = get_header(req, "To");
24843       char totag[128];
24844       set_pvt_allowed_methods(p, req);
24845 
24846       /* Check to see if a tag was provided, if so this is actually a resubscription of a dialog we no longer know about */
24847       if (!ast_strlen_zero(to) && gettag(req, "To", totag, sizeof(totag))) {
24848          if (req->debug)
24849             ast_verbose("Received resubscription for a dialog we no longer know about. Telling remote side to subscribe again.\n");
24850          transmit_response(p, "481 Subscription does not exist", req);
24851          pvt_set_needdestroy(p, "subscription does not exist");
24852          return 0;
24853       }
24854 
24855       /* Use this as the basis */
24856       if (req->debug)
24857          ast_verbose("Creating new subscription\n");
24858 
24859       copy_request(&p->initreq, req);
24860       if (sipdebug)
24861          ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
24862       check_via(p, req);
24863       build_route(p, req, 0, 0);
24864    } else if (req->debug && req->ignore)
24865       ast_verbose("Ignoring this SUBSCRIBE request\n");
24866 
24867    /* Find parameters to Event: header value and remove them for now */
24868    if (ast_strlen_zero(eventheader)) {
24869       transmit_response(p, "489 Bad Event", req);
24870       ast_debug(2, "Received SIP subscribe for unknown event package: <none>\n");
24871       pvt_set_needdestroy(p, "unknown event package in subscribe");
24872       return 0;
24873    }
24874 
24875    event_end = strchr(eventheader, ';');
24876    if (event_end) {
24877       event_len = event_end - eventheader;
24878    }
24879 
24880    /* Handle authentication if we're new and not a retransmission. We can't just
24881     * use if !req->ignore, because then we'll end up sending
24882     * a 200 OK if someone retransmits without sending auth */
24883    if (p->subscribed == NONE || resubscribe) {
24884       res = check_user_full(p, req, SIP_SUBSCRIBE, e, 0, addr, &authpeer);
24885 
24886       /* if an authentication response was sent, we are done here */
24887       if (res == AUTH_CHALLENGE_SENT)  /* authpeer = NULL here */
24888          return 0;
24889       if (res != AUTH_SUCCESSFUL) {
24890          if (res == AUTH_FAKE_AUTH) {
24891             ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
24892             transmit_fake_auth_response(p, SIP_SUBSCRIBE, req, XMIT_UNRELIABLE);
24893          } else {
24894             ast_log(LOG_NOTICE, "Failed to authenticate device %s for SUBSCRIBE\n", get_header(req, "From"));
24895             transmit_response_reliable(p, "403 Forbidden", req);
24896          }
24897 
24898          pvt_set_needdestroy(p, "authentication failed");
24899          return 0;
24900       }
24901    }
24902 
24903    /* At this point, we hold a reference to authpeer (if not NULL).  It
24904     * must be released when done.
24905     */
24906 
24907    /* Check if this device  is allowed to subscribe at all */
24908    if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
24909       transmit_response(p, "403 Forbidden (policy)", req);
24910       pvt_set_needdestroy(p, "subscription not allowed");
24911       if (authpeer) {
24912          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 1)");
24913       }
24914       return 0;
24915    }
24916 
24917    if (strncmp(eventheader, "message-summary", MAX(event_len, 15)) && strncmp(eventheader, "call-completion", MAX(event_len, 15))) {
24918       /* Get destination right away */
24919       gotdest = get_destination(p, NULL, NULL);
24920    }
24921 
24922    /* Get full contact header - this needs to be used as a request URI in NOTIFY's */
24923    parse_ok_contact(p, req);
24924 
24925    build_contact(p);
24926    if (gotdest != SIP_GET_DEST_EXTEN_FOUND) {
24927       if (gotdest == SIP_GET_DEST_INVALID_URI) {
24928          transmit_response(p, "416 Unsupported URI scheme", req);
24929       } else {
24930          transmit_response(p, "404 Not Found", req);
24931       }
24932       pvt_set_needdestroy(p, "subscription target not found");
24933       if (authpeer) {
24934          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
24935       }
24936       return 0;
24937    }
24938 
24939    /* Initialize tag for new subscriptions */   
24940    if (ast_strlen_zero(p->tag))
24941       make_our_tag(p);
24942 
24943    if (!strncmp(eventheader, "presence", MAX(event_len, 8)) || !strncmp(eventheader, "dialog", MAX(event_len, 6))) { /* Presence, RFC 3842 */
24944       unsigned int pidf_xml;
24945       const char *accept;
24946       int start = 0;
24947       enum subscriptiontype subscribed = NONE;
24948       const char *unknown_acceptheader = NULL;
24949 
24950       /* Header from Xten Eye-beam Accept: multipart/related, application/rlmi+xml, application/pidf+xml, application/xpidf+xml */
24951       accept = __get_header(req, "Accept", &start);
24952       while ((subscribed == NONE) && !ast_strlen_zero(accept)) {
24953          pidf_xml = strstr(accept, "application/pidf+xml") ? 1 : 0;
24954 
24955          /* Older versions of Polycom firmware will claim pidf+xml, but really
24956           * they only support xpidf+xml. */
24957          if (pidf_xml && strstr(p->useragent, "Polycom")) {
24958             subscribed = XPIDF_XML;
24959          } else if (pidf_xml) {
24960             subscribed = PIDF_XML;         /* RFC 3863 format */
24961          } else if (strstr(accept, "application/dialog-info+xml")) {
24962             subscribed = DIALOG_INFO_XML;
24963             /* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
24964          } else if (strstr(accept, "application/cpim-pidf+xml")) {
24965             subscribed = CPIM_PIDF_XML;    /* RFC 3863 format */
24966          } else if (strstr(accept, "application/xpidf+xml")) {
24967             subscribed = XPIDF_XML;        /* Early pre-RFC 3863 format with MSN additions (Microsoft Messenger) */
24968          } else {
24969             unknown_acceptheader = accept;
24970          }
24971          /* check to see if there is another Accept header present */
24972          accept = __get_header(req, "Accept", &start);
24973       }
24974 
24975       if (!start) {
24976          if (p->subscribed == NONE) { /* if the subscribed field is not already set, and there is no accept header... */
24977             transmit_response(p, "489 Bad Event", req);
24978             ast_log(LOG_WARNING,"SUBSCRIBE failure: no Accept header: pvt: "
24979                "stateid: %d, laststate: %d, dialogver: %u, subscribecont: "
24980                "'%s', subscribeuri: '%s'\n",
24981                p->stateid,
24982                p->laststate,
24983                p->dialogver,
24984                p->subscribecontext,
24985                p->subscribeuri);
24986             pvt_set_needdestroy(p, "no Accept header");
24987             if (authpeer) {
24988                unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
24989             }
24990             return 0;
24991          }
24992          /* if p->subscribed is non-zero, then accept is not obligatory; according to rfc 3265 section 3.1.3, at least.
24993             so, we'll just let it ride, keeping the value from a previous subscription, and not abort the subscription */
24994       } else if (subscribed == NONE) {
24995          /* Can't find a format for events that we know about */
24996          char mybuf[200];
24997          if (!ast_strlen_zero(unknown_acceptheader)) {
24998             snprintf(mybuf, sizeof(mybuf), "489 Bad Event (format %s)", unknown_acceptheader);
24999          } else {
25000             snprintf(mybuf, sizeof(mybuf), "489 Bad Event");
25001          }
25002          transmit_response(p, mybuf, req);
25003          ast_log(LOG_WARNING,"SUBSCRIBE failure: unrecognized format:"
25004             "'%s' pvt: subscribed: %d, stateid: %d, laststate: %d,"
25005             "dialogver: %u, subscribecont: '%s', subscribeuri: '%s'\n",
25006             unknown_acceptheader,
25007             (int)p->subscribed,
25008             p->stateid,
25009             p->laststate,
25010             p->dialogver,
25011             p->subscribecontext,
25012             p->subscribeuri);
25013          pvt_set_needdestroy(p, "unrecognized format");
25014          if (authpeer) {
25015             unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
25016          }
25017          return 0;
25018       } else {
25019          p->subscribed = subscribed;
25020       }
25021    } else if (!strncmp(eventheader, "message-summary", MAX(event_len, 15))) {
25022       int start = 0;
25023       int found_supported = 0;
25024       const char *acceptheader;
25025 
25026       acceptheader = __get_header(req, "Accept", &start);
25027       while (!found_supported && !ast_strlen_zero(acceptheader)) {
25028          found_supported = strcmp(acceptheader, "application/simple-message-summary") ? 0 : 1;
25029          if (!found_supported && (option_debug > 2)) {
25030             ast_log(LOG_DEBUG, "Received SIP mailbox subscription for unknown format: %s\n", acceptheader);
25031          }
25032          acceptheader = __get_header(req, "Accept", &start);
25033       }
25034       if (start && !found_supported) {
25035          /* Format requested that we do not support */
25036          transmit_response(p, "406 Not Acceptable", req);
25037          ast_debug(2, "Received SIP mailbox subscription for unknown format: %s\n", acceptheader);
25038          pvt_set_needdestroy(p, "unknown format");
25039          if (authpeer) {
25040             unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 3)");
25041          }
25042          return 0;
25043       }
25044       /* Looks like they actually want a mailbox status
25045         This version of Asterisk supports mailbox subscriptions
25046         The subscribed URI needs to exist in the dial plan
25047         In most devices, this is configurable to the voicemailmain extension you use
25048       */
25049       if (!authpeer || AST_LIST_EMPTY(&authpeer->mailboxes)) {
25050          if (!authpeer) {
25051             transmit_response(p, "404 Not found", req);
25052          } else {
25053             transmit_response(p, "404 Not found (no mailbox)", req);
25054             ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", S_OR(authpeer->name, ""));
25055          }
25056          pvt_set_needdestroy(p, "received 404 response");
25057          if (authpeer) {
25058             unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 3)");
25059          }
25060          return 0;
25061       }
25062 
25063       p->subscribed = MWI_NOTIFICATION;
25064       if (ast_test_flag(&authpeer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY)) {
25065          ao2_unlock(p);
25066          add_peer_mwi_subs(authpeer);
25067          ao2_lock(p);
25068       }
25069       if (authpeer->mwipvt != p) {  /* Destroy old PVT if this is a new one */
25070          /* We only allow one subscription per peer */
25071          if (authpeer->mwipvt) {
25072             dialog_unlink_all(authpeer->mwipvt);
25073             authpeer->mwipvt = dialog_unref(authpeer->mwipvt, "unref dialog authpeer->mwipvt");
25074          }
25075          authpeer->mwipvt = dialog_ref(p, "setting peers' mwipvt to p");
25076       }
25077       if (p->relatedpeer != authpeer) {
25078          if (p->relatedpeer) {
25079             unref_peer(p->relatedpeer, "Unref previously stored relatedpeer ptr");
25080          }
25081          p->relatedpeer = ref_peer(authpeer, "setting dialog's relatedpeer pointer");
25082       }
25083       /* Do not release authpeer here */
25084    } else if (!strncmp(eventheader, "call-completion", MAX(event_len, 15))) {
25085       handle_cc_subscribe(p, req);
25086    } else { /* At this point, Asterisk does not understand the specified event */
25087       transmit_response(p, "489 Bad Event", req);
25088       ast_debug(2, "Received SIP subscribe for unknown event package: %s\n", eventheader);
25089       pvt_set_needdestroy(p, "unknown event package");
25090       if (authpeer) {
25091          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 5)");
25092       }
25093       return 0;
25094    }
25095 
25096    /* Add subscription for extension state from the PBX core */
25097    if (p->subscribed != MWI_NOTIFICATION  && p->subscribed != CALL_COMPLETION && !resubscribe) {
25098       if (p->stateid != -1) {
25099          ast_extension_state_del(p->stateid, cb_extensionstate);
25100       }
25101       dialog_ref(p, "copying dialog ptr into extension state struct");
25102       p->stateid = ast_extension_state_add_destroy(p->context, p->exten,
25103          cb_extensionstate, cb_extensionstate_destroy, p);
25104       if (p->stateid == -1) {
25105          dialog_unref(p, "copying dialog ptr into extension state struct failed");
25106       }
25107    }
25108 
25109    if (!req->ignore) {
25110       p->lastinvite = seqno;
25111    }
25112    if (!p->needdestroy) {
25113       p->expiry = atoi(get_header(req, "Expires"));
25114 
25115       /* check if the requested expiry-time is within the approved limits from sip.conf */
25116       if (p->expiry > max_expiry) {
25117          p->expiry = max_expiry;
25118       } else if (p->expiry < min_expiry && p->expiry > 0) {
25119          transmit_response_with_minexpires(p, "423 Interval too small", req);
25120          ast_log(LOG_WARNING, "Received subscription for extension \"%s\" context \"%s\" "
25121             "with Expire header less that 'minexpire' limit. Received \"Expire: %d\" min is %d\n",
25122             p->exten, p->context, p->expiry, min_expiry);
25123          pvt_set_needdestroy(p, "Expires is less that the min expires allowed.");
25124          if (authpeer) {
25125             unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 6)");
25126          }
25127          return 0;
25128       }
25129 
25130       if (sipdebug) {
25131          const char *action = p->expiry > 0 ? "Adding" : "Removing";
25132          if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer) {
25133             ast_debug(2, "%s subscription for mailbox notification - peer %s\n",
25134                   action, p->relatedpeer->name);
25135          } else if (p->subscribed == CALL_COMPLETION) {
25136             ast_debug(2, "%s CC subscription for peer %s\n", action, p->username);
25137          } else {
25138             ast_debug(2, "%s subscription for extension %s context %s for peer %s\n",
25139                   action, p->exten, p->context, p->username);
25140          }
25141       }
25142       if (p->autokillid > -1 && sip_cancel_destroy(p))   /* Remove subscription expiry for renewals */
25143          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
25144       if (p->expiry > 0)
25145          sip_scheddestroy(p, (p->expiry + 10) * 1000);   /* Set timer for destruction of call at expiration */
25146 
25147       if (p->subscribed == MWI_NOTIFICATION) {
25148          ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
25149          transmit_response(p, "200 OK", req);
25150          if (p->relatedpeer) {   /* Send first notification */
25151             struct sip_peer *peer = p->relatedpeer;
25152             ref_peer(peer, "ensure a peer ref is held during MWI sending");
25153             ao2_unlock(p);
25154             sip_send_mwi_to_peer(peer, 0);
25155             ao2_lock(p);
25156             unref_peer(peer, "release a peer ref now that MWI is sent");
25157          }
25158       } else if (p->subscribed != CALL_COMPLETION) {
25159          sip_pvt_unlock(p);
25160          firststate = ast_extension_state(NULL, p->context, p->exten);
25161          sip_pvt_lock(p);
25162 
25163          if (firststate < 0) {
25164             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));
25165             transmit_response(p, "404 Not found", req);
25166             pvt_set_needdestroy(p, "no extension for SUBSCRIBE");
25167             if (authpeer) {
25168                unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 6)");
25169             }
25170             return 0;
25171          }
25172          ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
25173          transmit_response(p, "200 OK", req);
25174          transmit_state_notify(p, firststate, 1, FALSE); /* Send first notification */
25175          append_history(p, "Subscribestatus", "%s", ast_extension_state2str(firststate));
25176          /* hide the 'complete' exten/context in the refer_to field for later display */
25177          ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
25178          /* Deleted the slow iteration of all sip dialogs to find old subscribes from this peer for exten@context */
25179 
25180       }
25181       if (!p->expiry) {
25182          pvt_set_needdestroy(p, "forcing expiration");
25183       }
25184    }
25185 
25186    if (authpeer) {
25187       unref_peer(authpeer, "unref pointer into (*authpeer)");
25188    }
25189    return 1;
25190 }
25191 
25192 /*! \brief Handle incoming REGISTER request */
25193 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, const char *e)
25194 {
25195    enum check_auth_result res;
25196 
25197    /* If this is not the intial request, and the initial request isn't
25198     * a register, something screwy happened, so bail */
25199    if (p->initreq.headers && p->initreq.method != SIP_REGISTER) {
25200       ast_log(LOG_WARNING, "Ignoring spurious REGISTER with Call-ID: %s\n", p->callid);
25201       return -1;
25202    }
25203 
25204    /* Use this as the basis */
25205    copy_request(&p->initreq, req);
25206    if (sipdebug)
25207       ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
25208    check_via(p, req);
25209    if ((res = register_verify(p, addr, req, e)) < 0) {
25210       const char *reason;
25211 
25212       switch (res) {
25213       case AUTH_SECRET_FAILED:
25214          reason = "Wrong password";
25215          break;
25216       case AUTH_USERNAME_MISMATCH:
25217          reason = "Username/auth name mismatch";
25218          break;
25219       case AUTH_NOT_FOUND:
25220          reason = "No matching peer found";
25221          break;
25222       case AUTH_UNKNOWN_DOMAIN:
25223          reason = "Not a local domain";
25224          break;
25225       case AUTH_PEER_NOT_DYNAMIC:
25226          reason = "Peer is not supposed to register";
25227          break;
25228       case AUTH_ACL_FAILED:
25229          reason = "Device does not match ACL";
25230          break;
25231       case AUTH_BAD_TRANSPORT:
25232          reason = "Device not configured to use this transport type";
25233          break;
25234       default:
25235          reason = "Unknown failure";
25236          break;
25237       }
25238       ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
25239          get_header(req, "To"), ast_sockaddr_stringify(addr),
25240          reason);
25241       append_history(p, "RegRequest", "Failed : Account %s : %s", get_header(req, "To"), reason);
25242    } else {
25243       req->authenticated = 1;
25244       append_history(p, "RegRequest", "Succeeded : Account %s", get_header(req, "To"));
25245    }
25246 
25247    if (res < 1) {
25248       /* Destroy the session, but keep us around for just a bit in case they don't
25249          get our 200 OK */
25250       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25251    }
25252    return res;
25253 }
25254 
25255 /*!
25256  * \brief Handle incoming SIP requests (methods)
25257  * \note
25258  * This is where all incoming requests go first.
25259  * \note
25260  * called with p and p->owner locked
25261  */
25262 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct ast_sockaddr *addr, int *recount, int *nounlock)
25263 {
25264    /* Called with p->lock held, as well as p->owner->lock if appropriate, keeping things
25265       relatively static */
25266    const char *cmd;
25267    const char *cseq;
25268    const char *useragent;
25269    const char *via;
25270    const char *callid;
25271    int via_pos = 0;
25272    uint32_t seqno;
25273    int len;
25274    int respid;
25275    int res = 0;
25276    int debug = sip_debug_test_pvt(p);
25277    const char *e;
25278    int error = 0;
25279    int oldmethod = p->method;
25280    int acked = 0;
25281 
25282    /* RFC 3261 - 8.1.1 A valid SIP request must contain To, From, CSeq, Call-ID and Via.
25283     * 8.2.6.2 Response must have To, From, Call-ID CSeq, and Via related to the request,
25284     * so we can check to make sure these fields exist for all requests and responses */
25285    cseq = get_header(req, "Cseq");
25286    cmd = REQ_OFFSET_TO_STR(req, header[0]);
25287    /* Save the via_pos so we can check later that responses only have 1 Via header */
25288    via = __get_header(req, "Via", &via_pos);
25289    /* This must exist already because we've called find_call by now */
25290    callid = get_header(req, "Call-ID");
25291 
25292    /* Must have Cseq */
25293    if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq) || ast_strlen_zero(via)) {
25294       ast_log(LOG_ERROR, "Dropping this SIP message with Call-ID '%s', it's incomplete.\n", callid);
25295       error = 1;
25296    }
25297    if (!error && sscanf(cseq, "%30u%n", &seqno, &len) != 1) {
25298       ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
25299       error = 1;
25300    }
25301    if (error) {
25302       if (!p->initreq.headers) { /* New call */
25303          pvt_set_needdestroy(p, "no headers");
25304       }
25305       return -1;
25306    }
25307    /* Get the command XXX */
25308 
25309    cmd = REQ_OFFSET_TO_STR(req, rlPart1);
25310    e = ast_skip_blanks(REQ_OFFSET_TO_STR(req, rlPart2));
25311 
25312    /* Save useragent of the client */
25313    useragent = get_header(req, "User-Agent");
25314    if (!ast_strlen_zero(useragent))
25315       ast_string_field_set(p, useragent, useragent);
25316 
25317    /* Find out SIP method for incoming request */
25318    if (req->method == SIP_RESPONSE) {  /* Response to our request */
25319       /* ignore means "don't do anything with it" but still have to
25320        * respond appropriately.
25321        * But in this case this is a response already, so we really
25322        * have nothing to do with this message, and even setting the
25323        * ignore flag is pointless.
25324        */
25325       if (ast_strlen_zero(e)) {
25326          return 0;
25327       }
25328       if (sscanf(e, "%30d %n", &respid, &len) != 1) {
25329          ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
25330          return 0;
25331       }
25332       if (respid <= 0) {
25333          ast_log(LOG_WARNING, "Invalid SIP response code: '%d'\n", respid);
25334          return 0;
25335       }
25336       /* RFC 3261 - 8.1.3.3 If more than one Via header field value is present in a reponse
25337        * the UAC SHOULD discard the message. This is not perfect, as it will not catch multiple
25338        * headers joined with a comma. Fixing that would pretty much involve writing a new parser */
25339       if (!ast_strlen_zero(__get_header(req, "via", &via_pos))) {
25340          ast_log(LOG_WARNING, "Misrouted SIP response '%s' with Call-ID '%s', too many vias\n", e, callid);
25341          return 0;
25342       }
25343       if (p->ocseq && (p->ocseq < seqno)) {
25344          ast_debug(1, "Ignoring out of order response %u (expecting %u)\n", seqno, p->ocseq);
25345          return -1;
25346       } else {
25347          char causevar[256], causeval[256];
25348 
25349          if ((respid == 200) || ((respid >= 300) && (respid <= 399))) {
25350             extract_uri(p, req);
25351          }
25352 
25353          handle_response(p, respid, e + len, req, seqno);
25354 
25355          if (global_store_sip_cause && p->owner) {
25356             struct ast_channel *owner = p->owner;
25357 
25358             snprintf(causevar, sizeof(causevar), "MASTER_CHANNEL(HASH(SIP_CAUSE,%s))", owner->name);
25359             snprintf(causeval, sizeof(causeval), "SIP %s", REQ_OFFSET_TO_STR(req, rlPart2));
25360 
25361             ast_channel_ref(owner);
25362             sip_pvt_unlock(p);
25363             ast_channel_unlock(owner);
25364             *nounlock = 1;
25365             pbx_builtin_setvar_helper(owner, causevar, causeval);
25366             ast_channel_unref(owner);
25367             sip_pvt_lock(p);
25368          }
25369       }
25370       return 0;
25371    }
25372 
25373    /* New SIP request coming in
25374       (could be new request in existing SIP dialog as well...)
25375     */         
25376    
25377    p->method = req->method;   /* Find out which SIP method they are using */
25378    ast_debug(4, "**** Received %s (%d) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd);
25379 
25380    if (p->icseq && (p->icseq > seqno) ) {
25381       if (p->pendinginvite && seqno == p->pendinginvite && (req->method == SIP_ACK || req->method == SIP_CANCEL)) {
25382          ast_debug(2, "Got CANCEL or ACK on INVITE with transactions in between.\n");
25383       } else {
25384          ast_debug(1, "Ignoring too old SIP packet packet %u (expecting >= %u)\n", seqno, p->icseq);
25385          if (req->method == SIP_INVITE) {
25386             unsigned int ran = (ast_random() % 10) + 1;
25387             char seconds[4];
25388             snprintf(seconds, sizeof(seconds), "%u", ran);
25389             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 */
25390          } else if (req->method != SIP_ACK) {
25391             transmit_response(p, "500 Server error", req);  /* We must respond according to RFC 3261 sec 12.2 */
25392          }
25393          return -1;
25394       }
25395    } else if (p->icseq &&
25396          p->icseq == seqno &&
25397          req->method != SIP_ACK &&
25398          (p->method != SIP_CANCEL || p->alreadygone)) {
25399       /* ignore means "don't do anything with it" but still have to
25400          respond appropriately.  We do this if we receive a repeat of
25401          the last sequence number  */
25402       req->ignore = 1;
25403       ast_debug(3, "Ignoring SIP message because of retransmit (%s Seqno %u, ours %u)\n", sip_methods[p->method].text, p->icseq, seqno);
25404    }
25405 
25406    /* RFC 3261 section 9. "CANCEL has no effect on a request to which a UAS has
25407     * already given a final response." */
25408    if (!p->pendinginvite && (req->method == SIP_CANCEL)) {
25409       transmit_response(p, "481 Call/Transaction Does Not Exist", req);
25410       return res;
25411    }
25412 
25413    if (seqno >= p->icseq)
25414       /* Next should follow monotonically (but not necessarily
25415          incrementally -- thanks again to the genius authors of SIP --
25416          increasing */
25417       p->icseq = seqno;
25418 
25419    /* Find their tag if we haven't got it */
25420    if (ast_strlen_zero(p->theirtag)) {
25421       char tag[128];
25422 
25423       gettag(req, "From", tag, sizeof(tag));
25424       ast_string_field_set(p, theirtag, tag);
25425    }
25426    snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
25427 
25428    if (sip_cfg.pedanticsipchecking) {
25429       /* If this is a request packet without a from tag, it's not
25430          correct according to RFC 3261  */
25431       /* Check if this a new request in a new dialog with a totag already attached to it,
25432          RFC 3261 - section 12.2 - and we don't want to mess with recovery  */
25433       if (!p->initreq.headers && req->has_to_tag) {
25434          /* If this is a first request and it got a to-tag, it is not for us */
25435          if (!req->ignore && req->method == SIP_INVITE) {
25436             /* Just because we think this is a dialog-starting INVITE with a to-tag
25437              * doesn't mean it actually is. It could be a reinvite for an established, but
25438              * unknown dialog. In such a case, we need to change our tag to the
25439              * incoming INVITE's to-tag so that they will recognize the 481 we send and
25440              * so that we will properly match their incoming ACK.
25441              */
25442             char totag[128];
25443             gettag(req, "To", totag, sizeof(totag));
25444             ast_string_field_set(p, tag, totag);
25445             p->pendinginvite = p->icseq;
25446             transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
25447             /* Will cease to exist after ACK */
25448             return res;
25449          } else if (req->method != SIP_ACK) {
25450             transmit_response(p, "481 Call/Transaction Does Not Exist", req);
25451             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25452             return res;
25453          }
25454          /* Otherwise, this is an ACK. It will always have a to-tag */
25455       }
25456    }
25457 
25458    if (!e && (p->method == SIP_INVITE || p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_NOTIFY || p->method == SIP_PUBLISH)) {
25459       transmit_response(p, "400 Bad request", req);
25460       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25461       return -1;
25462    }
25463 
25464    /* Handle various incoming SIP methods in requests */
25465    switch (p->method) {
25466    case SIP_OPTIONS:
25467       res = handle_request_options(p, req, addr, e);
25468       break;
25469    case SIP_INVITE:
25470       res = handle_request_invite(p, req, debug, seqno, addr, recount, e, nounlock);
25471       break;
25472    case SIP_REFER:
25473       res = handle_request_refer(p, req, debug, seqno, nounlock);
25474       break;
25475    case SIP_CANCEL:
25476       res = handle_request_cancel(p, req);
25477       break;
25478    case SIP_BYE:
25479       res = handle_request_bye(p, req);
25480       break;
25481    case SIP_MESSAGE:
25482       res = handle_request_message(p, req);
25483       break;
25484    case SIP_PUBLISH:
25485       res = handle_request_publish(p, req, addr, seqno, e);
25486       break;
25487    case SIP_SUBSCRIBE:
25488       res = handle_request_subscribe(p, req, addr, seqno, e);
25489       break;
25490    case SIP_REGISTER:
25491       res = handle_request_register(p, req, addr, e);
25492       break;
25493    case SIP_INFO:
25494       if (req->debug)
25495          ast_verbose("Receiving INFO!\n");
25496       if (!req->ignore)
25497          handle_request_info(p, req);
25498       else  /* if ignoring, transmit response */
25499          transmit_response(p, "200 OK", req);
25500       break;
25501    case SIP_NOTIFY:
25502       res = handle_request_notify(p, req, addr, seqno, e);
25503       break;
25504    case SIP_UPDATE:
25505       res = handle_request_update(p, req);
25506       break;
25507    case SIP_ACK:
25508       /* Make sure we don't ignore this */
25509       if (seqno == p->pendinginvite) {
25510          p->invitestate = INV_TERMINATED;
25511          p->pendinginvite = 0;
25512          acked = __sip_ack(p, seqno, 1 /* response */, 0);
25513          if (find_sdp(req)) {
25514             if (process_sdp(p, req, SDP_T38_NONE)) {
25515                return -1;
25516             }
25517             if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
25518                ast_queue_control(p->owner, AST_CONTROL_SRCCHANGE);
25519             }
25520          }
25521          check_pendings(p);
25522       } else if (p->glareinvite == seqno) {
25523          /* handle ack for the 491 pending sent for glareinvite */
25524          p->glareinvite = 0;
25525          acked = __sip_ack(p, seqno, 1, 0);
25526       }
25527       if (!acked) {
25528          /* Got an ACK that did not match anything. Ignore
25529           * silently and restore previous method */
25530          p->method = oldmethod;
25531       }
25532       if (!p->lastinvite && ast_strlen_zero(p->randdata)) {
25533          pvt_set_needdestroy(p, "unmatched ACK");
25534       }
25535       break;
25536    default:
25537       transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
25538       ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n",
25539          cmd, ast_sockaddr_stringify(&p->sa));
25540       /* If this is some new method, and we don't have a call, destroy it now */
25541       if (!p->initreq.headers) {
25542          pvt_set_needdestroy(p, "unimplemented method");
25543       }
25544       break;
25545    }
25546    return res;
25547 }
25548 
25549 /*! \brief Read data from SIP UDP socket
25550 \note sipsock_read locks the owner channel while we are processing the SIP message
25551 \return 1 on error, 0 on success
25552 \note Successful messages is connected to SIP call and forwarded to handle_incoming()
25553 */
25554 static int sipsock_read(int *id, int fd, short events, void *ignore)
25555 {
25556    struct sip_request req;
25557    struct ast_sockaddr addr;
25558    int res;
25559    static char readbuf[65535];
25560 
25561    memset(&req, 0, sizeof(req));
25562    res = ast_recvfrom(fd, readbuf, sizeof(readbuf) - 1, 0, &addr);
25563    if (res < 0) {
25564 #if !defined(__FreeBSD__)
25565       if (errno == EAGAIN)
25566          ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
25567       else
25568 #endif
25569       if (errno != ECONNREFUSED)
25570          ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
25571       return 1;
25572    }
25573 
25574    readbuf[res] = '\0';
25575 
25576    if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
25577       return 1;
25578    }
25579 
25580    if (ast_str_set(&req.data, 0, "%s", readbuf) == AST_DYNSTR_BUILD_FAILED) {
25581       return -1;
25582    }
25583 
25584    req.socket.fd = sipsock;
25585    set_socket_transport(&req.socket, SIP_TRANSPORT_UDP);
25586    req.socket.tcptls_session  = NULL;
25587    req.socket.port = htons(ast_sockaddr_port(&bindaddr));
25588 
25589    handle_request_do(&req, &addr);
25590    deinit_req(&req);
25591 
25592    return 1;
25593 }
25594 
25595 /*! \brief Handle incoming SIP message - request or response
25596 
25597    This is used for all transports (udp, tcp and tcp/tls)
25598 */
25599 static int handle_request_do(struct sip_request *req, struct ast_sockaddr *addr)
25600 {
25601    struct sip_pvt *p;
25602    struct ast_channel *owner_chan_ref = NULL;
25603    int recount = 0;
25604    int nounlock = 0;
25605 
25606    if (sip_debug_test_addr(addr))   /* Set the debug flag early on packet level */
25607       req->debug = 1;
25608    if (sip_cfg.pedanticsipchecking)
25609       lws2sws(req->data);  /* Fix multiline headers */
25610    if (req->debug) {
25611       ast_verbose("\n<--- SIP read from %s:%s --->\n%s\n<------------->\n",
25612          get_transport(req->socket.type), ast_sockaddr_stringify(addr), req->data->str);
25613    }
25614 
25615    if (parse_request(req) == -1) { /* Bad packet, can't parse */
25616       ast_str_reset(req->data); /* nulling this out is NOT a good idea here. */
25617       return 1;
25618    }
25619    req->method = find_sip_method(REQ_OFFSET_TO_STR(req, rlPart1));
25620 
25621    if (req->debug)
25622       ast_verbose("--- (%d headers %d lines)%s ---\n", req->headers, req->lines, (req->headers + req->lines == 0) ? " Nat keepalive" : "");
25623 
25624    if (req->headers < 2) { /* Must have at least two headers */
25625       ast_str_reset(req->data); /* nulling this out is NOT a good idea here. */
25626       return 1;
25627    }
25628 
25629    /* Process request, with netlock held, and with usual deadlock avoidance */
25630    ast_mutex_lock(&netlock);
25631 
25632    /* Find the active SIP dialog or create a new one */
25633    p = find_call(req, addr, req->method); /* returns p with a reference only. _NOT_ locked*/
25634    if (p == NULL) {
25635       ast_debug(1, "Invalid SIP message - rejected , no callid, len %zu\n", ast_str_strlen(req->data));
25636       ast_mutex_unlock(&netlock);
25637       return 1;
25638    }
25639 
25640    /* Lock both the pvt and the owner if owner is present.  This will
25641     * not fail. */
25642    owner_chan_ref = sip_pvt_lock_full(p);
25643 
25644    copy_socket_data(&p->socket, &req->socket);
25645    ast_sockaddr_copy(&p->recv, addr);
25646 
25647    /* if we have an owner, then this request has been authenticated */
25648    if (p->owner) {
25649       req->authenticated = 1;
25650    }
25651 
25652    if (p->do_history) /* This is a request or response, note what it was for */
25653       append_history(p, "Rx", "%s / %s / %s", req->data->str, get_header(req, "CSeq"), REQ_OFFSET_TO_STR(req, rlPart2));
25654 
25655    if (handle_incoming(p, req, addr, &recount, &nounlock) == -1) {
25656       /* Request failed */
25657       ast_debug(1, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
25658    }
25659 
25660    if (recount) {
25661       ast_update_use_count();
25662    }
25663 
25664    if (p->owner && !nounlock) {
25665       ast_channel_unlock(p->owner);
25666    }
25667    if (owner_chan_ref) {
25668       ast_channel_unref(owner_chan_ref);
25669    }
25670    sip_pvt_unlock(p);
25671    ao2_t_ref(p, -1, "throw away dialog ptr from find_call at end of routine"); /* p is gone after the return */
25672    ast_mutex_unlock(&netlock);
25673 
25674    return 1;
25675 }
25676 
25677 /*! \brief Returns the port to use for this socket
25678  *
25679  * \param type The type of transport used
25680  * \param port Port we are checking to see if it's the standard port.
25681  * \note port is expected in host byte order
25682  */
25683 static int sip_standard_port(enum sip_transport type, int port)
25684 {
25685    if (type & SIP_TRANSPORT_TLS)
25686       return port == STANDARD_TLS_PORT;
25687    else
25688       return port == STANDARD_SIP_PORT;
25689 }
25690 
25691 static int threadinfo_locate_cb(void *obj, void *arg, int flags)
25692 {
25693    struct sip_threadinfo *th = obj;
25694    struct ast_sockaddr *s = arg;
25695 
25696    if (!ast_sockaddr_cmp(s, &th->tcptls_session->remote_address)) {
25697       return CMP_MATCH | CMP_STOP;
25698    }
25699 
25700    return 0;
25701 }
25702 
25703 /*!
25704  * \brief Find thread for TCP/TLS session (based on IP/Port
25705  *
25706  * \note This function returns an astobj2 reference
25707  */
25708 static struct ast_tcptls_session_instance *sip_tcp_locate(struct ast_sockaddr *s)
25709 {
25710    struct sip_threadinfo *th;
25711    struct ast_tcptls_session_instance *tcptls_instance = NULL;
25712 
25713    if ((th = ao2_callback(threadt, 0, threadinfo_locate_cb, s))) {
25714       tcptls_instance = (ao2_ref(th->tcptls_session, +1), th->tcptls_session);
25715       ao2_t_ref(th, -1, "decrement ref from callback");
25716    }
25717 
25718    return tcptls_instance;
25719 }
25720 
25721 /*!
25722  * \brief Helper for dns resolution to filter by address family.
25723  *
25724  * \note return 0 if addr is [::] else it returns addr's family.
25725  */
25726 int get_address_family_filter(unsigned int transport)
25727 {
25728    const struct ast_sockaddr *addr = NULL;
25729 
25730    if ((transport == SIP_TRANSPORT_UDP) || !transport) {
25731       addr = &bindaddr;
25732    }
25733    else if (transport == SIP_TRANSPORT_TCP) {
25734       addr = &sip_tcp_desc.local_address;
25735    }
25736    else if (transport == SIP_TRANSPORT_TLS) {
25737       addr = &sip_tls_desc.local_address;
25738    }
25739 
25740    if (ast_sockaddr_is_ipv6(addr) && ast_sockaddr_is_any(addr)) {
25741       return 0;
25742    }
25743 
25744    return addr->ss.ss_family;
25745 }
25746 
25747 /*! \todo Get socket for dialog, prepare if needed, and return file handle  */
25748 static int sip_prepare_socket(struct sip_pvt *p)
25749 {
25750    struct sip_socket *s = &p->socket;
25751    static const char name[] = "SIP socket";
25752    struct sip_threadinfo *th = NULL;
25753    struct ast_tcptls_session_instance *tcptls_session;
25754    struct ast_tcptls_session_args *ca;
25755    struct ast_sockaddr sa_tmp;
25756    pthread_t launched;
25757 
25758    /* check to see if a socket is already active */
25759    if ((s->fd != -1) && (s->type == SIP_TRANSPORT_UDP)) {
25760       return s->fd;
25761    }
25762    if ((s->type & (SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS)) &&
25763          (s->tcptls_session) &&
25764          (s->tcptls_session->fd != -1)) {
25765       return s->tcptls_session->fd;
25766    }
25767 
25768    /*! \todo Check this... This might be wrong, depending on the proxy configuration
25769       If proxy is in "force" mode its correct.
25770     */
25771    if (p->outboundproxy && p->outboundproxy->transport) {
25772       s->type = p->outboundproxy->transport;
25773    }
25774 
25775    if (s->type == SIP_TRANSPORT_UDP) {
25776       s->fd = sipsock;
25777       return s->fd;
25778    }
25779 
25780    /* At this point we are dealing with a TCP/TLS connection
25781     * 1. We need to check to see if a connection thread exists
25782     *    for this address, if so use that.
25783     * 2. If a thread does not exist for this address, but the tcptls_session
25784     *    exists on the socket, the connection was closed.
25785     * 3. If no tcptls_session thread exists for the address, and no tcptls_session
25786     *    already exists on the socket, create a new one and launch a new thread.
25787     */
25788 
25789    /* 1.  check for existing threads */
25790    ast_sockaddr_copy(&sa_tmp, sip_real_dst(p));
25791    if ((tcptls_session = sip_tcp_locate(&sa_tmp))) {
25792       s->fd = tcptls_session->fd;
25793       if (s->tcptls_session) {
25794          ao2_ref(s->tcptls_session, -1);
25795          s->tcptls_session = NULL;
25796       }
25797       s->tcptls_session = tcptls_session;
25798       return s->fd;
25799    /* 2.  Thread not found, if tcptls_session already exists, it once had a thread and is now terminated */
25800    } else if (s->tcptls_session) {
25801       return s->fd; /* XXX whether reconnection is ever necessary here needs to be investigated further */
25802    }
25803 
25804    /* 3.  Create a new TCP/TLS client connection */
25805    /* create new session arguments for the client connection */
25806    if (!(ca = ao2_alloc(sizeof(*ca), sip_tcptls_client_args_destructor)) ||
25807       !(ca->name = ast_strdup(name))) {
25808       goto create_tcptls_session_fail;
25809    }
25810    ca->accept_fd = -1;
25811    ast_sockaddr_copy(&ca->remote_address,sip_real_dst(p));
25812    /* if type is TLS, we need to create a tls cfg for this session arg */
25813    if (s->type == SIP_TRANSPORT_TLS) {
25814       if (!(ca->tls_cfg = ast_calloc(1, sizeof(*ca->tls_cfg)))) {
25815          goto create_tcptls_session_fail;
25816       }
25817       memcpy(ca->tls_cfg, &default_tls_cfg, sizeof(*ca->tls_cfg));
25818 
25819       if (!(ca->tls_cfg->certfile = ast_strdup(default_tls_cfg.certfile)) ||
25820          !(ca->tls_cfg->pvtfile = ast_strdup(default_tls_cfg.pvtfile)) ||
25821          !(ca->tls_cfg->cipher = ast_strdup(default_tls_cfg.cipher)) ||
25822          !(ca->tls_cfg->cafile = ast_strdup(default_tls_cfg.cafile)) ||
25823          !(ca->tls_cfg->capath = ast_strdup(default_tls_cfg.capath))) {
25824 
25825          goto create_tcptls_session_fail;
25826       }
25827 
25828       /* this host is used as the common name in ssl/tls */
25829       if (!ast_strlen_zero(p->tohost)) {
25830          ast_copy_string(ca->hostname, p->tohost, sizeof(ca->hostname));
25831       }
25832    }
25833 
25834    /* Create a client connection for address, this does not start the connection, just sets it up. */
25835    if (!(s->tcptls_session = ast_tcptls_client_create(ca))) {
25836       goto create_tcptls_session_fail;
25837    }
25838 
25839    s->fd = s->tcptls_session->fd;
25840 
25841    /* client connections need to have the sip_threadinfo object created before
25842     * the thread is detached.  This ensures the alert_pipe is up before it will
25843     * be used.  Note that this function links the new threadinfo object into the
25844     * threadt container. */
25845    if (!(th = sip_threadinfo_create(s->tcptls_session, s->type))) {
25846       goto create_tcptls_session_fail;
25847    }
25848 
25849    /* Give the new thread a reference to the tcptls_session */
25850    ao2_ref(s->tcptls_session, +1);
25851 
25852    if (ast_pthread_create_detached_background(&launched, NULL, sip_tcp_worker_fn, s->tcptls_session)) {
25853       ast_debug(1, "Unable to launch '%s'.", ca->name);
25854       ao2_ref(s->tcptls_session, -1); /* take away the thread ref we just gave it */
25855       goto create_tcptls_session_fail;
25856    }
25857 
25858    return s->fd;
25859 
25860 create_tcptls_session_fail:
25861    if (ca) {
25862       ao2_t_ref(ca, -1, "failed to create client, getting rid of client tcptls_session arguments");
25863    }
25864    if (s->tcptls_session) {
25865       ast_tcptls_close_session_file(s->tcptls_session);
25866       s->fd = -1;
25867       ao2_ref(s->tcptls_session, -1);
25868       s->tcptls_session = NULL;
25869    }
25870    if (th) {
25871       ao2_t_unlink(threadt, th, "Removing tcptls thread info object, thread failed to open");
25872    }
25873 
25874    return -1;
25875 }
25876 
25877 /*!
25878  * \brief Get cached MWI info
25879  * \return TRUE if found MWI in cache
25880  */
25881 static int get_cached_mwi(struct sip_peer *peer, int *new, int *old)
25882 {
25883    struct sip_mailbox *mailbox;
25884    int in_cache;
25885 
25886    in_cache = 0;
25887    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
25888       struct ast_event *event;
25889       event = ast_event_get_cached(AST_EVENT_MWI,
25890          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
25891          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
25892          AST_EVENT_IE_END);
25893       if (!event)
25894          continue;
25895       *new += ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
25896       *old += ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
25897       ast_event_destroy(event);
25898       in_cache = 1;
25899    }
25900 
25901    return in_cache;
25902 }
25903 
25904 /*! \brief Send message waiting indication to alert peer that they've got voicemail
25905  *  \note Both peer and associated sip_pvt must be unlocked prior to calling this function
25906 */
25907 static int sip_send_mwi_to_peer(struct sip_peer *peer, int cache_only)
25908 {
25909    /* Called with peer lock, but releases it */
25910    struct sip_pvt *p;
25911    int newmsgs = 0, oldmsgs = 0;
25912    const char *vmexten = NULL;
25913 
25914    ao2_lock(peer);
25915 
25916    if (peer->vmexten) {
25917       vmexten = ast_strdupa(peer->vmexten);
25918    }
25919 
25920    if (ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY) && !peer->mwipvt) {
25921       update_peer_lastmsgssent(peer, -1, 1);
25922       ao2_unlock(peer);
25923       return 0;
25924    }
25925 
25926    /* Do we have an IP address? If not, skip this peer */
25927    if (ast_sockaddr_isnull(&peer->addr) && ast_sockaddr_isnull(&peer->defaddr)) {
25928       update_peer_lastmsgssent(peer, -1, 1);
25929       ao2_unlock(peer);
25930       return 0;
25931    }
25932 
25933    /* Attempt to use cached mwi to get message counts. */
25934    if (!get_cached_mwi(peer, &newmsgs, &oldmsgs) && !cache_only) {
25935       /* Fall back to manually checking the mailbox if not cache_only and get_cached_mwi failed */
25936       struct ast_str *mailbox_str = ast_str_alloca(512);
25937       peer_mailboxes_to_str(&mailbox_str, peer);
25938       ao2_unlock(peer);
25939       /* If there is no mailbox do nothing */
25940       if (ast_strlen_zero(mailbox_str->str)) {
25941          update_peer_lastmsgssent(peer, -1, 0);
25942          return 0;
25943       }
25944       ast_app_inboxcount(mailbox_str->str, &newmsgs, &oldmsgs);
25945       ao2_lock(peer);
25946    }
25947 
25948    if (peer->mwipvt) {
25949       /* Base message on subscription */
25950       p = dialog_ref(peer->mwipvt, "sip_send_mwi_to_peer: Setting dialog ptr p from peer->mwipvt");
25951       ao2_unlock(peer);
25952    } else {
25953       ao2_unlock(peer);
25954       /* Build temporary dialog for this message */
25955       if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
25956          update_peer_lastmsgssent(peer, -1, 0);
25957          return -1;
25958       }
25959 
25960       /* If we don't set the socket type to 0, then create_addr_from_peer will fail immediately if the peer
25961        * uses any transport other than UDP. We set the type to 0 here and then let create_addr_from_peer copy
25962        * the peer's socket information to the sip_pvt we just allocated
25963        */
25964       set_socket_transport(&p->socket, 0);
25965       if (create_addr_from_peer(p, peer)) {
25966          /* Maybe they're not registered, etc. */
25967          dialog_unlink_all(p);
25968          dialog_unref(p, "unref dialog p just created via sip_alloc");
25969          update_peer_lastmsgssent(peer, -1, 0);
25970          return 0;
25971       }
25972       /* Recalculate our side, and recalculate Call ID */
25973       ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
25974       build_via(p);
25975 
25976       ao2_lock(peer);
25977       if (!ast_strlen_zero(peer->mwi_from)) {
25978          ast_string_field_set(p, mwi_from, peer->mwi_from);
25979       } else if (!ast_strlen_zero(default_mwi_from)) {
25980          ast_string_field_set(p, mwi_from, default_mwi_from);
25981       }
25982       ao2_unlock(peer);
25983 
25984       /* Change the dialog callid. */
25985       change_callid_pvt(p, NULL);
25986 
25987       /* Destroy this session after 32 secs */
25988       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
25989    }
25990 
25991    /* 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,
25992       we really need to have a lock on it */
25993    sip_pvt_lock(p);
25994 
25995    /* Send MWI */
25996    ast_set_flag(&p->flags[0], SIP_OUTGOING);
25997    /* the following will decrement the refcount on p as it finishes */
25998    transmit_notify_with_mwi(p, newmsgs, oldmsgs, vmexten);
25999    sip_pvt_unlock(p);
26000    dialog_unref(p, "unref dialog ptr p just before it goes out of scope at the end of sip_send_mwi_to_peer.");
26001 
26002    update_peer_lastmsgssent(peer, ((newmsgs > 0x7fff ? 0x7fff0000 : (newmsgs << 16)) | (oldmsgs > 0xffff ? 0xffff : oldmsgs)), 0);
26003 
26004    return 0;
26005 }
26006 
26007 /*! \brief helper function for the monitoring thread -- seems to be called with the assumption that the dialog is locked */
26008 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t)
26009 {
26010    /* If we have no RTP or no active owner, no need to check timers */
26011    if (!dialog->rtp || !dialog->owner)
26012       return;
26013    /* If the call is not in UP state or redirected outside Asterisk, no need to check timers */
26014 
26015    if (dialog->owner->_state != AST_STATE_UP || !ast_sockaddr_isnull(&dialog->redirip))
26016       return;
26017 
26018    /* If the call is involved in a T38 fax session do not check RTP timeout */
26019    if (dialog->t38.state == T38_ENABLED)
26020       return;
26021 
26022    /* If we have no timers set, return now */
26023    if (!ast_rtp_instance_get_keepalive(dialog->rtp) && !ast_rtp_instance_get_timeout(dialog->rtp) && !ast_rtp_instance_get_hold_timeout(dialog->rtp)) {
26024       return;
26025    }
26026 
26027    /* Check AUDIO RTP keepalives */
26028    if (dialog->lastrtptx && ast_rtp_instance_get_keepalive(dialog->rtp) &&
26029           (t > dialog->lastrtptx + ast_rtp_instance_get_keepalive(dialog->rtp))) {
26030       /* Need to send an empty RTP packet */
26031       dialog->lastrtptx = time(NULL);
26032       ast_rtp_instance_sendcng(dialog->rtp, 0);
26033    }
26034 
26035    /*! \todo Check video RTP keepalives
26036 
26037       Do we need to move the lastrtptx to the RTP structure to have one for audio and one
26038       for video? It really does belong to the RTP structure.
26039    */
26040 
26041    /* Check AUDIO RTP timers */
26042    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))) {
26043       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)))) {
26044          /* Needs a hangup */
26045          if (ast_rtp_instance_get_timeout(dialog->rtp)) {
26046             if (!dialog->owner || ast_channel_trylock(dialog->owner)) {
26047                /*
26048                 * Don't block, just try again later.
26049                 * If there was no owner, the call is dead already.
26050                 */
26051                return;
26052             }
26053             ast_log(LOG_NOTICE, "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
26054                dialog->owner->name, (long) (t - dialog->lastrtprx));
26055             /* Issue a softhangup */
26056             ast_softhangup_nolock(dialog->owner, AST_SOFTHANGUP_DEV);
26057             ast_channel_unlock(dialog->owner);
26058             /* forget the timeouts for this call, since a hangup
26059                has already been requested and we don't want to
26060                repeatedly request hangups
26061             */
26062             ast_rtp_instance_set_timeout(dialog->rtp, 0);
26063             ast_rtp_instance_set_hold_timeout(dialog->rtp, 0);
26064             if (dialog->vrtp) {
26065                ast_rtp_instance_set_timeout(dialog->vrtp, 0);
26066                ast_rtp_instance_set_hold_timeout(dialog->vrtp, 0);
26067             }
26068          }
26069       }
26070    }
26071 }
26072 
26073 /*! \brief The SIP monitoring thread
26074 \note This thread monitors all the SIP sessions and peers that needs notification of mwi
26075    (and thus do not have a separate thread) indefinitely
26076 */
26077 static void *do_monitor(void *data)
26078 {
26079    int res;
26080    time_t t;
26081    int reloading;
26082 
26083    /* Add an I/O event to our SIP UDP socket */
26084    if (sipsock > -1)
26085       sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
26086 
26087    /* From here on out, we die whenever asked */
26088    for(;;) {
26089       /* Check for a reload request */
26090       ast_mutex_lock(&sip_reload_lock);
26091       reloading = sip_reloading;
26092       sip_reloading = FALSE;
26093       ast_mutex_unlock(&sip_reload_lock);
26094       if (reloading) {
26095          ast_verb(1, "Reloading SIP\n");
26096          sip_do_reload(sip_reloadreason);
26097 
26098          /* Change the I/O fd of our UDP socket */
26099          if (sipsock > -1) {
26100             if (sipsock_read_id)
26101                sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
26102             else
26103                sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
26104          } else if (sipsock_read_id) {
26105             ast_io_remove(io, sipsock_read_id);
26106             sipsock_read_id = NULL;
26107          }
26108       }
26109 
26110       /* Check for dialogs needing to be killed */
26111       t = time(NULL);
26112       /* don't scan the dialogs list if it hasn't been a reasonable period
26113          of time since the last time we did it (when MWI is being sent, we can
26114          get back to this point every millisecond or less)
26115       */
26116       /*
26117        * We cannot hold the dialogs container lock when we destroy a
26118        * dialog because of potential deadlocks.  Instead we link the
26119        * doomed dialog into dialogs_to_destroy and then iterate over
26120        * that container destroying the dialogs.
26121        */
26122       ao2_t_callback(dialogs, OBJ_NODATA | OBJ_MULTIPLE, dialog_needdestroy, &t,
26123          "callback to monitor dialog status");
26124       if (ao2_container_count(dialogs_to_destroy)) {
26125          /* Now destroy the found dialogs that need to be destroyed. */
26126          ao2_t_callback(dialogs_to_destroy, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE,
26127             dialog_unlink_callback, NULL, "callback to dialog_unlink_all");
26128       }
26129 
26130       /* XXX TODO The scheduler usage in this module does not have sufficient
26131        * synchronization being done between running the scheduler and places
26132        * scheduling tasks.  As it is written, any scheduled item may not run
26133        * any sooner than about  1 second, regardless of whether a sooner time
26134        * was asked for. */
26135 
26136       pthread_testcancel();
26137       /* Wait for sched or io */
26138       res = ast_sched_wait(sched);
26139       if ((res < 0) || (res > 1000))
26140          res = 1000;
26141       res = ast_io_wait(io, res);
26142       if (res > 20)
26143          ast_debug(1, "chan_sip: ast_io_wait ran %d all at once\n", res);
26144       ast_mutex_lock(&monlock);
26145       res = ast_sched_runq(sched);
26146       if (res >= 20)
26147          ast_debug(1, "chan_sip: ast_sched_runq ran %d all at once\n", res);
26148       if (global_store_sip_cause && res >= 100)
26149          ast_log(LOG_WARNING, "scheduler delays detected, setting 'storesipcause' to 'no' in %s will improve performance\n", config);
26150       ast_mutex_unlock(&monlock);
26151    }
26152 
26153    /* Never reached */
26154    return NULL;
26155 }
26156 
26157 /*! \brief Start the channel monitor thread */
26158 static int restart_monitor(void)
26159 {
26160    /* If we're supposed to be stopped -- stay stopped */
26161    if (monitor_thread == AST_PTHREADT_STOP)
26162       return 0;
26163    ast_mutex_lock(&monlock);
26164    if (monitor_thread == pthread_self()) {
26165       ast_mutex_unlock(&monlock);
26166       ast_log(LOG_WARNING, "Cannot kill myself\n");
26167       return -1;
26168    }
26169    if (monitor_thread != AST_PTHREADT_NULL) {
26170       /* Wake up the thread */
26171       pthread_kill(monitor_thread, SIGURG);
26172    } else {
26173       /* Start a new monitor */
26174       if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
26175          ast_mutex_unlock(&monlock);
26176          ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
26177          return -1;
26178       }
26179    }
26180    ast_mutex_unlock(&monlock);
26181    return 0;
26182 }
26183 
26184 
26185 /*! \brief Session-Timers: Restart session timer */
26186 static void restart_session_timer(struct sip_pvt *p)
26187 {
26188    if (!p->stimer) {
26189       ast_log(LOG_WARNING, "Null stimer in restart_session_timer - %s\n", p->callid);
26190       return;
26191    }
26192 
26193    if (p->stimer->st_active == TRUE) {
26194       ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
26195       AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
26196             dialog_unref(p, "Removing session timer ref"));
26197       start_session_timer(p);
26198    }
26199 }
26200 
26201 
26202 /*! \brief Session-Timers: Stop session timer */
26203 static void stop_session_timer(struct sip_pvt *p)
26204 {
26205    if (!p->stimer) {
26206       ast_log(LOG_WARNING, "Null stimer in stop_session_timer - %s\n", p->callid);
26207       return;
26208    }
26209 
26210    if (p->stimer->st_active == TRUE) {
26211       p->stimer->st_active = FALSE;
26212       ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
26213       AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
26214             dialog_unref(p, "removing session timer ref"));
26215    }
26216 }
26217 
26218 
26219 /*! \brief Session-Timers: Start session timer */
26220 static void start_session_timer(struct sip_pvt *p)
26221 {
26222    if (!p->stimer) {
26223       ast_log(LOG_WARNING, "Null stimer in start_session_timer - %s\n", p->callid);
26224       return;
26225    }
26226 
26227    if (p->stimer->st_schedid > -1) {
26228       /* in the event a timer is already going, stop it */
26229       ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
26230       AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
26231          dialog_unref(p, "unref stimer->st_schedid from dialog"));
26232    }
26233 
26234    p->stimer->st_schedid  = ast_sched_add(sched, p->stimer->st_interval * 1000 / 2, proc_session_timer, 
26235          dialog_ref(p, "adding session timer ref"));
26236    if (p->stimer->st_schedid < 0) {
26237       dialog_unref(p, "removing session timer ref");
26238       ast_log(LOG_ERROR, "ast_sched_add failed - %s\n", p->callid);
26239    } else {
26240       p->stimer->st_active = TRUE;
26241       ast_debug(2, "Session timer started: %d - %s\n", p->stimer->st_schedid, p->callid);
26242    }
26243 }
26244 
26245 
26246 /*! \brief Session-Timers: Process session refresh timeout event */
26247 static int proc_session_timer(const void *vp)
26248 {
26249    struct sip_pvt *p = (struct sip_pvt *) vp;
26250    int res = 0;
26251 
26252    if (!p->stimer) {
26253       ast_log(LOG_WARNING, "Null stimer in proc_session_timer - %s\n", p->callid);
26254       goto return_unref;
26255    }
26256 
26257    ast_debug(2, "Session timer expired: %d - %s\n", p->stimer->st_schedid, p->callid);
26258 
26259    if (!p->owner) {
26260       goto return_unref;
26261    }
26262 
26263    if ((p->stimer->st_active != TRUE) || (p->owner->_state != AST_STATE_UP)) {
26264       goto return_unref;
26265    }
26266 
26267    if (p->stimer->st_ref == SESSION_TIMER_REFRESHER_US) {
26268       res = 1;
26269       transmit_reinvite_with_sdp(p, FALSE, TRUE);
26270    } else {
26271       p->stimer->st_expirys++;
26272       if (p->stimer->st_expirys >= 2) {
26273          if (p->stimer->quit_flag) {
26274             goto return_unref;
26275          }
26276          ast_log(LOG_WARNING, "Session-Timer expired - %s\n", p->callid);
26277          sip_pvt_lock(p);
26278          while (p->owner && ast_channel_trylock(p->owner)) {
26279             sip_pvt_unlock(p);
26280             usleep(1);
26281             if (p->stimer && p->stimer->quit_flag) {
26282                goto return_unref;
26283             }
26284             sip_pvt_lock(p);
26285          }
26286 
26287          ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
26288          ast_channel_unlock(p->owner);
26289          sip_pvt_unlock(p);
26290       } else {
26291          res = 1;
26292       }
26293    }
26294 
26295 return_unref:
26296    if (!res) {
26297       /* An error occurred.  Stop session timer processing */
26298       if (p->stimer) {
26299          ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
26300          p->stimer->st_schedid = -1;
26301          stop_session_timer(p);
26302       }
26303 
26304       /* If we are not asking to be rescheduled, then we need to release our
26305        * reference to the dialog. */
26306       dialog_unref(p, "removing session timer ref");
26307    }
26308 
26309    return res;
26310 }
26311 
26312 
26313 /*! \brief Session-Timers: Function for parsing Min-SE header */
26314 int parse_minse (const char *p_hdrval, int *const p_interval)
26315 {
26316    if (ast_strlen_zero(p_hdrval)) {
26317       ast_log(LOG_WARNING, "Null Min-SE header\n");
26318       return -1;
26319    }
26320 
26321    *p_interval = 0;
26322    p_hdrval = ast_skip_blanks(p_hdrval);
26323    if (!sscanf(p_hdrval, "%30d", p_interval)) {
26324       ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
26325       return -1;
26326    }
26327 
26328    ast_debug(2, "Received Min-SE: %d\n", *p_interval);
26329    return 0;
26330 }
26331 
26332 
26333 /*! \brief Session-Timers: Function for parsing Session-Expires header */
26334 int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher_param *const p_ref)
26335 {
26336    char *p_token;
26337    int  ref_idx;
26338    char *p_se_hdr;
26339 
26340    if (ast_strlen_zero(p_hdrval)) {
26341       ast_log(LOG_WARNING, "Null Session-Expires header\n");
26342       return -1;
26343    }
26344 
26345    *p_ref = SESSION_TIMER_REFRESHER_PARAM_UNKNOWN;
26346    *p_interval = 0;
26347 
26348    p_se_hdr = ast_strdupa(p_hdrval);
26349    p_se_hdr = ast_skip_blanks(p_se_hdr);
26350 
26351    while ((p_token = strsep(&p_se_hdr, ";"))) {
26352       p_token = ast_skip_blanks(p_token);
26353       if (!sscanf(p_token, "%30d", p_interval)) {
26354          ast_log(LOG_WARNING, "Parsing of Session-Expires failed\n");
26355          return -1;
26356       }
26357 
26358       ast_debug(2, "Session-Expires: %d\n", *p_interval);
26359 
26360       if (!p_se_hdr)
26361          continue;
26362 
26363       p_se_hdr = ast_skip_blanks(p_se_hdr);
26364       ref_idx = strlen("refresher=");
26365       if (!strncasecmp(p_se_hdr, "refresher=", ref_idx)) {
26366          p_se_hdr += ref_idx;
26367          p_se_hdr = ast_skip_blanks(p_se_hdr);
26368 
26369          if (!strncasecmp(p_se_hdr, "uac", strlen("uac"))) {
26370             *p_ref = SESSION_TIMER_REFRESHER_PARAM_UAC;
26371             ast_debug(2, "Refresher: UAC\n");
26372          } else if (!strncasecmp(p_se_hdr, "uas", strlen("uas"))) {
26373             *p_ref = SESSION_TIMER_REFRESHER_PARAM_UAS;
26374             ast_debug(2, "Refresher: UAS\n");
26375          } else {
26376             ast_log(LOG_WARNING, "Invalid refresher value %s\n", p_se_hdr);
26377             return -1;
26378          }
26379          break;
26380       }
26381    }
26382    return 0;
26383 }
26384 
26385 
26386 /*! \brief Handle 422 response to INVITE with session-timer requested
26387 
26388    Session-Timers:   An INVITE originated by Asterisk that asks for session-timers support
26389    from the UAS can result into a 422 response. This is how a UAS or an intermediary proxy
26390    server tells Asterisk that the session refresh interval offered by Asterisk is too low
26391    for them.  The proc_422_rsp() function handles a 422 response.  It extracts the Min-SE
26392    header that comes back in 422 and sends a new INVITE accordingly. */
26393 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp)
26394 {
26395    int rtn;
26396    const char *p_hdrval;
26397    int minse;
26398 
26399    p_hdrval = get_header(rsp, "Min-SE");
26400    if (ast_strlen_zero(p_hdrval)) {
26401       ast_log(LOG_WARNING, "422 response without a Min-SE header %s\n", p_hdrval);
26402       return;
26403    }
26404    rtn = parse_minse(p_hdrval, &minse);
26405    if (rtn != 0) {
26406       ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
26407       return;
26408    }
26409    p->stimer->st_interval = minse;
26410    transmit_invite(p, SIP_INVITE, 1, 2, NULL);
26411 }
26412 
26413 
26414 /*! \brief Get Max or Min SE (session timer expiry)
26415  * \param p pointer to the SIP dialog
26416  * \param max if true, get max se, otherwise min se
26417 */
26418 int st_get_se(struct sip_pvt *p, int max)
26419 {
26420    if (max == TRUE) {
26421       if (p->stimer->st_cached_max_se) {
26422          return  p->stimer->st_cached_max_se;
26423       }
26424       if (p->relatedpeer) {
26425          p->stimer->st_cached_max_se = p->relatedpeer->stimer.st_max_se;
26426          return (p->stimer->st_cached_max_se);
26427       }
26428       p->stimer->st_cached_max_se = global_max_se;
26429       return (p->stimer->st_cached_max_se);
26430    } 
26431    /* Find Min SE timer */
26432    if (p->stimer->st_cached_min_se) {
26433       return p->stimer->st_cached_min_se;
26434    } 
26435    if (p->relatedpeer) {
26436       p->stimer->st_cached_min_se = p->relatedpeer->stimer.st_min_se;
26437       return (p->stimer->st_cached_min_se);
26438    }
26439    p->stimer->st_cached_min_se = global_min_se;
26440    return (p->stimer->st_cached_min_se);
26441 }
26442 
26443 
26444 /*! \brief Get the entity (UAC or UAS) that's acting as the session-timer refresher
26445  * \note This is only called when processing an INVITE, so in that case Asterisk is
26446  *       always currently the UAS. If this is ever used to process responses, the
26447  *       function will have to be changed.
26448  * \param p pointer to the SIP dialog
26449 */
26450 enum st_refresher st_get_refresher(struct sip_pvt *p)
26451 {
26452    if (p->stimer->st_cached_ref != SESSION_TIMER_REFRESHER_AUTO) {
26453       return p->stimer->st_cached_ref;
26454    }
26455 
26456    if (p->relatedpeer) {
26457       p->stimer->st_cached_ref = (p->relatedpeer->stimer.st_ref == SESSION_TIMER_REFRESHER_PARAM_UAC) ? SESSION_TIMER_REFRESHER_THEM : SESSION_TIMER_REFRESHER_US;
26458       return p->stimer->st_cached_ref;
26459    }
26460    
26461    p->stimer->st_cached_ref = (global_st_refresher == SESSION_TIMER_REFRESHER_PARAM_UAC) ? SESSION_TIMER_REFRESHER_THEM : SESSION_TIMER_REFRESHER_US;
26462    return p->stimer->st_cached_ref;
26463 }
26464 
26465 
26466 /*!
26467  * \brief Get the session-timer mode 
26468  * \param p pointer to the SIP dialog 
26469  * \param no_cached, set this to true in order to force a peername lookup on
26470  *        the session timer mode.
26471 */
26472 enum st_mode st_get_mode(struct sip_pvt *p, int no_cached)
26473 {
26474    if (!p->stimer) {
26475       sip_st_alloc(p);
26476       if (!p->stimer) {
26477          return SESSION_TIMER_MODE_INVALID;
26478       }
26479    }
26480 
26481    if (!no_cached && p->stimer->st_cached_mode != SESSION_TIMER_MODE_INVALID)
26482       return p->stimer->st_cached_mode;
26483 
26484    if (p->relatedpeer) {
26485       p->stimer->st_cached_mode = p->relatedpeer->stimer.st_mode_oper;
26486       return p->stimer->st_cached_mode;
26487    }
26488 
26489    p->stimer->st_cached_mode = global_st_mode;
26490    return global_st_mode;
26491 }
26492 
26493 
26494 /*! \brief React to lack of answer to Qualify poke */
26495 static int sip_poke_noanswer(const void *data)
26496 {
26497    struct sip_peer *peer = (struct sip_peer *)data;
26498 
26499    peer->pokeexpire = -1;
26500 
26501    if (peer->lastms > -1) {
26502       ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE!  Last qualify: %d\n", peer->name, peer->lastms);
26503       if (sip_cfg.peer_rtupdate) {
26504          ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", "-1", SENTINEL);
26505       }
26506       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
26507       if (sip_cfg.regextenonqualify) {
26508          register_peer_exten(peer, FALSE);
26509       }
26510    }
26511 
26512    if (peer->call) {
26513       dialog_unlink_all(peer->call);
26514       peer->call = dialog_unref(peer->call, "unref dialog peer->call");
26515       /* peer->call = sip_destroy(peer->call);*/
26516    }
26517 
26518    /* Don't send a devstate change if nothing changed. */
26519    if (peer->lastms > -1) {
26520       peer->lastms = -1;
26521       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
26522    }
26523 
26524    /* Try again quickly */
26525    AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
26526          DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer,
26527          unref_peer(_data, "removing poke peer ref"),
26528          unref_peer(peer, "removing poke peer ref"),
26529          ref_peer(peer, "adding poke peer ref"));
26530 
26531    /* Release the ref held by the running scheduler entry */
26532    unref_peer(peer, "release peer poke noanswer ref");
26533 
26534    return 0;
26535 }
26536 
26537 /*! \brief Check availability of peer, also keep NAT open
26538 \note This is done with 60 seconds between each ping,
26539    unless forced by cli or manager. If peer is unreachable,
26540    we check every 10th second by default.
26541 */
26542 static int sip_poke_peer(struct sip_peer *peer, int force)
26543 {
26544    struct sip_pvt *p;
26545    int xmitres = 0;
26546    
26547    if ((!peer->maxms && !force) || ast_sockaddr_isnull(&peer->addr)) {
26548       /* IF we have no IP, or this isn't to be monitored, return
26549         immediately after clearing things out */
26550       AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
26551             unref_peer(peer, "removing poke peer ref"));
26552       
26553       peer->lastms = 0;
26554       if (peer->call) {
26555          peer->call = dialog_unref(peer->call, "unref dialog peer->call");
26556       }
26557       return 0;
26558    }
26559    if (peer->call) {
26560       if (sipdebug) {
26561          ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
26562       }
26563       dialog_unlink_all(peer->call);
26564       peer->call = dialog_unref(peer->call, "unref dialog peer->call");
26565       /* peer->call = sip_destroy(peer->call); */
26566    }
26567    if (!(p = sip_alloc(NULL, NULL, 0, SIP_OPTIONS, NULL))) {
26568       return -1;
26569    }
26570    peer->call = dialog_ref(p, "copy sip alloc from p to peer->call");
26571 
26572    p->sa = peer->addr;
26573    p->recv = peer->addr;
26574    copy_socket_data(&p->socket, &peer->socket);
26575    ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
26576    ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
26577    ast_copy_flags(&p->flags[2], &peer->flags[2], SIP_PAGE3_FLAGS_TO_COPY);
26578 
26579    /* Send OPTIONs to peer's fullcontact */
26580    if (!ast_strlen_zero(peer->fullcontact)) {
26581       ast_string_field_set(p, fullcontact, peer->fullcontact);
26582    }
26583 
26584    if (!ast_strlen_zero(peer->fromuser)) {
26585       ast_string_field_set(p, fromuser, peer->fromuser);
26586    }
26587 
26588    if (!ast_strlen_zero(peer->tohost)) {
26589       ast_string_field_set(p, tohost, peer->tohost);
26590    } else {
26591       ast_string_field_set(p, tohost, ast_sockaddr_stringify_host_remote(&peer->addr));
26592    }
26593 
26594    /* Recalculate our side, and recalculate Call ID */
26595    ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
26596    build_via(p);
26597 
26598    /* Change the dialog callid. */
26599    change_callid_pvt(p, NULL);
26600 
26601    AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
26602          unref_peer(peer, "removing poke peer ref"));
26603    
26604    if (p->relatedpeer)
26605       p->relatedpeer = unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
26606    p->relatedpeer = ref_peer(peer, "setting the relatedpeer field in the dialog");
26607    ast_set_flag(&p->flags[0], SIP_OUTGOING);
26608 #ifdef VOCAL_DATA_HACK
26609    ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
26610    xmitres = transmit_invite(p, SIP_INVITE, 0, 2, NULL); /* sinks the p refcount */
26611 #else
26612    xmitres = transmit_invite(p, SIP_OPTIONS, 0, 2, NULL); /* sinks the p refcount */
26613 #endif
26614    peer->ps = ast_tvnow();
26615    if (xmitres == XMIT_ERROR) {
26616       /* Immediately unreachable, network problems */
26617       sip_poke_noanswer(ref_peer(peer, "add ref for peerexpire (fake, for sip_poke_noanswer to remove)"));
26618    } else if (!force) {
26619       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, peer->maxms * 2, sip_poke_noanswer, peer,
26620             unref_peer(_data, "removing poke peer ref"),
26621             unref_peer(peer, "removing poke peer ref"),
26622             ref_peer(peer, "adding poke peer ref"));
26623    }
26624    dialog_unref(p, "unref dialog at end of sip_poke_peer, obtained from sip_alloc, just before it goes out of scope");
26625    return 0;
26626 }
26627 
26628 /*! \brief Part of PBX channel interface
26629 \note
26630 \par  Return values:---
26631 
26632    If we have qualify on and the device is not reachable, regardless of registration
26633    state we return AST_DEVICE_UNAVAILABLE
26634 
26635    For peers with call limit:
26636       - not registered        AST_DEVICE_UNAVAILABLE
26637       - registered, no call         AST_DEVICE_NOT_INUSE
26638       - registered, active calls    AST_DEVICE_INUSE
26639       - registered, call limit reached AST_DEVICE_BUSY
26640       - registered, onhold       AST_DEVICE_ONHOLD
26641       - registered, ringing         AST_DEVICE_RINGING
26642 
26643    For peers without call limit:
26644       - not registered        AST_DEVICE_UNAVAILABLE
26645       - registered            AST_DEVICE_NOT_INUSE
26646       - fixed IP (!dynamic)         AST_DEVICE_NOT_INUSE
26647    
26648    Peers that does not have a known call and can't be reached by OPTIONS
26649       - unreachable           AST_DEVICE_UNAVAILABLE
26650 
26651    If we return AST_DEVICE_UNKNOWN, the device state engine will try to find
26652    out a state by walking the channel list.
26653 
26654    The queue system (\ref app_queue.c) treats a member as "active"
26655    if devicestate is != AST_DEVICE_UNAVAILBALE && != AST_DEVICE_INVALID
26656 
26657    When placing a call to the queue member, queue system sets a member to busy if
26658    != AST_DEVICE_NOT_INUSE and != AST_DEVICE_UNKNOWN
26659 
26660 */
26661 static int sip_devicestate(void *data)
26662 {
26663    char *host;
26664    char *tmp;
26665    struct sip_peer *p;
26666 
26667    int res = AST_DEVICE_INVALID;
26668 
26669    /* make sure data is not null. Maybe unnecessary, but better be safe */
26670    host = ast_strdupa(data ? data : "");
26671    if ((tmp = strchr(host, '@')))
26672       host = tmp + 1;
26673 
26674    ast_debug(3, "Checking device state for peer %s\n", host);
26675 
26676    /* If find_peer asks for a realtime peer, then this breaks rtautoclear.  This
26677     * is because when a peer tries to autoexpire, the last thing it does is to
26678     * queue up an event telling the system that the devicestate has changed
26679     * (presumably to unavailable).  If we ask for a realtime peer here, this would
26680     * load it BACK into memory, thus defeating the point of trying to clear dead
26681     * hosts out of memory.
26682     */
26683    if ((p = find_peer(host, NULL, FALSE, FINDALLDEVICES, TRUE, 0))) {
26684       if (!(ast_sockaddr_isnull(&p->addr) && ast_sockaddr_isnull(&p->defaddr))) {
26685          /* we have an address for the peer */
26686       
26687          /* Check status in this order
26688             - Hold
26689             - Ringing
26690             - Busy (enforced only by call limit)
26691             - Inuse (we have a call)
26692             - Unreachable (qualify)
26693             If we don't find any of these state, report AST_DEVICE_NOT_INUSE
26694             for registered devices */
26695 
26696          if (p->onHold)
26697             /* First check for hold or ring states */
26698             res = AST_DEVICE_ONHOLD;
26699          else if (p->inRinging) {
26700             if (p->inRinging == p->inUse)
26701                res = AST_DEVICE_RINGING;
26702             else
26703                res = AST_DEVICE_RINGINUSE;
26704          } else if (p->call_limit && (p->inUse == p->call_limit))
26705             /* check call limit */
26706             res = AST_DEVICE_BUSY;
26707          else if (p->call_limit && p->busy_level && p->inUse >= p->busy_level)
26708             /* We're forcing busy before we've reached the call limit */
26709             res = AST_DEVICE_BUSY;
26710          else if (p->call_limit && p->inUse)
26711             /* Not busy, but we do have a call */
26712             res = AST_DEVICE_INUSE;
26713          else if (p->maxms && ((p->lastms > p->maxms) || (p->lastms < 0)))
26714             /* We don't have a call. Are we reachable at all? Requires qualify= */
26715             res = AST_DEVICE_UNAVAILABLE;
26716          else  /* Default reply if we're registered and have no other data */
26717             res = AST_DEVICE_NOT_INUSE;
26718       } else {
26719          /* there is no address, it's unavailable */
26720          res = AST_DEVICE_UNAVAILABLE;
26721       }
26722       unref_peer(p, "unref_peer, from sip_devicestate, release ref from find_peer");
26723    }
26724 
26725    return res;
26726 }
26727 
26728 /*! \brief PBX interface function -build SIP pvt structure
26729  * SIP calls initiated by the PBX arrive here.
26730  *
26731  * \verbatim   
26732  *    SIP Dial string syntax
26733  *    SIP/exten@host!dnid
26734  * or SIP/host/exten!dnid
26735  * or SIP/host!dnid
26736  * \endverbatim
26737 */
26738 static struct ast_channel *sip_request_call(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause)
26739 {
26740    struct sip_pvt *p;
26741    struct ast_channel *tmpc = NULL;
26742    char *ext = NULL, *host;
26743    char tmp[256];
26744    char *dest = data;
26745    char *dnid;
26746    char *secret = NULL;
26747    char *md5secret = NULL;
26748    char *authname = NULL;
26749    char *trans = NULL;
26750    char dialstring[256];
26751    char *remote_address;
26752    enum sip_transport transport = 0;
26753    format_t oldformat = format;
26754    AST_DECLARE_APP_ARGS(args,
26755       AST_APP_ARG(peerorhost);
26756       AST_APP_ARG(exten);
26757       AST_APP_ARG(remote_address);
26758    );
26759 
26760    /* mask request with some set of allowed formats.
26761     * XXX this needs to be fixed.
26762     * The original code uses AST_FORMAT_AUDIO_MASK, but it is
26763     * unclear what to use here. We have global_capabilities, which is
26764     * configured from sip.conf, and sip_tech.capabilities, which is
26765     * hardwired to all audio formats.
26766     */
26767    format &= AST_FORMAT_AUDIO_MASK;
26768    if (!format) {
26769       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));
26770       *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;   /* Can't find codec to connect to host */
26771       return NULL;
26772    }
26773    ast_debug(1, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), oldformat));
26774 
26775    if (ast_strlen_zero(dest)) {
26776       ast_log(LOG_ERROR, "Unable to create channel with empty destination.\n");
26777       *cause = AST_CAUSE_CHANNEL_UNACCEPTABLE;
26778       return NULL;
26779    }
26780 
26781    if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE, NULL))) {
26782       ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", dest);
26783       *cause = AST_CAUSE_SWITCH_CONGESTION;
26784       return NULL;
26785    }
26786 
26787    p->outgoing_call = TRUE;
26788 
26789    snprintf(dialstring, sizeof(dialstring), "%s/%s", type, dest);
26790    ast_string_field_set(p, dialstring, dialstring);
26791 
26792    if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
26793       dialog_unlink_all(p);
26794       dialog_unref(p, "unref dialog p from mem fail");
26795       /* sip_destroy(p); */
26796       ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
26797       *cause = AST_CAUSE_SWITCH_CONGESTION;
26798       return NULL;
26799    }
26800 
26801    /* Save the destination, the SIP dial string */
26802    ast_copy_string(tmp, dest, sizeof(tmp));
26803 
26804    /* Find DNID and take it away */
26805    dnid = strchr(tmp, '!');
26806    if (dnid != NULL) {
26807       *dnid++ = '\0';
26808       ast_string_field_set(p, todnid, dnid);
26809    }
26810 
26811    /* Divvy up the items separated by slashes */
26812    AST_NONSTANDARD_APP_ARGS(args, tmp, '/');
26813 
26814    /* Find at sign - @ */
26815    host = strchr(args.peerorhost, '@');
26816    if (host) {
26817       *host++ = '\0';
26818       ext = args.peerorhost;
26819       secret = strchr(ext, ':');
26820    }
26821    if (secret) {
26822       *secret++ = '\0';
26823       md5secret = strchr(secret, ':');
26824    }
26825    if (md5secret) {
26826       *md5secret++ = '\0';
26827       authname = strchr(md5secret, ':');
26828    }
26829    if (authname) {
26830       *authname++ = '\0';
26831       trans = strchr(authname, ':');
26832    }
26833    if (trans) {
26834       *trans++ = '\0';
26835       if (!strcasecmp(trans, "tcp"))
26836          transport = SIP_TRANSPORT_TCP;
26837       else if (!strcasecmp(trans, "tls"))
26838          transport = SIP_TRANSPORT_TLS;
26839       else {
26840          if (strcasecmp(trans, "udp"))
26841             ast_log(LOG_WARNING, "'%s' is not a valid transport option to Dial() for SIP calls, using udp by default.\n", trans);
26842          transport = SIP_TRANSPORT_UDP;
26843       }
26844    } else { /* use default */
26845       transport = SIP_TRANSPORT_UDP;
26846    }
26847 
26848    if (!host) {
26849       ext = args.exten;
26850       host = args.peerorhost;
26851       remote_address = args.remote_address;
26852    } else {
26853       remote_address = args.remote_address;
26854       if (!ast_strlen_zero(args.exten)) {
26855          ast_log(LOG_NOTICE, "Conflicting extension values given. Using '%s' and not '%s'\n", ext, args.exten);
26856       }
26857    }
26858 
26859    if (!ast_strlen_zero(remote_address)) {
26860       p->options->outboundproxy = proxy_from_config(remote_address, 0, NULL);
26861       if (!p->options->outboundproxy) {
26862          ast_log(LOG_WARNING, "Unable to parse outboundproxy %s. We will not use this remote IP address\n", remote_address);
26863       }
26864    }
26865 
26866    set_socket_transport(&p->socket, transport);
26867 
26868    /* We now have
26869       host = peer name, DNS host name or DNS domain (for SRV)
26870       ext = extension (user part of URI)
26871       dnid = destination of the call (applies to the To: header)
26872    */
26873    if (create_addr(p, host, NULL, 1)) {
26874       *cause = AST_CAUSE_UNREGISTERED;
26875       ast_debug(3, "Cant create SIP call - target device not registered\n");
26876       dialog_unlink_all(p);
26877       dialog_unref(p, "unref dialog p UNREGISTERED");
26878       /* sip_destroy(p); */
26879       return NULL;
26880    }
26881    if (ast_strlen_zero(p->peername) && ext)
26882       ast_string_field_set(p, peername, ext);
26883    /* Recalculate our side, and recalculate Call ID */
26884    ast_sip_ouraddrfor(&p->sa, &p->ourip, p);
26885    build_via(p);
26886 
26887    /* Change the dialog callid. */
26888    change_callid_pvt(p, NULL);
26889 
26890    /* We have an extension to call, don't use the full contact here */
26891    /* This to enable dialing registered peers with extension dialling,
26892       like SIP/peername/extension   
26893       SIP/peername will still use the full contact
26894     */
26895    if (ext) {
26896       ast_string_field_set(p, username, ext);
26897       ast_string_field_set(p, fullcontact, NULL);
26898    }
26899    if (secret && !ast_strlen_zero(secret))
26900       ast_string_field_set(p, peersecret, secret);
26901 
26902    if (md5secret && !ast_strlen_zero(md5secret))
26903       ast_string_field_set(p, peermd5secret, md5secret);
26904 
26905    if (authname && !ast_strlen_zero(authname))
26906       ast_string_field_set(p, authname, authname);
26907 #if 0
26908    printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
26909 #endif
26910    p->prefcodec = oldformat;           /* Format for this call */
26911    p->jointcapability = oldformat & p->capability;
26912    sip_pvt_lock(p);
26913    tmpc = sip_new(p, AST_STATE_DOWN, host, requestor ? requestor->linkedid : NULL); /* Place the call */
26914    if (sip_cfg.callevents)
26915       manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
26916          "Channel: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
26917          p->owner? p->owner->name : "", "SIP", p->callid, p->fullcontact, p->peername);
26918    sip_pvt_unlock(p);
26919    if (!tmpc) {
26920       dialog_unlink_all(p);
26921       /* sip_destroy(p); */
26922    } else {
26923       ast_channel_unlock(tmpc);
26924    }
26925    dialog_unref(p, "toss pvt ptr at end of sip_request_call");
26926    ast_update_use_count();
26927    restart_monitor();
26928    return tmpc;
26929 }
26930 
26931 /*! \brief Parse insecure= setting in sip.conf and set flags according to setting */
26932 static void set_insecure_flags (struct ast_flags *flags, const char *value, int lineno)
26933 {
26934    if (ast_strlen_zero(value))
26935       return;
26936 
26937    if (!ast_false(value)) {
26938       char buf[64];
26939       char *word, *next;
26940 
26941       ast_copy_string(buf, value, sizeof(buf));
26942       next = buf;
26943       while ((word = strsep(&next, ","))) {
26944          if (!strcasecmp(word, "port"))
26945             ast_set_flag(&flags[0], SIP_INSECURE_PORT);
26946          else if (!strcasecmp(word, "invite"))
26947             ast_set_flag(&flags[0], SIP_INSECURE_INVITE);
26948          else
26949             ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", value, lineno);
26950       }
26951    }
26952 }
26953 
26954 /*!
26955   \brief Handle T.38 configuration options common to users and peers
26956   \returns non-zero if any config options were handled, zero otherwise
26957 */
26958 static int handle_t38_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v,
26959                int *maxdatagram)
26960 {
26961    int res = 1;
26962 
26963    if (!strcasecmp(v->name, "t38pt_udptl")) {
26964       char *buf = ast_strdupa(v->value);
26965       char *word, *next = buf;
26966 
26967       ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT);
26968 
26969       while ((word = strsep(&next, ","))) {
26970          if (ast_true(word) || !strcasecmp(word, "fec")) {
26971             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
26972             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_FEC);
26973          } else if (!strcasecmp(word, "redundancy")) {
26974             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
26975             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY);
26976          } else if (!strcasecmp(word, "none")) {
26977             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
26978             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL);
26979          } else if (!strncasecmp(word, "maxdatagram=", 12)) {
26980             if (sscanf(&word[12], "%30u", maxdatagram) != 1) {
26981                ast_log(LOG_WARNING, "Invalid maxdatagram '%s' at line %d of %s\n", v->value, v->lineno, config);
26982                *maxdatagram = global_t38_maxdatagram;
26983             }
26984          }
26985       }
26986    } else if (!strcasecmp(v->name, "t38pt_usertpsource")) {
26987       ast_set_flag(&mask[1], SIP_PAGE2_UDPTL_DESTINATION);
26988       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_UDPTL_DESTINATION);
26989    } else {
26990       res = 0;
26991    }
26992 
26993    return res;
26994 }
26995 
26996 /*!
26997   \brief Handle flag-type options common to configuration of devices - peers
26998   \param flags array of two struct ast_flags
26999   \param mask array of two struct ast_flags
27000   \param v linked list of config variables to process
27001   \returns non-zero if any config options were handled, zero otherwise
27002 */
27003 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
27004 {
27005    int res = 1;
27006 
27007    if (!strcasecmp(v->name, "trustrpid")) {
27008       ast_set_flag(&mask[0], SIP_TRUSTRPID);
27009       ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
27010    } else if (!strcasecmp(v->name, "sendrpid")) {
27011       ast_set_flag(&mask[0], SIP_SENDRPID);
27012       if (!strcasecmp(v->value, "pai")) {
27013          ast_set_flag(&flags[0], SIP_SENDRPID_PAI);
27014       } else if (!strcasecmp(v->value, "rpid")) {
27015          ast_set_flag(&flags[0], SIP_SENDRPID_RPID);
27016       } else if (ast_true(v->value)) {
27017          ast_set_flag(&flags[0], SIP_SENDRPID_RPID);
27018       }
27019    } else if (!strcasecmp(v->name, "rpid_update")) {
27020       ast_set_flag(&mask[1], SIP_PAGE2_RPID_UPDATE);
27021       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RPID_UPDATE);
27022    } else if (!strcasecmp(v->name, "rpid_immediate")) {
27023       ast_set_flag(&mask[1], SIP_PAGE2_RPID_IMMEDIATE);
27024       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RPID_IMMEDIATE);
27025    } else if (!strcasecmp(v->name, "g726nonstandard")) {
27026       ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
27027       ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
27028    } else if (!strcasecmp(v->name, "useclientcode")) {
27029       ast_set_flag(&mask[0], SIP_USECLIENTCODE);
27030       ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
27031    } else if (!strcasecmp(v->name, "dtmfmode")) {
27032       ast_set_flag(&mask[0], SIP_DTMF);
27033       ast_clear_flag(&flags[0], SIP_DTMF);
27034       if (!strcasecmp(v->value, "inband"))
27035          ast_set_flag(&flags[0], SIP_DTMF_INBAND);
27036       else if (!strcasecmp(v->value, "rfc2833"))
27037          ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
27038       else if (!strcasecmp(v->value, "info"))
27039          ast_set_flag(&flags[0], SIP_DTMF_INFO);
27040       else if (!strcasecmp(v->value, "shortinfo"))
27041          ast_set_flag(&flags[0], SIP_DTMF_SHORTINFO);
27042       else if (!strcasecmp(v->value, "auto"))
27043          ast_set_flag(&flags[0], SIP_DTMF_AUTO);
27044       else {
27045          ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
27046          ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
27047       }
27048    } else if (!strcasecmp(v->name, "nat")) {
27049       ast_set_flag(&mask[0], SIP_NAT_FORCE_RPORT);
27050       ast_set_flag(&flags[0], SIP_NAT_FORCE_RPORT); /* Default to "force_rport" */
27051       if (!strcasecmp(v->value, "no")) {
27052          ast_clear_flag(&flags[0], SIP_NAT_FORCE_RPORT);
27053       } else if (!strcasecmp(v->value, "yes")) {
27054          /* We've already defaulted to force_rport */
27055          ast_set_flag(&mask[1], SIP_PAGE2_SYMMETRICRTP);
27056          ast_set_flag(&flags[1], SIP_PAGE2_SYMMETRICRTP);
27057       } else if (!strcasecmp(v->value, "comedia")) {
27058          ast_clear_flag(&flags[0], SIP_NAT_FORCE_RPORT);
27059          ast_set_flag(&mask[1], SIP_PAGE2_SYMMETRICRTP);
27060          ast_set_flag(&flags[1], SIP_PAGE2_SYMMETRICRTP);
27061       }
27062    } else if (!strcasecmp(v->name, "directmedia") || !strcasecmp(v->name, "canreinvite")) {
27063       ast_set_flag(&mask[0], SIP_REINVITE);
27064       ast_clear_flag(&flags[0], SIP_REINVITE);
27065       if (ast_true(v->value)) {
27066          ast_set_flag(&flags[0], SIP_DIRECT_MEDIA | SIP_DIRECT_MEDIA_NAT);
27067       } else if (!ast_false(v->value)) {
27068          char buf[64];
27069          char *word, *next = buf;
27070 
27071          ast_copy_string(buf, v->value, sizeof(buf));
27072          while ((word = strsep(&next, ","))) {
27073             if (!strcasecmp(word, "update")) {
27074                ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_DIRECT_MEDIA);
27075             } else if (!strcasecmp(word, "nonat")) {
27076                ast_set_flag(&flags[0], SIP_DIRECT_MEDIA);
27077                ast_clear_flag(&flags[0], SIP_DIRECT_MEDIA_NAT);
27078             } else if (!strcasecmp(word, "outgoing")) {
27079                ast_set_flag(&flags[0], SIP_DIRECT_MEDIA);
27080                ast_set_flag(&mask[2], SIP_PAGE3_DIRECT_MEDIA_OUTGOING);
27081                ast_set_flag(&flags[2], SIP_PAGE3_DIRECT_MEDIA_OUTGOING);
27082             } else {
27083                ast_log(LOG_WARNING, "Unknown directmedia mode '%s' on line %d\n", v->value, v->lineno);
27084             }
27085          }
27086       }
27087    } else if (!strcasecmp(v->name, "insecure")) {
27088       ast_set_flag(&mask[0], SIP_INSECURE);
27089       ast_clear_flag(&flags[0], SIP_INSECURE);
27090       set_insecure_flags(&flags[0], v->value, v->lineno);   
27091    } else if (!strcasecmp(v->name, "progressinband")) {
27092       ast_set_flag(&mask[0], SIP_PROG_INBAND);
27093       ast_clear_flag(&flags[0], SIP_PROG_INBAND);
27094       if (ast_true(v->value))
27095          ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
27096       else if (strcasecmp(v->value, "never"))
27097          ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
27098    } else if (!strcasecmp(v->name, "promiscredir")) {
27099       ast_set_flag(&mask[0], SIP_PROMISCREDIR);
27100       ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
27101    } else if (!strcasecmp(v->name, "videosupport")) {
27102       if (!strcasecmp(v->value, "always")) {
27103          ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
27104          ast_set_flag(&flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
27105       } else {
27106          ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
27107          ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
27108       }
27109    } else if (!strcasecmp(v->name, "textsupport")) {
27110       ast_set_flag(&mask[1], SIP_PAGE2_TEXTSUPPORT);
27111       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_TEXTSUPPORT);
27112       res = 1;
27113    } else if (!strcasecmp(v->name, "allowoverlap")) {
27114       ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
27115       ast_clear_flag(&flags[1], SIP_PAGE2_ALLOWOVERLAP);
27116       if (ast_true(v->value)) {
27117          ast_set_flag(&flags[1], SIP_PAGE2_ALLOWOVERLAP_YES);
27118       } else if (!strcasecmp(v->value, "dtmf")){
27119          ast_set_flag(&flags[1], SIP_PAGE2_ALLOWOVERLAP_DTMF);
27120       }
27121    } else if (!strcasecmp(v->name, "allowsubscribe")) {
27122       ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
27123       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
27124    } else if (!strcasecmp(v->name, "ignoresdpversion")) {
27125       ast_set_flag(&mask[1], SIP_PAGE2_IGNORESDPVERSION);
27126       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_IGNORESDPVERSION);
27127    } else if (!strcasecmp(v->name, "faxdetect")) {
27128       ast_set_flag(&mask[1], SIP_PAGE2_FAX_DETECT);
27129       if (ast_true(v->value)) {
27130          ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
27131       } else if (ast_false(v->value)) {
27132          ast_clear_flag(&flags[1], SIP_PAGE2_FAX_DETECT_BOTH);
27133       } else {
27134          char *buf = ast_strdupa(v->value);
27135          char *word, *next = buf;
27136 
27137          while ((word = strsep(&next, ","))) {
27138             if (!strcasecmp(word, "cng")) {
27139                ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_CNG);
27140             } else if (!strcasecmp(word, "t38")) {
27141                ast_set_flag(&flags[1], SIP_PAGE2_FAX_DETECT_T38);
27142             } else {
27143                ast_log(LOG_WARNING, "Unknown faxdetect mode '%s' on line %d.\n", word, v->lineno);
27144             }
27145          }
27146       }
27147    } else if (!strcasecmp(v->name, "rfc2833compensate")) {
27148       ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
27149       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
27150    } else if (!strcasecmp(v->name, "buggymwi")) {
27151       ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
27152       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
27153    } else
27154       res = 0;
27155 
27156    return res;
27157 }
27158 
27159 /*! \brief Add SIP domain to list of domains we are responsible for */
27160 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
27161 {
27162    struct domain *d;
27163 
27164    if (ast_strlen_zero(domain)) {
27165       ast_log(LOG_WARNING, "Zero length domain.\n");
27166       return 1;
27167    }
27168 
27169    if (!(d = ast_calloc(1, sizeof(*d))))
27170       return 0;
27171 
27172    ast_copy_string(d->domain, domain, sizeof(d->domain));
27173 
27174    if (!ast_strlen_zero(context))
27175       ast_copy_string(d->context, context, sizeof(d->context));
27176 
27177    d->mode = mode;
27178 
27179    AST_LIST_LOCK(&domain_list);
27180    AST_LIST_INSERT_TAIL(&domain_list, d, list);
27181    AST_LIST_UNLOCK(&domain_list);
27182 
27183    if (sipdebug)  
27184       ast_debug(1, "Added local SIP domain '%s'\n", domain);
27185 
27186    return 1;
27187 }
27188 
27189 /*! \brief  check_sip_domain: Check if domain part of uri is local to our server */
27190 static int check_sip_domain(const char *domain, char *context, size_t len)
27191 {
27192    struct domain *d;
27193    int result = 0;
27194 
27195    AST_LIST_LOCK(&domain_list);
27196    AST_LIST_TRAVERSE(&domain_list, d, list) {
27197       if (strcasecmp(d->domain, domain)) {
27198          continue;
27199       }
27200 
27201       if (len && !ast_strlen_zero(d->context))
27202          ast_copy_string(context, d->context, len);
27203       
27204       result = 1;
27205       break;
27206    }
27207    AST_LIST_UNLOCK(&domain_list);
27208 
27209    return result;
27210 }
27211 
27212 /*! \brief Clear our domain list (at reload) */
27213 static void clear_sip_domains(void)
27214 {
27215    struct domain *d;
27216 
27217    AST_LIST_LOCK(&domain_list);
27218    while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
27219       ast_free(d);
27220    AST_LIST_UNLOCK(&domain_list);
27221 }
27222 
27223 /*!
27224  * \internal
27225  * \brief Realm authentication container destructor.
27226  *
27227  * \param obj Container object to destroy.
27228  *
27229  * \return Nothing
27230  */
27231 static void destroy_realm_authentication(void *obj)
27232 {
27233    struct sip_auth_container *credentials = obj;
27234    struct sip_auth *auth;
27235 
27236    while ((auth = AST_LIST_REMOVE_HEAD(&credentials->list, node))) {
27237       ast_free(auth);
27238    }
27239 }
27240 
27241 /*!
27242  * \internal
27243  * \brief Add realm authentication to credentials.
27244  *
27245  * \param credentials Realm authentication container to create/add authentication credentials.
27246  * \param configuration Credential configuration value.
27247  * \param lineno Line number in config file.
27248  *
27249  * \return Nothing
27250  */
27251 static void add_realm_authentication(struct sip_auth_container **credentials, const char *configuration, int lineno)
27252 {
27253    char *authcopy;
27254    char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
27255    struct sip_auth *auth;
27256 
27257    if (ast_strlen_zero(configuration)) {
27258       /* Nothing to add */
27259       return;
27260    }
27261 
27262    ast_debug(1, "Auth config ::  %s\n", configuration);
27263 
27264    authcopy = ast_strdupa(configuration);
27265    username = authcopy;
27266 
27267    /* split user[:secret] and relm */
27268    realm = strrchr(username, '@');
27269    if (realm)
27270       *realm++ = '\0';
27271    if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
27272       ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
27273       return;
27274    }
27275 
27276    /* parse username at ':' for secret, or '#" for md5secret */
27277    if ((secret = strchr(username, ':'))) {
27278       *secret++ = '\0';
27279    } else if ((md5secret = strchr(username, '#'))) {
27280       *md5secret++ = '\0';
27281    }
27282 
27283    /* Create the continer if needed. */
27284    if (!*credentials) {
27285       *credentials = ao2_t_alloc(sizeof(**credentials), destroy_realm_authentication,
27286          "Create realm auth container.");
27287       if (!*credentials) {
27288          /* Failed to create the credentials container. */
27289          return;
27290       }
27291    }
27292 
27293    /* Create the authentication credential entry. */
27294    auth = ast_calloc(1, sizeof(*auth));
27295    if (!auth) {
27296       return;
27297    }
27298    ast_copy_string(auth->realm, realm, sizeof(auth->realm));
27299    ast_copy_string(auth->username, username, sizeof(auth->username));
27300    if (secret)
27301       ast_copy_string(auth->secret, secret, sizeof(auth->secret));
27302    if (md5secret)
27303       ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
27304 
27305    /* Add credential to container list. */
27306    AST_LIST_INSERT_TAIL(&(*credentials)->list, auth, node);
27307 
27308    ast_verb(3, "Added authentication for realm %s\n", realm);
27309 }
27310 
27311 /*!
27312  * \internal
27313  * \brief Find authentication for a specific realm.
27314  *
27315  * \param credentials Realm authentication container to search.
27316  * \param realm Authentication realm to find.
27317  *
27318  * \return Found authentication credential or NULL.
27319  */
27320 static struct sip_auth *find_realm_authentication(struct sip_auth_container *credentials, const char *realm)
27321 {
27322    struct sip_auth *auth;
27323 
27324    if (credentials) {
27325       AST_LIST_TRAVERSE(&credentials->list, auth, node) {
27326          if (!strcasecmp(auth->realm, realm)) {
27327             break;
27328          }
27329       }
27330    } else {
27331       auth = NULL;
27332    }
27333 
27334    return auth;
27335 }
27336 
27337 /*! \brief
27338  * implement the setvar config line
27339  */
27340 static struct ast_variable *add_var(const char *buf, struct ast_variable *list)
27341 {
27342    struct ast_variable *tmpvar = NULL;
27343    char *varname = ast_strdupa(buf), *varval = NULL;
27344    
27345    if ((varval = strchr(varname, '='))) {
27346       *varval++ = '\0';
27347       if ((tmpvar = ast_variable_new(varname, varval, ""))) {
27348          tmpvar->next = list;
27349          list = tmpvar;
27350       }
27351    }
27352    return list;
27353 }
27354 
27355 /*! \brief Set peer defaults before configuring specific configurations */
27356 static void set_peer_defaults(struct sip_peer *peer)
27357 {
27358    if (peer->expire == 0) {
27359       /* Don't reset expire or port time during reload
27360          if we have an active registration
27361       */
27362       peer->expire = -1;
27363       peer->pokeexpire = -1;
27364       set_socket_transport(&peer->socket, SIP_TRANSPORT_UDP);
27365    }
27366    peer->type = SIP_TYPE_PEER;
27367    ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
27368    ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
27369    ast_copy_flags(&peer->flags[2], &global_flags[2], SIP_PAGE3_FLAGS_TO_COPY);
27370    ast_string_field_set(peer, context, sip_cfg.default_context);
27371    ast_string_field_set(peer, subscribecontext, sip_cfg.default_subscribecontext);
27372    ast_string_field_set(peer, language, default_language);
27373    ast_string_field_set(peer, mohinterpret, default_mohinterpret);
27374    ast_string_field_set(peer, mohsuggest, default_mohsuggest);
27375    ast_string_field_set(peer, engine, default_engine);
27376    ast_sockaddr_setnull(&peer->addr);
27377    ast_sockaddr_setnull(&peer->defaddr);
27378    peer->capability = sip_cfg.capability;
27379    peer->maxcallbitrate = default_maxcallbitrate;
27380    peer->rtptimeout = global_rtptimeout;
27381    peer->rtpholdtimeout = global_rtpholdtimeout;
27382    peer->rtpkeepalive = global_rtpkeepalive;
27383    peer->allowtransfer = sip_cfg.allowtransfer;
27384    peer->autoframing = global_autoframing;
27385    peer->t38_maxdatagram = global_t38_maxdatagram;
27386    peer->qualifyfreq = global_qualifyfreq;
27387    if (global_callcounter)
27388       peer->call_limit=INT_MAX;
27389    ast_string_field_set(peer, vmexten, default_vmexten);
27390    ast_string_field_set(peer, secret, "");
27391    ast_string_field_set(peer, remotesecret, "");
27392    ast_string_field_set(peer, md5secret, "");
27393    ast_string_field_set(peer, cid_num, "");
27394    ast_string_field_set(peer, cid_name, "");
27395    ast_string_field_set(peer, cid_tag, "");
27396    ast_string_field_set(peer, fromdomain, "");
27397    ast_string_field_set(peer, fromuser, "");
27398    ast_string_field_set(peer, regexten, "");
27399    peer->callgroup = 0;
27400    peer->pickupgroup = 0;
27401    peer->maxms = default_qualify;
27402    peer->prefs = default_prefs;
27403    peer->stimer.st_mode_oper = global_st_mode;  /* Session-Timers */
27404    peer->stimer.st_ref = global_st_refresher;
27405    peer->stimer.st_min_se = global_min_se;
27406    peer->stimer.st_max_se = global_max_se;
27407    peer->timer_t1 = global_t1;
27408    peer->timer_b = global_timer_b;
27409    clear_peer_mailboxes(peer);
27410    peer->disallowed_methods = sip_cfg.disallowed_methods;
27411    peer->transports = default_transports;
27412    peer->default_outbound_transport = default_primary_transport;
27413 }
27414 
27415 /*! \brief Create temporary peer (used in autocreatepeer mode) */
27416 static struct sip_peer *temp_peer(const char *name)
27417 {
27418    struct sip_peer *peer;
27419 
27420    if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
27421       return NULL;
27422 
27423    if (ast_string_field_init(peer, 512)) {
27424       ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
27425       return NULL;
27426    }
27427    
27428    if (!(peer->cc_params = ast_cc_config_params_init())) {
27429       ao2_t_ref(peer, -1, "failed to allocate cc_params for peer");
27430       return NULL;
27431    }
27432 
27433    ast_atomic_fetchadd_int(&apeerobjs, 1);
27434    set_peer_defaults(peer);
27435 
27436    ast_copy_string(peer->name, name, sizeof(peer->name));
27437 
27438    peer->selfdestruct = TRUE;
27439    peer->host_dynamic = TRUE;
27440    peer->prefs = default_prefs;
27441    reg_source_db(peer);
27442 
27443    return peer;
27444 }
27445 
27446 /*! \todo document this function */
27447 static void add_peer_mailboxes(struct sip_peer *peer, const char *value)
27448 {
27449    char *next, *mbox, *context;
27450 
27451    next = ast_strdupa(value);
27452 
27453    while ((mbox = context = strsep(&next, ","))) {
27454       struct sip_mailbox *mailbox;
27455       int duplicate = 0;
27456       /* remove leading/trailing whitespace from mailbox string */
27457       mbox = ast_strip(mbox);
27458       strsep(&context, "@");
27459 
27460       if (ast_strlen_zero(mbox)) {
27461          continue;
27462       }
27463 
27464       /* Check whether the mailbox is already in the list */
27465       AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
27466          if (!strcmp(mailbox->mailbox, mbox) && !strcmp(S_OR(mailbox->context, ""), S_OR(context, ""))) {
27467             duplicate = 1;
27468             break;
27469          }
27470       }
27471       if (duplicate) {
27472          continue;
27473       }
27474 
27475       if (!(mailbox = ast_calloc(1, sizeof(*mailbox) + strlen(mbox) + strlen(S_OR(context, ""))))) {
27476          continue;
27477       }
27478 
27479       if (!ast_strlen_zero(context)) {
27480          mailbox->context = mailbox->mailbox + strlen(mbox) + 1;
27481          strcpy(mailbox->context, context); /* SAFE */
27482       }
27483       strcpy(mailbox->mailbox, mbox); /* SAFE */
27484 
27485       AST_LIST_INSERT_TAIL(&peer->mailboxes, mailbox, entry);
27486    }
27487 }
27488 
27489 /*! \brief Build peer from configuration (file or realtime static/dynamic) */
27490 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only)
27491 {
27492    struct sip_peer *peer = NULL;
27493    struct ast_ha *oldha = NULL;
27494    struct ast_ha *olddirectmediaha = NULL;
27495    int found = 0;
27496    int firstpass = 1;
27497    uint16_t port = 0;
27498    int format = 0;      /* Ama flags */
27499    int timerb_set = 0, timert1_set = 0;
27500    time_t regseconds = 0;
27501    struct ast_flags peerflags[3] = {{(0)}};
27502    struct ast_flags mask[3] = {{(0)}};
27503    char callback[256] = "";
27504    struct sip_peer tmp_peer;
27505    const char *srvlookup = NULL;
27506    static int deprecation_warning = 1;
27507    int alt_fullcontact = alt ? 1 : 0, headercount = 0;
27508    struct ast_str *fullcontact = ast_str_alloca(512);
27509 
27510    if (!realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
27511       /* Note we do NOT use find_peer here, to avoid realtime recursion */
27512       /* We also use a case-sensitive comparison (unlike find_peer) so
27513          that case changes made to the peer name will be properly handled
27514          during reload
27515       */
27516       ast_copy_string(tmp_peer.name, name, sizeof(tmp_peer.name));
27517       peer = ao2_t_find(peers, &tmp_peer, OBJ_POINTER | OBJ_UNLINK, "find and unlink peer from peers table");
27518    }
27519 
27520    if (peer) {
27521       /* Already in the list, remove it and it will be added back (or FREE'd)  */
27522       found++;
27523       /* we've unlinked the peer from the peers container but not unlinked from the peers_by_ip container yet
27524         this leads to a wrong refcounter and the peer object is never destroyed */
27525       if (!ast_sockaddr_isnull(&peer->addr)) {
27526          ao2_t_unlink(peers_by_ip, peer, "ao2_unlink peer from peers_by_ip table");
27527       }
27528       if (!(peer->the_mark))
27529          firstpass = 0;
27530    } else {
27531       if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
27532          return NULL;
27533 
27534       if (ast_string_field_init(peer, 512)) {
27535          ao2_t_ref(peer, -1, "failed to string_field_init, drop peer");
27536          return NULL;
27537       }
27538 
27539       if (!(peer->cc_params = ast_cc_config_params_init())) {
27540          ao2_t_ref(peer, -1, "failed to allocate cc_params for peer");
27541          return NULL;
27542       }
27543 
27544       if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
27545          ast_atomic_fetchadd_int(&rpeerobjs, 1);
27546          ast_debug(3, "-REALTIME- peer built. Name: %s. Peer objects: %d\n", name, rpeerobjs);
27547       } else
27548          ast_atomic_fetchadd_int(&speerobjs, 1);
27549    }
27550 
27551    /* Note that our peer HAS had its reference count increased */
27552    if (firstpass) {
27553       peer->lastmsgssent = -1;
27554       oldha = peer->ha;
27555       peer->ha = NULL;
27556       olddirectmediaha = peer->directmediaha;
27557       peer->directmediaha = NULL;
27558       set_peer_defaults(peer);   /* Set peer defaults */
27559       peer->type = 0;
27560    }
27561 
27562    /* in case the case of the peer name has changed, update the name */
27563    ast_copy_string(peer->name, name, sizeof(peer->name));
27564 
27565    /* If we have channel variables, remove them (reload) */
27566    if (peer->chanvars) {
27567       ast_variables_destroy(peer->chanvars);
27568       peer->chanvars = NULL;
27569       /* XXX should unregister ? */
27570    }
27571 
27572    if (found)
27573       peer->portinuri = 0;
27574 
27575    /* If we have realm authentication information, remove them (reload) */
27576    ao2_lock(peer);
27577    if (peer->auth) {
27578       ao2_t_ref(peer->auth, -1, "Removing old peer authentication");
27579       peer->auth = NULL;
27580    }
27581    ao2_unlock(peer);
27582 
27583    /* clear the transport information.  We will detect if a default value is required after parsing the config */
27584    peer->default_outbound_transport = 0;
27585    peer->transports = 0;
27586 
27587    if (!devstate_only) {
27588       struct sip_mailbox *mailbox;
27589       AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
27590          mailbox->delme = 1;
27591       }
27592    }
27593 
27594    for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
27595       if (!devstate_only) {
27596          if (handle_common_options(&peerflags[0], &mask[0], v)) {
27597             continue;
27598          }
27599          if (handle_t38_options(&peerflags[0], &mask[0], v, &peer->t38_maxdatagram)) {
27600             continue;
27601          }
27602          if (!strcasecmp(v->name, "transport")) {
27603             char *val = ast_strdupa(v->value);
27604             char *trans;
27605 
27606             peer->transports = peer->default_outbound_transport = 0;
27607             while ((trans = strsep(&val, ","))) {
27608                trans = ast_skip_blanks(trans);
27609 
27610                if (!strncasecmp(trans, "udp", 3)) {
27611                   peer->transports |= SIP_TRANSPORT_UDP;
27612                } else if (sip_cfg.tcp_enabled && !strncasecmp(trans, "tcp", 3)) {
27613                   peer->transports |= SIP_TRANSPORT_TCP;
27614                } else if (default_tls_cfg.enabled && !strncasecmp(trans, "tls", 3)) {
27615                   peer->transports |= SIP_TRANSPORT_TLS;
27616                } else if (!strncasecmp(trans, "tcp", 3) || !strncasecmp(trans, "tls", 3)) {
27617                   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);
27618                } else {
27619                   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);
27620                }
27621 
27622                if (!peer->default_outbound_transport) { /*!< The first transport listed should be default outbound */
27623                   peer->default_outbound_transport = peer->transports;
27624                }
27625             }
27626          } else if (realtime && !strcasecmp(v->name, "regseconds")) {
27627             ast_get_time_t(v->value, &regseconds, 0, NULL);
27628          } else if (realtime && !strcasecmp(v->name, "name")) {
27629             ast_copy_string(peer->name, v->value, sizeof(peer->name));
27630          } else if (realtime && !strcasecmp(v->name, "useragent")) {
27631             ast_string_field_set(peer, useragent, v->value);
27632          } else if (!strcasecmp(v->name, "type")) {
27633             if (!strcasecmp(v->value, "peer")) {
27634                peer->type |= SIP_TYPE_PEER;
27635             } else if (!strcasecmp(v->value, "user")) {
27636                peer->type |= SIP_TYPE_USER;
27637             } else if (!strcasecmp(v->value, "friend")) {
27638                peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
27639             }
27640          } else if (!strcasecmp(v->name, "remotesecret")) {
27641             ast_string_field_set(peer, remotesecret, v->value);
27642          } else if (!strcasecmp(v->name, "secret")) {
27643             ast_string_field_set(peer, secret, v->value);
27644          } else if (!strcasecmp(v->name, "md5secret")) {
27645             ast_string_field_set(peer, md5secret, v->value);
27646          } else if (!strcasecmp(v->name, "auth")) {
27647             add_realm_authentication(&peer->auth, v->value, v->lineno);
27648          } else if (!strcasecmp(v->name, "callerid")) {
27649             char cid_name[80] = { '\0' }, cid_num[80] = { '\0' };
27650 
27651             ast_callerid_split(v->value, cid_name, sizeof(cid_name), cid_num, sizeof(cid_num));
27652             ast_string_field_set(peer, cid_name, cid_name);
27653             ast_string_field_set(peer, cid_num, cid_num);
27654          } else if (!strcasecmp(v->name, "mwi_from")) {
27655             ast_string_field_set(peer, mwi_from, v->value);
27656          } else if (!strcasecmp(v->name, "fullname")) {
27657             ast_string_field_set(peer, cid_name, v->value);
27658          } else if (!strcasecmp(v->name, "trunkname")) {
27659             /* This is actually for a trunk, so we don't want to override callerid */
27660             ast_string_field_set(peer, cid_name, "");
27661          } else if (!strcasecmp(v->name, "cid_number")) {
27662             ast_string_field_set(peer, cid_num, v->value);
27663          } else if (!strcasecmp(v->name, "cid_tag")) {
27664             ast_string_field_set(peer, cid_tag, v->value);
27665          } else if (!strcasecmp(v->name, "context")) {
27666             ast_string_field_set(peer, context, v->value);
27667             ast_set_flag(&peer->flags[1], SIP_PAGE2_HAVEPEERCONTEXT);
27668          } else if (!strcasecmp(v->name, "subscribecontext")) {
27669             ast_string_field_set(peer, subscribecontext, v->value);
27670          } else if (!strcasecmp(v->name, "fromdomain")) {
27671             char *fromdomainport;
27672             ast_string_field_set(peer, fromdomain, v->value);
27673             if ((fromdomainport = strchr(peer->fromdomain, ':'))) {
27674                *fromdomainport++ = '\0';
27675                if (!(peer->fromdomainport = port_str2int(fromdomainport, 0))) {
27676                   ast_log(LOG_NOTICE, "'%s' is not a valid port number for fromdomain.\n",fromdomainport);
27677                }
27678             } else {
27679                peer->fromdomainport = STANDARD_SIP_PORT;
27680             }
27681          } else if (!strcasecmp(v->name, "usereqphone")) {
27682             ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
27683          } else if (!strcasecmp(v->name, "fromuser")) {
27684             ast_string_field_set(peer, fromuser, v->value);
27685          } else if (!strcasecmp(v->name, "outboundproxy")) {
27686             struct sip_proxy *proxy;
27687             if (ast_strlen_zero(v->value)) {
27688                ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf\n", v->lineno);
27689                continue;
27690             }
27691             proxy = proxy_from_config(v->value, v->lineno, peer->outboundproxy);
27692             if (!proxy) {
27693                ast_log(LOG_WARNING, "failure parsing the outbound proxy on line %d of sip.conf.\n", v->lineno);
27694                continue;
27695             }
27696             peer->outboundproxy = proxy;
27697          } else if (!strcasecmp(v->name, "host")) {
27698             if (!strcasecmp(v->value, "dynamic")) {
27699                /* They'll register with us */
27700                if (!found || !peer->host_dynamic) {
27701                   /* Initialize stuff if this is a new peer, or if it used to
27702                    * not be dynamic before the reload. */
27703                   ast_sockaddr_setnull(&peer->addr);
27704                }
27705                peer->host_dynamic = TRUE;
27706             } else {
27707                /* Non-dynamic.  Make sure we become that way if we're not */
27708                AST_SCHED_DEL_UNREF(sched, peer->expire,
27709                      unref_peer(peer, "removing register expire ref"));
27710                peer->host_dynamic = FALSE;
27711                srvlookup = v->value;
27712             }
27713          } else if (!strcasecmp(v->name, "defaultip")) {
27714             if (!ast_strlen_zero(v->value) && ast_get_ip(&peer->defaddr, v->value)) {
27715                unref_peer(peer, "unref_peer: from build_peer defaultip");
27716                return NULL;
27717             }
27718          } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
27719             int ha_error = 0;
27720             if (!ast_strlen_zero(v->value)) {
27721                peer->ha = ast_append_ha(v->name, v->value, peer->ha, &ha_error);
27722             }
27723             if (ha_error) {
27724                ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
27725             }
27726          } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
27727             int ha_error = 0;
27728             if (!ast_strlen_zero(v->value)) {
27729                peer->contactha = ast_append_ha(v->name + 7, v->value, peer->contactha, &ha_error);
27730             }
27731             if (ha_error) {
27732                ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
27733             }
27734          } else if (!strcasecmp(v->name, "directmediapermit") || !strcasecmp(v->name, "directmediadeny")) {
27735             int ha_error = 0;
27736             peer->directmediaha = ast_append_ha(v->name + 11, v->value, peer->directmediaha, &ha_error);
27737             if (ha_error) {
27738                ast_log(LOG_ERROR, "Bad directmedia ACL entry in configuration line %d : %s\n", v->lineno, v->value);
27739             }
27740          } else if (!strcasecmp(v->name, "port")) {
27741             peer->portinuri = 1;
27742             if (!(port = port_str2int(v->value, 0))) {
27743                if (realtime) {
27744                   /* If stored as integer, could be 0 for some DBs (notably MySQL) */
27745                   peer->portinuri = 0;
27746                } else {
27747                   ast_log(LOG_WARNING, "Invalid peer port configuration at line %d : %s\n", v->lineno, v->value);
27748                }
27749             }
27750          } else if (!strcasecmp(v->name, "callingpres")) {
27751             peer->callingpres = ast_parse_caller_presentation(v->value);
27752             if (peer->callingpres == -1) {
27753                peer->callingpres = atoi(v->value);
27754             }
27755          } else if (!strcasecmp(v->name, "username") || !strcmp(v->name, "defaultuser")) {   /* "username" is deprecated */
27756             ast_string_field_set(peer, username, v->value);
27757             if (!strcasecmp(v->name, "username")) {
27758                if (deprecation_warning) {
27759                   ast_log(LOG_NOTICE, "The 'username' field for sip peers has been deprecated in favor of the term 'defaultuser'\n");
27760                   deprecation_warning = 0;
27761                }
27762                peer->deprecated_username = 1;
27763             }
27764          } else if (!strcasecmp(v->name, "language")) {
27765             ast_string_field_set(peer, language, v->value);
27766          } else if (!strcasecmp(v->name, "regexten")) {
27767             ast_string_field_set(peer, regexten, v->value);
27768          } else if (!strcasecmp(v->name, "callbackextension")) {
27769             ast_copy_string(callback, v->value, sizeof(callback));
27770          } else if (!strcasecmp(v->name, "amaflags")) {
27771             format = ast_cdr_amaflags2int(v->value);
27772             if (format < 0) {
27773                ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
27774             } else {
27775                peer->amaflags = format;
27776             }
27777          } else if (!strcasecmp(v->name, "maxforwards")) {
27778             if (sscanf(v->value, "%30d", &peer->maxforwards) != 1
27779                || peer->maxforwards < 1 || 255 < peer->maxforwards) {
27780                ast_log(LOG_WARNING, "'%s' is not a valid maxforwards value at line %d.  Using default.\n", v->value, v->lineno);
27781                peer->maxforwards = sip_cfg.default_max_forwards;
27782             }
27783          } else if (!strcasecmp(v->name, "accountcode")) {
27784             ast_string_field_set(peer, accountcode, v->value);
27785          } else if (!strcasecmp(v->name, "mohinterpret")) {
27786             ast_string_field_set(peer, mohinterpret, v->value);
27787          } else if (!strcasecmp(v->name, "mohsuggest")) {
27788             ast_string_field_set(peer, mohsuggest, v->value);
27789          } else if (!strcasecmp(v->name, "parkinglot")) {
27790             ast_string_field_set(peer, parkinglot, v->value);
27791          } else if (!strcasecmp(v->name, "rtp_engine")) {
27792             ast_string_field_set(peer, engine, v->value);
27793          } else if (!strcasecmp(v->name, "mailbox")) {
27794             add_peer_mailboxes(peer, v->value);
27795          } else if (!strcasecmp(v->name, "hasvoicemail")) {
27796             /* People expect that if 'hasvoicemail' is set, that the mailbox will
27797              * be also set, even if not explicitly specified. */
27798             if (ast_true(v->value) && AST_LIST_EMPTY(&peer->mailboxes)) {
27799                add_peer_mailboxes(peer, name);
27800             }
27801          } else if (!strcasecmp(v->name, "subscribemwi")) {
27802             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
27803          } else if (!strcasecmp(v->name, "vmexten")) {
27804             ast_string_field_set(peer, vmexten, v->value);
27805          } else if (!strcasecmp(v->name, "callgroup")) {
27806             peer->callgroup = ast_get_group(v->value);
27807          } else if (!strcasecmp(v->name, "allowtransfer")) {
27808             peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
27809          } else if (!strcasecmp(v->name, "pickupgroup")) {
27810             peer->pickupgroup = ast_get_group(v->value);
27811          } else if (!strcasecmp(v->name, "allow")) {
27812             int error =  ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, TRUE);
27813             if (error) {
27814                ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
27815             }
27816          } else if (!strcasecmp(v->name, "disallow")) {
27817             int error =  ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, FALSE);
27818             if (error) {
27819                ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
27820             }
27821          } else if (!strcasecmp(v->name, "preferred_codec_only")) {
27822             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_PREFERRED_CODEC);
27823          } else if (!strcasecmp(v->name, "autoframing")) {
27824             peer->autoframing = ast_true(v->value);
27825          } else if (!strcasecmp(v->name, "rtptimeout")) {
27826             if ((sscanf(v->value, "%30d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
27827                ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
27828                peer->rtptimeout = global_rtptimeout;
27829             }
27830          } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
27831             if ((sscanf(v->value, "%30d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
27832                ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
27833                peer->rtpholdtimeout = global_rtpholdtimeout;
27834             }
27835          } else if (!strcasecmp(v->name, "rtpkeepalive")) {
27836             if ((sscanf(v->value, "%30d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
27837                ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d.  Using default.\n", v->value, v->lineno);
27838                peer->rtpkeepalive = global_rtpkeepalive;
27839             }
27840          } else if (!strcasecmp(v->name, "timert1")) {
27841             if ((sscanf(v->value, "%30d", &peer->timer_t1) != 1) || (peer->timer_t1 < 200) || (peer->timer_t1 < global_t1min)) {
27842                ast_log(LOG_WARNING, "'%s' is not a valid T1 time at line %d.  Using default.\n", v->value, v->lineno);
27843                peer->timer_t1 = global_t1min;
27844             }
27845             timert1_set = 1;
27846          } else if (!strcasecmp(v->name, "timerb")) {
27847             if ((sscanf(v->value, "%30d", &peer->timer_b) != 1) || (peer->timer_b < 200)) {
27848                ast_log(LOG_WARNING, "'%s' is not a valid Timer B time at line %d.  Using default.\n", v->value, v->lineno);
27849                peer->timer_b = global_timer_b;
27850             }
27851             timerb_set = 1;
27852          } else if (!strcasecmp(v->name, "setvar")) {
27853             peer->chanvars = add_var(v->value, peer->chanvars);
27854          } else if (!strcasecmp(v->name, "header")) {
27855             char tmp[4096];
27856             snprintf(tmp, sizeof(tmp), "__SIPADDHEADERpre%2d=%s", ++headercount, v->value);
27857             peer->chanvars = add_var(tmp, peer->chanvars);
27858          } else if (!strcasecmp(v->name, "qualifyfreq")) {
27859             int i;
27860             if (sscanf(v->value, "%30d", &i) == 1) {
27861                peer->qualifyfreq = i * 1000;
27862             } else {
27863                ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
27864                peer->qualifyfreq = global_qualifyfreq;
27865             }
27866          } else if (!strcasecmp(v->name, "maxcallbitrate")) {
27867             peer->maxcallbitrate = atoi(v->value);
27868             if (peer->maxcallbitrate < 0) {
27869                peer->maxcallbitrate = default_maxcallbitrate;
27870             }
27871          } else if (!strcasecmp(v->name, "session-timers")) {
27872             int i = (int) str2stmode(v->value);
27873             if (i < 0) {
27874                ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
27875                peer->stimer.st_mode_oper = global_st_mode;
27876             } else {
27877                peer->stimer.st_mode_oper = i;
27878             }
27879          } else if (!strcasecmp(v->name, "session-expires")) {
27880             if (sscanf(v->value, "%30d", &peer->stimer.st_max_se) != 1) {
27881                ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
27882                peer->stimer.st_max_se = global_max_se;
27883             }
27884          } else if (!strcasecmp(v->name, "session-minse")) {
27885             if (sscanf(v->value, "%30d", &peer->stimer.st_min_se) != 1) {
27886                ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
27887                peer->stimer.st_min_se = global_min_se;
27888             }
27889             if (peer->stimer.st_min_se < 90) {
27890                ast_log(LOG_WARNING, "session-minse '%s' at line %d of %s is not allowed to be < 90 secs\n", v->value, v->lineno, config);
27891                peer->stimer.st_min_se = global_min_se;
27892             }
27893          } else if (!strcasecmp(v->name, "session-refresher")) {
27894             int i = (int) str2strefresherparam(v->value);
27895             if (i < 0) {
27896                ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
27897                peer->stimer.st_ref = global_st_refresher;
27898             } else {
27899                peer->stimer.st_ref = i;
27900             }
27901          } else if (!strcasecmp(v->name, "disallowed_methods")) {
27902             char *disallow = ast_strdupa(v->value);
27903             mark_parsed_methods(&peer->disallowed_methods, disallow);
27904          } else if (!strcasecmp(v->name, "unsolicited_mailbox")) {
27905             ast_string_field_set(peer, unsolicited_mailbox, v->value);
27906          } else if (!strcasecmp(v->name, "use_q850_reason")) {
27907             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_Q850_REASON);
27908          } else if (!strcasecmp(v->name, "encryption")) {
27909             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_USE_SRTP);
27910          } else if (!strcasecmp(v->name, "snom_aoc_enabled")) {
27911             ast_set2_flag(&peer->flags[2], ast_true(v->value), SIP_PAGE3_SNOM_AOC);
27912          }
27913       }
27914 
27915       /* These apply to devstate lookups */
27916       if (realtime && !strcasecmp(v->name, "lastms")) {
27917          sscanf(v->value, "%30d", &peer->lastms);
27918       } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
27919          ast_sockaddr_parse(&peer->addr, v->value, PARSE_PORT_FORBID);
27920       } else if (realtime && !strcasecmp(v->name, "fullcontact")) {
27921          if (alt_fullcontact && !alt) {
27922             /* Reset, because the alternate also has a fullcontact and we
27923              * do NOT want the field value to be doubled. It might be
27924              * tempting to skip this, but the first table might not have
27925              * fullcontact and since we're here, we know that the alternate
27926              * absolutely does. */
27927             alt_fullcontact = 0;
27928             ast_str_reset(fullcontact);
27929          }
27930          /* Reconstruct field, because realtime separates our value at the ';' */
27931          if (fullcontact->used > 0) {
27932             ast_str_append(&fullcontact, 0, ";%s", v->value);
27933          } else {
27934             ast_str_set(&fullcontact, 0, "%s", v->value);
27935          }
27936       } else if (!strcasecmp(v->name, "qualify")) {
27937          if (!strcasecmp(v->value, "no")) {
27938             peer->maxms = 0;
27939          } else if (!strcasecmp(v->value, "yes")) {
27940             peer->maxms = default_qualify ? default_qualify : DEFAULT_MAXMS;
27941          } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
27942             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);
27943             peer->maxms = 0;
27944          }
27945          if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->maxms > 0) {
27946             /* This would otherwise cause a network storm, where the
27947              * qualify response refreshes the peer from the database,
27948              * which in turn causes another qualify to be sent, ad
27949              * infinitum. */
27950             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);
27951             peer->maxms = 0;
27952          }
27953       } else if (!strcasecmp(v->name, "callcounter")) {
27954          peer->call_limit = ast_true(v->value) ? INT_MAX : 0;
27955       } else if (!strcasecmp(v->name, "call-limit")) {
27956          peer->call_limit = atoi(v->value);
27957          if (peer->call_limit < 0) {
27958             peer->call_limit = 0;
27959          }
27960       } else if (!strcasecmp(v->name, "busylevel")) {
27961          peer->busy_level = atoi(v->value);
27962          if (peer->busy_level < 0) {
27963             peer->busy_level = 0;
27964          }
27965       } else if (ast_cc_is_config_param(v->name)) {
27966          ast_cc_set_param(peer->cc_params, v->name, v->value);
27967       }
27968    }
27969 
27970    if (!devstate_only) {
27971       struct sip_mailbox *mailbox;
27972       AST_LIST_TRAVERSE_SAFE_BEGIN(&peer->mailboxes, mailbox, entry) {
27973          if (mailbox->delme) {
27974             AST_LIST_REMOVE_CURRENT(entry);
27975             destroy_mailbox(mailbox);
27976          }
27977       }
27978       AST_LIST_TRAVERSE_SAFE_END;
27979    }
27980 
27981    if (!can_parse_xml && (ast_get_cc_agent_policy(peer->cc_params) == AST_CC_AGENT_NATIVE)) {
27982       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);
27983       ast_set_cc_agent_policy(peer->cc_params, AST_CC_AGENT_NEVER);
27984    }
27985 
27986    /* Note that Timer B is dependent upon T1 and MUST NOT be lower
27987     * than T1 * 64, according to RFC 3261, Section 17.1.1.2 */
27988    if (peer->timer_b < peer->timer_t1 * 64) {
27989       if (timerb_set && timert1_set) {
27990          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);
27991       } else if (timerb_set) {
27992          if ((peer->timer_t1 = peer->timer_b / 64) < global_t1min) {
27993             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);
27994             peer->timer_t1 = global_t1min;
27995             peer->timer_b = peer->timer_t1 * 64;
27996          }
27997          peer->timer_t1 = peer->timer_b / 64;
27998       } else {
27999          peer->timer_b = peer->timer_t1 * 64;
28000       }
28001    }
28002 
28003    if (!peer->default_outbound_transport) {
28004       /* Set default set of transports */
28005       peer->transports = default_transports;
28006       /* Set default primary transport */
28007       peer->default_outbound_transport = default_primary_transport;
28008    }
28009 
28010    /* The default transport type set during build_peer should only replace the socket.type when...
28011     * 1. Registration is not present and the socket.type and default transport types are different.
28012     * 2. The socket.type is not an acceptable transport type after rebuilding peer.
28013     * 3. The socket.type is not set yet. */
28014    if (((peer->socket.type != peer->default_outbound_transport) && (peer->expire == -1)) ||
28015       !(peer->socket.type & peer->transports) || !(peer->socket.type)) {
28016 
28017       set_socket_transport(&peer->socket, peer->default_outbound_transport);
28018    }
28019 
28020    if (ast_str_strlen(fullcontact)) {
28021       ast_string_field_set(peer, fullcontact, ast_str_buffer(fullcontact));
28022       peer->rt_fromcontact = TRUE;
28023       /* We have a hostname in the fullcontact, but if we don't have an
28024        * address listed on the entry (or if it's 'dynamic'), then we need to
28025        * parse the entry to obtain the IP address, so a dynamic host can be
28026        * contacted immediately after reload (as opposed to waiting for it to
28027        * register once again). But if we have an address for this peer and NAT was
28028        * specified, use that address instead. */
28029       /* XXX May need to revisit the final argument; does the realtime DB store whether
28030        * the original contact was over TLS or not? XXX */
28031       if (!ast_test_flag(&peer->flags[0], SIP_NAT_FORCE_RPORT) || ast_sockaddr_isnull(&peer->addr)) {
28032          __set_address_from_contact(fullcontact->str, &peer->addr, 0);
28033       }
28034    }
28035 
28036    if (srvlookup && peer->dnsmgr == NULL) {
28037       char transport[MAXHOSTNAMELEN];
28038       char _srvlookup[MAXHOSTNAMELEN];
28039       char *params;
28040 
28041       ast_copy_string(_srvlookup, srvlookup, sizeof(_srvlookup));
28042       if ((params = strchr(_srvlookup, ';'))) {
28043          *params++ = '\0';
28044       }
28045 
28046       snprintf(transport, sizeof(transport), "_%s._%s", get_srv_service(peer->socket.type), get_srv_protocol(peer->socket.type));
28047 
28048       peer->addr.ss.ss_family = get_address_family_filter(peer->socket.type); /* Filter address family */
28049       if (ast_dnsmgr_lookup_cb(_srvlookup, &peer->addr, &peer->dnsmgr, sip_cfg.srvlookup && !peer->portinuri ? transport : NULL,
28050                on_dns_update_peer, ref_peer(peer, "Store peer on dnsmgr"))) {
28051          ast_log(LOG_ERROR, "srvlookup failed for host: %s, on peer %s, removing peer\n", _srvlookup, peer->name);
28052          unref_peer(peer, "dnsmgr lookup failed, getting rid of peer dnsmgr ref");
28053          unref_peer(peer, "getting rid of a peer pointer");
28054          return NULL;
28055       }
28056       if (!peer->dnsmgr) {
28057          /* dnsmgr refresh disabeld, release reference */
28058          unref_peer(peer, "dnsmgr disabled, unref peer");
28059       }
28060 
28061       ast_string_field_set(peer, tohost, srvlookup);
28062 
28063       if (global_dynamic_exclude_static && !ast_sockaddr_isnull(&peer->addr)) {
28064          int ha_error = 0;
28065          sip_cfg.contact_ha = ast_append_ha("deny", ast_sockaddr_stringify_addr(&peer->addr), 
28066                      sip_cfg.contact_ha, &ha_error);
28067          if (ha_error) {
28068             ast_log(LOG_ERROR, "Bad or unresolved host/IP entry in configuration for peer %s, cannot add to contact ACL\n", peer->name);
28069          }
28070       }
28071    } else if (peer->dnsmgr && !peer->host_dynamic) {
28072       /* force a refresh here on reload if dnsmgr already exists and host is set. */
28073       ast_dnsmgr_refresh(peer->dnsmgr);
28074    }
28075 
28076    if (port && !realtime && peer->host_dynamic) {
28077       ast_sockaddr_set_port(&peer->defaddr, port);
28078    } else if (port) {
28079       ast_sockaddr_set_port(&peer->addr, port);
28080    }
28081 
28082    if (ast_sockaddr_port(&peer->addr) == 0) {
28083       ast_sockaddr_set_port(&peer->addr,
28084                   (peer->socket.type & SIP_TRANSPORT_TLS) ?
28085                   STANDARD_TLS_PORT : STANDARD_SIP_PORT);
28086    }
28087    if (ast_sockaddr_port(&peer->defaddr) == 0) {
28088       ast_sockaddr_set_port(&peer->defaddr,
28089                   (peer->socket.type & SIP_TRANSPORT_TLS) ?
28090                   STANDARD_TLS_PORT : STANDARD_SIP_PORT);
28091    }
28092    if (!peer->socket.port) {
28093       peer->socket.port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
28094    }
28095 
28096    if (!sip_cfg.ignore_regexpire && peer->host_dynamic && realtime) {
28097       time_t nowtime = time(NULL);
28098 
28099       if ((nowtime - regseconds) > 0) {
28100          destroy_association(peer);
28101          memset(&peer->addr, 0, sizeof(peer->addr));
28102          peer->lastms = -1;
28103          ast_debug(1, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
28104       }
28105    }
28106 
28107    /* Startup regular pokes */
28108    if (!devstate_only && realtime && peer->lastms > 0) {
28109       ref_peer(peer, "schedule qualify");
28110       sip_poke_peer(peer, 0);
28111    }
28112 
28113    ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
28114    ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
28115    ast_copy_flags(&peer->flags[2], &peerflags[2], mask[2].flags);
28116    if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
28117       sip_cfg.allowsubscribe = TRUE;   /* No global ban any more */
28118    }
28119    /* If read-only RT backend, then refresh from local DB cache */
28120    if (peer->host_dynamic && (!peer->is_realtime || !sip_cfg.peer_rtupdate)) {
28121       reg_source_db(peer);
28122    }
28123 
28124    /* If they didn't request that MWI is sent *only* on subscribe, go ahead and
28125     * subscribe to it now. */
28126    if (!devstate_only && !ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
28127       !AST_LIST_EMPTY(&peer->mailboxes)) {
28128       add_peer_mwi_subs(peer);
28129       /* Send MWI from the event cache only.  This is so we can send initial
28130        * MWI if app_voicemail got loaded before chan_sip.  If it is the other
28131        * way, then we will get events when app_voicemail gets loaded. */
28132       sip_send_mwi_to_peer(peer, 1);
28133    }
28134 
28135    peer->the_mark = 0;
28136 
28137    ast_free_ha(oldha);
28138    ast_free_ha(olddirectmediaha);
28139    if (!ast_strlen_zero(callback)) { /* build string from peer info */
28140       char *reg_string;
28141       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) {
28142          sip_register(reg_string, 0); /* XXX TODO: count in registry_count */
28143          ast_free(reg_string);
28144       }
28145    }
28146    return peer;
28147 }
28148 
28149 static int peer_markall_func(void *device, void *arg, int flags)
28150 {
28151    struct sip_peer *peer = device;
28152    peer->the_mark = 1;
28153    return 0;
28154 }
28155 
28156 static void display_nat_warning(const char *cat, int reason, struct ast_flags *flags) {
28157    int global_nat, specific_nat;
28158 
28159    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))) {
28160       ast_log(LOG_WARNING, "!!! PLEASE NOTE: Setting 'nat' for a peer/user that differs from the  global setting can make\n");
28161       ast_log(LOG_WARNING, "!!! the name of that peer/user discoverable by an attacker. Replies for non-existent peers/users\n");
28162       ast_log(LOG_WARNING, "!!! will be sent to a different port than replies for an existing peer/user. If at all possible,\n");
28163       ast_log(LOG_WARNING, "!!! use the global 'nat' setting and do not set 'nat' per peer/user.\n");
28164       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));
28165    }
28166 }
28167 
28168 static void cleanup_all_regs(void)
28169 {
28170       /* First, destroy all outstanding registry calls */
28171       /* This is needed, since otherwise active registry entries will not be destroyed */
28172       ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {  /* regl is locked */
28173             ASTOBJ_WRLOCK(iterator); /* now regl is locked, and the object is also locked */
28174             if (iterator->call) {
28175                ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
28176                /* This will also remove references to the registry */
28177                dialog_unlink_all(iterator->call);
28178                iterator->call = dialog_unref(iterator->call, "remove iterator->call from registry traversal");
28179             }
28180             if (iterator->expire > -1) {
28181                AST_SCHED_DEL_UNREF(sched, iterator->expire, registry_unref(iterator, "reg ptr unref from reload config"));
28182             }
28183             if (iterator->timeout > -1) {
28184                AST_SCHED_DEL_UNREF(sched, iterator->timeout, registry_unref(iterator, "reg ptr unref from reload config"));
28185             }
28186             if (iterator->dnsmgr) {
28187                ast_dnsmgr_release(iterator->dnsmgr);
28188                iterator->dnsmgr = NULL;
28189                registry_unref(iterator, "reg ptr unref from dnsmgr");
28190             }
28191             ASTOBJ_UNLOCK(iterator);
28192       } while(0));
28193 }
28194 
28195 /*! \brief Re-read SIP.conf config file
28196 \note This function reloads all config data, except for
28197    active peers (with registrations). They will only
28198    change configuration data at restart, not at reload.
28199    SIP debug and recordhistory state will not change
28200  */
28201 static int reload_config(enum channelreloadreason reason)
28202 {
28203    struct ast_config *cfg, *ucfg;
28204    struct ast_variable *v;
28205    struct sip_peer *peer;
28206    char *cat, *stringp, *context, *oldregcontext;
28207    char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
28208    struct ast_flags dummy[2];
28209    struct ast_flags config_flags = { reason == CHANNEL_MODULE_LOAD ? 0 : ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) ? 0 : CONFIG_FLAG_FILEUNCHANGED };
28210    int auto_sip_domains = FALSE;
28211    struct ast_sockaddr old_bindaddr = bindaddr;
28212    int registry_count = 0, peer_count = 0, timerb_set = 0, timert1_set = 0;
28213    int subscribe_network_change = 1;
28214    time_t run_start, run_end;
28215    int bindport = 0;
28216 
28217    run_start = time(0);
28218    ast_unload_realtime("sipregs");
28219    ast_unload_realtime("sippeers");
28220    cfg = ast_config_load(config, config_flags);
28221 
28222    /* We *must* have a config file otherwise stop immediately */
28223    if (!cfg) {
28224       ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
28225       return -1;
28226    } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
28227       ucfg = ast_config_load("users.conf", config_flags);
28228       if (ucfg == CONFIG_STATUS_FILEUNCHANGED) {
28229          return 1;
28230       } else if (ucfg == CONFIG_STATUS_FILEINVALID) {
28231          ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
28232          return 1;
28233       }
28234       /* Must reread both files, because one changed */
28235       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
28236       if ((cfg = ast_config_load(config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
28237          ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
28238          ast_config_destroy(ucfg);
28239          return 1;
28240       }
28241       if (!cfg) {
28242          /* should have been able to reload here */
28243          ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
28244          return -1;
28245       }
28246    } else if (cfg == CONFIG_STATUS_FILEINVALID) {
28247       ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed\n", config);
28248       return 1;
28249    } else {
28250       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
28251       if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEINVALID) {
28252          ast_log(LOG_ERROR, "Contents of users.conf are invalid and cannot be parsed\n");
28253          ast_config_destroy(cfg);
28254          return 1;
28255       }
28256    }
28257 
28258    ast_free_ha(sip_cfg.contact_ha);
28259    sip_cfg.contact_ha = NULL;
28260 
28261    default_tls_cfg.enabled = FALSE;    /* Default: Disable TLS */
28262 
28263    if (reason != CHANNEL_MODULE_LOAD) {
28264       ast_debug(4, "--------------- SIP reload started\n");
28265 
28266       clear_sip_domains();
28267       ast_mutex_lock(&authl_lock);
28268       if (authl) {
28269          ao2_t_ref(authl, -1, "Removing old global authentication");
28270          authl = NULL;
28271       }
28272       ast_mutex_unlock(&authl_lock);
28273 
28274 
28275       cleanup_all_regs();
28276       /* Then, actually destroy users and registry */
28277       ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
28278       ast_debug(4, "--------------- Done destroying registry list\n");
28279       ao2_t_callback(peers, OBJ_NODATA, peer_markall_func, NULL, "callback to mark all peers");
28280    }
28281 
28282    /* Reset certificate handling for TLS sessions */
28283    if (reason != CHANNEL_MODULE_LOAD) {
28284       ast_free(default_tls_cfg.certfile);
28285       ast_free(default_tls_cfg.pvtfile);
28286       ast_free(default_tls_cfg.cipher);
28287       ast_free(default_tls_cfg.cafile);
28288       ast_free(default_tls_cfg.capath);
28289    }
28290    default_tls_cfg.certfile = ast_strdup(AST_CERTFILE); /*XXX Not sure if this is useful */
28291    default_tls_cfg.pvtfile = ast_strdup("");
28292    default_tls_cfg.cipher = ast_strdup("");
28293    default_tls_cfg.cafile = ast_strdup("");
28294    default_tls_cfg.capath = ast_strdup("");
28295 
28296    /* Initialize copy of current sip_cfg.regcontext for later use in removing stale contexts */
28297    ast_copy_string(oldcontexts, sip_cfg.regcontext, sizeof(oldcontexts));
28298    oldregcontext = oldcontexts;
28299 
28300    /* Clear all flags before setting default values */
28301    /* Preserve debugging settings for console */
28302    sipdebug &= sip_debug_console;
28303    ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
28304    ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
28305    ast_clear_flag(&global_flags[2], AST_FLAGS_ALL);
28306 
28307    /* Reset IP addresses  */
28308    ast_sockaddr_parse(&bindaddr, "0.0.0.0:0", 0);
28309    memset(&internip, 0, sizeof(internip));
28310 
28311    /* Free memory for local network address mask */
28312    ast_free_ha(localaddr);
28313    memset(&localaddr, 0, sizeof(localaddr));
28314    memset(&externaddr, 0, sizeof(externaddr));
28315    memset(&media_address, 0, sizeof(media_address));
28316    memset(&default_prefs, 0 , sizeof(default_prefs));
28317    memset(&sip_cfg.outboundproxy, 0, sizeof(struct sip_proxy));
28318    sip_cfg.outboundproxy.force = FALSE;      /*!< Don't force proxy usage, use route: headers */
28319    default_transports = SIP_TRANSPORT_UDP;
28320    default_primary_transport = SIP_TRANSPORT_UDP;
28321    ourport_tcp = STANDARD_SIP_PORT;
28322    ourport_tls = STANDARD_TLS_PORT;
28323    externtcpport = STANDARD_SIP_PORT;
28324    externtlsport = STANDARD_TLS_PORT;
28325    sip_cfg.srvlookup = DEFAULT_SRVLOOKUP;
28326    global_tos_sip = DEFAULT_TOS_SIP;
28327    global_tos_audio = DEFAULT_TOS_AUDIO;
28328    global_tos_video = DEFAULT_TOS_VIDEO;
28329    global_tos_text = DEFAULT_TOS_TEXT;
28330    global_cos_sip = DEFAULT_COS_SIP;
28331    global_cos_audio = DEFAULT_COS_AUDIO;
28332    global_cos_video = DEFAULT_COS_VIDEO;
28333    global_cos_text = DEFAULT_COS_TEXT;
28334 
28335    externhost[0] = '\0';         /* External host name (for behind NAT DynDNS support) */
28336    externexpire = 0;       /* Expiration for DNS re-issuing */
28337    externrefresh = 10;
28338 
28339    /* Reset channel settings to default before re-configuring */
28340    sip_cfg.allow_external_domains = DEFAULT_ALLOW_EXT_DOM;           /* Allow external invites */
28341    sip_cfg.regcontext[0] = '\0';
28342    sip_cfg.capability = DEFAULT_CAPABILITY;
28343    sip_cfg.regextenonqualify = DEFAULT_REGEXTENONQUALIFY;
28344    sip_cfg.legacy_useroption_parsing = DEFAULT_LEGACY_USEROPTION_PARSING;
28345    sip_cfg.notifyringing = DEFAULT_NOTIFYRINGING;
28346    sip_cfg.notifycid = DEFAULT_NOTIFYCID;
28347    sip_cfg.notifyhold = FALSE;      /*!< Keep track of hold status for a peer */
28348    sip_cfg.directrtpsetup = FALSE;     /* Experimental feature, disabled by default */
28349    sip_cfg.alwaysauthreject = DEFAULT_ALWAYSAUTHREJECT;
28350    sip_cfg.auth_options_requests = DEFAULT_AUTH_OPTIONS;
28351    sip_cfg.allowsubscribe = FALSE;
28352    sip_cfg.disallowed_methods = SIP_UNKNOWN;
28353    sip_cfg.contact_ha = NULL;    /* Reset the contact ACL */
28354    snprintf(global_useragent, sizeof(global_useragent), "%s %s", DEFAULT_USERAGENT, ast_get_version());
28355    snprintf(global_sdpsession, sizeof(global_sdpsession), "%s %s", DEFAULT_SDPSESSION, ast_get_version());
28356    snprintf(global_sdpowner, sizeof(global_sdpowner), "%s", DEFAULT_SDPOWNER);
28357    global_prematuremediafilter = TRUE;
28358    ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
28359    ast_copy_string(sip_cfg.realm, S_OR(ast_config_AST_SYSTEM_NAME, DEFAULT_REALM), sizeof(sip_cfg.realm));
28360    sip_cfg.domainsasrealm = DEFAULT_DOMAINSASREALM;
28361    ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
28362    ast_copy_string(default_mwi_from, DEFAULT_MWI_FROM, sizeof(default_mwi_from));
28363    sip_cfg.compactheaders = DEFAULT_COMPACTHEADERS;
28364    global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
28365    global_regattempts_max = 0;
28366    sip_cfg.pedanticsipchecking = DEFAULT_PEDANTIC;
28367    sip_cfg.autocreatepeer = DEFAULT_AUTOCREATEPEER;
28368    global_autoframing = 0;
28369    sip_cfg.allowguest = DEFAULT_ALLOWGUEST;
28370    global_callcounter = DEFAULT_CALLCOUNTER;
28371    global_match_auth_username = FALSE;    /*!< Match auth username if available instead of From: Default off. */
28372    global_rtptimeout = 0;
28373    global_rtpholdtimeout = 0;
28374    global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
28375    sip_cfg.allowtransfer = TRANSFER_OPENFORALL; /* Merrily accept all transfers by default */
28376    sip_cfg.rtautoclear = 120;
28377    ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE);   /* Default for all devices: TRUE */
28378    ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP_YES); /* Default for all devices: Yes */
28379    sip_cfg.peer_rtupdate = TRUE;
28380    global_dynamic_exclude_static = 0;  /* Exclude static peers */
28381    sip_cfg.tcp_enabled = FALSE;
28382 
28383    /* Session-Timers */
28384    global_st_mode = SESSION_TIMER_MODE_ACCEPT;
28385    global_st_refresher = SESSION_TIMER_REFRESHER_PARAM_UAS;
28386    global_min_se  = DEFAULT_MIN_SE;
28387    global_max_se  = DEFAULT_MAX_SE;
28388 
28389    /* Peer poking settings */
28390    global_qualify_gap = DEFAULT_QUALIFY_GAP;
28391    global_qualify_peers = DEFAULT_QUALIFY_PEERS;
28392 
28393    /* Initialize some reasonable defaults at SIP reload (used both for channel and as default for devices */
28394    ast_copy_string(sip_cfg.default_context, DEFAULT_CONTEXT, sizeof(sip_cfg.default_context));
28395    sip_cfg.default_subscribecontext[0] = '\0';
28396    sip_cfg.default_max_forwards = DEFAULT_MAX_FORWARDS;
28397    default_language[0] = '\0';
28398    default_fromdomain[0] = '\0';
28399    default_fromdomainport = 0;
28400    default_qualify = DEFAULT_QUALIFY;
28401    default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
28402    ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
28403    ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
28404    ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
28405    ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833);    /*!< Default DTMF setting: RFC2833 */
28406    ast_set_flag(&global_flags[0], SIP_DIRECT_MEDIA);    /*!< Allow re-invites */
28407    ast_set_flag(&global_flags[0], SIP_NAT_FORCE_RPORT); /*!< Default to nat=force_rport */
28408    ast_copy_string(default_engine, DEFAULT_ENGINE, sizeof(default_engine));
28409    ast_copy_string(default_parkinglot, DEFAULT_PARKINGLOT, sizeof(default_parkinglot));
28410 
28411    /* Debugging settings, always default to off */
28412    dumphistory = FALSE;
28413    recordhistory = FALSE;
28414    sipdebug &= ~sip_debug_config;
28415 
28416    /* Misc settings for the channel */
28417    global_relaxdtmf = FALSE;
28418    sip_cfg.callevents = DEFAULT_CALLEVENTS;
28419    global_authfailureevents = FALSE;
28420    global_t1 = DEFAULT_TIMER_T1;
28421    global_timer_b = 64 * DEFAULT_TIMER_T1;
28422    global_t1min = DEFAULT_T1MIN;
28423    global_qualifyfreq = DEFAULT_QUALIFYFREQ;
28424    global_t38_maxdatagram = -1;
28425    global_shrinkcallerid = 1;
28426    authlimit = DEFAULT_AUTHLIMIT;
28427    authtimeout = DEFAULT_AUTHTIMEOUT;
28428    global_store_sip_cause = DEFAULT_STORE_SIP_CAUSE;
28429 
28430    sip_cfg.matchexternaddrlocally = DEFAULT_MATCHEXTERNADDRLOCALLY;
28431 
28432    /* Copy the default jb config over global_jbconf */
28433    memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
28434 
28435    ast_clear_flag(&global_flags[1], SIP_PAGE2_FAX_DETECT);
28436    ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
28437    ast_clear_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT);
28438    ast_clear_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION);
28439 
28440 
28441    /* Read the [general] config section of sip.conf (or from realtime config) */
28442    for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
28443       if (handle_common_options(&global_flags[0], &dummy[0], v)) {
28444          continue;
28445       }
28446       if (handle_t38_options(&global_flags[0], &dummy[0], v, &global_t38_maxdatagram)) {
28447          continue;
28448       }
28449       /* handle jb conf */
28450       if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
28451          continue;
28452 
28453       /* handle tls conf */
28454       if (!ast_tls_read_conf(&default_tls_cfg, &sip_tls_desc, v->name, v->value)) {
28455          continue;
28456       }
28457 
28458       if (!strcasecmp(v->name, "context")) {
28459          ast_copy_string(sip_cfg.default_context, v->value, sizeof(sip_cfg.default_context));
28460       } else if (!strcasecmp(v->name, "subscribecontext")) {
28461          ast_copy_string(sip_cfg.default_subscribecontext, v->value, sizeof(sip_cfg.default_subscribecontext));
28462       } else if (!strcasecmp(v->name, "callcounter")) {
28463          global_callcounter = ast_true(v->value) ? 1 : 0;
28464       } else if (!strcasecmp(v->name, "allowguest")) {
28465          sip_cfg.allowguest = ast_true(v->value) ? 1 : 0;
28466       } else if (!strcasecmp(v->name, "realm")) {
28467          ast_copy_string(sip_cfg.realm, v->value, sizeof(sip_cfg.realm));
28468       } else if (!strcasecmp(v->name, "domainsasrealm")) {
28469          sip_cfg.domainsasrealm = ast_true(v->value);
28470       } else if (!strcasecmp(v->name, "useragent")) {
28471          ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
28472          ast_debug(1, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
28473       } else if (!strcasecmp(v->name, "sdpsession")) {
28474          ast_copy_string(global_sdpsession, v->value, sizeof(global_sdpsession));
28475       } else if (!strcasecmp(v->name, "sdpowner")) {
28476          /* Field cannot contain spaces */
28477          if (!strstr(v->value, " ")) {
28478             ast_copy_string(global_sdpowner, v->value, sizeof(global_sdpowner));
28479          } else {
28480             ast_log(LOG_WARNING, "'%s' must not contain spaces at line %d.  Using default.\n", v->value, v->lineno);
28481          }
28482       } else if (!strcasecmp(v->name, "allowtransfer")) {
28483          sip_cfg.allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
28484       } else if (!strcasecmp(v->name, "rtcachefriends")) {
28485          ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);
28486       } else if (!strcasecmp(v->name, "rtsavesysname")) {
28487          sip_cfg.rtsave_sysname = ast_true(v->value);
28488       } else if (!strcasecmp(v->name, "rtupdate")) {
28489          sip_cfg.peer_rtupdate = ast_true(v->value);
28490       } else if (!strcasecmp(v->name, "ignoreregexpire")) {
28491          sip_cfg.ignore_regexpire = ast_true(v->value);
28492       } else if (!strcasecmp(v->name, "timert1")) {
28493          /* Defaults to 500ms, but RFC 3261 states that it is recommended
28494           * for the value to be set higher, though a lower value is only
28495           * allowed on private networks unconnected to the Internet. */
28496          global_t1 = atoi(v->value);
28497       } else if (!strcasecmp(v->name, "timerb")) {
28498          int tmp = atoi(v->value);
28499          if (tmp < 500) {
28500             global_timer_b = global_t1 * 64;
28501             ast_log(LOG_WARNING, "Invalid value for timerb ('%s').  Setting to default ('%d').\n", v->value, global_timer_b);
28502          }
28503          timerb_set = 1;
28504       } else if (!strcasecmp(v->name, "t1min")) {
28505          global_t1min = atoi(v->value);
28506       } else if (!strcasecmp(v->name, "transport")) {
28507          char *val = ast_strdupa(v->value);
28508          char *trans;
28509 
28510          default_transports = default_primary_transport = 0;
28511          while ((trans = strsep(&val, ","))) {
28512             trans = ast_skip_blanks(trans);
28513 
28514             if (!strncasecmp(trans, "udp", 3)) {
28515                default_transports |= SIP_TRANSPORT_UDP;
28516             } else if (!strncasecmp(trans, "tcp", 3)) {
28517                default_transports |= SIP_TRANSPORT_TCP;
28518             } else if (!strncasecmp(trans, "tls", 3)) {
28519                default_transports |= SIP_TRANSPORT_TLS;
28520             } else {
28521                ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
28522             }
28523             if (default_primary_transport == 0) {
28524                default_primary_transport = default_transports;
28525             }
28526          }
28527       } else if (!strcasecmp(v->name, "tcpenable")) {
28528          if (!ast_false(v->value)) {
28529             ast_debug(2, "Enabling TCP socket for listening\n");
28530             sip_cfg.tcp_enabled = TRUE;
28531          }
28532       } else if (!strcasecmp(v->name, "tcpbindaddr")) {
28533          if (ast_parse_arg(v->value, PARSE_ADDR,
28534                  &sip_tcp_desc.local_address)) {
28535             ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
28536                v->name, v->value, v->lineno, config);
28537          }
28538          ast_debug(2, "Setting TCP socket address to %s\n",
28539               ast_sockaddr_stringify(&sip_tcp_desc.local_address));
28540       } else if (!strcasecmp(v->name, "dynamic_exclude_static") || !strcasecmp(v->name, "dynamic_excludes_static")) {
28541          global_dynamic_exclude_static = ast_true(v->value);
28542       } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
28543          int ha_error = 0;
28544          sip_cfg.contact_ha = ast_append_ha(v->name + 7, v->value, sip_cfg.contact_ha, &ha_error);
28545          if (ha_error) {
28546             ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
28547          }
28548       } else if (!strcasecmp(v->name, "rtautoclear")) {
28549          int i = atoi(v->value);
28550          if (i > 0) {
28551             sip_cfg.rtautoclear = i;
28552          } else {
28553             i = 0;
28554          }
28555          ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
28556       } else if (!strcasecmp(v->name, "usereqphone")) {
28557          ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);
28558       } else if (!strcasecmp(v->name, "prematuremedia")) {
28559          global_prematuremediafilter = ast_true(v->value);
28560       } else if (!strcasecmp(v->name, "relaxdtmf")) {
28561          global_relaxdtmf = ast_true(v->value);
28562       } else if (!strcasecmp(v->name, "vmexten")) {
28563          ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
28564       } else if (!strcasecmp(v->name, "rtptimeout")) {
28565          if ((sscanf(v->value, "%30d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
28566             ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
28567             global_rtptimeout = 0;
28568          }
28569       } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
28570          if ((sscanf(v->value, "%30d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
28571             ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
28572             global_rtpholdtimeout = 0;
28573          }
28574       } else if (!strcasecmp(v->name, "rtpkeepalive")) {
28575          if ((sscanf(v->value, "%30d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
28576             ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d.  Using default.\n", v->value, v->lineno);
28577             global_rtpkeepalive = DEFAULT_RTPKEEPALIVE;
28578          }
28579       } else if (!strcasecmp(v->name, "compactheaders")) {
28580          sip_cfg.compactheaders = ast_true(v->value);
28581       } else if (!strcasecmp(v->name, "notifymimetype")) {
28582          ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
28583       } else if (!strcasecmp(v->name, "directrtpsetup")) {
28584          sip_cfg.directrtpsetup = ast_true(v->value);
28585       } else if (!strcasecmp(v->name, "notifyringing")) {
28586          sip_cfg.notifyringing = ast_true(v->value);
28587       } else if (!strcasecmp(v->name, "notifyhold")) {
28588          sip_cfg.notifyhold = ast_true(v->value);
28589       } else if (!strcasecmp(v->name, "notifycid")) {
28590          if (!strcasecmp(v->value, "ignore-context")) {
28591             sip_cfg.notifycid = IGNORE_CONTEXT;
28592          } else {
28593             sip_cfg.notifycid = ast_true(v->value) ? ENABLED : DISABLED;
28594          }
28595       } else if (!strcasecmp(v->name, "alwaysauthreject")) {
28596          sip_cfg.alwaysauthreject = ast_true(v->value);
28597       } else if (!strcasecmp(v->name, "auth_options_requests")) {
28598          if (ast_true(v->value)) {
28599             sip_cfg.auth_options_requests = 1;
28600          }
28601       } else if (!strcasecmp(v->name, "mohinterpret")) {
28602          ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
28603       } else if (!strcasecmp(v->name, "mohsuggest")) {
28604          ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
28605       } else if (!strcasecmp(v->name, "language")) {
28606          ast_copy_string(default_language, v->value, sizeof(default_language));
28607       } else if (!strcasecmp(v->name, "regcontext")) {
28608          ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
28609          stringp = newcontexts;
28610          /* Let's remove any contexts that are no longer defined in regcontext */
28611          cleanup_stale_contexts(stringp, oldregcontext);
28612          /* Create contexts if they don't exist already */
28613          while ((context = strsep(&stringp, "&"))) {
28614             ast_copy_string(used_context, context, sizeof(used_context));
28615             ast_context_find_or_create(NULL, NULL, context, "SIP");
28616          }
28617          ast_copy_string(sip_cfg.regcontext, v->value, sizeof(sip_cfg.regcontext));
28618       } else if (!strcasecmp(v->name, "regextenonqualify")) {
28619          sip_cfg.regextenonqualify = ast_true(v->value);
28620       } else if (!strcasecmp(v->name, "legacy_useroption_parsing")) {
28621          sip_cfg.legacy_useroption_parsing = ast_true(v->value);
28622       } else if (!strcasecmp(v->name, "callerid")) {
28623          ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
28624       } else if (!strcasecmp(v->name, "mwi_from")) {
28625          ast_copy_string(default_mwi_from, v->value, sizeof(default_mwi_from));
28626       } else if (!strcasecmp(v->name, "fromdomain")) {
28627          char *fromdomainport;
28628          ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
28629          if ((fromdomainport = strchr(default_fromdomain, ':'))) {
28630             *fromdomainport++ = '\0';
28631             if (!(default_fromdomainport = port_str2int(fromdomainport, 0))) {
28632                ast_log(LOG_NOTICE, "'%s' is not a valid port number for fromdomain.\n",fromdomainport);
28633             }
28634          } else {
28635             default_fromdomainport = STANDARD_SIP_PORT;
28636          }
28637       } else if (!strcasecmp(v->name, "outboundproxy")) {
28638          struct sip_proxy *proxy;
28639          if (ast_strlen_zero(v->value)) {
28640             ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf\n", v->lineno);
28641             continue;
28642          }
28643          proxy = proxy_from_config(v->value, v->lineno, &sip_cfg.outboundproxy);
28644          if (!proxy) {
28645             ast_log(LOG_WARNING, "failure parsing the outbound proxy on line %d of sip.conf.\n", v->lineno);
28646             continue;
28647          }
28648       } else if (!strcasecmp(v->name, "autocreatepeer")) {
28649          sip_cfg.autocreatepeer = ast_true(v->value);
28650       } else if (!strcasecmp(v->name, "match_auth_username")) {
28651          global_match_auth_username = ast_true(v->value);
28652       } else if (!strcasecmp(v->name, "srvlookup")) {
28653          sip_cfg.srvlookup = ast_true(v->value);
28654       } else if (!strcasecmp(v->name, "pedantic")) {
28655          sip_cfg.pedanticsipchecking = ast_true(v->value);
28656       } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
28657          max_expiry = atoi(v->value);
28658          if (max_expiry < 1) {
28659             max_expiry = DEFAULT_MAX_EXPIRY;
28660          }
28661       } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
28662          min_expiry = atoi(v->value);
28663          if (min_expiry < 1) {
28664             min_expiry = DEFAULT_MIN_EXPIRY;
28665          }
28666       } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
28667          default_expiry = atoi(v->value);
28668          if (default_expiry < 1) {
28669             default_expiry = DEFAULT_DEFAULT_EXPIRY;
28670          }
28671       } else if (!strcasecmp(v->name, "mwiexpiry") || !strcasecmp(v->name, "mwiexpirey")) {
28672          mwi_expiry = atoi(v->value);
28673          if (mwi_expiry < 1) {
28674             mwi_expiry = DEFAULT_MWI_EXPIRY;
28675          }
28676       } else if (!strcasecmp(v->name, "tcpauthtimeout")) {
28677          if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
28678                  &authtimeout, DEFAULT_AUTHTIMEOUT, 1, INT_MAX)) {
28679             ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
28680                v->name, v->value, v->lineno, config);
28681          }
28682       } else if (!strcasecmp(v->name, "tcpauthlimit")) {
28683          if (ast_parse_arg(v->value, PARSE_INT32|PARSE_DEFAULT|PARSE_IN_RANGE,
28684                  &authlimit, DEFAULT_AUTHLIMIT, 1, INT_MAX)) {
28685             ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n",
28686                v->name, v->value, v->lineno, config);
28687          }
28688       } else if (!strcasecmp(v->name, "sipdebug")) {
28689          if (ast_true(v->value))
28690             sipdebug |= sip_debug_config;
28691       } else if (!strcasecmp(v->name, "dumphistory")) {
28692          dumphistory = ast_true(v->value);
28693       } else if (!strcasecmp(v->name, "recordhistory")) {
28694          recordhistory = ast_true(v->value);
28695       } else if (!strcasecmp(v->name, "registertimeout")) {
28696          global_reg_timeout = atoi(v->value);
28697          if (global_reg_timeout < 1) {
28698             global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
28699          }
28700       } else if (!strcasecmp(v->name, "registerattempts")) {
28701          global_regattempts_max = atoi(v->value);
28702       } else if (!strcasecmp(v->name, "bindaddr") || !strcasecmp(v->name, "udpbindaddr")) {
28703          if (ast_parse_arg(v->value, PARSE_ADDR, &bindaddr)) {
28704             ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
28705          }
28706       } else if (!strcasecmp(v->name, "localnet")) {
28707          struct ast_ha *na;
28708          int ha_error = 0;
28709 
28710          if (!(na = ast_append_ha("d", v->value, localaddr, &ha_error))) {
28711             ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
28712          } else {
28713             localaddr = na;
28714          }
28715          if (ha_error) {
28716             ast_log(LOG_ERROR, "Bad localnet configuration value line %d : %s\n", v->lineno, v->value);
28717          }
28718       } else if (!strcasecmp(v->name, "media_address")) {
28719          if (ast_parse_arg(v->value, PARSE_ADDR, &media_address))
28720             ast_log(LOG_WARNING, "Invalid address for media_address keyword: %s\n", v->value);
28721       } else if (!strcasecmp(v->name, "externaddr") || !strcasecmp(v->name, "externip")) {
28722          if (ast_parse_arg(v->value, PARSE_ADDR, &externaddr)) {
28723             ast_log(LOG_WARNING,
28724                "Invalid address for externaddr keyword: %s\n",
28725                v->value);
28726          }
28727          externexpire = 0;
28728       } else if (!strcasecmp(v->name, "externhost")) {
28729          ast_copy_string(externhost, v->value, sizeof(externhost));
28730          if (ast_sockaddr_resolve_first(&externaddr, externhost, 0)) {
28731             ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
28732          }
28733          externexpire = time(NULL);
28734       } else if (!strcasecmp(v->name, "externrefresh")) {
28735          if (sscanf(v->value, "%30d", &externrefresh) != 1) {
28736             ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
28737             externrefresh = 10;
28738          }
28739       } else if (!strcasecmp(v->name, "externtcpport")) {
28740          if (!(externtcpport = port_str2int(v->value, 0))) {
28741             ast_log(LOG_WARNING, "Invalid externtcpport value, must be a positive integer between 1 and 65535 at line %d\n", v->lineno);
28742             externtcpport = 0;
28743          }
28744       } else if (!strcasecmp(v->name, "externtlsport")) {
28745          if (!(externtlsport = port_str2int(v->value, STANDARD_TLS_PORT))) {
28746             ast_log(LOG_WARNING, "Invalid externtlsport value, must be a positive integer between 1 and 65535 at line %d\n", v->lineno);
28747          }
28748       } else if (!strcasecmp(v->name, "allow")) {
28749          int error =  ast_parse_allow_disallow(&default_prefs, &sip_cfg.capability, v->value, TRUE);
28750          if (error) {
28751             ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
28752          }
28753       } else if (!strcasecmp(v->name, "disallow")) {
28754          int error =  ast_parse_allow_disallow(&default_prefs, &sip_cfg.capability, v->value, FALSE);
28755          if (error) {
28756             ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
28757          }
28758       } else if (!strcasecmp(v->name, "preferred_codec_only")) {
28759          ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_PREFERRED_CODEC);
28760       } else if (!strcasecmp(v->name, "autoframing")) {
28761          global_autoframing = ast_true(v->value);
28762       } else if (!strcasecmp(v->name, "allowexternaldomains")) {
28763          sip_cfg.allow_external_domains = ast_true(v->value);
28764       } else if (!strcasecmp(v->name, "autodomain")) {
28765          auto_sip_domains = ast_true(v->value);
28766       } else if (!strcasecmp(v->name, "domain")) {
28767          char *domain = ast_strdupa(v->value);
28768          char *cntx = strchr(domain, ',');
28769 
28770          if (cntx) {
28771             *cntx++ = '\0';
28772          }
28773 
28774          if (ast_strlen_zero(cntx)) {
28775             ast_debug(1, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
28776          }
28777          if (ast_strlen_zero(domain)) {
28778             ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
28779          } else {
28780             add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, cntx ? ast_strip(cntx) : "");
28781          }
28782       } else if (!strcasecmp(v->name, "register")) {
28783          if (sip_register(v->value, v->lineno) == 0) {
28784             registry_count++;
28785          }
28786       } else if (!strcasecmp(v->name, "mwi")) {
28787          sip_subscribe_mwi(v->value, v->lineno);
28788       } else if (!strcasecmp(v->name, "tos_sip")) {
28789          if (ast_str2tos(v->value, &global_tos_sip)) {
28790             ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, refer to QoS documentation\n", v->lineno);
28791          }
28792       } else if (!strcasecmp(v->name, "tos_audio")) {
28793          if (ast_str2tos(v->value, &global_tos_audio)) {
28794             ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, refer to QoS documentation\n", v->lineno);
28795          }
28796       } else if (!strcasecmp(v->name, "tos_video")) {
28797          if (ast_str2tos(v->value, &global_tos_video)) {
28798             ast_log(LOG_WARNING, "Invalid tos_video value at line %d, refer to QoS documentation\n", v->lineno);
28799          }
28800       } else if (!strcasecmp(v->name, "tos_text")) {
28801          if (ast_str2tos(v->value, &global_tos_text)) {
28802             ast_log(LOG_WARNING, "Invalid tos_text value at line %d, refer to QoS documentation\n", v->lineno);
28803          }
28804       } else if (!strcasecmp(v->name, "cos_sip")) {
28805          if (ast_str2cos(v->value, &global_cos_sip)) {
28806             ast_log(LOG_WARNING, "Invalid cos_sip value at line %d, refer to QoS documentation\n", v->lineno);
28807          }
28808       } else if (!strcasecmp(v->name, "cos_audio")) {
28809          if (ast_str2cos(v->value, &global_cos_audio)) {
28810             ast_log(LOG_WARNING, "Invalid cos_audio value at line %d, refer to QoS documentation\n", v->lineno);
28811          }
28812       } else if (!strcasecmp(v->name, "cos_video")) {
28813          if (ast_str2cos(v->value, &global_cos_video)) {
28814             ast_log(LOG_WARNING, "Invalid cos_video value at line %d, refer to QoS documentation\n", v->lineno);
28815          }
28816       } else if (!strcasecmp(v->name, "cos_text")) {
28817          if (ast_str2cos(v->value, &global_cos_text)) {
28818             ast_log(LOG_WARNING, "Invalid cos_text value at line %d, refer to QoS documentation\n", v->lineno);
28819          }
28820       } else if (!strcasecmp(v->name, "bindport")) {
28821          if (sscanf(v->value, "%5d", &bindport) != 1) {
28822             ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
28823          }
28824       } else if (!strcasecmp(v->name, "qualify")) {
28825          if (!strcasecmp(v->value, "no")) {
28826             default_qualify = 0;
28827          } else if (!strcasecmp(v->value, "yes")) {
28828             default_qualify = DEFAULT_MAXMS;
28829          } else if (sscanf(v->value, "%30d", &default_qualify) != 1) {
28830             ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
28831             default_qualify = 0;
28832          }
28833       } else if (!strcasecmp(v->name, "qualifyfreq")) {
28834          int i;
28835          if (sscanf(v->value, "%30d", &i) == 1) {
28836             global_qualifyfreq = i * 1000;
28837          } else {
28838             ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
28839             global_qualifyfreq = DEFAULT_QUALIFYFREQ;
28840          }
28841       } else if (!strcasecmp(v->name, "callevents")) {
28842          sip_cfg.callevents = ast_true(v->value);
28843       } else if (!strcasecmp(v->name, "authfailureevents")) {
28844          global_authfailureevents = ast_true(v->value);
28845       } else if (!strcasecmp(v->name, "maxcallbitrate")) {
28846          default_maxcallbitrate = atoi(v->value);
28847          if (default_maxcallbitrate < 0)
28848             default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
28849       } else if (!strcasecmp(v->name, "matchexternaddrlocally") || !strcasecmp(v->name, "matchexterniplocally")) {
28850          sip_cfg.matchexternaddrlocally = ast_true(v->value);
28851       } else if (!strcasecmp(v->name, "session-timers")) {
28852          int i = (int) str2stmode(v->value);
28853          if (i < 0) {
28854             ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
28855             global_st_mode = SESSION_TIMER_MODE_ACCEPT;
28856          } else {
28857             global_st_mode = i;
28858          }
28859       } else if (!strcasecmp(v->name, "session-expires")) {
28860          if (sscanf(v->value, "%30d", &global_max_se) != 1) {
28861             ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
28862             global_max_se = DEFAULT_MAX_SE;
28863          }
28864       } else if (!strcasecmp(v->name, "session-minse")) {
28865          if (sscanf(v->value, "%30d", &global_min_se) != 1) {
28866             ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
28867             global_min_se = DEFAULT_MIN_SE;
28868          }
28869          if (global_min_se < 90) {
28870             ast_log(LOG_WARNING, "session-minse '%s' at line %d of %s is not allowed to be < 90 secs\n", v->value, v->lineno, config);
28871             global_min_se = DEFAULT_MIN_SE;
28872          }
28873       } else if (!strcasecmp(v->name, "session-refresher")) {
28874          int i = (int) str2strefresherparam(v->value);
28875          if (i < 0) {
28876             ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
28877             global_st_refresher = SESSION_TIMER_REFRESHER_PARAM_UAS;
28878          } else {
28879             global_st_refresher = i;
28880          }
28881       } else if (!strcasecmp(v->name, "storesipcause")) {
28882          global_store_sip_cause = ast_true(v->value);
28883       } else if (!strcasecmp(v->name, "qualifygap")) {
28884          if (sscanf(v->value, "%30d", &global_qualify_gap) != 1) {
28885             ast_log(LOG_WARNING, "Invalid qualifygap '%s' at line %d of %s\n", v->value, v->lineno, config);
28886             global_qualify_gap = DEFAULT_QUALIFY_GAP;
28887          }
28888       } else if (!strcasecmp(v->name, "qualifypeers")) {
28889          if (sscanf(v->value, "%30d", &global_qualify_peers) != 1) {
28890             ast_log(LOG_WARNING, "Invalid pokepeers '%s' at line %d of %s\n", v->value, v->lineno, config);
28891             global_qualify_peers = DEFAULT_QUALIFY_PEERS;
28892          }
28893       } else if (!strcasecmp(v->name, "disallowed_methods")) {
28894          char *disallow = ast_strdupa(v->value);
28895          mark_parsed_methods(&sip_cfg.disallowed_methods, disallow);
28896       } else if (!strcasecmp(v->name, "shrinkcallerid")) {
28897          if (ast_true(v->value)) {
28898             global_shrinkcallerid = 1;
28899          } else if (ast_false(v->value)) {
28900             global_shrinkcallerid = 0;
28901          } else {
28902             ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
28903          }
28904       } else if (!strcasecmp(v->name, "use_q850_reason")) {
28905          ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_Q850_REASON);
28906       } else if (!strcasecmp(v->name, "maxforwards")) {
28907          if (sscanf(v->value, "%30d", &sip_cfg.default_max_forwards) != 1
28908             || sip_cfg.default_max_forwards < 1 || 255 < sip_cfg.default_max_forwards) {
28909             ast_log(LOG_WARNING, "'%s' is not a valid maxforwards value at line %d.  Using default.\n", v->value, v->lineno);
28910             sip_cfg.default_max_forwards = DEFAULT_MAX_FORWARDS;
28911          }
28912       } else if (!strcasecmp(v->name, "subscribe_network_change_event")) {
28913          if (ast_true(v->value)) {
28914             subscribe_network_change = 1;
28915          } else if (ast_false(v->value)) {
28916             subscribe_network_change = 0;
28917          } else {
28918             ast_log(LOG_WARNING, "subscribe_network_change_event value %s is not valid at line %d.\n", v->value, v->lineno);
28919          }
28920       } else if (!strcasecmp(v->name, "snom_aoc_enabled")) {
28921          ast_set2_flag(&global_flags[2], ast_true(v->value), SIP_PAGE3_SNOM_AOC);
28922       } else if (!strcasecmp(v->name, "parkinglot")) {
28923          ast_copy_string(default_parkinglot, v->value, sizeof(default_parkinglot));
28924       }
28925    }
28926 
28927    if (subscribe_network_change) {
28928       network_change_event_subscribe();
28929    } else {
28930       network_change_event_unsubscribe();
28931    }
28932 
28933    if (global_t1 < global_t1min) {
28934       ast_log(LOG_WARNING, "'t1min' (%d) cannot be greater than 't1timer' (%d).  Resetting 't1timer' to the value of 't1min'\n", global_t1min, global_t1);
28935       global_t1 = global_t1min;
28936    }
28937 
28938    if (global_timer_b < global_t1 * 64) {
28939       if (timerb_set && timert1_set) {
28940          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);
28941       } else if (timerb_set) {
28942          if ((global_t1 = global_timer_b / 64) < global_t1min) {
28943             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);
28944             global_t1 = global_t1min;
28945             global_timer_b = global_t1 * 64;
28946          }
28947       } else {
28948          global_timer_b = global_t1 * 64;
28949       }
28950    }
28951    if (!sip_cfg.allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
28952       ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
28953       sip_cfg.allow_external_domains = 1;
28954    }
28955    /* If not or badly configured, set default transports */
28956    if (!sip_cfg.tcp_enabled && (default_transports & SIP_TRANSPORT_TCP)) {
28957       ast_log(LOG_WARNING, "Cannot use 'tcp' transport with tcpenable=no. Removing from available transports.\n");
28958       default_primary_transport &= ~SIP_TRANSPORT_TCP;
28959       default_transports &= ~SIP_TRANSPORT_TCP;
28960    }
28961    if (!default_tls_cfg.enabled && (default_transports & SIP_TRANSPORT_TLS)) {
28962       ast_log(LOG_WARNING, "Cannot use 'tls' transport with tlsenable=no. Removing from available transports.\n");
28963       default_primary_transport &= ~SIP_TRANSPORT_TLS;
28964       default_transports &= ~SIP_TRANSPORT_TLS;
28965    }
28966    if (!default_transports) {
28967       ast_log(LOG_WARNING, "No valid transports available, falling back to 'udp'.\n");
28968       default_transports = default_primary_transport = SIP_TRANSPORT_UDP;
28969    } else if (!default_primary_transport) {
28970       ast_log(LOG_WARNING, "No valid default transport. Selecting 'udp' as default.\n");
28971       default_primary_transport = SIP_TRANSPORT_UDP;
28972    }
28973 
28974    /* Build list of authentication to various SIP realms, i.e. service providers */
28975    for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
28976       /* Format for authentication is auth = username:password@realm */
28977       if (!strcasecmp(v->name, "auth")) {
28978          add_realm_authentication(&authl, v->value, v->lineno);
28979       }
28980    }
28981 
28982    if (bindport) {
28983       if (ast_sockaddr_port(&bindaddr)) {
28984          ast_log(LOG_WARNING, "bindport is also specified in bindaddr. "
28985             "Using %d.\n", bindport);
28986       }
28987       ast_sockaddr_set_port(&bindaddr, bindport);
28988    }
28989 
28990    if (!ast_sockaddr_port(&bindaddr)) {
28991       ast_sockaddr_set_port(&bindaddr, STANDARD_SIP_PORT);
28992    }
28993 
28994    /* Set UDP address and open socket */
28995    ast_sockaddr_copy(&internip, &bindaddr);
28996    if (ast_find_ourip(&internip, &bindaddr, 0)) {
28997       ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
28998       ast_config_destroy(cfg);
28999       return 0;
29000    }
29001 
29002    ast_mutex_lock(&netlock);
29003    if ((sipsock > -1) && (ast_sockaddr_cmp(&old_bindaddr, &bindaddr))) {
29004       close(sipsock);
29005       sipsock = -1;
29006    }
29007    if (sipsock < 0) {
29008       sipsock = socket(ast_sockaddr_is_ipv6(&bindaddr) ?
29009              AF_INET6 : AF_INET, SOCK_DGRAM, 0);
29010       if (sipsock < 0) {
29011          ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
29012          ast_config_destroy(cfg);
29013          ast_mutex_unlock(&netlock);
29014          return -1;
29015       } else {
29016          /* Allow SIP clients on the same host to access us: */
29017          const int reuseFlag = 1;
29018 
29019          setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
29020                (const char*)&reuseFlag,
29021                sizeof reuseFlag);
29022 
29023          ast_enable_packet_fragmentation(sipsock);
29024 
29025          if (ast_bind(sipsock, &bindaddr) < 0) {
29026             ast_log(LOG_WARNING, "Failed to bind to %s: %s\n",
29027                ast_sockaddr_stringify(&bindaddr), strerror(errno));
29028             close(sipsock);
29029             sipsock = -1;
29030          } else {
29031             ast_verb(2, "SIP Listening on %s\n", ast_sockaddr_stringify(&bindaddr));
29032             ast_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
29033          }
29034       }
29035    } else {
29036       ast_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
29037    }
29038    ast_mutex_unlock(&netlock);
29039 
29040    /* Start TCP server */
29041    if (sip_cfg.tcp_enabled) {
29042       if (ast_sockaddr_isnull(&sip_tcp_desc.local_address)) {
29043          ast_sockaddr_copy(&sip_tcp_desc.local_address, &bindaddr);
29044       }
29045       if (!ast_sockaddr_port(&sip_tcp_desc.local_address)) {
29046          ast_sockaddr_set_port(&sip_tcp_desc.local_address, STANDARD_SIP_PORT);
29047       }
29048    } else {
29049       ast_sockaddr_setnull(&sip_tcp_desc.local_address);
29050    }
29051    ast_tcptls_server_start(&sip_tcp_desc);
29052    if (sip_cfg.tcp_enabled && sip_tcp_desc.accept_fd == -1) {
29053       /* TCP server start failed. Tell the admin */
29054       ast_log(LOG_ERROR, "SIP TCP Server start failed. Not listening on TCP socket.\n");
29055    } else {
29056       ast_debug(2, "SIP TCP server started\n");
29057    }
29058 
29059    /* Start TLS server if needed */
29060    memcpy(sip_tls_desc.tls_cfg, &default_tls_cfg, sizeof(default_tls_cfg));
29061 
29062    if (ast_ssl_setup(sip_tls_desc.tls_cfg)) {
29063       if (ast_sockaddr_isnull(&sip_tls_desc.local_address)) {
29064          ast_sockaddr_copy(&sip_tls_desc.local_address, &bindaddr);
29065          ast_sockaddr_set_port(&sip_tls_desc.local_address,
29066                      STANDARD_TLS_PORT);
29067       }
29068       if (!ast_sockaddr_port(&sip_tls_desc.local_address)) {
29069          ast_sockaddr_set_port(&sip_tls_desc.local_address,
29070                      STANDARD_TLS_PORT);
29071       }
29072       ast_tcptls_server_start(&sip_tls_desc);
29073       if (default_tls_cfg.enabled && sip_tls_desc.accept_fd == -1) {
29074          ast_log(LOG_ERROR, "TLS Server start failed. Not listening on TLS socket.\n");
29075          sip_tls_desc.tls_cfg = NULL;
29076       }
29077    } else if (sip_tls_desc.tls_cfg->enabled) {
29078       sip_tls_desc.tls_cfg = NULL;
29079       ast_log(LOG_WARNING, "SIP TLS server did not load because of errors.\n");
29080    }
29081 
29082    if (ucfg) {
29083       struct ast_variable *gen;
29084       int genhassip, genregistersip;
29085       const char *hassip, *registersip;
29086       
29087       genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
29088       genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
29089       gen = ast_variable_browse(ucfg, "general");
29090       cat = ast_category_browse(ucfg, NULL);
29091       while (cat) {
29092          if (strcasecmp(cat, "general")) {
29093             hassip = ast_variable_retrieve(ucfg, cat, "hassip");
29094             registersip = ast_variable_retrieve(ucfg, cat, "registersip");
29095             if (ast_true(hassip) || (!hassip && genhassip)) {
29096                peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0, 0);
29097                if (peer) {
29098                   /* user.conf entries are always of type friend */
29099                   peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
29100                   ao2_t_link(peers, peer, "link peer into peer table");
29101                   if ((peer->type & SIP_TYPE_PEER) && !ast_sockaddr_isnull(&peer->addr)) {
29102                      ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
29103                   }
29104                   
29105                   unref_peer(peer, "unref_peer: from reload_config");
29106                   peer_count++;
29107                }
29108             }
29109             if (ast_true(registersip) || (!registersip && genregistersip)) {
29110                char tmp[256];
29111                const char *host = ast_variable_retrieve(ucfg, cat, "host");
29112                const char *username = ast_variable_retrieve(ucfg, cat, "username");
29113                const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
29114                const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
29115                const char *authuser = ast_variable_retrieve(ucfg, cat, "authuser");
29116                if (!host) {
29117                   host = ast_variable_retrieve(ucfg, "general", "host");
29118                }
29119                if (!username) {
29120                   username = ast_variable_retrieve(ucfg, "general", "username");
29121                }
29122                if (!secret) {
29123                   secret = ast_variable_retrieve(ucfg, "general", "secret");
29124                }
29125                if (!contact) {
29126                   contact = "s";
29127                }
29128                if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
29129                   if (!ast_strlen_zero(secret)) {
29130                      if (!ast_strlen_zero(authuser)) {
29131                         snprintf(tmp, sizeof(tmp), "%s?%s:%s:%s@%s/%s", cat, username, secret, authuser, host, contact);
29132                      } else {
29133                         snprintf(tmp, sizeof(tmp), "%s?%s:%s@%s/%s", cat, username, secret, host, contact);
29134                      }
29135                   } else if (!ast_strlen_zero(authuser)) {
29136                      snprintf(tmp, sizeof(tmp), "%s?%s::%s@%s/%s", cat, username, authuser, host, contact);
29137                   } else {
29138                      snprintf(tmp, sizeof(tmp), "%s?%s@%s/%s", cat, username, host, contact);
29139                   }
29140                   if (sip_register(tmp, 0) == 0) {
29141                      registry_count++;
29142                   }
29143                }
29144             }
29145          }
29146          cat = ast_category_browse(ucfg, cat);
29147       }
29148       ast_config_destroy(ucfg);
29149    }
29150 
29151    /* Load peers, users and friends */
29152    cat = NULL;
29153    while ( (cat = ast_category_browse(cfg, cat)) ) {
29154       const char *utype;
29155       if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
29156          continue;
29157       utype = ast_variable_retrieve(cfg, cat, "type");
29158       if (!utype) {
29159          ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
29160          continue;
29161       } else {
29162          if (!strcasecmp(utype, "user")) {
29163             ;
29164          } else if (!strcasecmp(utype, "friend")) {
29165             ;
29166          } else if (!strcasecmp(utype, "peer")) {
29167             ;
29168          } else {
29169             ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
29170             continue;
29171          }
29172          peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0, 0);
29173          if (peer) {
29174             display_nat_warning(cat, reason, &peer->flags[0]);
29175             ao2_t_link(peers, peer, "link peer into peers table");
29176             if ((peer->type & SIP_TYPE_PEER) && !ast_sockaddr_isnull(&peer->addr)) {
29177                ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
29178             }
29179             unref_peer(peer, "unref the result of the build_peer call. Now, the links from the tables are the only ones left.");
29180             peer_count++;
29181          }
29182       }
29183    }
29184 
29185    /* Add default domains - host name, IP address and IP:port
29186     * Only do this if user added any sip domain with "localdomains"
29187     * In order to *not* break backwards compatibility
29188     *    Some phones address us at IP only, some with additional port number
29189     */
29190    if (auto_sip_domains) {
29191       char temp[MAXHOSTNAMELEN];
29192 
29193       /* First our default IP address */
29194       if (!ast_sockaddr_isnull(&bindaddr) && !ast_sockaddr_is_any(&bindaddr)) {
29195          add_sip_domain(ast_sockaddr_stringify_addr(&bindaddr),
29196                    SIP_DOMAIN_AUTO, NULL);
29197       } else if (!ast_sockaddr_isnull(&internip) && !ast_sockaddr_is_any(&internip)) {
29198       /* Our internal IP address, if configured */
29199          add_sip_domain(ast_sockaddr_stringify_addr(&internip),
29200                    SIP_DOMAIN_AUTO, NULL);
29201       } else {
29202          ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
29203       }
29204 
29205       /* If TCP is running on a different IP than UDP, then add it too */
29206       if (!ast_sockaddr_isnull(&sip_tcp_desc.local_address) &&
29207           !ast_sockaddr_cmp(&bindaddr, &sip_tcp_desc.local_address)) {
29208          add_sip_domain(ast_sockaddr_stringify_addr(&sip_tcp_desc.local_address),
29209                    SIP_DOMAIN_AUTO, NULL);
29210       }
29211 
29212       /* If TLS is running on a different IP than UDP and TCP, then add that too */
29213       if (!ast_sockaddr_isnull(&sip_tls_desc.local_address) &&
29214           !ast_sockaddr_cmp(&bindaddr, &sip_tls_desc.local_address) &&
29215           !ast_sockaddr_cmp(&sip_tcp_desc.local_address,
29216                   &sip_tls_desc.local_address)) {
29217          add_sip_domain(ast_sockaddr_stringify_addr(&sip_tcp_desc.local_address),
29218                    SIP_DOMAIN_AUTO, NULL);
29219       }
29220 
29221       /* Our extern IP address, if configured */
29222       if (!ast_sockaddr_isnull(&externaddr)) {
29223          add_sip_domain(ast_sockaddr_stringify_addr(&externaddr),
29224                    SIP_DOMAIN_AUTO, NULL);
29225       }
29226 
29227       /* Extern host name (NAT traversal support) */
29228       if (!ast_strlen_zero(externhost)) {
29229          add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
29230       }
29231       
29232       /* Our host name */
29233       if (!gethostname(temp, sizeof(temp))) {
29234          add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
29235       }
29236    }
29237 
29238    /* Release configuration from memory */
29239    ast_config_destroy(cfg);
29240 
29241    /* Load the list of manual NOTIFY types to support */
29242    if (notify_types)
29243       ast_config_destroy(notify_types);
29244    if ((notify_types = ast_config_load(notify_config, config_flags)) == CONFIG_STATUS_FILEINVALID) {
29245       ast_log(LOG_ERROR, "Contents of %s are invalid and cannot be parsed.\n", notify_config);
29246       notify_types = NULL;
29247    }
29248 
29249    /* Done, tell the manager */
29250    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);
29251    run_end = time(0);
29252    ast_debug(4, "SIP reload_config done...Runtime= %d sec\n", (int)(run_end-run_start));
29253 
29254    return 0;
29255 }
29256 
29257 static int apply_directmedia_ha(struct sip_pvt *p1, struct sip_pvt *p2, const char *op)
29258 {
29259    struct ast_sockaddr us = { { 0, }, }, them = { { 0, }, };
29260    int res = AST_SENSE_ALLOW;
29261 
29262    ast_rtp_instance_get_remote_address(p1->rtp, &them);
29263    ast_rtp_instance_get_local_address(p1->rtp, &us);
29264 
29265    /* If p2 is a guest call, there will be no peer. If there is no peer, there
29266     * is no directmediaha, so go ahead and allow it */
29267    if (!p2->relatedpeer) {
29268       return res;
29269    }
29270 
29271    if ((res = ast_apply_ha(p2->relatedpeer->directmediaha, &them)) == AST_SENSE_DENY) {
29272       const char *us_addr = ast_strdupa(ast_sockaddr_stringify(&us));
29273       const char *them_addr = ast_strdupa(ast_sockaddr_stringify(&them));
29274 
29275       ast_debug(3, "Reinvite %s to %s denied by directmedia ACL on %s\n",
29276          op, them_addr, us_addr);
29277    }
29278 
29279    return res;
29280 }
29281 
29282 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan)
29283 {
29284    struct sip_pvt *p;
29285    struct ast_channel *opp_chan;
29286    struct sip_pvt *opp;
29287    struct ast_udptl *udptl = NULL;
29288 
29289    p = chan->tech_pvt;
29290    if (!p) {
29291       return NULL;
29292    }
29293 
29294    if (!(opp_chan = ast_bridged_channel(chan))) {
29295       return NULL;
29296    } else if (((opp_chan->tech != &sip_tech) && (opp_chan->tech != &sip_tech_info)) ||
29297          (!(opp = opp_chan->tech_pvt))) {
29298       return NULL;
29299    }
29300 
29301    sip_pvt_lock(p);
29302    while (sip_pvt_trylock(opp)) {
29303       sip_pvt_unlock(p);
29304       usleep(1);
29305       sip_pvt_lock(p);
29306    }
29307 
29308    if (p->udptl && ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
29309       if (apply_directmedia_ha(p, opp, "UDPTL T.38 data")) {
29310          udptl = p->udptl;
29311       }
29312    }
29313 
29314    sip_pvt_unlock(opp);
29315    sip_pvt_unlock(p);
29316    return udptl;
29317 }
29318 
29319 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl)
29320 {
29321    struct sip_pvt *p;
29322 
29323    /* Lock the channel and the private safely. */
29324    ast_channel_lock(chan);
29325    p = chan->tech_pvt;
29326    if (!p) {
29327       ast_channel_unlock(chan);
29328       return -1;
29329    }
29330    sip_pvt_lock(p);
29331    if (p->owner != chan) {
29332       /* I suppose it could be argued that if this happens it is a bug. */
29333       ast_debug(1, "The private is not owned by channel %s anymore.\n", chan->name);
29334       sip_pvt_unlock(p);
29335       ast_channel_unlock(chan);
29336       return 0;
29337    }
29338 
29339    if (udptl) {
29340       ast_udptl_get_peer(udptl, &p->udptlredirip);
29341    } else {
29342       memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
29343    }
29344    if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
29345       if (!p->pendinginvite) {
29346          ast_debug(3, "Sending reinvite on SIP '%s' - It's UDPTL soon redirected to IP %s\n",
29347                p->callid, ast_sockaddr_stringify(udptl ? &p->udptlredirip : &p->ourip));
29348          transmit_reinvite_with_sdp(p, TRUE, FALSE);
29349       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
29350          ast_debug(3, "Deferring reinvite on SIP '%s' - It's UDPTL will be redirected to IP %s\n",
29351                p->callid, ast_sockaddr_stringify(udptl ? &p->udptlredirip : &p->ourip));
29352          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
29353       }
29354    }
29355    /* Reset lastrtprx timer */
29356    p->lastrtprx = p->lastrtptx = time(NULL);
29357    sip_pvt_unlock(p);
29358    ast_channel_unlock(chan);
29359    return 0;
29360 }
29361 
29362 static enum ast_rtp_glue_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
29363 {
29364    struct sip_pvt *p = NULL;
29365    struct ast_channel *opp_chan;
29366    struct sip_pvt *opp = NULL;
29367    enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_LOCAL;
29368 
29369    if (!(p = chan->tech_pvt)) {
29370       return AST_RTP_GLUE_RESULT_FORBID;
29371    }
29372 
29373    if ((opp_chan = ast_bridged_channel(chan)) && (((opp_chan->tech != &sip_tech) && (opp_chan->tech != &sip_tech_info)) ||
29374                          (!(opp = opp_chan->tech_pvt)))) {
29375       return AST_RTP_GLUE_RESULT_FORBID;
29376    }
29377 
29378    sip_pvt_lock(p);
29379    while (opp && sip_pvt_trylock(opp)) {
29380       sip_pvt_unlock(p);
29381       usleep(1);
29382       sip_pvt_lock(p);
29383    }
29384 
29385    if (!(p->rtp)) {
29386       if (opp) {
29387          sip_pvt_unlock(opp);
29388       }
29389       sip_pvt_unlock(p);
29390       return AST_RTP_GLUE_RESULT_FORBID;
29391    }
29392 
29393    ao2_ref(p->rtp, +1);
29394    *instance = p->rtp;
29395 
29396    if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
29397       res = AST_RTP_GLUE_RESULT_REMOTE;
29398       if (opp && !apply_directmedia_ha(p, opp, "audio")) {
29399          res = AST_RTP_GLUE_RESULT_FORBID;
29400       }
29401    } else if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT)) {
29402       res = AST_RTP_GLUE_RESULT_REMOTE;
29403    } else if (ast_test_flag(&global_jbconf, AST_JB_FORCED)) {
29404       res = AST_RTP_GLUE_RESULT_FORBID;
29405    }
29406 
29407    if (opp) {
29408       sip_pvt_unlock(opp);
29409    }
29410 
29411    if (p->srtp) {
29412       res = AST_RTP_GLUE_RESULT_FORBID;
29413    }
29414 
29415    sip_pvt_unlock(p);
29416 
29417    return res;
29418 }
29419 
29420 static enum ast_rtp_glue_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
29421 {
29422    struct sip_pvt *p = NULL;
29423    struct ast_channel *opp_chan;
29424    struct sip_pvt *opp = NULL;
29425    enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_FORBID;
29426 
29427    if (!(p = chan->tech_pvt)) {
29428       return AST_RTP_GLUE_RESULT_FORBID;
29429    }
29430 
29431    if ((opp_chan = ast_bridged_channel(chan)) && (((opp_chan->tech != &sip_tech) && (opp_chan->tech != &sip_tech_info)) ||
29432                          (!(opp = opp_chan->tech_pvt)))) {
29433       return AST_RTP_GLUE_RESULT_FORBID;
29434    }
29435 
29436    sip_pvt_lock(p);
29437    while (opp && sip_pvt_trylock(opp)) {
29438       sip_pvt_unlock(p);
29439       usleep(1);
29440       sip_pvt_lock(p);
29441    }
29442 
29443    if (!(p->vrtp)) {
29444       if (opp) {
29445          sip_pvt_unlock(opp);
29446       }
29447       sip_pvt_unlock(p);
29448       return AST_RTP_GLUE_RESULT_FORBID;
29449    }
29450 
29451    ao2_ref(p->vrtp, +1);
29452    *instance = p->vrtp;
29453 
29454    if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
29455       res = AST_RTP_GLUE_RESULT_REMOTE;
29456       if (opp && !apply_directmedia_ha(p, opp, "video")) {
29457          res = AST_RTP_GLUE_RESULT_FORBID;
29458       }
29459    }
29460 
29461    if (opp) {
29462       sip_pvt_unlock(opp);
29463    }
29464    sip_pvt_unlock(p);
29465 
29466    return res;
29467 }
29468 
29469 static enum ast_rtp_glue_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
29470 {
29471    struct sip_pvt *p = NULL;
29472    struct ast_channel *opp_chan;
29473    struct sip_pvt *opp = NULL;
29474    enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_FORBID;
29475 
29476    if (!(p = chan->tech_pvt)) {
29477       return AST_RTP_GLUE_RESULT_FORBID;
29478    }
29479 
29480    if ((opp_chan = ast_bridged_channel(chan)) && (((opp_chan->tech != &sip_tech) && (opp_chan->tech != &sip_tech_info)) ||
29481                          (!(opp = opp_chan->tech_pvt)))) {
29482       return AST_RTP_GLUE_RESULT_FORBID;
29483    }
29484 
29485    sip_pvt_lock(p);
29486    while (opp && sip_pvt_trylock(opp)) {
29487       sip_pvt_unlock(p);
29488       usleep(1);
29489       sip_pvt_lock(p);
29490    }
29491 
29492    if (!(p->trtp)) {
29493       if (opp) {
29494          sip_pvt_unlock(opp);
29495       }
29496       sip_pvt_unlock(p);
29497       return AST_RTP_GLUE_RESULT_FORBID;
29498    }
29499 
29500    ao2_ref(p->trtp, +1);
29501    *instance = p->trtp;
29502 
29503    if (ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA)) {
29504       res = AST_RTP_GLUE_RESULT_REMOTE;
29505       if (opp && !apply_directmedia_ha(p, opp, "text")) {
29506          res = AST_RTP_GLUE_RESULT_FORBID;
29507       }
29508    }
29509 
29510    if (opp) {
29511       sip_pvt_unlock(opp);
29512    }
29513    sip_pvt_unlock(p);
29514 
29515    return res;
29516 }
29517 
29518 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)
29519 {
29520    struct sip_pvt *p;
29521    int changed = 0;
29522 
29523    /* Lock the channel and the private safely. */
29524    ast_channel_lock(chan);
29525    p = chan->tech_pvt;
29526    if (!p) {
29527       ast_channel_unlock(chan);
29528       return -1;
29529    }
29530    sip_pvt_lock(p);
29531    if (p->owner != chan) {
29532       /* I suppose it could be argued that if this happens it is a bug. */
29533       ast_debug(1, "The private is not owned by channel %s anymore.\n", chan->name);
29534       sip_pvt_unlock(p);
29535       ast_channel_unlock(chan);
29536       return 0;
29537    }
29538 
29539    /* Disable early RTP bridge  */
29540    if ((instance || vinstance || tinstance) &&
29541       !ast_bridged_channel(chan) &&
29542       !sip_cfg.directrtpsetup) {
29543       sip_pvt_unlock(p);
29544       ast_channel_unlock(chan);
29545       return 0;
29546    }
29547 
29548    if (p->alreadygone) {
29549       /* If we're destroyed, don't bother */
29550       sip_pvt_unlock(p);
29551       ast_channel_unlock(chan);
29552       return 0;
29553    }
29554 
29555    /* if this peer cannot handle reinvites of the media stream to devices
29556       that are known to be behind a NAT, then stop the process now
29557    */
29558    if (nat_active && !ast_test_flag(&p->flags[0], SIP_DIRECT_MEDIA_NAT)) {
29559       sip_pvt_unlock(p);
29560       ast_channel_unlock(chan);
29561       return 0;
29562    }
29563 
29564    if (instance) {
29565       changed |= ast_rtp_instance_get_and_cmp_remote_address(instance, &p->redirip);
29566 
29567       if (p->rtp) {
29568          /* Prevent audio RTCP reads */
29569          ast_channel_set_fd(chan, 1, -1);
29570          /* Silence RTCP while audio RTP is inactive */
29571          ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 0);
29572       }
29573    } else if (!ast_sockaddr_isnull(&p->redirip)) {
29574       memset(&p->redirip, 0, sizeof(p->redirip));
29575       changed = 1;
29576 
29577       if (p->rtp) {
29578          /* Enable RTCP since it will be inactive if we're coming back
29579           * from a reinvite */
29580          ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_RTCP, 1);
29581          /* Enable audio RTCP reads */
29582          ast_channel_set_fd(chan, 1, ast_rtp_instance_fd(p->rtp, 1));
29583       }
29584    }
29585 
29586    if (vinstance) {
29587       changed |= ast_rtp_instance_get_and_cmp_remote_address(vinstance, &p->vredirip);
29588 
29589       if (p->vrtp) {
29590          /* Prevent video RTCP reads */
29591          ast_channel_set_fd(chan, 3, -1);
29592          /* Silence RTCP while video RTP is inactive */
29593          ast_rtp_instance_set_prop(p->vrtp, AST_RTP_PROPERTY_RTCP, 0);
29594       }
29595    } else if (!ast_sockaddr_isnull(&p->vredirip)) {
29596       memset(&p->vredirip, 0, sizeof(p->vredirip));
29597       changed = 1;
29598 
29599       if (p->vrtp) {
29600          /* Enable RTCP since it will be inactive if we're coming back
29601           * from a reinvite */
29602          ast_rtp_instance_set_prop(p->vrtp, AST_RTP_PROPERTY_RTCP, 1);
29603          /* Enable video RTCP reads */
29604          ast_channel_set_fd(chan, 3, ast_rtp_instance_fd(p->vrtp, 1));
29605       }
29606    }
29607 
29608    if (tinstance) {
29609       changed |= ast_rtp_instance_get_and_cmp_remote_address(tinstance, &p->tredirip);
29610    } else if (!ast_sockaddr_isnull(&p->tredirip)) {
29611       memset(&p->tredirip, 0, sizeof(p->tredirip));
29612       changed = 1;
29613    }
29614    if (codecs && (p->redircodecs != codecs)) {
29615       p->redircodecs = codecs;
29616       changed = 1;
29617    }
29618 
29619    if (ast_test_flag(&p->flags[2], SIP_PAGE3_DIRECT_MEDIA_OUTGOING) && !p->outgoing_call) {
29620       /* We only wish to withhold sending the initial direct media reinvite on the incoming dialog.
29621        * Further direct media reinvites beyond the initial should be sent. In order to allow further
29622        * direct media reinvites to be sent, we clear this flag.
29623        */
29624       ast_clear_flag(&p->flags[2], SIP_PAGE3_DIRECT_MEDIA_OUTGOING);
29625       sip_pvt_unlock(p);
29626       ast_channel_unlock(chan);
29627       return 0;
29628    }
29629 
29630    if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER) && !ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
29631       if (chan->_state != AST_STATE_UP) {     /* We are in early state */
29632          if (p->do_history)
29633             append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
29634          ast_debug(1, "Early remote bridge setting SIP '%s' - Sending media to %s\n", p->callid, ast_sockaddr_stringify(instance ? &p->redirip : &p->ourip));
29635       } else if (!p->pendinginvite) {   /* We are up, and have no outstanding invite */
29636          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));
29637          transmit_reinvite_with_sdp(p, FALSE, FALSE);
29638       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
29639          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));
29640          /* We have a pending Invite. Send re-invite when we're done with the invite */
29641          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
29642       }
29643    }
29644    /* Reset lastrtprx timer */
29645    p->lastrtprx = p->lastrtptx = time(NULL);
29646    sip_pvt_unlock(p);
29647    ast_channel_unlock(chan);
29648    return 0;
29649 }
29650 
29651 static format_t sip_get_codec(struct ast_channel *chan)
29652 {
29653    struct sip_pvt *p = chan->tech_pvt;
29654    return p->peercapability ? p->peercapability : p->capability;
29655 }
29656 
29657 static struct ast_rtp_glue sip_rtp_glue = {
29658    .type = "SIP",
29659    .get_rtp_info = sip_get_rtp_peer,
29660    .get_vrtp_info = sip_get_vrtp_peer,
29661    .get_trtp_info = sip_get_trtp_peer,
29662    .update_peer = sip_set_rtp_peer,
29663    .get_codec = sip_get_codec,
29664 };
29665 
29666 static char *app_dtmfmode = "SIPDtmfMode";
29667 static char *app_sipaddheader = "SIPAddHeader";
29668 static char *app_sipremoveheader = "SIPRemoveHeader";
29669 
29670 /*! \brief Set the DTMFmode for an outbound SIP call (application) */
29671 static int sip_dtmfmode(struct ast_channel *chan, const char *data)
29672 {
29673    struct sip_pvt *p;
29674    const char *mode = data;
29675 
29676    if (!data) {
29677       ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
29678       return 0;
29679    }
29680    ast_channel_lock(chan);
29681    if (!IS_SIP_TECH(chan->tech)) {
29682       ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
29683       ast_channel_unlock(chan);
29684       return 0;
29685    }
29686    p = chan->tech_pvt;
29687    if (!p) {
29688       ast_channel_unlock(chan);
29689       return 0;
29690    }
29691    sip_pvt_lock(p);
29692    if (!strcasecmp(mode, "info")) {
29693       ast_clear_flag(&p->flags[0], SIP_DTMF);
29694       ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
29695       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
29696    } else if (!strcasecmp(mode, "shortinfo")) {
29697       ast_clear_flag(&p->flags[0], SIP_DTMF);
29698       ast_set_flag(&p->flags[0], SIP_DTMF_SHORTINFO);
29699       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
29700    } else if (!strcasecmp(mode, "rfc2833")) {
29701       ast_clear_flag(&p->flags[0], SIP_DTMF);
29702       ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
29703       p->jointnoncodeccapability |= AST_RTP_DTMF;
29704    } else if (!strcasecmp(mode, "inband")) {
29705       ast_clear_flag(&p->flags[0], SIP_DTMF);
29706       ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
29707       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
29708    } else {
29709       ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n", mode);
29710    }
29711    if (p->rtp)
29712       ast_rtp_instance_set_prop(p->rtp, AST_RTP_PROPERTY_DTMF, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
29713    if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) ||
29714        (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO)) {
29715       enable_dsp_detect(p);
29716    } else {
29717       disable_dsp_detect(p);
29718    }
29719    sip_pvt_unlock(p);
29720    ast_channel_unlock(chan);
29721    return 0;
29722 }
29723 
29724 /*! \brief Add a SIP header to an outbound INVITE */
29725 static int sip_addheader(struct ast_channel *chan, const char *data)
29726 {
29727    int no = 0;
29728    int ok = FALSE;
29729    char varbuf[30];
29730    const char *inbuf = data;
29731    char *subbuf;
29732    
29733    if (ast_strlen_zero(inbuf)) {
29734       ast_log(LOG_WARNING, "This application requires the argument: Header\n");
29735       return 0;
29736    }
29737    ast_channel_lock(chan);
29738 
29739    /* Check for headers */
29740    while (!ok && no <= 50) {
29741       no++;
29742       snprintf(varbuf, sizeof(varbuf), "__SIPADDHEADER%.2d", no);
29743 
29744       /* Compare without the leading underscores */
29745       if ((pbx_builtin_getvar_helper(chan, (const char *) varbuf + 2) == (const char *) NULL)) {
29746          ok = TRUE;
29747       }
29748    }
29749    if (ok) {
29750       size_t len = strlen(inbuf);
29751       subbuf = ast_alloca(len + 1);
29752       ast_get_encoded_str(inbuf, subbuf, len + 1);
29753       pbx_builtin_setvar_helper(chan, varbuf, subbuf);
29754       if (sipdebug) {
29755          ast_debug(1, "SIP Header added \"%s\" as %s\n", inbuf, varbuf);
29756       }
29757    } else {
29758       ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
29759    }
29760    ast_channel_unlock(chan);
29761    return 0;
29762 }
29763 
29764 /*! \brief Remove SIP headers added previously with SipAddHeader application */
29765 static int sip_removeheader(struct ast_channel *chan, const char *data)
29766 {
29767    struct ast_var_t *newvariable;
29768    struct varshead *headp;
29769    int removeall = 0;
29770    char *inbuf = (char *) data;
29771 
29772    if (ast_strlen_zero(inbuf)) {
29773       removeall = 1;
29774    }
29775    ast_channel_lock(chan);
29776 
29777    headp=&chan->varshead;
29778    AST_LIST_TRAVERSE_SAFE_BEGIN (headp, newvariable, entries) {
29779       if (strncasecmp(ast_var_name(newvariable), "SIPADDHEADER", strlen("SIPADDHEADER")) == 0) {
29780          if (removeall || (!strncasecmp(ast_var_value(newvariable),inbuf,strlen(inbuf)))) {
29781             if (sipdebug)
29782                ast_debug(1,"removing SIP Header \"%s\" as %s\n",
29783                   ast_var_value(newvariable),
29784                   ast_var_name(newvariable));
29785             AST_LIST_REMOVE_CURRENT(entries);
29786             ast_var_delete(newvariable);
29787          }
29788       }
29789    }
29790    AST_LIST_TRAVERSE_SAFE_END;
29791 
29792    ast_channel_unlock(chan);
29793    return 0;
29794 }
29795 
29796 /*! \brief Transfer call before connect with a 302 redirect
29797 \note Called by the transfer() dialplan application through the sip_transfer()
29798    pbx interface function if the call is in ringing state
29799 \todo Fix this function so that we wait for reply to the REFER and
29800    react to errors, denials or other issues the other end might have.
29801  */
29802 static int sip_sipredirect(struct sip_pvt *p, const char *dest)
29803 {
29804    char *cdest;
29805    char *extension, *domain;
29806 
29807    cdest = ast_strdupa(dest);
29808 
29809    extension = strsep(&cdest, "@");
29810    domain = cdest;
29811    if (ast_strlen_zero(extension)) {
29812       ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
29813       return 0;
29814    }
29815 
29816    /* we'll issue the redirect message here */
29817    if (!domain) {
29818       char *local_to_header;
29819       char to_header[256];
29820 
29821       ast_copy_string(to_header, get_header(&p->initreq, "To"), sizeof(to_header));
29822       if (ast_strlen_zero(to_header)) {
29823          ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
29824          return 0;
29825       }
29826       if (((local_to_header = strcasestr(to_header, "sip:")) || (local_to_header = strcasestr(to_header, "sips:")))
29827          && (local_to_header = strchr(local_to_header, '@'))) {
29828          char ldomain[256];
29829 
29830          memset(ldomain, 0, sizeof(ldomain));
29831          local_to_header++;
29832          /* This is okey because lhost and lport are as big as tmp */
29833          sscanf(local_to_header, "%256[^<>; ]", ldomain);
29834          if (ast_strlen_zero(ldomain)) {
29835             ast_log(LOG_ERROR, "Can't find the host address\n");
29836             return 0;
29837          }
29838          domain = ast_strdupa(ldomain);
29839       }
29840    }
29841 
29842    ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s>", extension, domain);
29843    transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);
29844 
29845    sip_scheddestroy(p, SIP_TRANS_TIMEOUT);   /* Make sure we stop send this reply. */
29846    sip_alreadygone(p);
29847 
29848    if (p->owner) {
29849       enum ast_control_transfer message = AST_TRANSFER_SUCCESS;
29850       ast_queue_control_data(p->owner, AST_CONTROL_TRANSFER, &message, sizeof(message));
29851    }
29852    /* hangup here */
29853    return 0;
29854 }
29855 
29856 static int sip_is_xml_parsable(void)
29857 {
29858 #ifdef HAVE_LIBXML2
29859    return TRUE;
29860 #else
29861    return FALSE;
29862 #endif
29863 }
29864 
29865 /*! \brief Send a poke to all known peers */
29866 static void sip_poke_all_peers(void)
29867 {
29868    int ms = 0, num = 0;
29869    struct ao2_iterator i;
29870    struct sip_peer *peer;
29871 
29872    if (!speerobjs) { /* No peers, just give up */
29873       return;
29874    }
29875 
29876    i = ao2_iterator_init(peers, 0);
29877    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
29878       ao2_lock(peer);
29879       /* Don't schedule poking on a peer without qualify */
29880       if (peer->maxms) {
29881          if (num == global_qualify_peers) {
29882             ms += global_qualify_gap;
29883             num = 0;
29884          } else {
29885             num++;
29886          }
29887          AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ms, sip_poke_peer_s, peer,
29888                unref_peer(_data, "removing poke peer ref"),
29889                unref_peer(peer, "removing poke peer ref"),
29890                ref_peer(peer, "adding poke peer ref"));
29891       }
29892       ao2_unlock(peer);
29893       unref_peer(peer, "toss iterator peer ptr");
29894    }
29895    ao2_iterator_destroy(&i);
29896 }
29897 
29898 /*! \brief Send all known registrations */
29899 static void sip_send_all_registers(void)
29900 {
29901    int ms;
29902    int regspacing;
29903    if (!regobjs)
29904       return;
29905    regspacing = default_expiry * 1000/regobjs;
29906    if (regspacing > 100) {
29907       regspacing = 100;
29908    }
29909    ms = regspacing;
29910    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
29911       ASTOBJ_WRLOCK(iterator);
29912       ms += regspacing;
29913       AST_SCHED_REPLACE_UNREF(iterator->expire, sched, ms, sip_reregister, iterator,
29914                         registry_unref(_data, "REPLACE sched del decs the refcount"),
29915                         registry_unref(iterator, "REPLACE sched add failure decs the refcount"),
29916                         registry_addref(iterator, "REPLACE sched add incs the refcount"));
29917       ASTOBJ_UNLOCK(iterator);
29918    } while (0)
29919    );
29920 }
29921 
29922 /*! \brief Send all MWI subscriptions */
29923 static void sip_send_all_mwi_subscriptions(void)
29924 {
29925    ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
29926       struct sip_subscription_mwi *saved;
29927       ASTOBJ_WRLOCK(iterator);
29928       AST_SCHED_DEL(sched, iterator->resub);
29929       saved = ASTOBJ_REF(iterator);
29930       if ((iterator->resub = ast_sched_add(sched, 1, sip_subscribe_mwi_do, saved)) < 0) {
29931          ASTOBJ_UNREF(saved, sip_subscribe_mwi_destroy);
29932       }
29933       ASTOBJ_UNLOCK(iterator);
29934    } while (0));
29935 }
29936 
29937 /* SRTP */
29938 static int setup_srtp(struct sip_srtp **srtp)
29939 {
29940    if (!ast_rtp_engine_srtp_is_registered()) {
29941       ast_log(LOG_ERROR, "No SRTP module loaded, can't setup SRTP session.\n");
29942       return -1;
29943    }
29944 
29945    if (!(*srtp = sip_srtp_alloc())) { /* Allocate SRTP data structure */
29946       return -1;
29947    }
29948 
29949    return 0;
29950 }
29951 
29952 static int process_crypto(struct sip_pvt *p, struct ast_rtp_instance *rtp, struct sip_srtp **srtp, const char *a)
29953 {
29954    /* If no RTP instance exists for this media stream don't bother processing the crypto line */
29955    if (!rtp) {
29956       ast_debug(3, "Received offer with crypto line for media stream that is not enabled\n");
29957       return FALSE;
29958    }
29959 
29960    if (strncasecmp(a, "crypto:", 7)) {
29961       return FALSE;
29962    }
29963    if (!*srtp) {
29964       if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
29965          ast_log(LOG_WARNING, "Ignoring unexpected crypto attribute in SDP answer\n");
29966          return FALSE;
29967       }
29968 
29969       if (setup_srtp(srtp) < 0) {
29970          return FALSE;
29971       }
29972    }
29973 
29974    if (!(*srtp)->crypto && !((*srtp)->crypto = sdp_crypto_setup())) {
29975       return FALSE;
29976    }
29977 
29978    if (sdp_crypto_process((*srtp)->crypto, a, rtp) < 0) {
29979       return FALSE;
29980    }
29981 
29982    ast_set_flag(*srtp, SRTP_CRYPTO_OFFER_OK);
29983 
29984    return TRUE;
29985 }
29986 
29987 /*! \brief Reload module */
29988 static int sip_do_reload(enum channelreloadreason reason)
29989 {
29990    time_t start_poke, end_poke;
29991    
29992    reload_config(reason);
29993    ast_sched_dump(sched);
29994 
29995    start_poke = time(0);
29996    /* Prune peers who still are supposed to be deleted */
29997    unlink_marked_peers_from_tables();
29998 
29999    ast_debug(4, "--------------- Done destroying pruned peers\n");
30000 
30001    /* Send qualify (OPTIONS) to all peers */
30002    sip_poke_all_peers();
30003 
30004    /* Register with all services */
30005    sip_send_all_registers();
30006 
30007    sip_send_all_mwi_subscriptions();
30008 
30009    end_poke = time(0);
30010    
30011    ast_debug(4, "do_reload finished. peer poke/prune reg contact time = %d sec.\n", (int)(end_poke-start_poke));
30012 
30013    ast_debug(4, "--------------- SIP reload done\n");
30014 
30015    return 0;
30016 }
30017 
30018 /*! \brief Force reload of module from cli */
30019 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
30020 {
30021    
30022    switch (cmd) {
30023    case CLI_INIT:
30024       e->command = "sip reload";
30025       e->usage =
30026          "Usage: sip reload\n"
30027          "       Reloads SIP configuration from sip.conf\n";
30028       return NULL;
30029    case CLI_GENERATE:
30030       return NULL;
30031    }
30032 
30033    ast_mutex_lock(&sip_reload_lock);
30034    if (sip_reloading) {
30035       ast_verbose("Previous SIP reload not yet done\n");
30036    } else {
30037       sip_reloading = TRUE;
30038       sip_reloadreason = (a && a->fd) ? CHANNEL_CLI_RELOAD : CHANNEL_MODULE_RELOAD;
30039    }
30040    ast_mutex_unlock(&sip_reload_lock);
30041    restart_monitor();
30042 
30043    return CLI_SUCCESS;
30044 }
30045 
30046 /*! \brief  Part of Asterisk module interface */
30047 static int reload(void)
30048 {
30049    if (sip_reload(0, 0, NULL))
30050       return 0;
30051    return 1;
30052 }
30053 
30054 /*! \brief  Return the first entry from ast_sockaddr_resolve filtered by address family
30055  *
30056  * \warn Using this function probably means you have a faulty design.
30057  */
30058 static int ast_sockaddr_resolve_first_af(struct ast_sockaddr *addr,
30059                   const char* name, int flag, int family)
30060 {
30061    struct ast_sockaddr *addrs;
30062    int addrs_cnt;
30063 
30064    addrs_cnt = ast_sockaddr_resolve(&addrs, name, flag, family);
30065    if (addrs_cnt <= 0) {
30066       return 1;
30067    }
30068    if (addrs_cnt > 1) {
30069       ast_debug(1, "Multiple addresses, using the first one only\n");
30070    }
30071 
30072    ast_sockaddr_copy(addr, &addrs[0]);
30073 
30074    ast_free(addrs);
30075    return 0;
30076 }
30077 
30078 /*! \brief  Return the first entry from ast_sockaddr_resolve filtered by family of binddaddr
30079  *
30080  * \warn Using this function probably means you have a faulty design.
30081  */
30082 static int ast_sockaddr_resolve_first(struct ast_sockaddr *addr,
30083                   const char* name, int flag)
30084 {
30085    return ast_sockaddr_resolve_first_af(addr, name, flag, get_address_family_filter(SIP_TRANSPORT_UDP));
30086 }
30087 
30088 /*! \brief  Return the first entry from ast_sockaddr_resolve filtered by family of binddaddr
30089  *
30090  * \warn Using this function probably means you have a faulty design.
30091  */
30092 static int ast_sockaddr_resolve_first_transport(struct ast_sockaddr *addr,
30093                   const char* name, int flag, unsigned int transport)
30094 {
30095         return ast_sockaddr_resolve_first_af(addr, name, flag, get_address_family_filter(transport));
30096 }
30097 
30098 /*! \brief
30099  * \note The only member of the peer used here is the name field
30100  */
30101 static int peer_hash_cb(const void *obj, const int flags)
30102 {
30103    const struct sip_peer *peer = obj;
30104 
30105    return ast_str_case_hash(peer->name);
30106 }
30107 
30108 /*!
30109  * \note The only member of the peer used here is the name field
30110  */
30111 static int peer_cmp_cb(void *obj, void *arg, int flags)
30112 {
30113    struct sip_peer *peer = obj, *peer2 = arg;
30114 
30115    return !strcasecmp(peer->name, peer2->name) ? CMP_MATCH | CMP_STOP : 0;
30116 }
30117 
30118 /*!
30119  * Hash function based on the the peer's ip address.  For IPv6, we use the end
30120  * of the address.
30121  * \todo Find a better hashing function
30122  */
30123 static int peer_iphash_cb(const void *obj, const int flags)
30124 {
30125    const struct sip_peer *peer = obj;
30126    int ret = 0;
30127 
30128    if (ast_sockaddr_isnull(&peer->addr)) {
30129       ast_log(LOG_ERROR, "Empty address\n");
30130    }
30131 
30132    ret = ast_sockaddr_hash(&peer->addr);
30133 
30134    if (ret < 0) {
30135       ret = -ret;
30136    }
30137 
30138    return ret;
30139 }
30140 
30141 /*!
30142  * Match Peers by IP and Port number.
30143  *
30144  * This function has two modes.
30145  *  - If the peer arg does not have INSECURE_PORT set, then we will only return
30146  *    a match for a peer that matches both the IP and port.
30147  *  - If the peer arg does have the INSECURE_PORT flag set, then we will only
30148  *    return a match for a peer that matches the IP and has insecure=port
30149  *    in its configuration.
30150  *
30151  * This callback will be used twice when doing peer matching.  There is a first
30152  * pass for full IP+port matching, and a second pass in case there is a match
30153  * that meets the insecure=port criteria.
30154  *
30155  * \note Connections coming in over TCP or TLS should never be matched by port.
30156  *
30157  * \note the peer's addr struct provides to fields combined to make a key: the sin_addr.s_addr and sin_port fields.
30158  */
30159 static int peer_ipcmp_cb(void *obj, void *arg, int flags)
30160 {
30161    struct sip_peer *peer = obj, *peer2 = arg;
30162 
30163    if (ast_sockaddr_cmp_addr(&peer->addr, &peer2->addr)) {
30164       /* IP doesn't match */
30165       return 0;
30166    }
30167 
30168    /* We matched the IP, check to see if we need to match by port as well. */
30169    if ((peer->transports & peer2->transports) & (SIP_TRANSPORT_TLS | SIP_TRANSPORT_TCP)) {
30170       /* peer matching on port is not possible with TCP/TLS */
30171       return CMP_MATCH | CMP_STOP;
30172    } else if (ast_test_flag(&peer2->flags[0], SIP_INSECURE_PORT)) {
30173       /* We are allowing match without port for peers configured that
30174        * way in this pass through the peers. */
30175       return ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT) ?
30176             (CMP_MATCH | CMP_STOP) : 0;
30177    }
30178 
30179    /* Now only return a match if the port matches, as well. */
30180    return ast_sockaddr_port(&peer->addr) == ast_sockaddr_port(&peer2->addr) ?
30181          (CMP_MATCH | CMP_STOP) : 0;
30182 }
30183 
30184 
30185 static int threadt_hash_cb(const void *obj, const int flags)
30186 {
30187    const struct sip_threadinfo *th = obj;
30188 
30189    return ast_sockaddr_hash(&th->tcptls_session->remote_address);
30190 }
30191 
30192 static int threadt_cmp_cb(void *obj, void *arg, int flags)
30193 {
30194    struct sip_threadinfo *th = obj, *th2 = arg;
30195 
30196    return (th->tcptls_session == th2->tcptls_session) ? CMP_MATCH | CMP_STOP : 0;
30197 }
30198 
30199 /*!
30200  * \note The only member of the dialog used here callid string
30201  */
30202 static int dialog_hash_cb(const void *obj, const int flags)
30203 {
30204    const struct sip_pvt *pvt = obj;
30205 
30206    return ast_str_case_hash(pvt->callid);
30207 }
30208 
30209 /*!
30210  * \note Same as dialog_cmp_cb, except without the CMP_STOP on match
30211  */
30212 static int dialog_find_multiple(void *obj, void *arg, int flags)
30213 {
30214    struct sip_pvt *pvt = obj, *pvt2 = arg;
30215 
30216    return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH : 0;
30217 }
30218 
30219 /*!
30220  * \note The only member of the dialog used here callid string
30221  */
30222 static int dialog_cmp_cb(void *obj, void *arg, int flags)
30223 {
30224    struct sip_pvt *pvt = obj, *pvt2 = arg;
30225 
30226    return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH | CMP_STOP : 0;
30227 }
30228 
30229 /*! \brief SIP Cli commands definition */
30230 static struct ast_cli_entry cli_sip[] = {
30231    AST_CLI_DEFINE(sip_show_channels, "List active SIP channels or subscriptions"),
30232    AST_CLI_DEFINE(sip_show_channelstats, "List statistics for active SIP channels"),
30233    AST_CLI_DEFINE(sip_show_domains, "List our local SIP domains"),
30234    AST_CLI_DEFINE(sip_show_inuse, "List all inuse/limits"),
30235    AST_CLI_DEFINE(sip_show_objects, "List all SIP object allocations"),
30236    AST_CLI_DEFINE(sip_show_peers, "List defined SIP peers"),
30237    AST_CLI_DEFINE(sip_show_registry, "List SIP registration status"),
30238    AST_CLI_DEFINE(sip_unregister, "Unregister (force expiration) a SIP peer from the registry"),
30239    AST_CLI_DEFINE(sip_show_settings, "Show SIP global settings"),
30240    AST_CLI_DEFINE(sip_show_mwi, "Show MWI subscriptions"),
30241    AST_CLI_DEFINE(sip_cli_notify, "Send a notify packet to a SIP peer"),
30242    AST_CLI_DEFINE(sip_show_channel, "Show detailed SIP channel info"),
30243    AST_CLI_DEFINE(sip_show_history, "Show SIP dialog history"),
30244    AST_CLI_DEFINE(sip_show_peer, "Show details on specific SIP peer"),
30245    AST_CLI_DEFINE(sip_show_users, "List defined SIP users"),
30246    AST_CLI_DEFINE(sip_show_user, "Show details on specific SIP user"),
30247    AST_CLI_DEFINE(sip_qualify_peer, "Send an OPTIONS packet to a peer"),
30248    AST_CLI_DEFINE(sip_show_sched, "Present a report on the status of the scheduler queue"),
30249    AST_CLI_DEFINE(sip_prune_realtime, "Prune cached Realtime users/peers"),
30250    AST_CLI_DEFINE(sip_do_debug, "Enable/Disable SIP debugging"),
30251    AST_CLI_DEFINE(sip_set_history, "Enable/Disable SIP history"),
30252    AST_CLI_DEFINE(sip_reload, "Reload SIP configuration"),
30253    AST_CLI_DEFINE(sip_show_tcp, "List TCP Connections")
30254 };
30255 
30256 /*! \brief SIP test registration */
30257 static void sip_register_tests(void)
30258 {
30259    sip_config_parser_register_tests();
30260    sip_request_parser_register_tests();
30261    sip_dialplan_function_register_tests();
30262 }
30263 
30264 /*! \brief SIP test registration */
30265 static void sip_unregister_tests(void)
30266 {
30267    sip_config_parser_unregister_tests();
30268    sip_request_parser_unregister_tests();
30269    sip_dialplan_function_unregister_tests();
30270 }
30271 
30272 #ifdef TEST_FRAMEWORK
30273 AST_TEST_DEFINE(test_sip_mwi_subscribe_parse)
30274 {
30275    int found = 0;
30276    enum ast_test_result_state res = AST_TEST_PASS;
30277    const char *mwi1 = "1234@mysipprovider.com/1234";
30278    const char *mwi2 = "1234:password@mysipprovider.com/1234";
30279    const char *mwi3 = "1234:password@mysipprovider.com:5061/1234";
30280    const char *mwi4 = "1234:password:authuser@mysipprovider.com/1234";
30281    const char *mwi5 = "1234:password:authuser@mysipprovider.com:5061/1234";
30282    const char *mwi6 = "1234:password";
30283 
30284    switch (cmd) {
30285    case TEST_INIT:
30286       info->name = "sip_mwi_subscribe_parse_test";
30287       info->category = "/channels/chan_sip/";
30288       info->summary = "SIP MWI subscribe line parse unit test";
30289       info->description =
30290          "Tests the parsing of mwi subscription lines (e.g., mwi => from sip.conf)";
30291       return AST_TEST_NOT_RUN;
30292    case TEST_EXECUTE:
30293       break;
30294    }
30295 
30296    if (sip_subscribe_mwi(mwi1, 1)) {
30297       res = AST_TEST_FAIL;
30298    } else {
30299       found = 0;
30300       res = AST_TEST_FAIL;
30301       ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
30302          ASTOBJ_WRLOCK(iterator);
30303          if (
30304             !strcmp(iterator->hostname, "mysipprovider.com") &&
30305             !strcmp(iterator->username, "1234") &&
30306             !strcmp(iterator->secret, "") &&
30307             !strcmp(iterator->authuser, "") &&
30308             !strcmp(iterator->mailbox, "1234") &&
30309             iterator->portno == 0) {
30310             found = 1;
30311             res = AST_TEST_PASS;
30312          }
30313          ASTOBJ_UNLOCK(iterator);
30314       } while(0));
30315       if (!found) {
30316          ast_test_status_update(test, "sip_subscribe_mwi test 1 failed\n");
30317       }
30318    }
30319 
30320    if (sip_subscribe_mwi(mwi2, 1)) {
30321       res = AST_TEST_FAIL;
30322    } else {
30323       found = 0;
30324       res = AST_TEST_FAIL;
30325       ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
30326          ASTOBJ_WRLOCK(iterator);
30327          if (
30328             !strcmp(iterator->hostname, "mysipprovider.com") &&
30329             !strcmp(iterator->username, "1234") &&
30330             !strcmp(iterator->secret, "password") &&
30331             !strcmp(iterator->authuser, "") &&
30332             !strcmp(iterator->mailbox, "1234") &&
30333             iterator->portno == 0) {
30334             found = 1;
30335             res = AST_TEST_PASS;
30336          }
30337          ASTOBJ_UNLOCK(iterator);
30338       } while(0));
30339       if (!found) {
30340          ast_test_status_update(test, "sip_subscribe_mwi test 2 failed\n");
30341       }
30342    }
30343 
30344    if (sip_subscribe_mwi(mwi3, 1)) {
30345       res = AST_TEST_FAIL;
30346    } else {
30347       found = 0;
30348       res = AST_TEST_FAIL;
30349       ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
30350          ASTOBJ_WRLOCK(iterator);
30351          if (
30352             !strcmp(iterator->hostname, "mysipprovider.com") &&
30353             !strcmp(iterator->username, "1234") &&
30354             !strcmp(iterator->secret, "password") &&
30355             !strcmp(iterator->authuser, "") &&
30356             !strcmp(iterator->mailbox, "1234") &&
30357             iterator->portno == 5061) {
30358             found = 1;
30359             res = AST_TEST_PASS;
30360          }
30361          ASTOBJ_UNLOCK(iterator);
30362       } while(0));
30363       if (!found) {
30364          ast_test_status_update(test, "sip_subscribe_mwi test 3 failed\n");
30365       }
30366    }
30367 
30368    if (sip_subscribe_mwi(mwi4, 1)) {
30369       res = AST_TEST_FAIL;
30370    } else {
30371       found = 0;
30372       res = AST_TEST_FAIL;
30373       ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
30374          ASTOBJ_WRLOCK(iterator);
30375          if (
30376             !strcmp(iterator->hostname, "mysipprovider.com") &&
30377             !strcmp(iterator->username, "1234") &&
30378             !strcmp(iterator->secret, "password") &&
30379             !strcmp(iterator->authuser, "authuser") &&
30380             !strcmp(iterator->mailbox, "1234") &&
30381             iterator->portno == 0) {
30382             found = 1;
30383             res = AST_TEST_PASS;
30384          }
30385          ASTOBJ_UNLOCK(iterator);
30386       } while(0));
30387       if (!found) {
30388          ast_test_status_update(test, "sip_subscribe_mwi test 4 failed\n");
30389       }
30390    }
30391 
30392    if (sip_subscribe_mwi(mwi5, 1)) {
30393       res = AST_TEST_FAIL;
30394    } else {
30395       found = 0;
30396       res = AST_TEST_FAIL;
30397       ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
30398          ASTOBJ_WRLOCK(iterator);
30399          if (
30400             !strcmp(iterator->hostname, "mysipprovider.com") &&
30401             !strcmp(iterator->username, "1234") &&
30402             !strcmp(iterator->secret, "password") &&
30403             !strcmp(iterator->authuser, "authuser") &&
30404             !strcmp(iterator->mailbox, "1234") &&
30405             iterator->portno == 5061) {
30406             found = 1;
30407             res = AST_TEST_PASS;
30408          }
30409          ASTOBJ_UNLOCK(iterator);
30410       } while(0));
30411       if (!found) {
30412          ast_test_status_update(test, "sip_subscribe_mwi test 5 failed\n");
30413       }
30414    }
30415    
30416    if (sip_subscribe_mwi(mwi6, 1)) {
30417       res = AST_TEST_PASS;
30418    } else {
30419       res = AST_TEST_FAIL;
30420    }
30421    return res;
30422 }
30423 
30424 AST_TEST_DEFINE(test_sip_peers_get)
30425 {
30426    struct sip_peer *peer;
30427    struct ast_data *node;
30428    struct ast_data_query query = {
30429       .path = "/asterisk/channel/sip/peers",
30430       .search = "peers/peer/name=test_peer_data_provider"
30431    };
30432 
30433    switch (cmd) {
30434       case TEST_INIT:
30435          info->name = "sip_peers_get_data_test";
30436          info->category = "/main/data/sip/peers/";
30437          info->summary = "SIP peers data providers unit test";
30438          info->description =
30439             "Tests whether the SIP peers data provider implementation works as expected.";
30440          return AST_TEST_NOT_RUN;
30441       case TEST_EXECUTE:
30442          break;
30443    }
30444 
30445    /* Create the peer that we will retrieve. */
30446    peer = build_peer("test_peer_data_provider", NULL, NULL, 0, 0);
30447    if (!peer) {
30448       return AST_TEST_FAIL;
30449    }
30450    peer->type = SIP_TYPE_USER;
30451    peer->call_limit = 10;
30452    ao2_link(peers, peer);
30453 
30454    /* retrieve the chan_sip/peers tree and check the created peer. */
30455    node = ast_data_get(&query);
30456    if (!node) {
30457       ao2_unlink(peers, peer);
30458       ao2_ref(peer, -1);
30459       return AST_TEST_FAIL;
30460    }
30461 
30462    /* compare item. */
30463    if (strcmp(ast_data_retrieve_string(node, "peer/name"), "test_peer_data_provider")) {
30464       ao2_unlink(peers, peer);
30465       ao2_ref(peer, -1);
30466       ast_data_free(node);
30467       return AST_TEST_FAIL;
30468    }
30469 
30470    if (strcmp(ast_data_retrieve_string(node, "peer/type"), "user")) {
30471       ao2_unlink(peers, peer);
30472       ao2_ref(peer, -1);
30473       ast_data_free(node);
30474       return AST_TEST_FAIL;
30475    }
30476 
30477    if (ast_data_retrieve_int(node, "peer/call_limit") != 10) {
30478       ao2_unlink(peers, peer);
30479       ao2_ref(peer, -1);
30480       ast_data_free(node);
30481       return AST_TEST_FAIL;
30482    }
30483 
30484    /* release resources */
30485    ast_data_free(node);
30486 
30487    ao2_unlink(peers, peer);
30488    ao2_ref(peer, -1);
30489 
30490    return AST_TEST_PASS;
30491 }
30492 
30493 #endif
30494 
30495 #define DATA_EXPORT_SIP_PEER(MEMBER)            \
30496    MEMBER(sip_peer, name, AST_DATA_STRING)         \
30497    MEMBER(sip_peer, secret, AST_DATA_PASSWORD)     \
30498    MEMBER(sip_peer, md5secret, AST_DATA_PASSWORD)     \
30499    MEMBER(sip_peer, remotesecret, AST_DATA_PASSWORD)  \
30500    MEMBER(sip_peer, context, AST_DATA_STRING)      \
30501    MEMBER(sip_peer, subscribecontext, AST_DATA_STRING)   \
30502    MEMBER(sip_peer, username, AST_DATA_STRING)     \
30503    MEMBER(sip_peer, accountcode, AST_DATA_STRING)     \
30504    MEMBER(sip_peer, tohost, AST_DATA_STRING)    \
30505    MEMBER(sip_peer, regexten, AST_DATA_STRING)     \
30506    MEMBER(sip_peer, fromuser, AST_DATA_STRING)     \
30507    MEMBER(sip_peer, fromdomain, AST_DATA_STRING)      \
30508    MEMBER(sip_peer, fullcontact, AST_DATA_STRING)     \
30509    MEMBER(sip_peer, cid_num, AST_DATA_STRING)      \
30510    MEMBER(sip_peer, cid_name, AST_DATA_STRING)     \
30511    MEMBER(sip_peer, vmexten, AST_DATA_STRING)      \
30512    MEMBER(sip_peer, language, AST_DATA_STRING)     \
30513    MEMBER(sip_peer, mohinterpret, AST_DATA_STRING)    \
30514    MEMBER(sip_peer, mohsuggest, AST_DATA_STRING)      \
30515    MEMBER(sip_peer, parkinglot, AST_DATA_STRING)      \
30516    MEMBER(sip_peer, useragent, AST_DATA_STRING)    \
30517    MEMBER(sip_peer, mwi_from, AST_DATA_STRING)     \
30518    MEMBER(sip_peer, engine, AST_DATA_STRING)    \
30519    MEMBER(sip_peer, unsolicited_mailbox, AST_DATA_STRING)   \
30520    MEMBER(sip_peer, is_realtime, AST_DATA_BOOLEAN)    \
30521    MEMBER(sip_peer, host_dynamic, AST_DATA_BOOLEAN)   \
30522    MEMBER(sip_peer, autoframing, AST_DATA_BOOLEAN)    \
30523    MEMBER(sip_peer, inUse, AST_DATA_INTEGER)    \
30524    MEMBER(sip_peer, inRinging, AST_DATA_INTEGER)      \
30525    MEMBER(sip_peer, onHold, AST_DATA_INTEGER)      \
30526    MEMBER(sip_peer, call_limit, AST_DATA_INTEGER)     \
30527    MEMBER(sip_peer, t38_maxdatagram, AST_DATA_INTEGER)   \
30528    MEMBER(sip_peer, maxcallbitrate, AST_DATA_INTEGER) \
30529    MEMBER(sip_peer, rtptimeout, AST_DATA_SECONDS)     \
30530    MEMBER(sip_peer, rtpholdtimeout, AST_DATA_SECONDS) \
30531    MEMBER(sip_peer, rtpkeepalive, AST_DATA_SECONDS)   \
30532    MEMBER(sip_peer, lastms, AST_DATA_MILLISECONDS)    \
30533    MEMBER(sip_peer, maxms, AST_DATA_MILLISECONDS)     \
30534    MEMBER(sip_peer, qualifyfreq, AST_DATA_MILLISECONDS)  \
30535    MEMBER(sip_peer, timer_t1, AST_DATA_MILLISECONDS)  \
30536    MEMBER(sip_peer, timer_b, AST_DATA_MILLISECONDS)
30537 
30538 AST_DATA_STRUCTURE(sip_peer, DATA_EXPORT_SIP_PEER);
30539 
30540 static int peers_data_provider_get(const struct ast_data_search *search,
30541    struct ast_data *data_root)
30542 {
30543    struct sip_peer *peer;
30544    struct ao2_iterator i;
30545    struct ast_data *data_peer, *data_peer_mailboxes = NULL, *data_peer_mailbox, *enum_node;
30546    struct ast_data *data_sip_options;
30547    int total_mailboxes, x;
30548    struct sip_mailbox *mailbox;
30549 
30550    i = ao2_iterator_init(peers, 0);
30551    while ((peer = ao2_iterator_next(&i))) {
30552       ao2_lock(peer);
30553 
30554       data_peer = ast_data_add_node(data_root, "peer");
30555       if (!data_peer) {
30556          ao2_unlock(peer);
30557          ao2_ref(peer, -1);
30558          continue;
30559       }
30560 
30561       ast_data_add_structure(sip_peer, data_peer, peer);
30562 
30563       /* transfer mode */
30564       enum_node = ast_data_add_node(data_peer, "allowtransfer");
30565       if (!enum_node) {
30566          ao2_unlock(peer);
30567          ao2_ref(peer, -1);
30568          continue;
30569       }
30570       ast_data_add_str(enum_node, "text", transfermode2str(peer->allowtransfer));
30571       ast_data_add_int(enum_node, "value", peer->allowtransfer);
30572 
30573       /* transports */
30574       ast_data_add_str(data_peer, "transports", get_transport_list(peer->transports));
30575 
30576       /* peer type */
30577       if ((peer->type & SIP_TYPE_USER) && (peer->type & SIP_TYPE_PEER)) {
30578          ast_data_add_str(data_peer, "type", "friend");
30579       } else if (peer->type & SIP_TYPE_PEER) {
30580          ast_data_add_str(data_peer, "type", "peer");
30581       } else if (peer->type & SIP_TYPE_USER) {
30582          ast_data_add_str(data_peer, "type", "user");
30583       }
30584 
30585       /* mailboxes */
30586       total_mailboxes = 0;
30587       AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
30588          if (!total_mailboxes) {
30589             data_peer_mailboxes = ast_data_add_node(data_peer, "mailboxes");
30590             if (!data_peer_mailboxes) {
30591                break;
30592             }
30593             total_mailboxes++;
30594          }
30595 
30596          data_peer_mailbox = ast_data_add_node(data_peer_mailboxes, "mailbox");
30597          if (!data_peer_mailbox) {
30598             continue;
30599          }
30600          ast_data_add_str(data_peer_mailbox, "mailbox", mailbox->mailbox);
30601          ast_data_add_str(data_peer_mailbox, "context", mailbox->context);
30602       }
30603 
30604       /* amaflags */
30605       enum_node = ast_data_add_node(data_peer, "amaflags");
30606       if (!enum_node) {
30607          ao2_unlock(peer);
30608          ao2_ref(peer, -1);
30609          continue;
30610       }
30611       ast_data_add_int(enum_node, "value", peer->amaflags);
30612       ast_data_add_str(enum_node, "text", ast_cdr_flags2str(peer->amaflags));
30613 
30614       /* sip options */
30615       data_sip_options = ast_data_add_node(data_peer, "sipoptions");
30616       if (!data_sip_options) {
30617          ao2_unlock(peer);
30618          ao2_ref(peer, -1);
30619          continue;
30620       }
30621       for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
30622          ast_data_add_bool(data_sip_options, sip_options[x].text, peer->sipoptions & sip_options[x].id);
30623       }
30624 
30625       /* callingpres */
30626       enum_node = ast_data_add_node(data_peer, "callingpres");
30627       if (!enum_node) {
30628          ao2_unlock(peer);
30629          ao2_ref(peer, -1);
30630          continue;
30631       }
30632       ast_data_add_int(enum_node, "value", peer->callingpres);
30633       ast_data_add_str(enum_node, "text", ast_describe_caller_presentation(peer->callingpres));
30634 
30635       /* codecs */
30636       ast_data_add_codecs(data_peer, "codecs", peer->capability);
30637 
30638       if (!ast_data_search_match(search, data_peer)) {
30639          ast_data_remove_node(data_root, data_peer);
30640       }
30641 
30642       ao2_unlock(peer);
30643       ao2_ref(peer, -1);
30644    }
30645    ao2_iterator_destroy(&i);
30646 
30647    return 0;
30648 }
30649 
30650 static const struct ast_data_handler peers_data_provider = {
30651    .version = AST_DATA_HANDLER_VERSION,
30652    .get = peers_data_provider_get
30653 };
30654 
30655 static const struct ast_data_entry sip_data_providers[] = {
30656    AST_DATA_ENTRY("asterisk/channel/sip/peers", &peers_data_provider),
30657 };
30658 
30659 /*! \brief PBX load module - initialization */
30660 static int load_module(void)
30661 {
30662    ast_verbose("SIP channel loading...\n");
30663 
30664    /* the fact that ao2_containers can't resize automatically is a major worry! */
30665    /* if the number of objects gets above MAX_XXX_BUCKETS, things will slow down */
30666    peers = ao2_t_container_alloc(HASH_PEER_SIZE, peer_hash_cb, peer_cmp_cb, "allocate peers");
30667    peers_by_ip = ao2_t_container_alloc(HASH_PEER_SIZE, peer_iphash_cb, peer_ipcmp_cb, "allocate peers_by_ip");
30668    dialogs = ao2_t_container_alloc(HASH_DIALOG_SIZE, dialog_hash_cb, dialog_cmp_cb, "allocate dialogs");
30669    dialogs_to_destroy = ao2_t_container_alloc(1, NULL, NULL, "allocate dialogs_to_destroy");
30670    threadt = ao2_t_container_alloc(HASH_DIALOG_SIZE, threadt_hash_cb, threadt_cmp_cb, "allocate threadt table");
30671    if (!peers || !peers_by_ip || !dialogs || !dialogs_to_destroy || !threadt) {
30672       ast_log(LOG_ERROR, "Unable to create primary SIP container(s)\n");
30673       return AST_MODULE_LOAD_FAILURE;
30674    }
30675 
30676    ASTOBJ_CONTAINER_INIT(&regl); /* Registry object list -- not searched for anything */
30677    ASTOBJ_CONTAINER_INIT(&submwil); /* MWI subscription object list */
30678 
30679    if (!(sched = sched_context_create())) {
30680       ast_log(LOG_ERROR, "Unable to create scheduler context\n");
30681       return AST_MODULE_LOAD_FAILURE;
30682    }
30683 
30684    if (!(io = io_context_create())) {
30685       ast_log(LOG_ERROR, "Unable to create I/O context\n");
30686       sched_context_destroy(sched);
30687       return AST_MODULE_LOAD_FAILURE;
30688    }
30689 
30690    sip_reloadreason = CHANNEL_MODULE_LOAD;
30691 
30692    can_parse_xml = sip_is_xml_parsable();
30693    if (reload_config(sip_reloadreason)) { /* Load the configuration from sip.conf */
30694       return AST_MODULE_LOAD_DECLINE;
30695    }
30696 
30697    /* Prepare the version that does not require DTMF BEGIN frames.
30698     * We need to use tricks such as memcpy and casts because the variable
30699     * has const fields.
30700     */
30701    memcpy(&sip_tech_info, &sip_tech, sizeof(sip_tech));
30702    memset((void *) &sip_tech_info.send_digit_begin, 0, sizeof(sip_tech_info.send_digit_begin));
30703 
30704    /* Make sure we can register our sip channel type */
30705    if (ast_channel_register(&sip_tech)) {
30706       ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
30707       io_context_destroy(io);
30708       sched_context_destroy(sched);
30709       return AST_MODULE_LOAD_FAILURE;
30710    }
30711 
30712 #ifdef TEST_FRAMEWORK
30713    AST_TEST_REGISTER(test_sip_peers_get);
30714    AST_TEST_REGISTER(test_sip_mwi_subscribe_parse);
30715 #endif
30716 
30717    /* Register AstData providers */
30718    ast_data_register_multiple(sip_data_providers, ARRAY_LEN(sip_data_providers));
30719 
30720    /* Register all CLI functions for SIP */
30721    ast_cli_register_multiple(cli_sip, ARRAY_LEN(cli_sip));
30722 
30723    /* Tell the UDPTL subdriver that we're here */
30724    ast_udptl_proto_register(&sip_udptl);
30725 
30726    /* Tell the RTP engine about our RTP glue */
30727    ast_rtp_glue_register(&sip_rtp_glue);
30728 
30729    /* Register dialplan applications */
30730    ast_register_application_xml(app_dtmfmode, sip_dtmfmode);
30731    ast_register_application_xml(app_sipaddheader, sip_addheader);
30732    ast_register_application_xml(app_sipremoveheader, sip_removeheader);
30733 
30734    /* Register dialplan functions */
30735    ast_custom_function_register(&sip_header_function);
30736    ast_custom_function_register(&sippeer_function);
30737    ast_custom_function_register(&sipchaninfo_function);
30738    ast_custom_function_register(&checksipdomain_function);
30739 
30740    /* Register manager commands */
30741    ast_manager_register_xml("SIPpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peers);
30742    ast_manager_register_xml("SIPshowpeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peer);
30743    ast_manager_register_xml("SIPqualifypeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_qualify_peer);
30744    ast_manager_register_xml("SIPshowregistry", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_show_registry);
30745    ast_manager_register_xml("SIPnotify", EVENT_FLAG_SYSTEM, manager_sipnotify);
30746    sip_poke_all_peers();   
30747    sip_send_all_registers();
30748    sip_send_all_mwi_subscriptions();
30749    initialize_escs();
30750 
30751    if (sip_epa_register(&cc_epa_static_data)) {
30752       return AST_MODULE_LOAD_DECLINE;
30753    }
30754 
30755    if (sip_reqresp_parser_init() == -1) {
30756       ast_log(LOG_ERROR, "Unable to initialize the SIP request and response parser\n");
30757       return AST_MODULE_LOAD_DECLINE;
30758    }
30759 
30760    if (can_parse_xml) {
30761       /* SIP CC agents require the ability to parse XML PIDF bodies
30762        * in incoming PUBLISH requests
30763        */
30764       if (ast_cc_agent_register(&sip_cc_agent_callbacks)) {
30765          return AST_MODULE_LOAD_DECLINE;
30766       }
30767    }
30768    if (ast_cc_monitor_register(&sip_cc_monitor_callbacks)) {
30769       return AST_MODULE_LOAD_DECLINE;
30770    }
30771    if (!(sip_monitor_instances = ao2_container_alloc(37, sip_monitor_instance_hash_fn, sip_monitor_instance_cmp_fn))) {
30772       return AST_MODULE_LOAD_DECLINE;
30773    }
30774 
30775    /* And start the monitor for the first time */
30776    restart_monitor();
30777 
30778    ast_realtime_require_field(ast_check_realtime("sipregs") ? "sipregs" : "sippeers",
30779       "name", RQ_CHAR, 10,
30780       "ipaddr", RQ_CHAR, INET6_ADDRSTRLEN - 1,
30781       "port", RQ_UINTEGER2, 5,
30782       "regseconds", RQ_INTEGER4, 11,
30783       "defaultuser", RQ_CHAR, 10,
30784       "fullcontact", RQ_CHAR, 35,
30785       "regserver", RQ_CHAR, 20,
30786       "useragent", RQ_CHAR, 20,
30787       "lastms", RQ_INTEGER4, 11,
30788       SENTINEL);
30789 
30790 
30791    sip_register_tests();
30792    network_change_event_subscribe();
30793 
30794    return AST_MODULE_LOAD_SUCCESS;
30795 }
30796 
30797 /*! \brief PBX unload module API */
30798 static int unload_module(void)
30799 {
30800    struct sip_pvt *p;
30801    struct sip_threadinfo *th;
30802    struct ast_context *con;
30803    struct ao2_iterator i;
30804    int wait_count;
30805 
30806    network_change_event_unsubscribe();
30807 
30808    ast_sched_dump(sched);
30809    
30810    /* First, take us out of the channel type list */
30811    ast_channel_unregister(&sip_tech);
30812 
30813    /* Unregister dial plan functions */
30814    ast_custom_function_unregister(&sipchaninfo_function);
30815    ast_custom_function_unregister(&sippeer_function);
30816    ast_custom_function_unregister(&sip_header_function);
30817    ast_custom_function_unregister(&checksipdomain_function);
30818 
30819    /* Unregister dial plan applications */
30820    ast_unregister_application(app_dtmfmode);
30821    ast_unregister_application(app_sipaddheader);
30822    ast_unregister_application(app_sipremoveheader);
30823 
30824 #ifdef TEST_FRAMEWORK
30825    AST_TEST_UNREGISTER(test_sip_peers_get);
30826    AST_TEST_UNREGISTER(test_sip_mwi_subscribe_parse);
30827 #endif
30828    /* Unregister all the AstData providers */
30829    ast_data_unregister(NULL);
30830 
30831    /* Unregister CLI commands */
30832    ast_cli_unregister_multiple(cli_sip, ARRAY_LEN(cli_sip));
30833 
30834    /* Disconnect from UDPTL */
30835    ast_udptl_proto_unregister(&sip_udptl);
30836 
30837    /* Disconnect from RTP engine */
30838    ast_rtp_glue_unregister(&sip_rtp_glue);
30839 
30840    /* Unregister AMI actions */
30841    ast_manager_unregister("SIPpeers");
30842    ast_manager_unregister("SIPshowpeer");
30843    ast_manager_unregister("SIPqualifypeer");
30844    ast_manager_unregister("SIPshowregistry");
30845    ast_manager_unregister("SIPnotify");
30846    
30847    /* Kill TCP/TLS server threads */
30848    if (sip_tcp_desc.master) {
30849       ast_tcptls_server_stop(&sip_tcp_desc);
30850    }
30851    if (sip_tls_desc.master) {
30852       ast_tcptls_server_stop(&sip_tls_desc);
30853    }
30854    ast_ssl_teardown(sip_tls_desc.tls_cfg);
30855 
30856    /* Kill all existing TCP/TLS threads */
30857    i = ao2_iterator_init(threadt, 0);
30858    while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
30859       pthread_t thread = th->threadid;
30860       th->stop = 1;
30861       pthread_kill(thread, SIGURG);
30862       ao2_t_ref(th, -1, "decrement ref from iterator");
30863    }
30864    ao2_iterator_destroy(&i);
30865 
30866    /* Hangup all dialogs if they have an owner */
30867    i = ao2_iterator_init(dialogs, 0);
30868    while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
30869       if (p->owner)
30870          ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
30871       ao2_t_ref(p, -1, "toss dialog ptr from iterator_next");
30872    }
30873    ao2_iterator_destroy(&i);
30874 
30875    unlink_all_peers_from_tables();
30876 
30877    ast_mutex_lock(&monlock);
30878    if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
30879       pthread_cancel(monitor_thread);
30880       pthread_kill(monitor_thread, SIGURG);
30881       pthread_join(monitor_thread, NULL);
30882    }
30883    monitor_thread = AST_PTHREADT_STOP;
30884    ast_mutex_unlock(&monlock);
30885 
30886    /* Destroy all the dialogs and free their memory */
30887    i = ao2_iterator_init(dialogs, 0);
30888    while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
30889       dialog_unlink_all(p);
30890       ao2_t_ref(p, -1, "throw away iterator result");
30891    }
30892    ao2_iterator_destroy(&i);
30893 
30894    /* Free memory for local network address mask */
30895    ast_free_ha(localaddr);
30896 
30897    ast_mutex_lock(&authl_lock);
30898    if (authl) {
30899       ao2_t_ref(authl, -1, "Removing global authentication");
30900       authl = NULL;
30901    }
30902    ast_mutex_unlock(&authl_lock);
30903 
30904    sip_epa_unregister_all();
30905    destroy_escs();
30906 
30907    ast_free(default_tls_cfg.certfile);
30908    ast_free(default_tls_cfg.pvtfile);
30909    ast_free(default_tls_cfg.cipher);
30910    ast_free(default_tls_cfg.cafile);
30911    ast_free(default_tls_cfg.capath);
30912 
30913    cleanup_all_regs();
30914    ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
30915    ASTOBJ_CONTAINER_DESTROY(&regl);
30916 
30917    ASTOBJ_CONTAINER_TRAVERSE(&submwil, 1, do {
30918       ASTOBJ_WRLOCK(iterator);
30919       if (iterator->dnsmgr) {
30920          ast_dnsmgr_release(iterator->dnsmgr);
30921          iterator->dnsmgr = NULL;
30922          ASTOBJ_UNREF(iterator, sip_subscribe_mwi_destroy);
30923       }
30924       ASTOBJ_UNLOCK(iterator);
30925    } while(0));
30926    ASTOBJ_CONTAINER_DESTROYALL(&submwil, sip_subscribe_mwi_destroy);
30927    ASTOBJ_CONTAINER_DESTROY(&submwil);
30928 
30929    /*
30930     * Wait awhile for the TCP/TLS thread container to become empty.
30931     *
30932     * XXX This is a hack, but the worker threads cannot be created
30933     * joinable.  They can die on their own and remove themselves
30934     * from the container thus resulting in a huge memory leak.
30935     */
30936    wait_count = 1000;
30937    while (ao2_container_count(threadt) && --wait_count) {
30938       sched_yield();
30939    }
30940    if (!wait_count) {
30941       ast_debug(2, "TCP/TLS thread container did not become empty :(\n");
30942    }
30943 
30944    ao2_t_ref(peers, -1, "unref the peers table");
30945    ao2_t_ref(peers_by_ip, -1, "unref the peers_by_ip table");
30946    ao2_t_ref(dialogs, -1, "unref the dialogs table");
30947    ao2_t_ref(dialogs_to_destroy, -1, "unref dialogs_to_destroy");
30948    ao2_t_ref(threadt, -1, "unref the thread table");
30949    ao2_t_ref(sip_monitor_instances, -1, "unref the sip_monitor_instances table");
30950 
30951    clear_sip_domains();
30952    ast_free_ha(sip_cfg.contact_ha);
30953    close(sipsock);
30954    sched_context_destroy(sched);
30955    con = ast_context_find(used_context);
30956    if (con) {
30957       ast_context_destroy(con, "SIP");
30958    }
30959    ast_unload_realtime("sipregs");
30960    ast_unload_realtime("sippeers");
30961    ast_cc_monitor_unregister(&sip_cc_monitor_callbacks);
30962    ast_cc_agent_unregister(&sip_cc_agent_callbacks);
30963 
30964    sip_reqresp_parser_exit();
30965    sip_unregister_tests();
30966 
30967    return 0;
30968 }
30969 
30970 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Session Initiation Protocol (SIP)",
30971       .load = load_module,
30972       .unload = unload_module,
30973       .reload = reload,
30974       .load_pri = AST_MODPRI_CHANNEL_DRIVER,
30975       .nonoptreq = "res_crypto,chan_local",
30976           );